Compare commits

..

643 Commits

Author SHA1 Message Date
github-actions[bot]
9acb900153 Version Packages (#1303)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-10-14 11:47:13 +02:00
Ralph Khreish
c4f5d89e72 Merge pull request #1297 from eyaltoledano/next 2025-10-14 10:08:08 +02:00
Ralph Khreish
e308cf4f46 chore: exit pre mode 2025-10-13 22:46:24 +02:00
Ralph Khreish
11b7354010 fix: export url (#1288) 2025-10-13 21:51:19 +02:00
Ralph Khreish
4c1ef2ca94 fix: auth refresh token (#1299)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-10-13 21:50:22 +02:00
Ralph Khreish
663aa2dfe9 chore: fix CI 2025-10-12 17:10:24 +02:00
Ralph Khreish
8f60a0561e chore: add hiring banner 2025-10-12 16:52:58 +02:00
Ralph Khreish
9a22622e9c chore: cleanup changelog and pre exit 2025-10-11 21:21:04 +02:00
github-actions[bot]
8d3c7e4116 chore: rc version bump 2025-10-11 19:09:36 +00:00
Ralph Khreish
3010b90d98 feat: add claude code plugin support (#1293)
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 21:01:10 +02:00
Ralph Khreish
90e6bdcf1c fix: expand_all now uses complexity analysis recommendations (#1287)
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 11:54:31 +02:00
Ralph Khreish
25a00dca67 Merge pull request #1291 from eyaltoledano/raplh/chore/merge.main 2025-10-11 11:40:42 +02:00
Ralph Khreish
f263d4b2e0 Merge remote-tracking branch 'origin/main' into raplh/chore/merge.main 2025-10-11 11:32:47 +02:00
Ralph Khreish
f12a16d096 feat: add changelog highlights to auto-update notifications (#1286)
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-10 18:49:59 +02:00
Ralph Khreish
aaf903ff2f fix: resolve cross-level dependency bug in add-dependency command (#1191)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Fixes #542
2025-10-08 15:30:20 +02:00
Ralph Khreish
2a910a40ba feat: add rpg method prd example template (#1285) 2025-10-08 15:00:52 +02:00
github-actions[bot]
0df6595245 Version Packages (#1283)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-10-07 20:43:13 +02:00
Ralph Khreish
33e3fbb20f Release 0.28.0 2025-10-07 20:08:47 +02:00
Ralph Khreish
5cb7ed557a chore: exit pre 2025-10-07 19:34:56 +02:00
github-actions[bot]
b9e644c556 chore: rc version bump 2025-10-06 14:06:45 +00:00
Ralph Khreish
7265a6cf53 feat: implement export tasks (#1260) 2025-10-06 16:03:56 +02:00
Ralph Khreish
db6f405f23 feat: add api-storage improvements (#1278) 2025-10-06 15:23:48 +02:00
Ralph Khreish
7b5a7c4495 fix: remove deprecated generateTaskFiles calls from MCP tools (#1277)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Resolves issue #1271 - MCP Connection Closed Error After Upgrading to v0.27.3
2025-10-06 11:55:26 +02:00
Ralph Khreish
caee040907 fix(mcp-server): construct default tasks.json path when file parameter not provided (#1276)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Fixes #1272
2025-10-06 11:50:45 +02:00
github-actions[bot]
4b5473860b docs: Auto-update and format models.md 2025-10-05 20:04:58 +00:00
Ben Vargas
b43b7ce201 feat: Add Codex CLI provider with OAuth authentication (#1273)
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-10-05 22:04:45 +02:00
github-actions[bot]
86027f1ee4 chore: rc version bump 2025-10-04 17:26:07 +00:00
Ralph Khreish
4f984f8a69 chore: fix build issues (#1274) 2025-10-04 19:24:31 +02:00
github-actions[bot]
f7646f41b5 chore: rc version bump 2025-10-04 16:56:52 +00:00
Ralph Khreish
20004a39ea fix: add complexity score to tm list and tm show (#1270) 2025-10-03 18:47:05 +02:00
Ralph Khreish
f1393f47b1 fix: pricing show 0 when it is defined (#1266) 2025-10-03 16:21:32 +02:00
Ralph Khreish
738ec51c04 feat: Migrate Task Master to generateObject for structured AI responses (#1262)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Ben Vargas <ben@example.com>
2025-10-02 16:23:34 +02:00
Ralph Khreish
c7418c4594 fix: make tag listing table use dynamic column widths to prevent truncation (#1264)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2025-10-02 15:39:31 +02:00
Ralph Khreish
0747f1c772 Merge pull request #1265 from eyaltoledano/ralph/chore/update.from.main 2025-10-02 15:31:42 +02:00
Ralph Khreish
ffe24a2e35 Merge remote-tracking branch 'origin/main' into ralph/chore/update.from.main 2025-10-02 15:11:24 +02:00
Ralph Khreish
604b94baa9 chore: replace dotenv-mono with dotenv and try to fix env variables (#1261) 2025-10-02 11:52:25 +02:00
Ralph Khreish
2ea4bb6a81 chore: fix CI 2025-09-30 10:41:43 +02:00
Ralph Khreish
3e96387715 chore: fix extension CI 2025-09-30 10:41:43 +02:00
Ralph Khreish
100c3dc47d chore: apply requested changes 2025-09-30 10:41:43 +02:00
Ralph Khreish
986ac117ae feat: update grok-cli ai sdk provider to v5 (#1252) 2025-09-30 10:41:43 +02:00
tommy-ca
18aa416035 feat: Claude Code AI SDK v5 Integration (#1114)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-30 10:41:43 +02:00
github-actions[bot]
3b3dbabed1 Version Packages (#1255)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-27 08:56:38 +02:00
Ralph Khreish
af53525cbc fix: handle subtasks in getTask method (#1254)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2025-09-26 20:58:15 +02:00
Joe Danziger
0079b7defd feat: Add Cursor IDE custom slash commands support (#1215) 2025-09-26 19:21:16 +02:00
Ralph Khreish
0b2c6967c4 fix: improve subtask & parent task management (#1251) 2025-09-26 11:04:38 +02:00
Ralph Khreish
c0682ac795 Merge pull request #1250 from eyaltoledano/chore/merge.main.september 2025-09-26 01:10:57 +02:00
Ralph Khreish
01a7faea8f Merge remote-tracking branch 'origin/main' into chore/merge.main.september 2025-09-26 01:10:12 +02:00
github-actions[bot]
b7f32eac5a Version Packages (#1249)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-26 01:06:52 +02:00
Ralph Khreish
044a7bfc98 fix: implement subtask status update functionality (#1248)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2025-09-26 01:01:55 +02:00
Ralph Khreish
814265cd33 chore: adjust CI to run on all PRs (#1244) 2025-09-24 20:19:09 +02:00
Ralph Khreish
9b7b2ca7b2 Merge pull request #1245 from eyaltoledano/ralph/chore/update.from.main 2025-09-24 20:14:00 +02:00
Ralph Khreish
949f091179 Merge remote-tracking branch 'origin/main' into ralph/chore/update.from.main 2025-09-24 20:10:19 +02:00
github-actions[bot]
51a351760c Version Packages (#1243)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-24 19:21:21 +02:00
Ralph Khreish
732b2c61ad Merge pull request #1233 from eyaltoledano/ralph/chore/fix.ci.failure.main 2025-09-24 17:10:42 +02:00
Ralph Khreish
32c2b03c23 Merge pull request #1242 from eyaltoledano/ralph/fix.main.merges
fix CI failing to release (#1232)
2025-09-24 14:28:33 +02:00
Ralph Khreish
3bfd999d81 Merge remote-tracking branch 'origin/main' into ralph/fix.main.merges 2025-09-24 14:28:09 +02:00
Ralph Khreish
9fa79eb026 chore: fix CI failing to release (#1232) 2025-09-24 14:26:41 +02:00
Jungwoo Song
875134247a Add Q Developer CLI at README.md (#1159) 2025-09-24 11:06:16 +02:00
Ralph Khreish
4c2801d5eb chore: run format and fix CI 2025-09-24 11:00:04 +02:00
Ralph Khreish
c911608f60 chore: last round of touchups and bug fixes 2025-09-24 10:57:17 +02:00
github-actions[bot]
8f1497407f chore: rc version bump 2025-09-23 20:43:32 +00:00
Ralph Khreish
10b64ec6f5 chore: re-enter rc mode for a last pre-release 2025-09-23 22:38:55 +02:00
Ralph Khreish
1a1879483b chore: do final test 2025-09-23 21:47:37 +02:00
Ralph Khreish
d691cbb7ae chore: CI fix format 2025-09-23 20:27:41 +02:00
Ralph Khreish
1b7c9637a5 chore: fix CI and tsdown config 2025-09-23 20:24:11 +02:00
Ralph Khreish
9ff5f158d5 chore: fix format 2025-09-23 19:27:57 +02:00
Ralph Khreish
b2ff06e8c5 fix: CI and unit tests 2025-09-23 19:26:02 +02:00
Ralph Khreish
c2fc61ddb3 chore: mintlify fix broken links (#1237) 2025-09-23 18:32:51 +02:00
Ralph Khreish
aaacc3dae3 fix: improve docs and command help for analzye-complexity (#1235) 2025-09-23 18:19:32 +02:00
Ralph Khreish
46cd5dc186 fix: add installation instructions for claude-code mcp (#1236) 2025-09-23 18:16:40 +02:00
github-actions[bot]
49a31be416 docs: Auto-update and format models.md 2025-09-23 15:45:03 +00:00
JeonSeongHyeon
2b69936ee7 fix: update model ID for sonar deep research (#1192)
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-23 17:44:40 +02:00
Ralph Khreish
6438f6c7c8 chore: exit pre-release mode and format 2025-09-23 11:46:20 +02:00
Ralph Khreish
6bbd777552 chore: fix --version weird error 2025-09-23 11:45:46 +02:00
github-actions[bot]
100482722f chore: rc version bump 2025-09-23 09:10:24 +00:00
Ralph Khreish
7ff882bf23 fix: improve commander instance in commands.js 2025-09-23 11:05:24 +02:00
Ralph Khreish
6ab768f6ec chore: fix CI failure 2025-09-22 22:41:21 +02:00
Julien Pelletier
b5fe723f8e Fix/claude code path executable setting (#1172)
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-22 22:39:37 +02:00
Ralph Khreish
f487736670 chore: fix CI failing to release (#1232) 2025-09-22 22:34:12 +02:00
olssonsten
d67b81d25d feat: add MCP timeout configuration for long-running operations (#1112) 2025-09-22 19:55:10 +02:00
Ralph Khreish
66c05053c0 Merge pull request #1231 from eyaltoledano/ralph/merge.from.main 2025-09-22 19:54:12 +02:00
Ralph Khreish
d7ab4609aa chore: fix CI 2025-09-22 19:25:44 +02:00
github-actions[bot]
05f6242f7e Version Packages (#1228)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-09-22 19:23:22 +02:00
Ralph Khreish
a58719cf50 Merge pull request #1230 from eyaltoledano/next 2025-09-22 19:20:40 +02:00
Ralph Khreish
674d1f6de7 fix: update MCP config paths in various files (#1229) 2025-09-22 19:15:17 +02:00
Ralph Khreish
f106fb8e0b Merge pull request Release 0.27.0 #1224 from eyaltoledano/next 2025-09-22 18:40:55 +02:00
Ralph Khreish
fd9dd43ee0 fix: improve weekly metrics workflow with 14-day window and debug output (#1226) 2025-09-22 15:47:03 +02:00
Ralph Khreish
c395e93696 chore: remove pre-mode (get out of RC) 2025-09-20 01:11:50 +02:00
Ralph Khreish
a621ff05ea feat: update tm models defaults (#1225) 2025-09-20 01:07:33 +02:00
github-actions[bot]
47ddb60231 docs: Auto-update and format models.md 2025-09-19 22:08:36 +00:00
Eyal Toledano
fce841490a Tm start (#1200)
Co-authored-by: Max Tuzzolino <maxtuzz@Maxs-MacBook-Pro.local>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Max Tuzzolino <max.tuzsmith@gmail.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-20 00:08:20 +02:00
Ralph Khreish
4e126430a0 chore: update docs to remove --package refs (#1220) 2025-09-18 23:39:50 +02:00
github-actions[bot]
a33abe6c21 chore: rc version bump 2025-09-18 21:17:55 +00:00
Eyal Toledano
2b0cbdbc84 feat: extends the tm context command to accept a brief ID directly or… (#1219)
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-18 23:12:08 +02:00
github-actions[bot]
f1cdf78aa6 chore: rc version bump 2025-09-18 16:37:06 +00:00
Ralph Khreish
e6de285cea feat: add auto-update to every command when your task-master instance is out of date (#1217) 2025-09-18 18:35:32 +02:00
github-actions[bot]
cf3339fa48 chore: rc version bump 2025-09-18 15:18:17 +00:00
Ralph Khreish
255b9f0334 chore: test pre-release functionality with new system 2025-09-18 17:16:26 +02:00
github-actions[bot]
cb2c266b2d chore: rc version bump 2025-09-18 12:56:01 +00:00
Ralph Khreish
170d6f2f65 feat: implement api update-task (#1214) 2025-09-18 01:48:01 +02:00
Ralph Khreish
137ef36278 chore: fix pre-release CI (#1213)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-09-18 00:34:13 +02:00
Ralph Khreish
1a3a528bf7 Merge pull request #1212 from eyaltoledano/ralph/main/rebase 2025-09-17 22:05:13 +02:00
Ralph Khreish
c164adc6ff chore: move to tsdown (#1211)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-09-17 22:00:37 +02:00
Ralph Khreish
9d61e0447d fix: UI list and show (#1210) 2025-09-17 22:00:37 +02:00
Ralph Khreish
ee11b735b3 chore: fix env variables (#1204)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-09-17 22:00:37 +02:00
losolosol
6d978228d9 feat: added vscode start task button (#1201)
Co-authored-by: Carlos Montoya <carlos@Carloss-MacBook-Pro.local>
Co-authored-by: Carlos Montoya <los@losmontoya.com>
2025-09-17 22:00:36 +02:00
Ralph Khreish
ea9341e7af chore: fix CI p2 2025-09-17 22:00:36 +02:00
Ralph Khreish
4296e383ea chore: fix CI 2025-09-17 22:00:36 +02:00
Ralph Khreish
97b2781709 feat: add tm show (#1199) 2025-09-17 22:00:36 +02:00
Ralph Khreish
96553e4a5f chore: fix CI with new typescript setup (#1194)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2025-09-17 22:00:36 +02:00
Ralph Khreish
7582219365 chore: fix format 2025-09-17 22:00:35 +02:00
Ralph Khreish
84baedc3d2 feat: implement tm list remote (#1185) 2025-09-17 22:00:35 +02:00
Ralph Khreish
78da39edff chore: address oauth PR concerns (#1184) 2025-09-17 22:00:35 +02:00
Ralph Khreish
4d1416b175 feat: add oauth with remote server (#1178) 2025-09-17 22:00:35 +02:00
Ralph Khreish
dc811eb45e feat: create tm-core and apps/cli (#1093)
- add typescript
- add npm workspaces
2025-09-17 22:00:34 +02:00
Ralph Khreish
3c41a113fe chore: move to tsdown (#1211)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-09-17 21:55:53 +02:00
Ralph Khreish
0e8c42c7cb fix: UI list and show (#1210) 2025-09-17 15:05:33 +02:00
Ralph Khreish
799d1d2cce chore: fix env variables (#1204)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-09-13 01:34:50 +02:00
losolosol
83af314879 feat: added vscode start task button (#1201)
Co-authored-by: Carlos Montoya <carlos@Carloss-MacBook-Pro.local>
Co-authored-by: Carlos Montoya <los@losmontoya.com>
2025-09-12 05:35:57 +02:00
Ralph Khreish
dd03374496 chore: fix CI p2 2025-09-11 18:44:40 -07:00
Ralph Khreish
4ab0affba7 chore: fix CI 2025-09-11 18:35:07 -07:00
Ralph Khreish
77e1ddc237 feat: add tm show (#1199) 2025-09-12 03:34:32 +02:00
Ralph Khreish
3eeb19590a chore: fix CI with new typescript setup (#1194)
Co-authored-by: Ralph Khreish <Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2025-09-09 23:35:47 +02:00
Ralph Khreish
587745046f chore: fix format 2025-09-09 03:32:48 +02:00
Ralph Khreish
c61c73f827 feat: implement tm list remote (#1185) 2025-09-09 03:32:48 +02:00
Ralph Khreish
15900d9fd5 chore: address oauth PR concerns (#1184) 2025-09-09 03:32:48 +02:00
Ralph Khreish
7cf4004038 feat: add oauth with remote server (#1178) 2025-09-09 03:32:48 +02:00
Ralph Khreish
0f3ab00f26 feat: create tm-core and apps/cli (#1093)
- add typescript
- add npm workspaces
2025-09-09 03:32:48 +02:00
github-actions[bot]
e81040def5 Version Packages (#1189)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-09-09 03:17:22 +02:00
Ralph Khreish
597f6b03b4 Merge pull request #1164 (Release 0.26.0) 2025-09-08 22:17:30 +02:00
Ralph Khreish
a7ad4c8e92 chore: improve Claude documentation workflows (#1155) 2025-09-08 22:11:46 +02:00
Ralph Khreish
0d54747894 chore: fix CI 2025-09-08 12:46:07 -07:00
Jeremy Watt
df26c65632 fix: re-add and re-name claude code clear tm commands (#1133)
* fix: remove claude code clear tm commands

* readded taskmaster claude code commands previously removed

* Update crazy-zebras-drum.md

Updated via nudging from task rabbit - changeset now more direct and no longer mentions issues.

* claude code remove subtasks added back to assets

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Jeremy Watt <jeremywatt@Jeremys-Mac-mini.local>
2025-09-01 11:54:17 +02:00
github-actions[bot]
e80e5bb7cd chore: rc version bump 2025-08-28 22:29:10 +00:00
Ralph Khreish
c4f92f6a0a feat: add optional feature flag for code context (#1165)
* feat: add featureFlag for codebase analysis

* chore: add changeset

* chore: run format
2025-08-29 00:28:00 +02:00
github-actions[bot]
be0c0f267c chore: rc version bump 2025-08-28 22:11:59 +00:00
Ralph Khreish
a983f75d4f Merge pull request #1167 from eyaltoledano/ralph/chore.merge.main.into.next.august
ralph/chore.merge.main.into.next.august
2025-08-29 00:10:36 +02:00
Ralph Khreish
e743aaa8c2 chore: run format 2025-08-29 00:10:05 +02:00
Ralph Khreish
16ffffaf68 Merge remote-tracking branch 'origin/main' into next-backup 2025-08-29 00:08:26 +02:00
Ralph Khreish
f254aed4a6 chore: run format 2025-08-29 00:07:34 +02:00
github-actions[bot]
dd3b47bb2b Version Packages (#1154)
* Version Packages

* chore: fix changelog

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-29 00:07:34 +02:00
Ralph Khreish
37af0f1912 feat: add codebase context capabilities to gemini-cli (#1163)
* feat: add support for claude code context

- code context for:
  - add-task
  - update-subtask
  - update-task
  - update

* feat: fix CI and format + refactor

* chore: format

* chore: fix test

* feat: add gemini-cli support for codebase context

* feat: add google cli integration and fix tests

* chore: apply requested coderabbit changes

* chore: bump gemini cli package
2025-08-28 22:44:52 +02:00
Parthy
8783708e5e Improve cross-tag move UX and safety; add MCP suggestions and CLI tips (#1135)
* docs: Auto-update and format models.md

* docs(ui,cli): remove --force from cross-tag move guidance; recommend --with-dependencies/--ignore-dependencies

- scripts/modules/ui.js: drop force tip in conflict resolution
- scripts/modules/commands.js: remove force examples from move help
- docs/cross-tag-task-movement.md: purge force mentions; add explicit with/ignore examples

* test(move): update cross-tag move tests to drop --force; assert with/ignore deps behavior and current-tag fallback

- CLI integration: remove force expectations, keep with/ignore, current-tag fallback
- Integration: remove force-path test
- Unit: add scoped traversal test, adjust fixtures to avoid id collision

* fix(move): scope dependency traversal to source tag; tag-aware ignore-dependencies filtering

- resolveDependencies: traverse only sourceTag tasks to avoid cross-tag contamination
- filter dependent IDs to those present in source tag, numeric only
- ignore-dependencies: drop deps pointing to tasks from sourceTag; keep targetTag deps

* test(mcp): ensure cross-tag move passes only with/ignore options and returns conflict suggestions

- new test: tests/unit/mcp/tools/move-task-cross-tag-options.test.js

* feat(move): add advisory tips when ignoring cross-tag dependencies; add integration test case

* feat(cli/move): improve ID collision UX for cross-tag moves\n\n- Print Next Steps tips when core returns them (e.g., after ignore-dependencies)\n- Add dedicated help block when an ID already exists in target tag

* feat(move/mcp): improve ID collision UX and suggestions\n\n- Core: include suggestions on TASK_ALREADY_EXISTS errors\n- MCP: map ID collision to TASK_ALREADY_EXISTS with suggestions\n- Tests: add MCP unit test for ID collision suggestions

* test(move/cli): print tips on ignore-dependencies results; print ID collision suggestions\n\n- CLI integration test: assert Next Steps tips printed when result.tips present\n- Integration test: assert TASK_ALREADY_EXISTS error includes suggestions payload

* chore(changeset): add changeset for cross-tag move UX improvements (CLI/MCP/core/tests)

* Add cross-tag task movement help and validation improvements

- Introduced a detailed help command for cross-tag task movement, enhancing user guidance on usage and options.
- Updated validation logic in `validateCrossTagMove` to include checks for indirect dependencies, improving accuracy in conflict detection.
- Refactored tests to ensure comprehensive coverage of new validation scenarios and error handling.
- Cleaned up documentation to reflect the latest changes in task movement functionality.

* refactor(commands): remove redundant tips printing after move operation

- Eliminated duplicate printing of tips for next steps after the move operation, streamlining the output for users.
- This change enhances clarity by ensuring tips are only displayed when relevant, improving overall user experience.

* docs(move): clarify "force move" options and improve examples

- Updated documentation to replace the deprecated "force move" concept with clear alternatives: `--with-dependencies` and `--ignore-dependencies`.
- Enhanced Scenario 3 with explicit options and improved inline comments for better readability.
- Removed confusing commented code in favor of a straightforward note in the Force Move section.

* chore: run formatter

* Update .changeset/clarify-force-move-docs.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update docs/cross-tag-task-movement.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update tests/unit/scripts/modules/task-manager/move-task-cross-tag.test.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* test(move): add test for dependency traversal scoping with --with-dependencies option

- Introduced a new test to ensure that the dependency traversal is limited to tasks from the source tag when using the --with-dependencies option, addressing potential ID collisions across tags.

* test(move): enhance tips validation in cross-tag task movement integration test

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-08-28 19:02:00 +02:00
Ralph Khreish
4dad2fd613 feat: add support for code context in more commands (#1162)
* feat: add support for claude code context

- code context for:
  - add-task
  - update-subtask
  - update-task
  - update

* feat: fix CI and format + refactor

* chore: format

* chore: fix broken tests

* chore: fix test
2025-08-28 18:05:31 +02:00
github-actions[bot]
4cae2991d4 Version Packages (#1154)
* Version Packages

* chore: fix changelog

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-23 00:44:25 +02:00
Ralph Khreish
0d7ff627c9 Merge pull request #1152 from eyaltoledano/next 2025-08-23 00:34:40 +02:00
Ralph Khreish
db720a954d Fix: disable streaming for parse prd (#1151)
* fix: temporarily disable streaming
2025-08-22 18:33:02 +02:00
Ben Vargas
89335578ff fix(claude-code): prevent "Right-hand side of instanceof is not an object" when SDK missing; improve CLI stability (#1146)
* fix: handle missing @anthropic-ai/claude-code SDK gracefully

Add defensive checks to prevent "Right-hand side of 'instanceof' is not an object" errors when the optional Claude Code SDK is not installed.

Changes:
- Check if AbortError exists before using instanceof
- Check if query function exists before calling it
- Provide clear error messages when SDK is missing

This fixes the issue reported by users in v0.24.0 and v0.25.0 where Task Master would crash with instanceof errors when using the claude-code provider without the SDK installed.

* chore: bump @anthropic-ai/claude-code to ^1.0.88 and regenerate lockfile
2025-08-22 17:01:34 +02:00
Ralph Khreish
781b8ef2af remove claude code mentioning 2025-08-22 17:01:34 +02:00
github-actions[bot]
7d564920b5 Version Packages (#1143)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-08-19 23:04:40 +02:00
Ralph Khreish
2737fbaa67 Release 0.25.0 #1134 from eyaltoledano/next
Release 0.25.0
2025-08-19 21:10:44 +02:00
Ralph Khreish
9feb8d2dbf chore: fix CI of claude code docs updater 2025-08-19 16:11:57 +02:00
Ralph Khreish
8a991587f1 chore: fix CI 2025-08-19 16:09:08 +02:00
Ralph Khreish
7ceba2f572 chore: exit pre-release mode 2025-08-19 16:01:31 +02:00
Ralph Khreish
10565f07d3 chore: run format 2025-08-19 16:00:48 +02:00
Ralph Khreish
f27ce34fe9 chore: fix changeset 2025-08-14 14:24:08 +02:00
github-actions[bot]
71be933a8d chore: rc version bump 2025-08-13 22:37:59 +00:00
Ralph Khreish
5d94f1b471 chore: add a bunch of automations (#1132)
* chore: add a bunch of automations

* chore: run format

* Update .github/scripts/auto-close-duplicates.mjs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: run format

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-08-14 00:36:18 +02:00
Joe Danziger
3dee60dc3d fix: update Cursor one-click install link to new URL format (#1131)
* add /en to link

* add changeset
2025-08-13 18:02:47 +02:00
Ralph Khreish
f469515228 feat: add Claude documentation updater workflow (#1130)
This commit introduces a new GitHub Actions workflow that automatically updates documentation based on changes pushed to the 'next' branch. The workflow checks for modified files, creates a new branch for documentation updates, and utilizes the Claude Code Action to analyze changes and suggest necessary documentation revisions. If updates are made, a pull request is created for review.
2025-08-13 15:10:47 +02:00
Ralph Khreish
2fd0f026d3 chore: remove pre-release CI for extension, too much work and doesn't make sense for us (#1129) 2025-08-13 15:08:55 +02:00
Joe Danziger
e3ed4d7c14 feat: CLI & MCP progress tracking for parse-prd command (#1048)
* initial cutover

* update log to debug

* update tracker to pass units

* update test to match new base tracker format

* add streamTextService mocks

* remove unused imports

* Ensure the CLI waits for async main() completion

* refactor to reduce code duplication

* update comment

* reuse function

* ensure targetTag is defined in streaming mode

* avoid throwing inside process.exit spy

* check for null

* remove reference to generate

* fix formatting

* fix textStream assignment

* ensure no division by 0

* fix jest chalk mocks

* refactor for maintainability

* Improve bar chart calculation logic for consistent visual representation

* use custom streaming error types; fix mocks

* Update streamText extraction in parse-prd.js to match actual service response

* remove check - doesn't belong here

* update mocks

* remove streaming test that wasn't really doing anything

* add comment

* make parsing logic more DRY

* fix formatting

* Fix textStream extraction to match actual service response

* fix mock

* Add a cleanup method to ensure proper resource disposal and prevent memory leaks

* debounce progress updates to reduce UI flicker during rapid updates

* Implement timeout protection for streaming operations (60-second timeout) with automatic fallback to non-streaming mode.

* clear timeout properly

* Add a maximum buffer size limit (1MB) to prevent unbounded memory growth with very large streaming responses.

* fix formatting

* remove duplicate mock

* better docs

* fix formatting

* sanitize the dynamic property name

* Fix incorrect remaining progress calculation

* Use onError callback instead of console.warn

* Remove unused chalk import

* Add missing custom validator in fallback parsing configuration

* add custom validator parameter in fallback parsing

* chore: fix package-lock.json

* chore: large code refactor

* chore: increase timeout from 1 minute to 3 minutes

* fix: refactor and fix streaming

* Merge remote-tracking branch 'origin/next' into joedanz/parse-prd-progress

* fix: cleanup and fix unit tests

* chore: fix unit tests

* chore: fix format

* chore: run format

* chore: fix weird CI unit test error

* chore: fix format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-12 22:37:07 +02:00
Dominique Vidjanagni
fc47714340 Feat/add-kilocode-rules (#1040)
* feat: Add Kilo Code integration to TaskMaster

* feat: Add Kilo profile configuration to rule transformer tests

* refactor: Improve code formatting and consistency in Kilo profile and tests

* fix: Correct formatting of workspaces in package.json

* chore: add changeset for Kilo Code integration

* feat: add Kilo Code rules and mode configurations

- Add comprehensive rule sets for all modes (architect, ask, code, debug, orchestrator, test)
- Update .kilocodemodes configuration with mode-specific settings
- Configure MCP integration for Kilo Code profile
- Establish consistent rule structure across all modes

* refactor(kilo): simplify profile to reuse roo rules with replacements

Remove duplicate Kilo-specific rule files and assets in favor of reusing roo rules with dynamic replacements, eliminating 900+ lines of duplicated code while maintaining full Kilo functionality.

The profile now:
- Reuses ROO_MODES constant instead of maintaining separate KILO_MODES
- Applies text replacements to convert roo references to kilo
- Maps roo rule files to kilo equivalents via fileMap
- Removes all duplicate rule files from assets/kilocode directory

* refactor(kilo): restructure object literals for consistency and remove duplicate customReplacements array based on CodeRabbit's suggestion

* chore: remove disabled .mcp.json by mistake

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-12 22:35:57 +02:00
github-actions[bot]
30ae0e9a57 docs: Auto-update and format models.md 2025-08-12 17:01:24 +00:00
Ralph Khreish
95640dcde8 feat: add gpt-oss models to ollama (#1124) 2025-08-12 19:01:10 +02:00
Ralph Khreish
311b2433e2 fix: remove claude code clear tm commands (#1123) 2025-08-11 18:59:35 +02:00
Parthy
04e11b5e82 feat: implement cross-tag task movement functionality (#1088)
* feat: enhance move command with cross-tag functionality

- Updated the `move` command to allow moving tasks between different tags, including options for handling dependencies.
- Added new options: `--from-tag`, `--to-tag`, `--with-dependencies`, `--ignore-dependencies`, and `--force`.
- Implemented validation for cross-tag moves and dependency checks.
- Introduced helper functions in the dependency manager for validating and resolving cross-tag dependencies.
- Added integration and unit tests to cover new functionality and edge cases.

* fix: refactor cross-tag move logic and enhance validation

- Moved the import of `moveTasksBetweenTags` to the correct location in `commands.js` for better clarity.
- Added new helper functions in `dependency-manager.js` to improve validation and error handling for cross-tag moves.
- Enhanced existing functions to ensure proper handling of task dependencies and conflicts.
- Updated tests to cover new validation scenarios and ensure robust error messaging for invalid task IDs and tags.

* fix: improve task ID handling and error messaging in cross-tag moves

- Refactored `moveTasksBetweenTags` to normalize task IDs for comparison, ensuring consistent handling of string and numeric IDs.
- Enhanced error messages for cases where source and target tags are the same but no destination is specified.
- Updated tests to validate new behavior, including handling string dependencies correctly during cross-tag moves.
- Cleaned up existing code for better readability and maintainability.

* test: add comprehensive tests for cross-tag move and dependency validation

- Introduced new test files for `move-cross-tag` and `cross-tag-dependencies` to cover various scenarios in cross-tag task movement.
- Implemented tests for handling task movement with and without dependencies, including edge cases for error handling.
- Enhanced existing tests in `fix-dependencies-command` and `move-task` to ensure robust validation of task IDs and dependencies.
- Mocked necessary modules and functions to isolate tests and improve reliability.
- Ensured coverage for both successful and failed cross-tag move operations, validating expected outcomes and error messages.

* test: refactor cross-tag move tests for better clarity and reusability

- Introduced a helper function `simulateCrossTagMove` to streamline cross-tag move test cases, reducing redundancy and improving readability.
- Updated existing tests to utilize the new helper function, ensuring consistent handling of expected messages and options.
- Enhanced test coverage for various scenarios, including handling of dependencies and flags.

* feat: add cross-tag task movement functionality

- Introduced new commands for moving tasks between different tags, enhancing project organization capabilities.
- Updated README with usage examples for cross-tag movement, including options for handling dependencies.
- Created comprehensive documentation for cross-tag task movement, detailing usage, error handling, and best practices.
- Implemented core logic for cross-tag moves, including validation for dependencies and error handling.
- Added integration and unit tests to ensure robust functionality and coverage for various scenarios, including edge cases.

* fix: enhance error handling and logging in cross-tag task movement

- Improved logging in `moveTaskCrossTagDirect` to include detailed arguments for better traceability.
- Refactored error handling to utilize structured error objects, providing clearer suggestions for resolving cross-tag dependency conflicts and subtask movement restrictions.
- Updated documentation to reflect changes in error handling and provide clearer guidance on task movement options.
- Added integration tests for cross-tag movement scenarios, ensuring robust validation of error handling and task movement logic.
- Cleaned up existing tests for clarity and reusability, enhancing overall test coverage.

* feat: enhance dependency resolution and error handling in task movement

- Added recursive dependency resolution for tasks in `moveTasksBetweenTags`, improving handling of complex task relationships.
- Introduced helper functions to find all dependencies and reverse dependencies, ensuring comprehensive coverage during task moves.
- Enhanced error messages in `validateSubtaskMove` and `displaySubtaskMoveError` for better clarity on movement restrictions.
- Updated tests to cover new functionality, including integration tests for complex cross-tag movement scenarios and edge cases.
- Refactored existing code for improved readability and maintainability, ensuring consistent handling of task IDs and dependencies.

* feat: unify dependency traversal and enhance task management utilities

- Introduced `traverseDependencies` utility for unified forward and reverse dependency traversal, improving code reusability and clarity.
- Refactored `findAllDependenciesRecursively` to leverage the new utility, streamlining dependency resolution in task management.
- Added `formatTaskIdForDisplay` helper for better task ID formatting in UI, enhancing user experience during error displays.
- Updated tests to cover new utility functions and ensure robust validation of dependency handling across various scenarios.
- Improved overall code organization and readability, ensuring consistent handling of task dependencies and IDs.

* fix: improve validation for dependency parameters in `findAllDependenciesRecursively`

- Added checks to ensure `sourceTasks` and `allTasks` are arrays, throwing errors if not, to prevent runtime issues.
- Updated documentation comment for clarity on the function's purpose and parameters.

* fix: remove `force` option from task movement parameters

- Eliminated the `force` parameter from the `moveTaskCrossTagDirect` function and related tools, simplifying the task movement logic.
- Updated documentation and tests to reflect the removal of the `force` option, ensuring clarity and consistency across the codebase.
- Adjusted related functions and tests to focus on `ignoreDependencies` as the primary control for handling dependency conflicts during task moves.

* Add cross-tag task movement functionality

- Introduced functionality for organizing tasks across different contexts by enabling cross-tag movement.
- Added `formatTaskIdForDisplay` helper to improve task ID formatting in UI error messages.
- Updated relevant tests to incorporate new functionality and ensure accurate error displays during task movements.

* Update scripts/modules/dependency-manager.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* refactor(dependency-manager): Fix subtask resolution and extract helper functions

1. Fix subtask finding logic (lines 1315-1330):
   - Correctly locate parent task by numeric ID
   - Search within parent's subtasks array instead of top-level tasks
   - Properly handle relative subtask references

2. Extract helper functions from getDependentTaskIds (lines 1440-1636):
   - Move findTasksThatDependOn as module-level function
   - Move taskDependsOnSource as module-level function
   - Move subtasksDependOnSource as module-level function
   - Improves readability, maintainability, and testability

Both fixes address architectural issues and improve code organization.

* refactor(dependency-manager): Enhance subtask resolution and dependency validation

- Improved subtask resolution logic to correctly find parent tasks and their subtasks, ensuring accurate identification of dependencies.
- Filtered out null/undefined dependencies before processing, enhancing robustness in dependency checks.
- Updated comments for clarity on the logic flow and purpose of changes, improving code maintainability.

* refactor(move-task): clarify destination ID description and improve skipped task handling

- Updated the description for the destination ID to clarify its usage in cross-tag moves.
- Simplified the handling of skipped tasks during multiple task movements, improving readability and logging.
- Enhanced the API result response to include detailed information about moved and skipped tasks, ensuring better feedback for users.

* refactor(commands): remove redundant tag validation logic

- Eliminated the check for identical source and target tags in the task movement logic, simplifying the code.
- This change streamlines the flow for within-tag moves, enhancing readability and maintainability.

* refactor(commands): enhance move command logic and error handling

- Introduced helper functions for better organization of cross-tag and within-tag move logic, improving code readability and maintainability.
- Enhanced error handling with structured error objects, providing clearer feedback for dependency conflicts and invalid tag combinations.
- Updated move command help output to include best practices and error resolution tips, ensuring users have comprehensive guidance during task movements.
- Streamlined task movement logic to handle multiple tasks more effectively, including detailed logging of successful and failed moves.

* test(dependency-manager): add subtasks to task structure and mock dependency traversal

- Updated `circular-dependencies.test.js` to include subtasks in task definitions, enhancing test coverage for task structures with nested dependencies.
- Mocked `traverseDependencies` in `fix-dependencies-command.test.js` to ensure consistent behavior during tests, improving reliability of dependency-related tests.

* refactor(dependency-manager): extract subtask finding logic into helper function

- Added `findSubtaskInParent` function to encapsulate subtask resolution within a parent task's subtasks array, improving code organization and readability.
- Updated `findDependencyTask` to utilize the new helper function, streamlining the logic for finding subtasks and enhancing maintainability.
- Enhanced comments for clarity on the purpose and functionality of the new subtask finding logic.

* refactor(ui): enhance subtask ID validation and improve error handling

- Added validation for subtask ID format in `formatDependenciesWithStatus` and `taskExists`, ensuring proper handling of invalid formats.
- Updated error logging in `displaySubtaskMoveError` to provide warnings for unexpected task ID formats, improving user feedback.
- Converted hints to a Set in `displayDependencyValidationHints` to ensure unique hints are displayed, enhancing clarity in the UI.

* test(cli): remove redundant timing check in complex cross-tag scenarios

- Eliminated the timing check for task completion within 5 seconds in `complex-cross-tag-scenarios.test.js`, streamlining the test logic.
- This change focuses on verifying task success without unnecessary timing constraints, enhancing test clarity and maintainability.

* test(integration): enhance task movement tests with mock file system

- Added integration tests for moving tasks within the same tag and between different tags using the actual `moveTask` and `moveTasksBetweenTags` functions.
- Implemented `mock-fs` to simulate file system interactions, improving test isolation and reliability.
- Verified task movement success and ensured proper handling of subtasks and dependencies, enhancing overall test coverage for task management functionality.
- Included error handling tests for missing tags and task IDs to ensure robustness in task movement operations.

* test(unit): add comprehensive tests for moveTaskCrossTagDirect functionality

- Introduced new test cases to verify mock functionality, ensuring that mocks for `findTasksPath` and `readJSON` are working as expected.
- Added tests for parameter validation, error handling, and function call flow, including scenarios for missing project roots and identical source/target tags.
- Enhanced coverage for ID parsing and move options, ensuring robust handling of various input conditions and improving overall test reliability.

* test(integration): skip tests for dependency conflict handling and withDependencies option

- Marked tests for handling dependency conflicts and the withDependencies option as skipped due to issues with the mock setup.
- Added TODOs to address the mock-fs setup for complex dependency scenarios, ensuring future improvements in test reliability.

* test(unit): expand cross-tag move command tests with comprehensive mocks

- Added extensive mocks for various modules to enhance the testing of the cross-tag move functionality in `move-cross-tag.test.js`.
- Implemented detailed test cases for handling cross-tag moves, including validation for missing parameters and identical source/target tags.
- Improved error handling tests to ensure robust feedback for invalid operations, enhancing overall test reliability and coverage.

* test(integration): add complex dependency scenarios to task movement tests

- Introduced new integration tests for handling complex dependency scenarios in task movement, utilizing the actual `moveTasksBetweenTags` function.
- Added tests for circular dependencies, nested dependency chains, and cross-tag dependency resolution, enhancing coverage and reliability.
- Documented limitations of the mock-fs setup for complex scenarios and provided warnings in the test output to guide future improvements.
- Skipped tests for dependency conflicts and the withDependencies option due to mock setup issues, with TODOs for resolution.

* test(unit): refactor move-cross-tag tests with focused mock system

- Simplified mocking in `move-cross-tag.test.js` by implementing a configuration-driven mock system, reducing the number of mocked modules from 20+ to 5 core functionalities.
- Introduced a reusable mock factory to streamline the creation of mocks based on configuration, enhancing maintainability and clarity.
- Added documentation for the new mock system, detailing usage examples and benefits, including reduced complexity and improved test focus.
- Implemented tests to validate the mock configuration, ensuring flexibility in enabling/disabling specific mocks.

* test(unit): clean up mocks and improve isEmpty function in fix-dependencies-command tests

- Removed the mock for `traverseDependencies` as it was unnecessary, simplifying the test setup.
- Updated the `isEmpty` function to clarify its behavior regarding null and undefined values, enhancing code readability and maintainability.

* test(unit): update traverseDependencies mock for consistency across tests

- Standardized the mock implementation of `traverseDependencies` in both `fix-dependencies-command.test.js` and `complexity-report-tag-isolation.test.js` to accept `sourceTasks`, `allTasks`, and `options` parameters, ensuring uniformity in test setups.
- This change enhances clarity and maintainability of the tests by aligning the mock behavior across different test files.

* fix(core): improve task movement error handling and ID normalization

- Wrapped task movement logic in a try-finally block to ensure console output is restored even on errors, enhancing reliability.
- Normalized source IDs to handle mixed string/number comparisons, preventing potential issues in dependency checks.
- Added tests for ID type consistency to verify that the normalization fix works correctly across various scenarios, improving test coverage and robustness.

* refactor(task-manager): restructure task movement logic for improved validation and execution

- Renamed and refactored `moveTasksBetweenTags` to streamline the task movement process into distinct phases: validation, data preparation, dependency resolution, execution, and finalization.
- Introduced `validateMove`, `prepareTaskData`, `resolveDependencies`, `executeMoveOperation`, and `finalizeMove` functions to enhance modularity and clarity.
- Updated documentation comments to reflect changes in function responsibilities and parameters.
- Added comprehensive unit tests for the new structure, ensuring robust validation and error handling across various scenarios.
- Improved handling of dependencies and task existence checks during the move operation, enhancing overall reliability.

* fix(move-task): streamline task movement logic and improve error handling

- Refactored the task movement process to enhance clarity and maintainability by replacing `forEach` with a `for...of` loop for better async handling.
- Consolidated error handling and result logging to ensure consistent feedback during task moves.
- Updated the logic for generating files only on the last move, improving performance and reducing unnecessary operations.
- Enhanced validation for skipped tasks, ensuring accurate reporting of moved and skipped tasks in the final result.

* fix(docs): update error message formatting and enhance clarity in task movement documentation

- Changed code block syntax from generic to `text` for better readability in error messages related to task movement and dependency conflicts.
- Ensured consistent formatting across all error message examples to improve user understanding of task movement restrictions and resolutions.
- Added a newline at the end of the file for proper formatting.

* Update .changeset/crazy-meals-hope.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: improve changeset

* chore: improve changeset

* fix referenced bug in docs and remove docs

* chore: fix format

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-11 18:58:51 +02:00
Ladi
782728ff95 feat: add --compact flag for minimal task list output (#1054)
* feat: add --compact flag for minimal task list output

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-08-11 18:35:23 +02:00
Fábio Vedovelli
30ca144231 feat: Add task id to task details UI (#1100)
* Display current task ID on task details page

* Changeset

* Implement CodeRabbit review suggestion.

* chore: fix CI errors

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-11 14:42:31 +02:00
Ralph Khreish
0220d0e994 chore: pimp my readme (#1122) 2025-08-11 14:29:49 +02:00
Ralph Khreish
41a8c2406a chore: add docs to monorepo (#1111) 2025-08-09 13:31:45 +02:00
github-actions[bot]
a003041cd8 Version Packages (#1107)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-08-08 22:00:39 +02:00
Ralph Khreish
6b57ead106 Release 0.24.0 #1098 from eyaltoledano/next
Release 0.24.0
2025-08-08 21:58:41 +02:00
Ralph Khreish
7b6e117b1d chore: prepare for release (exit pre mode) 2025-08-08 21:21:25 +02:00
Ralph Khreish
03b045e9cd chore: run format 2025-08-08 21:18:33 +02:00
neonwatty
699afdae59 feat: add task-checker agent to assets directory 2025-08-08 08:47:20 -07:00
github-actions[bot]
80c09802e8 chore: rc version bump 2025-08-08 12:41:29 +00:00
github-actions[bot]
cf8f0f4b1c docs: Auto-update and format models.md 2025-08-08 12:38:58 +00:00
Ralph Khreish
75c514cf5b feat: add gpt-5 support (#1105)
* feat: add gpt-5 support
2025-08-08 14:38:44 +02:00
Ralph Khreish
41d1e671b1 chore: fix CI checker, improve it (#1099) 2025-08-07 15:52:49 +02:00
Ralph Khreish
a464e550b8 feat(extension): implement simple solution to --package flag (#1090)
* feat(extension): implement simple solution to --package flag
2025-08-07 15:10:34 +02:00
Ralph Khreish
3a852afdae chore: implement pre-release for extensions (#1097)
* chore: implement pre-release for extensions

* chore: run format
2025-08-07 15:08:14 +02:00
Ralph Khreish
4bb63706b8 feat: implement claude code agents (#1091)
* feat: implement claude code agents

* chore: add changeset

- run format

* feat: improve task-checker, executor, and orchestrator

* chore: improve changeset
2025-08-07 12:37:06 +02:00
Ralph Khreish
fcf14e09be chore: improve release check for release-check and release flow (#1095)
* chore: improve release check for release-check and release flow

* chore: fix format
2025-08-06 23:19:28 +02:00
Ralph Khreish
4357af3f13 fix(expand-task): include parent task context in complexity report variant (#1094)
- Fixed bug where expand task generated generic authentication subtasks
- The complexity-report prompt variant now includes parent task details
- Added comprehensive unit tests to prevent regression
- Added debug logging to help diagnose similar issues

Previously, when using a complexity report with expansionPrompt, only the
expansion guidance was sent to the AI, missing the actual task context.
This caused the AI to generate unrelated generic subtasks.

Fixes the issue where all tasks would get the same generic auth-related
subtasks regardless of their actual purpose (AWS infrastructure, Docker
containerization, etc.)

Co-authored-by: Sadaqat Ali <32377500+sadaqat12@users.noreply.github.com>
2025-08-06 21:00:32 +02:00
Ralph Khreish
59f7676051 feat: add prompt for claude code to include context when generating tasks (#1092) 2025-08-06 12:41:19 +02:00
Ralph Khreish
36468f3c93 feat: add prompt for claude code to include context when generating tasks 2025-08-06 12:17:49 +02:00
Ralph Khreish
ca4d93ee6a chore: prepare prd for tm-core creation phase 1 (#1045) 2025-08-06 10:10:29 +02:00
Ralph Khreish
37fb569a62 Release 0.23.1 #1084 from eyaltoledano/next
chore: exit pre-release mode
2025-08-04 20:43:46 +03:00
Ralph Khreish
ed0d4e6641 chore: implement requested changes 2025-08-04 14:40:11 +03:00
Ralph Khreish
5184f8e7b2 chore: implement requested changes 2025-08-04 14:37:24 +03:00
Ralph Khreish
587523a23b chore: improve release-check CI 2025-08-04 14:29:03 +03:00
Ralph Khreish
7a50f0c6ec chore: add release-check CI to check if we are in release mode (#1086) 2025-08-04 13:22:46 +02:00
Ralph Khreish
adeb76ee15 chore: exit pre-release mode 2025-08-04 10:02:00 +03:00
Ralph Khreish
d342070375 Merge pull request #1081 from eyaltoledano/next 2025-08-03 21:38:19 +03:00
github-actions[bot]
5e4dbac525 chore: rc version bump 2025-08-03 14:07:15 +00:00
Ralph Khreish
fb15c2eaf7 chore: improve pre-release CI to just use dropdown (#1080)
* chore: improve pre-release CI to just use dropdown

* chore: implement requested changes
2025-08-03 16:04:29 +02:00
Ralph Khreish
e8ceb08341 chore: improve release and pre-release CI (#1075)
* chore: improve release and pre-release CI

* chore: apply requested changes

* Update .github/workflows/pre-release.yml

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: apply requested changes

* chore: apply requested changes

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-08-03 15:17:18 +02:00
Ralph Khreish
e495b2b559 feat: improve scope up and down command & parse-prd improvements (#1079)
* feat: improve scope up and down command & parse-prd improvements

* chore: run format
2025-08-03 14:12:46 +02:00
Ralph Khreish
e0d1d03f33 chore: fix tag-extension and improve debugging (#1074) 2025-08-02 23:10:57 +02:00
Ralph Khreish
4a4bca905d chore: fix tag-extension package.json not found for extension (#1073)
* chore: fix tag-extension package.json not found for extension

* chore: fix format
2025-08-02 22:56:53 +02:00
github-actions[bot]
9d5f50ac8e Version Packages (#1072)
* Version Packages

* chore: add eyal instead of crunchyman to eyal's feature

* chore: run format

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-08-02 22:43:08 +02:00
Ralph Khreish
bbeaa9163a chore: exit pre (#1071) 2025-08-02 22:35:46 +02:00
Ralph Khreish
a4a172be94 Release 0.23.0 #1064 from eyaltoledano/next
Release 0.23.0
2025-08-02 23:18:05 +03:00
github-actions[bot]
028ed9c444 chore: rc version bump 2025-08-02 20:07:43 +00:00
Ralph Khreish
53903f1e8e chore: trick rc bump 2025-08-02 23:06:37 +03:00
github-actions[bot]
36c56231cc chore: rc version bump 2025-08-02 20:04:33 +00:00
Ralph Khreish
b82d858f81 chore: rename chagneset for rc bump 2025-08-02 23:03:10 +03:00
Ralph Khreish
9808967d6b chore: change from patch to minor 2025-08-02 23:00:56 +03:00
Ralph Khreish
3fee7515f3 fix: fix mcp tool call in extension (#1070)
* fix: fix mcp tool call in extension

- fix console.log directly being used in scope-adjutment.js breaking mcp

* chore: run format and fix tests

* chore: format
2025-08-02 21:59:02 +02:00
github-actions[bot]
82b17bdb57 chore: rc version bump 2025-08-02 16:44:19 +00:00
Eyal Toledano
72ca68edeb Task 104: Implement 'scope-up' and 'scope-down' CLI Commands for Dynamic Task Complexity Adjustment (#1069)
* feat(task-104): Complete task 104 - Implement scope-up and scope-down CLI Commands

- Added new CLI commands 'scope-up' and 'scope-down' with comma-separated ID support
- Implemented strength levels (light/regular/heavy) and custom prompt functionality
- Created core complexity adjustment logic with AI integration
- Added MCP tool equivalents for integrated environments
- Comprehensive error handling and task validation
- Full test coverage with TDD approach
- Updated task manager core and UI components

Task 104: Implement 'scope-up' and 'scope-down' CLI Commands for Dynamic Task Complexity Adjustment - Complete implementation with CLI, MCP integration, and testing

* chore: Add changeset for scope-up and scope-down features

- Comprehensive user-facing description with usage examples
- Key features and benefits explanation
- CLI and MCP integration details
- Real-world use cases for agile workflows

* feat(extension): Add scope-up and scope-down to VS Code extension task details

- Added useScopeUpTask and useScopeDownTask hooks in useTaskQueries.ts
- Enhanced AIActionsSection with Task Complexity Adjustment section
- Added strength selection (light/regular/heavy) and custom prompt support
- Integrated scope buttons with proper loading states and error handling
- Uses existing mcpRequest handler for scope_up_task and scope_down_task tools
- Maintains consistent UI patterns with existing AI actions

Extension now supports dynamic task complexity adjustment directly from task details view.
2025-08-02 18:43:04 +02:00
DavidMaliglowka
64302dc191 feat(extension): complete VS Code extension with kanban board interface (#997)
---------
Co-authored-by: DavidMaliglowka <13022280+DavidMaliglowka@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-08-01 14:04:22 +02:00
github-actions[bot]
60c03c548d chore: rc version bump 2025-07-31 22:15:10 +00:00
Ralph Khreish
2ae6e7e6be fix: normalize task IDs to numbers on load to fix comparison issues (#1063)
* fix: normalize task IDs to numbers on load to fix comparison issues

When tasks.json contains string IDs (e.g., "5" instead of 5), task lookups
fail because the code uses parseInt() and strict equality (===) for comparisons.

This fix normalizes all task and subtask IDs to numbers when loading the JSON,
ensuring consistent comparisons throughout the codebase without requiring
changes to multiple comparison locations.

Fixes task not found errors when using string IDs in tasks.json.

* Added test

* Don't mess up formatting

* Fix formatting once and for all

* Update scripts/modules/utils.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update scripts/modules/utils.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update scripts/modules/utils.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: normalize task IDs to numbers on load to fix comparison issues

- Added normalizeTaskIds function to convert string IDs to numbers
- Applied normalization in readJSON for all code paths
- Fixed set-task-status, add-task, and move-task to normalize IDs when working with raw data
- Exported normalizeTaskIds function for use in other modules
- Added test case for string ID normalization

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Simplified implementation

* refactor: normalize IDs once when loading JSON instead of scattered calls

- Normalize all tags' data when creating _rawTaggedData in readJSON
- Add support for handling malformed dotted subtask IDs (e.g., "5.1" -> 1)
- Remove redundant normalizeTaskIds calls from set-task-status, add-task, and move-task
- Add comprehensive test for mixed ID formats (string IDs and dotted notation)
- Cleaner, more maintainable solution that normalizes IDs at load time

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: run format to resolve CI issues

---------

Co-authored-by: Carl Mercier <carl@carlmercier.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-08-01 00:06:51 +02:00
Ben Vargas
45a14c323d fix: remove default value from complexity report option to enable tag-specific detection (#1049)
Removes the default empty array value from the complexity report option to properly detect when tags are explicitly provided vs when no tags are provided, fixing the expand --all command behavior with tagged tasks.

Co-authored-by: Ben Vargas <ben@example.com>
2025-07-26 15:26:45 +02:00
github-actions[bot]
29e67fafa4 Version Packages (#1050)
* Version Packages

* chore: fix release 0.22

todo: fix CI

* chore: run format

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-26 00:45:07 +02:00
Ralph Khreish
43e4d7c9d3 Release 0.22 #1038 from eyaltoledano/next
Release 0.22
2025-07-26 01:24:38 +03:00
Ralph Khreish
1bd1e64cac feat: add pull request templates for bug fixes, features, and integrations (#1044)
* feat: add pull request templates for bug fixes, features, and integrations

- Introduced a comprehensive pull request template structure to streamline contributions.
- Added specific templates for bug fixes, new features, and integrations to enhance clarity and consistency in PR submissions.
- Configured the pull request template settings for better user guidance during the contribution process.

* chore: fix format

* Update .github/PULL_REQUEST_TEMPLATE.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update .github/PULL_REQUEST_TEMPLATE.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update .github/PULL_REQUEST_TEMPLATE.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: implement PR requested changes

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-07-24 17:33:43 +02:00
Ralph Khreish
dc44ed9de8 feat: Improved the CLI user interface to suggest generating a complexity report if it is missing, instead of showing an error. (#1043)
* feat: fix CLI UI error when trying to display non-existent complexity report

* chore: fix git issue

* chore: run format

* Update .changeset/thick-squids-attend.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update .changeset/thick-squids-attend.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update .changeset/thick-squids-attend.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-07-24 15:50:18 +02:00
github-actions[bot]
31b8407dbc chore: rc version bump 2025-07-23 16:29:49 +00:00
Ralph Khreish
2df4f13f65 chore: improve pre-release CI to be able to release more than one release candidate (#1036)
* chore: improve pre-release CI to be able to release more than one release candidate

* chore: implement requested changes from coderabbit

* chore: apply requested changes
2025-07-23 18:28:17 +02:00
github-actions[bot]
a37017e5a5 docs: Auto-update and format models.md 2025-07-23 16:03:40 +00:00
Ralph Khreish
fb7d588137 feat: improve config-manager max tokens for openrouter and kimi-k2 model (#1035) 2025-07-23 18:03:26 +02:00
Ralph Khreish
bdb11fb2db chore: remove useless file 2025-07-23 18:04:13 +03:00
Ralph Khreish
4423119a5e feat: Add Kiro hooks and configuration for Taskmaster integration (#1032)
* feat: Add Kiro hooks and configuration for Taskmaster integration

- Introduced multiple Kiro hooks to automate task management workflows, including:
  - Code Change Task Tracker
  - Complexity Analyzer
  - Daily Standup Assistant
  - Git Commit Task Linker
  - Import Cleanup on Delete
  - New File Boilerplate
  - PR Readiness Checker
  - Task Dependency Auto-Progression
  - Test Success Task Completer
- Added .mcp.json configuration for Taskmaster AI integration.
- Updated development workflow documentation to reflect new hook-driven processes and best practices.

This commit enhances the automation capabilities of Taskmaster, streamlining task management and improving developer efficiency.

* chore: run format

* chore: improve unit tests on kiro rules

* chore: run format

* chore: run format

* feat: improve PR and add changeset
2025-07-23 17:02:16 +02:00
Ben Vargas
7b90568326 fix: bump ai-sdk-provider-gemini-cli to v0.1.1 (#1033)
* fix: bump ai-sdk-provider-gemini-cli to v0.1.1

Updates ai-sdk-provider-gemini-cli from v0.0.4 to v0.1.1 to fix a breaking change
introduced in @google/gemini-cli-core v0.1.12+ where createContentGeneratorConfig
signature changed, causing "config.getModel is not a function" errors.

The new version includes:
- Fixed compatibility with @google/gemini-cli-core ^0.1.13
- Added proxy support via configuration
- Resolved the breaking API change

Fixes compatibility issues when using newer versions of gemini-cli-core.

See: https://github.com/ben-vargas/ai-sdk-provider-gemini-cli/releases/tag/v0.1.1

* chore: fix package-lock.json being too big

---------

Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-23 17:01:59 +02:00
github-actions[bot]
9b0630fdf1 docs: Auto-update and format models.md 2025-07-22 18:15:35 +00:00
Parthy
ced04bddd3 docs(models): update model configuration to add supported field (#1030) 2025-07-22 20:15:22 +02:00
Andre Silva
6ae66b2afb fix(profiles): fix vscode profile generation (#1027)
* fix(profiles): fix vscode profile generation

- Add .instructions.md extension for VSCode Copilot instructions file.
- Add customReplacement to remove unsupported property `alwaysApply` from YAML front-matter in VSCode instructions files.
- Add missing property `targetExtension` to the base profile object to
  support the change to file extension.

* chore: run format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-21 21:17:57 +02:00
Joe Danziger
8781794c56 fix: Clean up remaining automatic task file generation calls (#1025)
* Don't generate task files unless requested

* add changeset

* switch to optional generate flag instead of skip-generate based on new default

* switch generate default to false and update flags and docs

* revert DO/DON'T section

* use simpler non ANSI-C quoting
2025-07-21 21:15:53 +02:00
Ralph Khreish
fede909fe1 chore: fix package-lock.json after new release 2025-07-21 22:13:51 +03:00
Parthy
77cc5e4537 Fix: Correct tag handling for expand --all and show commands (#1026)
Fix: Correct tag handling for expand --all and show commands
2025-07-21 22:13:22 +03:00
Ralph Khreish
d31ef7a39c Merge pull request #1015 from eyaltoledano/changeset-release/main
Version Packages
2025-07-20 00:57:39 +03:00
github-actions[bot]
66555099ca Version Packages 2025-07-19 21:56:03 +00:00
Ralph Khreish
1e565eab53 Release 0.21 (#1009)
* fix: prevent CLAUDE.md overwrite by using imports (#949)

* fix: prevent CLAUDE.md overwrite by using imports

- Copy Task Master instructions to .taskmaster/CLAUDE.md
- Add import section to user's CLAUDE.md instead of overwriting
- Preserve existing user content
- Clean removal of Task Master content on uninstall

Closes #929

* chore: add changeset for Claude import fix

* fix: task master (tm) custom slash commands w/ proper syntax (#968)

* feat: add task master (tm) custom slash commands

Add comprehensive task management system integration via custom slash commands.
Includes commands for:
- Project initialization and setup
- Task parsing from PRD documents
- Task creation, update, and removal
- Subtask management
- Dependency tracking and validation
- Complexity analysis and task expansion
- Project status and reporting
- Workflow automation

This provides a complete task management workflow directly within Claude Code.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: add changeset

---------

Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>

* chore: create extension scaffolding (#989)

* chore: create extension scaffolding

* chore: fix workspace for changeset

* chore: fix package-lock

* feat(profiles): Add MCP configuration to Claude Code rules (#980)

* add .mcp.json with claude profile

* add changeset

* update changeset

* update test

* fix: show command no longer requires complexity report to exist (#979)

Co-authored-by: Ben Vargas <ben@example.com>

* feat: complete Groq provider integration and add Kimi K2 model (#978)

* feat: complete Groq provider integration and add Kimi K2 model

- Add missing getRequiredApiKeyName() method to GroqProvider class
- Register GroqProvider in ai-services-unified.js PROVIDERS object
- Add Groq API key handling to config-manager.js (isApiKeySet and getMcpApiKeyStatus)
- Add GROQ_API_KEY to env.example with format hint
- Add moonshotai/kimi-k2-instruct model to Groq provider ($1/$3 per 1M tokens, 16k max)
- Fix import sorting for linting compliance
- Add GroqProvider mock to ai-services-unified tests

Fixes missing implementation pieces that prevented Groq provider from working.

* chore: improve changeset

---------

Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* docs: Auto-update and format models.md

* feat: Add Amp rule profile with AGENT.md and MCP config (#973)

* Amp profile + tests

* generatlize to Agent instead of Claude Code to support any agent

* add changeset

* unnecessary tab formatting

* fix exports

* fix formatting

* feat: Add Zed editor rule profile with agent rules and MCP config (#974)

* zed profile

* add changeset

* update changeset

* fix: Add missing API keys to .env.example and README.md (#972)

* add OLLAMA_API_KEY

* add missing API keys

* add changeset

* update keys and fix OpenAI comment

* chore: create extension scaffolding (#989)

* chore: create extension scaffolding

* chore: fix workspace for changeset

* chore: fix package-lock

* feat(profiles): Add MCP configuration to Claude Code rules (#980)

* add .mcp.json with claude profile

* add changeset

* update changeset

* update test

* fix: show command no longer requires complexity report to exist (#979)

Co-authored-by: Ben Vargas <ben@example.com>

* feat: complete Groq provider integration and add Kimi K2 model (#978)

* feat: complete Groq provider integration and add Kimi K2 model

- Add missing getRequiredApiKeyName() method to GroqProvider class
- Register GroqProvider in ai-services-unified.js PROVIDERS object
- Add Groq API key handling to config-manager.js (isApiKeySet and getMcpApiKeyStatus)
- Add GROQ_API_KEY to env.example with format hint
- Add moonshotai/kimi-k2-instruct model to Groq provider ($1/$3 per 1M tokens, 16k max)
- Fix import sorting for linting compliance
- Add GroqProvider mock to ai-services-unified tests

Fixes missing implementation pieces that prevented Groq provider from working.

* chore: improve changeset

---------

Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* docs: Auto-update and format models.md

* feat: Add Amp rule profile with AGENT.md and MCP config (#973)

* Amp profile + tests

* generatlize to Agent instead of Claude Code to support any agent

* add changeset

* unnecessary tab formatting

* fix exports

* fix formatting

* feat: Add Zed editor rule profile with agent rules and MCP config (#974)

* zed profile

* add changeset

* update changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* feat: Add OpenCode rule profile with AGENTS.md and MCP config (#970)

* add opencode to profile lists

* add opencode profile / modify mcp config after add

* add changeset

* not necessary; main config being updated

* add issue link

* add/fix tests

* fix url and docsUrl

* update test for new urls

* fix formatting

* update/fix tests

* chore: add coderabbit configuration (#992)

* chore: add coderabbit configuration

* chore: fix coderabbit config

* chore: improve coderabbit config

* chore: more coderabbit reviews

* chore: remove all defaults

* docs: Update MCP server name for consistency and use 'Add to Cursor' button (#995)

* update MCP server name to task-master-ai for consistency

* add changeset

* update cursor link & switch to https

* switch back to Add to Cursor button (https link)

* update changeset

* update changeset

* update changeset

* update changeset

* use GitHub markdown format

* fix(ai-validation): comprehensive fixes for AI response validation issues (#1000)

* fix(ai-validation): comprehensive fixes for AI response validation issues

  - Fix update command validation when AI omits subtasks/status/dependencies
  - Fix add-task command when AI returns non-string details field
  - Fix update-task command when AI subtasks miss required fields
  - Add preprocessing to ensure proper field types before validation
  - Prevent split() errors on non-string fields
  - Set proper defaults for missing required fields

* chore: run format

* chore: implement coderabbit suggestions

* feat: add kiro profile (#1001)

* feat: add kiro profile

* chore: fix format

* chore: implement requested changes

* chore: fix CI

* refactor: remove unused resource and resource template initialization (#1002)

* refactor: remove unused resource and resource template initialization

* chore: implement requested changes

* fix(core): Implement Boundary-First Tag Resolution (#943)

* refactor(context): Standardize tag and projectRoot handling across all task tools

This commit unifies context management by adopting a boundary-first resolution strategy. All task-scoped tools now resolve `tag` and `projectRoot` at their entry point and forward these values to the underlying direct functions.

This approach centralizes context logic, ensuring consistent behavior and enhanced flexibility in multi-tag environments.

* fix(tag): Clean up tag handling in task functions and sync process

This commit refines the handling of the `tag` parameter across multiple functions, ensuring consistent context management. The `tag` is now passed more efficiently in `listTasksDirect`, `setTaskStatusDirect`, and `syncTasksToReadme`, improving clarity and reducing redundancy. Additionally, a TODO comment has been added in `sync-readme.js` to address future tag support enhancements.

* feat(tag): Implement Boundary-First Tag Resolution for consistent tag handling

This commit introduces Boundary-First Tag Resolution in the task manager, ensuring consistent and deterministic tag handling across CLI and MCP. This change resolves potential race conditions and improves the reliability of tag-specific operations.

Additionally, the `expandTask` function has been updated to use the resolved tag when writing JSON, enhancing data integrity during task updates.

* chore(biome): formatting

* fix(expand-task): Update writeJSON call to use tag instead of resolvedTag

* fix(commands): Enhance complexity report path resolution and task initialization
`resolveComplexityReportPath` function to streamline output path generation based on tag context and user-defined output.
- Improved clarity and maintainability of command handling by centralizing path resolution logic.

* Fix: unknown currentTag

* fix(task-manager): Update generateTaskFiles calls to include tag and projectRoot parameters

This commit modifies the `moveTask` and `updateSubtaskById` functions to pass the `tag` and `projectRoot` parameters to the `generateTaskFiles` function. This ensures that task files are generated with the correct context when requested, enhancing consistency in task management operations.

* fix(commands): Refactor tag handling and complexity report path resolution
This commit updates the `registerCommands` function to utilize `taskMaster.getCurrentTag()` for consistent tag retrieval across command actions. It also enhances the initialization of `TaskMaster` by passing the tag directly, improving clarity and maintainability. The complexity report path resolution is streamlined to ensure correct file naming based on the current tag context.

* fix(task-master): Update complexity report path expectations in tests
This commit modifies the `initTaskMaster` test to expect a valid string for the complexity report path, ensuring it matches the expected file naming convention. This change enhances test reliability by verifying the correct output format when the path is generated.

* fix(set-task-status): Enhance logging and tag resolution in task status updates
This commit improves the logging output in the `registerSetTaskStatusTool` function to include the tag context when setting task statuses. It also updates the tag handling by resolving the tag using the `resolveTag` utility, ensuring that the correct tag is used when updating task statuses. Additionally, the `setTaskStatus` function is modified to remove the tag parameter from the `readJSON` and `writeJSON` calls, streamlining the data handling process.

* fix(commands, expand-task, task-manager): Add complexity report option and enhance path handling
This commit introduces a new `--complexity-report` option in the `registerCommands` function, allowing users to specify a custom path for the complexity report. The `expandTask` function is updated to accept the `complexityReportPath` from the context, ensuring it is utilized correctly during task expansion. Additionally, the `setTaskStatus` function now includes the `tag` parameter in the `readJSON` and `writeJSON` calls, improving task status updates with proper context. The `initTaskMaster` function is also modified to create parent directories for output paths, enhancing file handling robustness.

* fix(expand-task): Add complexityReportPath to context for task expansion tests

This commit updates the test for the `expandTask` function by adding the `complexityReportPath` to the context object. This change ensures that the complexity report path is correctly utilized in the test, aligning with recent enhancements to complexity report handling in the task manager.

* chore: implement suggested changes

* fix(parse-prd): Clarify tag parameter description for task organization
Updated the documentation for the `tag` parameter in the `parse-prd.js` file to provide a clearer context on its purpose for organizing tasks into separate task lists.

* Fix Inconsistent tag resolution pattern.

* fix: Enhance complexity report path handling with tag support

This commit updates various functions to incorporate the `tag` parameter when resolving complexity report paths. The `expandTaskDirect`, `resolveComplexityReportPath`, and related tools now utilize the current tag context, improving consistency in task management. Additionally, the complexity report path is now correctly passed through the context in the `expand-task` and `set-task-status` tools, ensuring accurate report retrieval based on the active tag.

* Updated the JSDoc for the `tag` parameter in the `show-task.js` file.

* Remove redundant comment on tag parameter in readJSON call

* Remove unused import for getTagAwareFilePath

* Add missed complexityReportPath to args for task expansion

* fix(tests): Enhance research tests with tag-aware functionality

This commit updates the `research.test.js` file to improve the testing of the `performResearch` function by incorporating tag-aware functionality. Key changes include mocking the `findProjectRoot` to return a valid path, enhancing the `ContextGatherer` and `FuzzyTaskSearch` mocks, and adding comprehensive tests for tag parameter handling in various scenarios. The tests now cover passing different tag values, ensuring correct behavior when tags are provided, undefined, or null, and validating the integration of tags in task discovery and context gathering processes.

* Remove unused import for

* fix: Refactor complexity report path handling and improve argument destructuring

This commit enhances the `expandTaskDirect` function by improving the destructuring of arguments for better readability. It also updates the `analyze.js` and `analyze-task-complexity.js` files to utilize the new `resolveComplexityReportOutputPath` function, ensuring tag-aware resolution of output paths. Additionally, logging has been added to provide clarity on the report path being used.

* test: Add complexity report tag isolation tests and improve path handling

This commit introduces a new test file for complexity report tag isolation, ensuring that different tags maintain separate complexity reports. It enhances the existing tests in `analyze-task-complexity.test.js` by updating expectations to use `expect.stringContaining` for file paths, improving robustness against path changes. The new tests cover various scenarios, including path resolution and report generation for both master and feature tags, ensuring no cross-tag contamination occurs.

* Update scripts/modules/task-manager/list-tasks.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update scripts/modules/task-manager/list-tasks.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* test(complexity-report): Fix tag slugification in filename expectations

- Update mocks to use slugifyTagForFilePath for cross-platform compatibility
- Replace raw tag values with slugified versions in expected filenames
- Fix test expecting 'feature/user-auth-v2' to expect 'feature-user-auth-v2'
- Align test with actual filename generation logic that sanitizes special chars

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: Update VS Code profile with MCP config transformation (#971)

* remove dash in server name

* add OLLAMA_API_KEY to VS Code MCP instructions

* transform vscode mcp to correct format

* add changeset

* switch back to task-master-ai

* use task-master-ai

* Batch fixes before release (#1011)

* fix: improve projectRoot

* fix: improve task-master lang command

* feat: add documentation to the readme so more people can access it

* fix: expand command subtask dependency validation

* fix: update command more reliable with perplexity and other models

* chore: fix CI

* chore: implement requested changes

* chore: fix CI

* chore: fix changeset release for extension package (#1012)

* chore: fix changeset release for extension package

* chore: fix CI

* chore: rc version bump

* chore: adjust kimi k2 max tokens (#1014)

* docs: Auto-update and format models.md

---------

Co-authored-by: Ben Vargas <ben@vargas.com>
Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-07-20 00:55:29 +03:00
github-actions[bot]
d87a7f1076 docs: Auto-update and format models.md 2025-07-20 00:51:41 +03:00
Ralph Khreish
5b3dd3f29b chore: adjust kimi k2 max tokens (#1014) 2025-07-20 00:51:41 +03:00
github-actions[bot]
b7804302a1 chore: rc version bump 2025-07-20 00:51:41 +03:00
Ralph Khreish
b2841c261f chore: fix changeset release for extension package (#1012)
* chore: fix changeset release for extension package

* chore: fix CI
2025-07-20 00:51:41 +03:00
Ralph Khreish
444aa5ae19 Batch fixes before release (#1011)
* fix: improve projectRoot

* fix: improve task-master lang command

* feat: add documentation to the readme so more people can access it

* fix: expand command subtask dependency validation

* fix: update command more reliable with perplexity and other models

* chore: fix CI

* chore: implement requested changes

* chore: fix CI
2025-07-20 00:51:41 +03:00
Joe Danziger
858d4a1c54 fix: Update VS Code profile with MCP config transformation (#971)
* remove dash in server name

* add OLLAMA_API_KEY to VS Code MCP instructions

* transform vscode mcp to correct format

* add changeset

* switch back to task-master-ai

* use task-master-ai
2025-07-20 00:51:41 +03:00
Parthy
fd005c4c54 fix(core): Implement Boundary-First Tag Resolution (#943)
* refactor(context): Standardize tag and projectRoot handling across all task tools

This commit unifies context management by adopting a boundary-first resolution strategy. All task-scoped tools now resolve `tag` and `projectRoot` at their entry point and forward these values to the underlying direct functions.

This approach centralizes context logic, ensuring consistent behavior and enhanced flexibility in multi-tag environments.

* fix(tag): Clean up tag handling in task functions and sync process

This commit refines the handling of the `tag` parameter across multiple functions, ensuring consistent context management. The `tag` is now passed more efficiently in `listTasksDirect`, `setTaskStatusDirect`, and `syncTasksToReadme`, improving clarity and reducing redundancy. Additionally, a TODO comment has been added in `sync-readme.js` to address future tag support enhancements.

* feat(tag): Implement Boundary-First Tag Resolution for consistent tag handling

This commit introduces Boundary-First Tag Resolution in the task manager, ensuring consistent and deterministic tag handling across CLI and MCP. This change resolves potential race conditions and improves the reliability of tag-specific operations.

Additionally, the `expandTask` function has been updated to use the resolved tag when writing JSON, enhancing data integrity during task updates.

* chore(biome): formatting

* fix(expand-task): Update writeJSON call to use tag instead of resolvedTag

* fix(commands): Enhance complexity report path resolution and task initialization
`resolveComplexityReportPath` function to streamline output path generation based on tag context and user-defined output.
- Improved clarity and maintainability of command handling by centralizing path resolution logic.

* Fix: unknown currentTag

* fix(task-manager): Update generateTaskFiles calls to include tag and projectRoot parameters

This commit modifies the `moveTask` and `updateSubtaskById` functions to pass the `tag` and `projectRoot` parameters to the `generateTaskFiles` function. This ensures that task files are generated with the correct context when requested, enhancing consistency in task management operations.

* fix(commands): Refactor tag handling and complexity report path resolution
This commit updates the `registerCommands` function to utilize `taskMaster.getCurrentTag()` for consistent tag retrieval across command actions. It also enhances the initialization of `TaskMaster` by passing the tag directly, improving clarity and maintainability. The complexity report path resolution is streamlined to ensure correct file naming based on the current tag context.

* fix(task-master): Update complexity report path expectations in tests
This commit modifies the `initTaskMaster` test to expect a valid string for the complexity report path, ensuring it matches the expected file naming convention. This change enhances test reliability by verifying the correct output format when the path is generated.

* fix(set-task-status): Enhance logging and tag resolution in task status updates
This commit improves the logging output in the `registerSetTaskStatusTool` function to include the tag context when setting task statuses. It also updates the tag handling by resolving the tag using the `resolveTag` utility, ensuring that the correct tag is used when updating task statuses. Additionally, the `setTaskStatus` function is modified to remove the tag parameter from the `readJSON` and `writeJSON` calls, streamlining the data handling process.

* fix(commands, expand-task, task-manager): Add complexity report option and enhance path handling
This commit introduces a new `--complexity-report` option in the `registerCommands` function, allowing users to specify a custom path for the complexity report. The `expandTask` function is updated to accept the `complexityReportPath` from the context, ensuring it is utilized correctly during task expansion. Additionally, the `setTaskStatus` function now includes the `tag` parameter in the `readJSON` and `writeJSON` calls, improving task status updates with proper context. The `initTaskMaster` function is also modified to create parent directories for output paths, enhancing file handling robustness.

* fix(expand-task): Add complexityReportPath to context for task expansion tests

This commit updates the test for the `expandTask` function by adding the `complexityReportPath` to the context object. This change ensures that the complexity report path is correctly utilized in the test, aligning with recent enhancements to complexity report handling in the task manager.

* chore: implement suggested changes

* fix(parse-prd): Clarify tag parameter description for task organization
Updated the documentation for the `tag` parameter in the `parse-prd.js` file to provide a clearer context on its purpose for organizing tasks into separate task lists.

* Fix Inconsistent tag resolution pattern.

* fix: Enhance complexity report path handling with tag support

This commit updates various functions to incorporate the `tag` parameter when resolving complexity report paths. The `expandTaskDirect`, `resolveComplexityReportPath`, and related tools now utilize the current tag context, improving consistency in task management. Additionally, the complexity report path is now correctly passed through the context in the `expand-task` and `set-task-status` tools, ensuring accurate report retrieval based on the active tag.

* Updated the JSDoc for the `tag` parameter in the `show-task.js` file.

* Remove redundant comment on tag parameter in readJSON call

* Remove unused import for getTagAwareFilePath

* Add missed complexityReportPath to args for task expansion

* fix(tests): Enhance research tests with tag-aware functionality

This commit updates the `research.test.js` file to improve the testing of the `performResearch` function by incorporating tag-aware functionality. Key changes include mocking the `findProjectRoot` to return a valid path, enhancing the `ContextGatherer` and `FuzzyTaskSearch` mocks, and adding comprehensive tests for tag parameter handling in various scenarios. The tests now cover passing different tag values, ensuring correct behavior when tags are provided, undefined, or null, and validating the integration of tags in task discovery and context gathering processes.

* Remove unused import for

* fix: Refactor complexity report path handling and improve argument destructuring

This commit enhances the `expandTaskDirect` function by improving the destructuring of arguments for better readability. It also updates the `analyze.js` and `analyze-task-complexity.js` files to utilize the new `resolveComplexityReportOutputPath` function, ensuring tag-aware resolution of output paths. Additionally, logging has been added to provide clarity on the report path being used.

* test: Add complexity report tag isolation tests and improve path handling

This commit introduces a new test file for complexity report tag isolation, ensuring that different tags maintain separate complexity reports. It enhances the existing tests in `analyze-task-complexity.test.js` by updating expectations to use `expect.stringContaining` for file paths, improving robustness against path changes. The new tests cover various scenarios, including path resolution and report generation for both master and feature tags, ensuring no cross-tag contamination occurs.

* Update scripts/modules/task-manager/list-tasks.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update scripts/modules/task-manager/list-tasks.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* test(complexity-report): Fix tag slugification in filename expectations

- Update mocks to use slugifyTagForFilePath for cross-platform compatibility
- Replace raw tag values with slugified versions in expected filenames
- Fix test expecting 'feature/user-auth-v2' to expect 'feature-user-auth-v2'
- Align test with actual filename generation logic that sanitizes special chars

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-07-20 00:51:41 +03:00
Ralph Khreish
0451ebcc32 refactor: remove unused resource and resource template initialization (#1002)
* refactor: remove unused resource and resource template initialization

* chore: implement requested changes
2025-07-20 00:51:41 +03:00
Ralph Khreish
9c58a92243 feat: add kiro profile (#1001)
* feat: add kiro profile

* chore: fix format

* chore: implement requested changes

* chore: fix CI
2025-07-20 00:51:41 +03:00
Ralph Khreish
f772a96d00 fix(ai-validation): comprehensive fixes for AI response validation issues (#1000)
* fix(ai-validation): comprehensive fixes for AI response validation issues

  - Fix update command validation when AI omits subtasks/status/dependencies
  - Fix add-task command when AI returns non-string details field
  - Fix update-task command when AI subtasks miss required fields
  - Add preprocessing to ensure proper field types before validation
  - Prevent split() errors on non-string fields
  - Set proper defaults for missing required fields

* chore: run format

* chore: implement coderabbit suggestions
2025-07-20 00:51:41 +03:00
Joe Danziger
0886c83d0c docs: Update MCP server name for consistency and use 'Add to Cursor' button (#995)
* update MCP server name to task-master-ai for consistency

* add changeset

* update cursor link & switch to https

* switch back to Add to Cursor button (https link)

* update changeset

* update changeset

* update changeset

* update changeset

* use GitHub markdown format
2025-07-20 00:51:41 +03:00
Ralph Khreish
806ec99939 chore: add coderabbit configuration (#992)
* chore: add coderabbit configuration

* chore: fix coderabbit config

* chore: improve coderabbit config

* chore: more coderabbit reviews

* chore: remove all defaults
2025-07-20 00:51:41 +03:00
Joe Danziger
36c4a7a869 feat: Add OpenCode rule profile with AGENTS.md and MCP config (#970)
* add opencode to profile lists

* add opencode profile / modify mcp config after add

* add changeset

* not necessary; main config being updated

* add issue link

* add/fix tests

* fix url and docsUrl

* update test for new urls

* fix formatting

* update/fix tests
2025-07-20 00:51:41 +03:00
Joe Danziger
88c434a939 fix: Add missing API keys to .env.example and README.md (#972)
* add OLLAMA_API_KEY

* add missing API keys

* add changeset

* update keys and fix OpenAI comment

* chore: create extension scaffolding (#989)

* chore: create extension scaffolding

* chore: fix workspace for changeset

* chore: fix package-lock

* feat(profiles): Add MCP configuration to Claude Code rules (#980)

* add .mcp.json with claude profile

* add changeset

* update changeset

* update test

* fix: show command no longer requires complexity report to exist (#979)

Co-authored-by: Ben Vargas <ben@example.com>

* feat: complete Groq provider integration and add Kimi K2 model (#978)

* feat: complete Groq provider integration and add Kimi K2 model

- Add missing getRequiredApiKeyName() method to GroqProvider class
- Register GroqProvider in ai-services-unified.js PROVIDERS object
- Add Groq API key handling to config-manager.js (isApiKeySet and getMcpApiKeyStatus)
- Add GROQ_API_KEY to env.example with format hint
- Add moonshotai/kimi-k2-instruct model to Groq provider ($1/$3 per 1M tokens, 16k max)
- Fix import sorting for linting compliance
- Add GroqProvider mock to ai-services-unified tests

Fixes missing implementation pieces that prevented Groq provider from working.

* chore: improve changeset

---------

Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* docs: Auto-update and format models.md

* feat: Add Amp rule profile with AGENT.md and MCP config (#973)

* Amp profile + tests

* generatlize to Agent instead of Claude Code to support any agent

* add changeset

* unnecessary tab formatting

* fix exports

* fix formatting

* feat: Add Zed editor rule profile with agent rules and MCP config (#974)

* zed profile

* add changeset

* update changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-07-20 00:51:41 +03:00
Joe Danziger
b0e09c76ed feat: Add Zed editor rule profile with agent rules and MCP config (#974)
* zed profile

* add changeset

* update changeset
2025-07-20 00:51:41 +03:00
Joe Danziger
6c5e0f97f8 feat: Add Amp rule profile with AGENT.md and MCP config (#973)
* Amp profile + tests

* generatlize to Agent instead of Claude Code to support any agent

* add changeset

* unnecessary tab formatting

* fix exports

* fix formatting
2025-07-20 00:51:41 +03:00
github-actions[bot]
8774e7d5ae docs: Auto-update and format models.md 2025-07-20 00:51:41 +03:00
Ben Vargas
58a301c380 feat: complete Groq provider integration and add Kimi K2 model (#978)
* feat: complete Groq provider integration and add Kimi K2 model

- Add missing getRequiredApiKeyName() method to GroqProvider class
- Register GroqProvider in ai-services-unified.js PROVIDERS object
- Add Groq API key handling to config-manager.js (isApiKeySet and getMcpApiKeyStatus)
- Add GROQ_API_KEY to env.example with format hint
- Add moonshotai/kimi-k2-instruct model to Groq provider ($1/$3 per 1M tokens, 16k max)
- Fix import sorting for linting compliance
- Add GroqProvider mock to ai-services-unified tests

Fixes missing implementation pieces that prevented Groq provider from working.

* chore: improve changeset

---------

Co-authored-by: Ben Vargas <ben@example.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-20 00:51:41 +03:00
Ben Vargas
624922ca59 fix: show command no longer requires complexity report to exist (#979)
Co-authored-by: Ben Vargas <ben@example.com>
2025-07-20 00:51:41 +03:00
Joe Danziger
0a70ab6179 feat(profiles): Add MCP configuration to Claude Code rules (#980)
* add .mcp.json with claude profile

* add changeset

* update changeset

* update test
2025-07-20 00:51:41 +03:00
Ralph Khreish
901eec1058 chore: create extension scaffolding (#989)
* chore: create extension scaffolding

* chore: fix workspace for changeset

* chore: fix package-lock
2025-07-20 00:51:41 +03:00
Ralph Khreish
4629128943 fix: task master (tm) custom slash commands w/ proper syntax (#968)
* feat: add task master (tm) custom slash commands

Add comprehensive task management system integration via custom slash commands.
Includes commands for:
- Project initialization and setup
- Task parsing from PRD documents
- Task creation, update, and removal
- Subtask management
- Dependency tracking and validation
- Complexity analysis and task expansion
- Project status and reporting
- Workflow automation

This provides a complete task management workflow directly within Claude Code.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: add changeset

---------

Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-07-20 00:51:41 +03:00
Ben Vargas
6d69d02fe0 fix: prevent CLAUDE.md overwrite by using imports (#949)
* fix: prevent CLAUDE.md overwrite by using imports

- Copy Task Master instructions to .taskmaster/CLAUDE.md
- Add import section to user's CLAUDE.md instead of overwriting
- Preserve existing user content
- Clean removal of Task Master content on uninstall

Closes #929

* chore: add changeset for Claude import fix
2025-07-20 00:51:41 +03:00
Ralph Khreish
458496e3b6 Merge pull request #961 from eyaltoledano/changeset-release/main 2025-07-12 22:49:56 +03:00
github-actions[bot]
fb92693d81 Version Packages 2025-07-12 19:31:08 +00:00
Ralph Khreish
f6ba4a36ee Merge pull request #958 from eyaltoledano/next 2025-07-12 22:30:36 +03:00
Ralph Khreish
baf9bd545a fix: add-task fixes (#960)
- remove task-generation
- fix mcp add-task generation in manual mode
2025-07-12 08:19:21 +02:00
Ralph Khreish
fbea48d8ec chore: fix configuration file 2025-07-12 00:54:16 +03:00
Ralph Khreish
d0fe7dc25a chore: add the deleted tasks.json back 2025-07-12 00:44:14 +03:00
Ralph Khreish
f380b8e86c chore: revert config.json to what it was initially 2025-07-12 00:42:52 +03:00
github-actions[bot]
bd89061a1d chore: rc version bump 2025-07-11 16:18:25 +00:00
Ralph Khreish
7d5ebf05e3 fix: mcp bug when expanding task (#957)
* fix: mcp bug when expanding task

* chore: fix format
2025-07-11 18:16:05 +02:00
Ralph Khreish
21392a1117 fix: more regression bugs (#956)
* fix: more regression bugs

* chore: fix format

* chore: fix unit tests

* chore: fix format
2025-07-11 14:23:54 +02:00
Ben Vargas
3e61d26235 fix: resolve path resolution and context gathering errors across multiple commands (#954)
* fix: resolve path resolution issues in parse-prd and analyze-complexity commands

This commit fixes critical path resolution regressions where commands were requiring files they create to already exist.

## Changes Made:

### 1. parse-prd Command (Lines 808, 828-835, 919-921)
**Problem**: Command required tasks.json to exist before it could create it (catch-22)
**Root Cause**: Default value in option definition meant options.output was always set
**Fixes**:
- Removed default value from --output option definition (line 808)
- Modified initTaskMaster to only include tasksPath when explicitly specified
- Added null handling for output path with fallback to default location

### 2. analyze-complexity Command (Lines 1637-1640, 1673-1680, 1695-1696)
**Problem**: Command required complexity report file to exist before creating it
**Root Cause**: Default value in option definition meant options.output was always set
**Fixes**:
- Removed default value from --output option definition (lines 1637-1640)
- Modified initTaskMaster to only include complexityReportPath when explicitly specified
- Added null handling for report path with fallback to default location

## Technical Details:

The core issue was that Commander.js option definitions with default values always populate the options object, making conditional checks like `if (options.output)` always true. By removing default values from option definitions, we ensure paths are only included in initTaskMaster when users explicitly provide them.

This approach is cleaner than using boolean flags (true/false) for required/optional, as it eliminates the path entirely when not needed, letting initTaskMaster use its default behavior.

## Testing:
- parse-prd now works on fresh projects without existing tasks.json
- analyze-complexity creates report file without requiring it to exist
- Commands maintain backward compatibility when paths are explicitly provided

Fixes issues reported in PATH-FIXES.md and extends the solution to other affected commands.

* fix: update expand-task test to match context gathering fix

The test was expecting gatheredContext to be a string, but the actual
implementation returns an object with a context property. Updated the
ContextGatherer mock to return the correct format and added missing
FuzzyTaskSearch mock.

---------

Co-authored-by: Ben Vargas <ben@example.com>
2025-07-11 05:46:28 +02:00
github-actions[bot]
dc5de53dcd docs: Auto-update and format models.md 2025-07-10 09:56:54 +00:00
Ralph Khreish
4312d3bd67 fix: models setup command not working (#952)
* fix: models command not working

* chore: re-order supported models to something that makes more sense

* chore: format
2025-07-10 11:56:41 +02:00
Chris Covington
0253f3ed87 Update the sync-readme command to a use markdown tables. (#859)
* Convert the sync-readme command to output markdown tables.

* chore: fix format

---------

Co-authored-by: Chris Covington <chris.covington@hey.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-10 10:03:15 +02:00
Joe Danziger
a65ad0a47c feat: Centralize AI prompts into JSON templates (#882)
* centralize prompt management

* add changeset

* add variant key to determine prompt version

* update tests and add prompt manager test

* determine internal path, don't use projectRoot

* add promptManager mock

* detailed prompt docs

* add schemas and validator packages

* add validate prompts command

* add schema validation

* update tests

* move schemas to src/prompts/schemas

* use this.promptsDir for better semantics

* add prompt schemas

* version schema files & update links

* remove validate command

* expect dependencies

* update docs

* fix test

* remove suggestmode to ensure clean keys

* remove default variant from research and update schema

* now handled by prompt manager

* add manual test to verify prompts

* remove incorrect batch variant

* consolidate variants

* consolidate analyze-complexity to just default variant

* consolidate parse-prd variants

* add eq handler for handlebars

* consolidate research prompt variants

* use brevity

* consolidate variants for update subtask

* add not handler

* consolidate variants for update-task

* consolidate update-tasks variants

* add conditional content to prompt when research used

* update prompt tests

* show correct research variant

* make variant names link to below

* remove changset

* restore gitignore

* Merge branch 'next' of https://github.com/eyaltoledano/claude-task-master into joedanz/centralize-prompts

# Conflicts:
#	package-lock.json
#	scripts/modules/task-manager/expand-task.js
#	scripts/modules/task-manager/parse-prd.js

remove unused

* add else

* update tests

* update biome optional dependencies

* responsive html output for mobile
2025-07-10 09:52:11 +02:00
Parthy
4bc8029080 refactor: streamline task path resolution in commands.js (#948)
- Replaced local `tasksPath` variable assignments with direct calls to `taskMaster.getTasksPath()` for consistency and clarity across multiple command functions.
- This change enhances maintainability by ensuring a single source of truth for task paths, reducing redundancy in path handling logic.
2025-07-10 09:25:56 +02:00
github-actions[bot]
31d395322f docs: Auto-update and format models.md 2025-07-10 07:25:01 +00:00
Ben Vargas
699e9eefb5 feat: add support for xAI Grok 4 model (#950)
- Add grok-4 to supported models with $3/$15 per 1M token pricing
- Enable main, fallback, and research roles for grok-4
- Update models.md documentation to include grok-4 in all tables
2025-07-10 09:24:48 +02:00
Joe Danziger
95c299df64 Unify and streamline profile system architecture (#853)
* move claude rules and commands to assets/claude

* update claude profile to copy assets/claude to .claude

* fix formatting

* feat(profiles): Implement unified profile system

- Convert Claude and Codex profiles to use createProfile() factory
- Remove simple vs complex profile distinction in rule transformer
- Unify convertAllRulesToProfileRules() to handle all profiles consistently
- Fix mcpConfigPath construction in base-profile.js for null mcpConfigName
- Update terminology from 'simpleProfiles' to 'assetOnlyProfiles' throughout
- Ensure Claude .claude directory copying works in both CLI and MCP contexts
- All profiles now follow same execution flow with proper lifecycle functions

Changes:
- src/profiles/claude.js: Convert to createProfile() factory pattern
- src/profiles/codex.js: Convert to createProfile() factory pattern
- src/utils/rule-transformer.js: Unified profile handling logic
- src/utils/profiles.js: Remove simple profile categorization
- src/profiles/base-profile.js: Fix mcpConfigPath construction
- scripts/modules/commands.js: Update variable naming
- tests/: Update all tests for unified system and terminology

Fixes Claude profile asset copying issue in MCP context.
All tests passing (617 passed, 11 skipped).

* re-checkin claude files

* fix formatting

* chore: clean up test Claude rules files

* chore: add changeset for unified profile system

* add claude files back

* add changeset

* restore proper gitignore

* remove claude agents file from root

* remove incorrect doc

* simplify profiles and update tests

* update changeset

* update changeset

* remove profile specific code

* streamline profiles with defaults and update tests

* update changeset

* add newline at end of gitignore

* restore changes

* streamline profiles with defaults; update tests and add vscode test

* update rule profile tests

* update wording for clearer profile management

* refactor and clarify terminology

* use original projectRoot var name

* revert param desc

* use updated claude assets from neno

* add "YOUR_" before api key here

* streamline codex profile

* add gemini profile

* update gemini profile

* update tests

* relocate function

* update rules interactive setup Gemini desc

* remove duplicative code

* add comma
2025-07-09 13:22:11 +02:00
Ralph Khreish
5f009a5e1f feat: improve add-task (#946)
* feat: improve add-task

* chore: format
2025-07-09 13:09:10 +02:00
github-actions[bot]
38e6f3798e docs: Auto-update and format models.md 2025-07-09 08:54:54 +00:00
Oren Me
b53065713c feat: add support for MCP Sampling as AI provider (#863)
* feat: support MCP sampling

* support provider registry

* use standard config options for MCP provider

* update fastmcp to support passing params to requestSampling

* move key name definition to base provider

* moved check for required api key to provider class

* remove unused code

* more cleanup

* more cleanup

* refactor provider

* remove not needed files

* more cleanup

* more cleanup

* more cleanup

* update docs

* fix tests

* add tests

* format fix

* clean files

* merge fixes

* format fix

* feat: add support for MCP Sampling as AI provider

* initial mcp ai sdk

* fix references to old provider

* update models

* lint

* fix gemini-cli conflicts

* ran format

* Update src/provider-registry/index.js

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* fix circular dependency

Circular Dependency Issue  FIXED
Root Cause: BaseAIProvider was importing from index.js, which includes commands.js and other modules that eventually import back to AI providers
Solution: Changed imports to use direct paths to avoid circular dependencies:
Updated base-provider.js to import log directly from utils.js
Updated gemini-cli.js to import log directly from utils.js
Result: Fixed 11 failing tests in mcp-provider.test.js

* fix gemini test

* fix(claude-code): recover from CLI JSON truncation bug (#913) (#920)

Gracefully handle SyntaxError thrown by @anthropic-ai/claude-code when the CLI truncates large JSON outputs (4–16 kB cut-offs).\n\nKey points:\n• Detect JSON parse error + existing buffered text in both doGenerate() and doStream() code paths.\n• Convert the failure into a recoverable 'truncated' finish state and push a provider-warning.\n• Allows Task Master to continue parsing long PRDs / expand-task operations instead of crashing.\n\nA patch changeset (.changeset/claude-code-json-truncation.md) is included for the next release.\n\nRef: eyaltoledano/claude-task-master#913

* docs: fix gemini-cli authentication documentation (#923)

Remove erroneous 'gemini auth login' command references and replace with correct 'gemini' command authentication flow. Update documentation to reflect proper OAuth setup process via the gemini CLI interactive interface.

* fix tests

* fix: update ai-sdk-provider-gemini-cli to 0.0.4 for improved authentication (#932)

- Fixed authentication compatibility issues with Google auth
- Added support for 'api-key' auth type alongside 'gemini-api-key'
- Resolved "Unsupported authType: undefined" runtime errors
- Updated @google/gemini-cli-core dependency to 0.1.9
- Improved documentation and removed invalid auth references
- Maintained backward compatibility while enhancing type validation

* call logging directly

Need to patch upstream fastmcp to allow easier access and bootstrap the TM mcp logger to use the fastmcp logger which today is only exposed in the tools handler

* fix tests

* removing logs until we figure out how to pass mcp logger

* format

* fix tests

* format

* clean up

* cleanup

* readme fix

---------

Co-authored-by: Oren Melamed <oren.m@gloat.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
2025-07-09 10:54:38 +02:00
Chris Covington
de28026b32 Phase 1 refactoring path resolution. (#877)
* feat: implement centralized path management system with initTaskMaster

This commit introduces a comprehensive refactoring of the TaskMaster CLI's path handling system, consolidating all path resolution logic into a centralized initTaskMaster function and TaskMaster class. This architectural change eliminates circular dependencies and provides consistent path management across all CLI commands.

Key changes:

• **Created new TaskMaster class and initTaskMaster factory function** in src/task-master.js
  - Centralized path resolution with boolean override logic (string = explicit path, true = required search, false/undefined = optional)
  - Built-in error handling with automatic process.exit() for missing required paths
  - Immutable path objects with getter methods for safe access

• **Replaced findProjectRoot() calls throughout CLI** in scripts/modules/commands.js
  - Updated all 25+ CLI commands to use initTaskMaster() instead of scattered path handling
  - Eliminated hundreds of lines of redundant path resolution and error handling code
  - Consistent project root validation and path discovery across all commands

• **Added comprehensive test suite** in tests/unit/task-master.test.js
  - 22 test cases covering project root detection, path resolution, override validation, and edge cases
  - Tests use temporary directories with proper cleanup and mock process.exit/console.error
  - Validates both successful scenarios and error conditions with proper exit codes

* bring Usage for Parse PRD back, and revamp initTaskMaster to throw errors not error/exit.

* fix(claude-code): recover from CLI JSON truncation bug (#913) (#920)

Gracefully handle SyntaxError thrown by @anthropic-ai/claude-code when the CLI truncates large JSON outputs (4–16 kB cut-offs).\n\nKey points:\n• Detect JSON parse error + existing buffered text in both doGenerate() and doStream() code paths.\n• Convert the failure into a recoverable 'truncated' finish state and push a provider-warning.\n• Allows Task Master to continue parsing long PRDs / expand-task operations instead of crashing.\n\nA patch changeset (.changeset/claude-code-json-truncation.md) is included for the next release.\n\nRef: eyaltoledano/claude-task-master#913

* docs: fix gemini-cli authentication documentation (#923)

Remove erroneous 'gemini auth login' command references and replace with correct 'gemini' command authentication flow. Update documentation to reflect proper OAuth setup process via the gemini CLI interactive interface.

* fix: .gitignore missing trailing newline during project initialization (#855)

* Support for Additional Anthropic Models on Bedrock (#870)

* Add additional Anthropic Models for Bedrock

* Update Models Docs from `scripts/modules/supported-models.json`

* feat(models): add additional Bedrock supported models

* docs: Auto-update and format models.md

* fix: Ensure projectRoot is a string (potential WSL fix) (#892)

* ensure projectRoot is a string

* add changeset

* Fix/spelling mistakes (#876)

* docs: Auto-update and format models.md

* fix: correct typos in documentation for parse-prd and taskmaster commands

- Updated the `parse-prd` documentation to fix the spelling of "multiple."
- Clarified the description of the `id` parameter in the `taskmaster` documentation to ensure proper syntax and readability.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Fix `rules` command to use reliable project root detection like other commands (#908)

* update/fix projectRoot call for consistency

* internal naming consistency

* add changeset

* fix: Subtask generation fails on gemini-2.5-pro (#852)

* fix: clarify details format in task expansion prompt

* chore: add changeset

* fix: use tag-specific complexity reports (#857)

* fix(expand-task): Use tag-specific complexity reports

- Add getTagAwareFilePath utility function to resolve tag-specific file paths
- Update expandTask to use tag-aware complexity report paths
- Fix issue where expand-task always used default complexity report
- Add comprehensive tests for getTagAwareFilePath utility
- Ensure proper handling of file extensions and directory structures

Fixes #850: Expanding tasks not using tag-specific complexity reports

The expandTask function now correctly uses complexity reports specific
to the current tag context (e.g., task-complexity-report_feature-branch.json)
instead of always using the default task-complexity-report.json file.

This enables proper task expansion behavior when working with multiple
tag contexts, ensuring complexity analysis is tag-specific and accurate.

* chore: Add changeset for tag-specific complexity reports fix

* test(expand-task): Add tests for tag-specific complexity report integration

- Introduced a new test suite for verifying the integration of tag-specific complexity reports in the expandTask function.
- Added a test case to ensure the correct complexity report is used when available for a specific tag.
- Mocked file system interactions to simulate the presence of tag-specific complexity reports.

This enhances the test coverage for task expansion behavior, ensuring it accurately reflects the complexity analysis based on the current tag context.

* refactor(task-manager): unify and simplify tag-aware file path logic and tests

- Reformatted imports and cleaned up comments in test files for readability
- Centralized mocks: moved getTagAwareFilePath & slugifyTagForFilePath
  mocks to setup.js for consistency and maintainability
- Simplified utils/getTagAwareFilePath: replaced manual parsing with
  path.parse() & path.format(); improved extension handling
- Enhanced test mocks for path.parse, path.format & reset path.join
  in beforeEach to avoid interference
- All tests now pass consistently; no change in functionality

* fix: prevent tag corruption in bulk updates (#856)

* fix(task-manager): prevent tag corruption in bulk updates and add tag preservation test

- Fix writeJSON call in scripts/modules/task-manager/update-tasks.js (line 469) to include projectRoot and tag parameters.
- Ensure tagged task lists maintain data integrity during bulk updates, preventing task disappearance in tagged contexts.
- Update MCP tools to properly pass tag context through the call chain.
- Introduce a comprehensive test case to verify that all tags are preserved when updating tasks, covering both master and feature-branch scenarios.

Addresses an issue where bulk updates could corrupt tasks.json in tagged task list structures, reinforcing task management robustness.

* style(tests): format task data in update-tasks test

* fix: Critical writeJSON Context Fixes - Prevent Tag Corruption (#910)

* feat(tasks): Fix critical tag corruption bug in task management

- Fixed missing context parameters in writeJSON calls across add-task, remove-task, and add-subtask functions
- Added projectRoot and tag parameters to prevent data corruption in multi-tag environments
- Re-enabled generateTaskFiles calls to ensure markdown files are updated after operations
- Enhanced add_subtask MCP tool with tag parameter support
- Refactored addSubtaskDirect function to properly pass context to core logic
- Streamlined codebase by removing deprecated functionality

This resolves the critical bug where task operations in one tag context would corrupt or delete tasks from other tags in tasks.json.

* feat(task-manager): Enhance addSubtask with current tag support

- Added `getCurrentTag` utility to retrieve the current tag context for task operations.
- Updated `addSubtask` to use the current tag when reading and writing tasks, ensuring proper context handling.
- Refactored tests to accommodate changes in the `addSubtask` function, ensuring accurate mock implementations and expectations.
- Cleaned up test cases for better readability and maintainability.

This improves task management by preventing tag-related data corruption and enhances the overall functionality of the task manager.

* feat(remove-task): Add tag support for task removal and enhance error handling

- Introduced `tag` parameter in `removeTaskDirect` to specify context for task operations, improving multi-tag support.
- Updated logging to include tag context in messages for better traceability.
- Refactored task removal logic to streamline the process and improve error reporting.
- Added comprehensive unit tests to validate tag handling and ensure robust error management.

This enhancement prevents task data corruption across different tags and improves the overall reliability of the task management system.

* feat(add-task): Add projectRoot and tag parameters to addTask tests

- Updated `addTask` unit tests to include `projectRoot` and `tag` parameters for better context handling.
- Enhanced test cases to ensure accurate expectations and improve overall test coverage.

This change aligns with recent enhancements in task management, ensuring consistency across task operations.

* feat(set-task-status): Add tag parameter support and enhance task status handling

- Introduced `tag` parameter in `setTaskStatusDirect` and related functions to improve context management in multi-tag environments.
- Updated `writeJSON` calls to ensure task data integrity across different tags.
- Enhanced unit tests to validate tag preservation during task status updates, ensuring robust functionality.

This change aligns with recent improvements in task management, preventing data corruption and enhancing overall reliability.

* feat(tag-management): Enhance writeJSON calls to preserve tag context

- Updated `writeJSON` calls in `createTag`, `deleteTag`, `renameTag`, `copyTag`, and `enhanceTagsWithMetadata` to include `projectRoot` for better context management and to prevent tag corruption.
- Added comprehensive unit tests for tag management functions to ensure data integrity and proper tag handling during operations.

This change improves the reliability of tag management by ensuring that operations do not corrupt existing tags and maintains the overall structure of the task data.

* feat(expand-task): Update writeJSON to include projectRoot and tag context

- Modified `writeJSON` call in `expandTaskDirect` to pass `projectRoot` and `tag` parameters, ensuring proper context management when saving tasks.json.
- This change aligns with recent enhancements in task management, preventing potential data corruption and improving overall reliability.

* feat(fix-dependencies): Add projectRoot and tag parameters for enhanced context management

- Updated `fixDependenciesDirect` and `registerFixDependenciesTool` to include `projectRoot` and `tag` parameters, improving context handling during dependency fixes.
- Introduced a new unit test for `fixDependenciesCommand` to ensure proper preservation of projectRoot and tag data in JSON outputs.

This change enhances the reliability of dependency management by ensuring that context is maintained across operations, preventing potential data issues.

* fix(context): propagate projectRoot and tag through dependency, expansion, status-update and tag-management commands to prevent cross-tag data corruption

* test(fix-dependencies): Enhance unit tests for fixDependenciesCommand

- Refactored tests to use unstable mocks for utils, ui, and task-manager modules, improving isolation and reliability.
- Added checks for process.exit to ensure proper handling of invalid data scenarios.
- Updated test cases to verify writeJSON calls with projectRoot and tag parameters, ensuring accurate context preservation during dependency fixes.

This change strengthens the test suite for dependency management, ensuring robust functionality and preventing potential data issues.

* chore(plan): remove outdated fix plan for `writeJSON` context parameters

* feat: Add gemini-cli provider integration for Task Master (#897)

* feat: Add gemini-cli provider integration for Task Master

This commit adds comprehensive support for the Gemini CLI provider, enabling users
to leverage Google's Gemini models through OAuth authentication via the gemini CLI
tool. This integration provides a seamless experience for users who prefer using
their existing Google account authentication rather than managing API keys.

## Implementation Details

### Provider Class (`src/ai-providers/gemini-cli.js`)
- Created GeminiCliProvider extending BaseAIProvider
- Implements dual authentication support:
  - Primary: OAuth authentication via `gemini auth login` (authType: 'oauth-personal')
  - Secondary: API key authentication for compatibility (authType: 'api-key')
- Uses the npm package `ai-sdk-provider-gemini-cli` (v0.0.3) for SDK integration
- Properly handles authentication validation without console output

### Model Configuration (`scripts/modules/supported-models.json`)
- Added two Gemini models with accurate specifications:
  - gemini-2.5-pro: 72% SWE score, 65,536 max output tokens
  - gemini-2.5-flash: 71% SWE score, 65,536 max output tokens
- Both models support main, fallback, and research roles
- Configured with zero cost (free tier)

### System Integration
- Registered provider in PROVIDERS map (`scripts/modules/ai-services-unified.js`)
- Added to OPTIONAL_AUTH_PROVIDERS set for flexible authentication
- Added GEMINI_CLI constant to provider constants (`src/constants/providers.js`)
- Exported GeminiCliProvider from index (`src/ai-providers/index.js`)

### Command Line Support (`scripts/modules/commands.js`)
- Added --gemini-cli flag to models command for provider hint
- Integrated into model selection logic (setModel function)
- Updated error messages to include gemini-cli in provider list
- Removed unrelated azure/vertex changes to maintain PR focus

### Documentation (`docs/providers/gemini-cli.md`)
- Comprehensive provider documentation emphasizing OAuth-first approach
- Clear explanation of why users would choose gemini-cli over standard google provider
- Detailed installation, authentication, and configuration instructions
- Troubleshooting section with common issues and solutions

### Testing (`tests/unit/ai-providers/gemini-cli.test.js`)
- Complete test suite with 12 tests covering all functionality
- Tests for both OAuth and API key authentication paths
- Error handling and edge case coverage
- Updated mocks in ai-services-unified.test.js for integration testing

## Key Design Decisions

1. **OAuth-First Design**: The provider assumes users want to leverage their existing
   `gemini auth login` credentials, making this the default authentication method.

2. **Authentication Type Mapping**: Discovered through testing that the SDK expects:
   - 'oauth-personal' for OAuth/CLI authentication (not 'gemini-cli' or 'oauth')
   - 'api-key' for API key authentication (not 'gemini-api-key')

3. **Silent Operation**: Removed console.log statements from validateAuth to match
   the pattern used by other providers like claude-code.

4. **Limited Model Support**: Only gemini-2.5-pro and gemini-2.5-flash are available
   through the CLI, as confirmed by the package author.

## Usage

```bash
# Install gemini CLI globally
npm install -g @google/gemini-cli

# Authenticate with Google account
gemini auth login

# Configure Task Master to use gemini-cli
task-master models --set-main gemini-2.5-pro --gemini-cli

# Use Task Master normally
task-master new "Create a REST API endpoint"
```

## Dependencies
- Added `ai-sdk-provider-gemini-cli@^0.0.3` to package.json
- This package wraps the Google Gemini CLI Core functionality for Vercel AI SDK

## Testing
All tests pass (613 total), including the new gemini-cli provider tests.
Code has been formatted with biome to maintain consistency.

This implementation provides a clean, well-tested integration that follows Task Master's
existing patterns while offering users a convenient way to use Gemini models with their
existing Google authentication.

* feat: implement lazy loading for gemini-cli provider

- Move ai-sdk-provider-gemini-cli to optionalDependencies
- Implement dynamic import with loadGeminiCliModule() function
- Make getClient() async to support lazy loading
- Update base-provider to handle async getClient() calls
- Update tests to handle async getClient() method

This allows the application to start without the gemini-cli package
installed, only loading it when actually needed.

* feat(gemini-cli): replace regex-based JSON extraction with jsonc-parser

- Add jsonc-parser dependency for robust JSON parsing
- Replace simple regex approach with progressive parsing strategy:
  1. Direct parsing after cleanup
  2. Smart boundary detection with single-pass analysis
  3. Limited fallback for edge cases
- Optimize performance with early termination and strategic sampling
- Add comprehensive tests for variable declarations, trailing commas,
  escaped quotes, nested objects, and performance edge cases
- Improve reliability for complex JSON structures that Gemini commonly produces
- Fix code formatting with biome

This addresses JSON parsing failures in generateObject operations while
maintaining backward compatibility and significantly improving performance
for large responses.

* fix: update package-lock.json and fix formatting for CI/CD

- Add jsonc-parser to package-lock.json for proper npm ci compatibility
- Fix biome formatting issues in gemini-cli provider and tests
- Ensure all CI/CD checks pass

* feat(gemini-cli): implement comprehensive JSON output reliability system

- Add automatic JSON request detection via content analysis patterns
- Implement task-specific prompt simplification for improved AI compliance
- Add strict JSON enforcement through enhanced system prompts
- Implement response interception with intelligent JSON extraction fallback
- Add comprehensive test coverage for all new JSON handling methods
- Move debug logging to appropriate level for clean user experience

This multi-layered approach addresses gemini-cli's conversational response
tendencies, ensuring reliable structured JSON output for task expansion
operations. Achieves 100% success rate in end-to-end testing while
maintaining full backward compatibility with existing functionality.

Technical implementation includes:
• JSON detection via user message content analysis
• Expand-task prompt simplification with cleaner instructions
• System prompt enhancement with strict JSON enforcement
• Response processing with jsonc-parser-based extraction
• Comprehensive unit test coverage for edge cases
• Debug-level logging to prevent user interface clutter

Resolves: gemini-cli JSON formatting inconsistencies
Tested: All 46 test suites pass, formatting verified

* chore: add changeset for gemini-cli provider implementation

Adds minor version bump for comprehensive gemini-cli provider with:
- Lazy loading and optional dependency management
- Advanced JSON parsing with jsonc-parser
- Multi-layer reliability system for structured output
- Complete test coverage and CI/CD compliance

* refactor: consolidate optional auth provider logic

- Add gemini-cli to existing providersWithoutApiKeys array in config-manager
- Export providersWithoutApiKeys for reuse across modules
- Remove duplicate OPTIONAL_AUTH_PROVIDERS Set from ai-services-unified
- Update ai-services-unified to import and use centralized array
- Fix Jest mock to include new providersWithoutApiKeys export

This eliminates code duplication and provides a single source of truth
for which providers support optional authentication, addressing PR
reviewer feedback about existing similar functionality in src/constants.

* docs: Auto-update and format models.md

* Feat: Added automatic determination of task number based on complexity (#884)

- Added 'defaultNumTasks: 10' to default config, now used in 'parse-prd'
- Adjusted 'parse-prd' and 'expand-task' to:
  - Accept a 'numTasks' value of 0
  - Updated tool and command descriptions
  - Updated prompts to 'an appropriate number of' when value is 0
- Updated 'README-task-master.md' and 'command-reference.md' docs
- Added more tests for: 'parse-prd', 'expand-task' and 'config-manager'

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* feat: Support custom response language (#510)

* feat: Support custom response language

* fix: Add default values for response language in config-manager.js

* chore: Update configuration file and add default response language settings

* feat: Support MCP/CLI custom response language

* chore: Update test comments to English for consistency

* docs: Auto-update and format models.md

* chore: fix format

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* Feat: Implemented advanced settings for Claude Code AI provider (#872)

* Feat: Implemented advanced settings for Claude Code AI provider

- Added new 'claudeCode' property to default config
- Added getters and validation functions to 'config-manager.js'
- Added new 'isEmpty' utility to 'utils.js'
- Added new constants file 'commands.js' for AI_COMMAND_NAMES
- Updated Claude Code AI provider to use new config functions
- Updated 'claude-code-usage.md' documentation
- Added 'config-manager.test.js' tests to cover new settings

* chore: run format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* fix: issues with release (#915)

Fix remove-task bug with mcp
Fix response-language using old config file .taskmaster

* fix(claude-code): recover from CLI JSON truncation bug (#913) (#920)

Gracefully handle SyntaxError thrown by @anthropic-ai/claude-code when the CLI truncates large JSON outputs (4–16 kB cut-offs).\n\nKey points:\n• Detect JSON parse error + existing buffered text in both doGenerate() and doStream() code paths.\n• Convert the failure into a recoverable 'truncated' finish state and push a provider-warning.\n• Allows Task Master to continue parsing long PRDs / expand-task operations instead of crashing.\n\nA patch changeset (.changeset/claude-code-json-truncation.md) is included for the next release.\n\nRef: eyaltoledano/claude-task-master#913

* docs: fix gemini-cli authentication documentation (#923)

Remove erroneous 'gemini auth login' command references and replace with correct 'gemini' command authentication flow. Update documentation to reflect proper OAuth setup process via the gemini CLI interactive interface.

* chore: run format

* fix: add initTaskMaster to new commands

Fixes CI and broken commands

* chore: format

---------

Co-authored-by: Chris Covington <chris.covington@hey.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Nicholas Spalding <nishedcob@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ofer Shaal <oshaal@phase2technology.com>
Co-authored-by: Shandy Hermawan <hrm.shandy05@gmail.com>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: Geoff Hammond <geoff@geoffhammond.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: shenysun <40556411+shenysun@users.noreply.github.com>
2025-07-08 09:59:21 +02:00
github-actions[bot]
f62eaad709 docs: Auto-update and format models.md 2025-07-08 06:37:53 +00:00
OTYAK
98d1c97436 feat: Add GROQ API key support and integrate GROQ provider (#930)
* feat: Add GROQ API key support and integrate GROQ provider

* feat: Add support for Groq provider
- Added a new changeset documenting the addition of Groq provider support.
-Ran npm run format

* feat: Add support for Groq provider
- Added a new changeset documenting the addition of Groq provider support.
-Ran npm run format
2025-07-08 08:37:38 +02:00
Ben Vargas
3334e409ae fix: update ai-sdk-provider-gemini-cli to 0.0.4 for improved authentication (#932)
- Fixed authentication compatibility issues with Google auth
- Added support for 'api-key' auth type alongside 'gemini-api-key'
- Resolved "Unsupported authType: undefined" runtime errors
- Updated @google/gemini-cli-core dependency to 0.1.9
- Improved documentation and removed invalid auth references
- Maintained backward compatibility while enhancing type validation
2025-07-07 21:50:17 +03:00
Ben Vargas
5b9416f673 docs: fix gemini-cli authentication documentation (#923)
Remove erroneous 'gemini auth login' command references and replace with correct 'gemini' command authentication flow. Update documentation to reflect proper OAuth setup process via the gemini CLI interactive interface.
2025-07-07 21:50:17 +03:00
Ben Vargas
6c88a4a749 fix(claude-code): recover from CLI JSON truncation bug (#913) (#920)
Gracefully handle SyntaxError thrown by @anthropic-ai/claude-code when the CLI truncates large JSON outputs (4–16 kB cut-offs).\n\nKey points:\n• Detect JSON parse error + existing buffered text in both doGenerate() and doStream() code paths.\n• Convert the failure into a recoverable 'truncated' finish state and push a provider-warning.\n• Allows Task Master to continue parsing long PRDs / expand-task operations instead of crashing.\n\nA patch changeset (.changeset/claude-code-json-truncation.md) is included for the next release.\n\nRef: eyaltoledano/claude-task-master#913
2025-07-07 21:50:17 +03:00
github-actions[bot]
e5d2b61297 Version Packages (#919) 2025-07-05 08:18:20 +03:00
Ralph Khreish
0726bc966c Merge pull request #917 from eyaltoledano/next 2025-07-04 07:23:21 +03:00
Ralph Khreish
7fea9968ef fix: issues with release (#915)
Fix remove-task bug with mcp
Fix response-language using old config file .taskmaster
2025-07-03 13:22:58 +02:00
Geoff Hammond
f7fbdd6755 Feat: Implemented advanced settings for Claude Code AI provider (#872)
* Feat: Implemented advanced settings for Claude Code AI provider

- Added new 'claudeCode' property to default config
- Added getters and validation functions to 'config-manager.js'
- Added new 'isEmpty' utility to 'utils.js'
- Added new constants file 'commands.js' for AI_COMMAND_NAMES
- Updated Claude Code AI provider to use new config functions
- Updated 'claude-code-usage.md' documentation
- Added 'config-manager.test.js' tests to cover new settings

* chore: run format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-02 22:43:46 +02:00
shenysun
c99df64f65 feat: Support custom response language (#510)
* feat: Support custom response language

* fix: Add default values for response language in config-manager.js

* chore: Update configuration file and add default response language settings

* feat: Support MCP/CLI custom response language

* chore: Update test comments to English for consistency

* docs: Auto-update and format models.md

* chore: fix format

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-02 22:35:49 +02:00
Geoff Hammond
5eafc5ea11 Feat: Added automatic determination of task number based on complexity (#884)
- Added 'defaultNumTasks: 10' to default config, now used in 'parse-prd'
- Adjusted 'parse-prd' and 'expand-task' to:
  - Accept a 'numTasks' value of 0
  - Updated tool and command descriptions
  - Updated prompts to 'an appropriate number of' when value is 0
- Updated 'README-task-master.md' and 'command-reference.md' docs
- Added more tests for: 'parse-prd', 'expand-task' and 'config-manager'

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-07-02 22:12:27 +02:00
github-actions[bot]
a33d6ecfeb docs: Auto-update and format models.md 2025-07-02 19:46:30 +00:00
Ben Vargas
dd96f51179 feat: Add gemini-cli provider integration for Task Master (#897)
* feat: Add gemini-cli provider integration for Task Master

This commit adds comprehensive support for the Gemini CLI provider, enabling users
to leverage Google's Gemini models through OAuth authentication via the gemini CLI
tool. This integration provides a seamless experience for users who prefer using
their existing Google account authentication rather than managing API keys.

## Implementation Details

### Provider Class (`src/ai-providers/gemini-cli.js`)
- Created GeminiCliProvider extending BaseAIProvider
- Implements dual authentication support:
  - Primary: OAuth authentication via `gemini auth login` (authType: 'oauth-personal')
  - Secondary: API key authentication for compatibility (authType: 'api-key')
- Uses the npm package `ai-sdk-provider-gemini-cli` (v0.0.3) for SDK integration
- Properly handles authentication validation without console output

### Model Configuration (`scripts/modules/supported-models.json`)
- Added two Gemini models with accurate specifications:
  - gemini-2.5-pro: 72% SWE score, 65,536 max output tokens
  - gemini-2.5-flash: 71% SWE score, 65,536 max output tokens
- Both models support main, fallback, and research roles
- Configured with zero cost (free tier)

### System Integration
- Registered provider in PROVIDERS map (`scripts/modules/ai-services-unified.js`)
- Added to OPTIONAL_AUTH_PROVIDERS set for flexible authentication
- Added GEMINI_CLI constant to provider constants (`src/constants/providers.js`)
- Exported GeminiCliProvider from index (`src/ai-providers/index.js`)

### Command Line Support (`scripts/modules/commands.js`)
- Added --gemini-cli flag to models command for provider hint
- Integrated into model selection logic (setModel function)
- Updated error messages to include gemini-cli in provider list
- Removed unrelated azure/vertex changes to maintain PR focus

### Documentation (`docs/providers/gemini-cli.md`)
- Comprehensive provider documentation emphasizing OAuth-first approach
- Clear explanation of why users would choose gemini-cli over standard google provider
- Detailed installation, authentication, and configuration instructions
- Troubleshooting section with common issues and solutions

### Testing (`tests/unit/ai-providers/gemini-cli.test.js`)
- Complete test suite with 12 tests covering all functionality
- Tests for both OAuth and API key authentication paths
- Error handling and edge case coverage
- Updated mocks in ai-services-unified.test.js for integration testing

## Key Design Decisions

1. **OAuth-First Design**: The provider assumes users want to leverage their existing
   `gemini auth login` credentials, making this the default authentication method.

2. **Authentication Type Mapping**: Discovered through testing that the SDK expects:
   - 'oauth-personal' for OAuth/CLI authentication (not 'gemini-cli' or 'oauth')
   - 'api-key' for API key authentication (not 'gemini-api-key')

3. **Silent Operation**: Removed console.log statements from validateAuth to match
   the pattern used by other providers like claude-code.

4. **Limited Model Support**: Only gemini-2.5-pro and gemini-2.5-flash are available
   through the CLI, as confirmed by the package author.

## Usage

```bash
# Install gemini CLI globally
npm install -g @google/gemini-cli

# Authenticate with Google account
gemini auth login

# Configure Task Master to use gemini-cli
task-master models --set-main gemini-2.5-pro --gemini-cli

# Use Task Master normally
task-master new "Create a REST API endpoint"
```

## Dependencies
- Added `ai-sdk-provider-gemini-cli@^0.0.3` to package.json
- This package wraps the Google Gemini CLI Core functionality for Vercel AI SDK

## Testing
All tests pass (613 total), including the new gemini-cli provider tests.
Code has been formatted with biome to maintain consistency.

This implementation provides a clean, well-tested integration that follows Task Master's
existing patterns while offering users a convenient way to use Gemini models with their
existing Google authentication.

* feat: implement lazy loading for gemini-cli provider

- Move ai-sdk-provider-gemini-cli to optionalDependencies
- Implement dynamic import with loadGeminiCliModule() function
- Make getClient() async to support lazy loading
- Update base-provider to handle async getClient() calls
- Update tests to handle async getClient() method

This allows the application to start without the gemini-cli package
installed, only loading it when actually needed.

* feat(gemini-cli): replace regex-based JSON extraction with jsonc-parser

- Add jsonc-parser dependency for robust JSON parsing
- Replace simple regex approach with progressive parsing strategy:
  1. Direct parsing after cleanup
  2. Smart boundary detection with single-pass analysis
  3. Limited fallback for edge cases
- Optimize performance with early termination and strategic sampling
- Add comprehensive tests for variable declarations, trailing commas,
  escaped quotes, nested objects, and performance edge cases
- Improve reliability for complex JSON structures that Gemini commonly produces
- Fix code formatting with biome

This addresses JSON parsing failures in generateObject operations while
maintaining backward compatibility and significantly improving performance
for large responses.

* fix: update package-lock.json and fix formatting for CI/CD

- Add jsonc-parser to package-lock.json for proper npm ci compatibility
- Fix biome formatting issues in gemini-cli provider and tests
- Ensure all CI/CD checks pass

* feat(gemini-cli): implement comprehensive JSON output reliability system

- Add automatic JSON request detection via content analysis patterns
- Implement task-specific prompt simplification for improved AI compliance
- Add strict JSON enforcement through enhanced system prompts
- Implement response interception with intelligent JSON extraction fallback
- Add comprehensive test coverage for all new JSON handling methods
- Move debug logging to appropriate level for clean user experience

This multi-layered approach addresses gemini-cli's conversational response
tendencies, ensuring reliable structured JSON output for task expansion
operations. Achieves 100% success rate in end-to-end testing while
maintaining full backward compatibility with existing functionality.

Technical implementation includes:
• JSON detection via user message content analysis
• Expand-task prompt simplification with cleaner instructions
• System prompt enhancement with strict JSON enforcement
• Response processing with jsonc-parser-based extraction
• Comprehensive unit test coverage for edge cases
• Debug-level logging to prevent user interface clutter

Resolves: gemini-cli JSON formatting inconsistencies
Tested: All 46 test suites pass, formatting verified

* chore: add changeset for gemini-cli provider implementation

Adds minor version bump for comprehensive gemini-cli provider with:
- Lazy loading and optional dependency management
- Advanced JSON parsing with jsonc-parser
- Multi-layer reliability system for structured output
- Complete test coverage and CI/CD compliance

* refactor: consolidate optional auth provider logic

- Add gemini-cli to existing providersWithoutApiKeys array in config-manager
- Export providersWithoutApiKeys for reuse across modules
- Remove duplicate OPTIONAL_AUTH_PROVIDERS Set from ai-services-unified
- Update ai-services-unified to import and use centralized array
- Fix Jest mock to include new providersWithoutApiKeys export

This eliminates code duplication and provides a single source of truth
for which providers support optional authentication, addressing PR
reviewer feedback about existing similar functionality in src/constants.
2025-07-02 21:46:19 +02:00
Parthy
2852149a47 fix: Critical writeJSON Context Fixes - Prevent Tag Corruption (#910)
* feat(tasks): Fix critical tag corruption bug in task management

- Fixed missing context parameters in writeJSON calls across add-task, remove-task, and add-subtask functions
- Added projectRoot and tag parameters to prevent data corruption in multi-tag environments
- Re-enabled generateTaskFiles calls to ensure markdown files are updated after operations
- Enhanced add_subtask MCP tool with tag parameter support
- Refactored addSubtaskDirect function to properly pass context to core logic
- Streamlined codebase by removing deprecated functionality

This resolves the critical bug where task operations in one tag context would corrupt or delete tasks from other tags in tasks.json.

* feat(task-manager): Enhance addSubtask with current tag support

- Added `getCurrentTag` utility to retrieve the current tag context for task operations.
- Updated `addSubtask` to use the current tag when reading and writing tasks, ensuring proper context handling.
- Refactored tests to accommodate changes in the `addSubtask` function, ensuring accurate mock implementations and expectations.
- Cleaned up test cases for better readability and maintainability.

This improves task management by preventing tag-related data corruption and enhances the overall functionality of the task manager.

* feat(remove-task): Add tag support for task removal and enhance error handling

- Introduced `tag` parameter in `removeTaskDirect` to specify context for task operations, improving multi-tag support.
- Updated logging to include tag context in messages for better traceability.
- Refactored task removal logic to streamline the process and improve error reporting.
- Added comprehensive unit tests to validate tag handling and ensure robust error management.

This enhancement prevents task data corruption across different tags and improves the overall reliability of the task management system.

* feat(add-task): Add projectRoot and tag parameters to addTask tests

- Updated `addTask` unit tests to include `projectRoot` and `tag` parameters for better context handling.
- Enhanced test cases to ensure accurate expectations and improve overall test coverage.

This change aligns with recent enhancements in task management, ensuring consistency across task operations.

* feat(set-task-status): Add tag parameter support and enhance task status handling

- Introduced `tag` parameter in `setTaskStatusDirect` and related functions to improve context management in multi-tag environments.
- Updated `writeJSON` calls to ensure task data integrity across different tags.
- Enhanced unit tests to validate tag preservation during task status updates, ensuring robust functionality.

This change aligns with recent improvements in task management, preventing data corruption and enhancing overall reliability.

* feat(tag-management): Enhance writeJSON calls to preserve tag context

- Updated `writeJSON` calls in `createTag`, `deleteTag`, `renameTag`, `copyTag`, and `enhanceTagsWithMetadata` to include `projectRoot` for better context management and to prevent tag corruption.
- Added comprehensive unit tests for tag management functions to ensure data integrity and proper tag handling during operations.

This change improves the reliability of tag management by ensuring that operations do not corrupt existing tags and maintains the overall structure of the task data.

* feat(expand-task): Update writeJSON to include projectRoot and tag context

- Modified `writeJSON` call in `expandTaskDirect` to pass `projectRoot` and `tag` parameters, ensuring proper context management when saving tasks.json.
- This change aligns with recent enhancements in task management, preventing potential data corruption and improving overall reliability.

* feat(fix-dependencies): Add projectRoot and tag parameters for enhanced context management

- Updated `fixDependenciesDirect` and `registerFixDependenciesTool` to include `projectRoot` and `tag` parameters, improving context handling during dependency fixes.
- Introduced a new unit test for `fixDependenciesCommand` to ensure proper preservation of projectRoot and tag data in JSON outputs.

This change enhances the reliability of dependency management by ensuring that context is maintained across operations, preventing potential data issues.

* fix(context): propagate projectRoot and tag through dependency, expansion, status-update and tag-management commands to prevent cross-tag data corruption

* test(fix-dependencies): Enhance unit tests for fixDependenciesCommand

- Refactored tests to use unstable mocks for utils, ui, and task-manager modules, improving isolation and reliability.
- Added checks for process.exit to ensure proper handling of invalid data scenarios.
- Updated test cases to verify writeJSON calls with projectRoot and tag parameters, ensuring accurate context preservation during dependency fixes.

This change strengthens the test suite for dependency management, ensuring robust functionality and preventing potential data issues.

* chore(plan): remove outdated fix plan for `writeJSON` context parameters
2025-07-02 21:45:10 +02:00
Parthy
43e0025f4c fix: prevent tag corruption in bulk updates (#856)
* fix(task-manager): prevent tag corruption in bulk updates and add tag preservation test

- Fix writeJSON call in scripts/modules/task-manager/update-tasks.js (line 469) to include projectRoot and tag parameters.
- Ensure tagged task lists maintain data integrity during bulk updates, preventing task disappearance in tagged contexts.
- Update MCP tools to properly pass tag context through the call chain.
- Introduce a comprehensive test case to verify that all tags are preserved when updating tasks, covering both master and feature-branch scenarios.

Addresses an issue where bulk updates could corrupt tasks.json in tagged task list structures, reinforcing task management robustness.

* style(tests): format task data in update-tasks test
2025-07-02 12:53:12 +02:00
Parthy
598e687067 fix: use tag-specific complexity reports (#857)
* fix(expand-task): Use tag-specific complexity reports

- Add getTagAwareFilePath utility function to resolve tag-specific file paths
- Update expandTask to use tag-aware complexity report paths
- Fix issue where expand-task always used default complexity report
- Add comprehensive tests for getTagAwareFilePath utility
- Ensure proper handling of file extensions and directory structures

Fixes #850: Expanding tasks not using tag-specific complexity reports

The expandTask function now correctly uses complexity reports specific
to the current tag context (e.g., task-complexity-report_feature-branch.json)
instead of always using the default task-complexity-report.json file.

This enables proper task expansion behavior when working with multiple
tag contexts, ensuring complexity analysis is tag-specific and accurate.

* chore: Add changeset for tag-specific complexity reports fix

* test(expand-task): Add tests for tag-specific complexity report integration

- Introduced a new test suite for verifying the integration of tag-specific complexity reports in the expandTask function.
- Added a test case to ensure the correct complexity report is used when available for a specific tag.
- Mocked file system interactions to simulate the presence of tag-specific complexity reports.

This enhances the test coverage for task expansion behavior, ensuring it accurately reflects the complexity analysis based on the current tag context.

* refactor(task-manager): unify and simplify tag-aware file path logic and tests

- Reformatted imports and cleaned up comments in test files for readability
- Centralized mocks: moved getTagAwareFilePath & slugifyTagForFilePath
  mocks to setup.js for consistency and maintainability
- Simplified utils/getTagAwareFilePath: replaced manual parsing with
  path.parse() & path.format(); improved extension handling
- Enhanced test mocks for path.parse, path.format & reset path.join
  in beforeEach to avoid interference
- All tests now pass consistently; no change in functionality
2025-07-02 12:52:45 +02:00
Shandy Hermawan
f38abd6843 fix: Subtask generation fails on gemini-2.5-pro (#852)
* fix: clarify details format in task expansion prompt

* chore: add changeset
2025-07-02 07:16:09 +02:00
Joe Danziger
24e9206da0 Fix rules command to use reliable project root detection like other commands (#908)
* update/fix projectRoot call for consistency

* internal naming consistency

* add changeset
2025-07-02 07:05:30 +02:00
Ofer Shaal
8d9fcf2064 Fix/spelling mistakes (#876)
* docs: Auto-update and format models.md

* fix: correct typos in documentation for parse-prd and taskmaster commands

- Updated the `parse-prd` documentation to fix the spelling of "multiple."
- Clarified the description of the `id` parameter in the `taskmaster` documentation to ensure proper syntax and readability.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-07-01 11:44:44 +02:00
Joe Danziger
56a415ef79 fix: Ensure projectRoot is a string (potential WSL fix) (#892)
* ensure projectRoot is a string

* add changeset
2025-07-01 10:55:48 +02:00
github-actions[bot]
f081bba83c docs: Auto-update and format models.md 2025-06-25 13:49:17 +00:00
Nicholas Spalding
6fd5e23396 Support for Additional Anthropic Models on Bedrock (#870)
* Add additional Anthropic Models for Bedrock

* Update Models Docs from `scripts/modules/supported-models.json`

* feat(models): add additional Bedrock supported models
2025-06-25 15:49:02 +02:00
Joe Danziger
e4456b11bc fix: .gitignore missing trailing newline during project initialization (#855) 2025-06-24 07:42:23 +03:00
github-actions[bot]
295087a5b8 docs: Auto-update and format models.md 2025-06-23 06:13:28 +00:00
Ralph Khreish
5f2b7323ad Merge pull request #849 from eyaltoledano/chore/update.next.june
Chore: rebase next after Release 0.18.0
2025-06-23 09:13:08 +03:00
Ralph Khreish
9ddc521757 chore: fix CI and weird conflicts 2025-06-23 09:11:30 +03:00
Ralph Khreish
e7087cf88f chore: fix format 2025-06-23 09:08:34 +03:00
Ralph Khreish
08f86f19c3 Merge remote-tracking branch 'origin/next' into chore/update.next.june 2025-06-23 09:06:52 +03:00
Joe Danziger
f272748965 Default to Cursor profile for MCP init when no rules specified (#846) 2025-06-23 08:57:42 +03:00
Ralph Khreish
15e15a1f17 chore: format fix 2025-06-23 08:57:42 +03:00
github-actions[bot]
3a30e9acd4 Version Packages 2025-06-23 08:57:42 +03:00
Ralph Khreish
15286c029d feat: make more compatible with "o" family models (#839) 2025-06-23 08:57:39 +03:00
neno
c39e5158b4 feat: Claude Code slash commands for Task Master (#774)
* Fix Cursor deeplink installation with copy-paste instructions (#723)

* fix: expand-task (#755)

* docs: Update o3 model price (#751)

* docs: Auto-update and format models.md

* docs: Auto-update and format models.md

* feat: Add Claude Code task master commands

Adds Task Master slash commands for Claude Code under /project:tm/ namespace

---------

Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Volodymyr Zahorniak <7808206+zahorniak@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
2025-06-23 08:57:38 +03:00
github-actions[bot]
4bda8f4d76 chore: rc version bump 2025-06-23 08:57:36 +03:00
Joe Danziger
49976e864b Call rules interactive setup during init (#833) 2025-06-23 08:57:34 +03:00
Joe Danziger
30b873a7da store tasks in git by default (#835) 2025-06-23 08:57:34 +03:00
Ralph Khreish
ab37859a7e fix: update task by id (#834) 2025-06-23 08:57:32 +03:00
Joe Danziger
e704ba12fd feat: Enhanced project initialization with Git worktree detection (#743)
* Fix Cursor deeplink installation with copy-paste instructions (#723)

* detect git worktree

* add changeset

* add aliases and git flags

* add changeset

* rename and update test

* add store tasks in git functionality

* update changeset

* fix newline

* remove unused import

* update command wording

* update command option text
2025-06-23 08:56:43 +03:00
Joe Danziger
64b2d8f79e Rename Roo Code "Boomerang" role to "Orchestrator" (#831) 2025-06-23 08:56:42 +03:00
Ralph Khreish
bbb4bbcc11 Feature/compatibleapisupport (#830)
* add compatible platform api support

* Adjust the code according to the suggestions

* Fully revised as requested: restored all required checks, improved compatibility, and converted all comments to English.

* feat: Add support for compatible API endpoints via baseURL

* chore: Add changeset for compatible API support

* chore: cleanup

* chore: improve changeset

* fix: package-lock.json

* fix: package-lock.json

---------

Co-authored-by: He-Xun <1226807142@qq.com>
2025-06-23 08:56:39 +03:00
Ben Vargas
8e38348203 chore: add changeset for Claude Code provider feature 2025-06-23 08:56:36 +03:00
Ben Vargas
01b651bddc revert: remove maxTokens update functionality from init
This functionality was out of scope for the Claude Code provider PR.
The automatic updating of maxTokens values in config.json during
initialization is a general improvement that should be in a separate PR.

Additionally, Claude Code ignores maxTokens and temperature parameters
anyway, making this change irrelevant for the Claude Code integration.

Removed:
- scripts/modules/update-config-tokens.js
- Import and usage in scripts/init.js
2025-06-23 08:56:34 +03:00
Ben Vargas
0840ad8316 feat: make @anthropic-ai/claude-code an optional dependency
This change makes the Claude Code SDK package optional, preventing installation failures for users who don't need Claude Code functionality.

Changes:
- Added @anthropic-ai/claude-code to optionalDependencies in package.json
- Implemented lazy loading in language-model.js to only import the SDK when actually used
- Updated documentation to explain the optional installation requirement
- Applied formatting fixes to ensure code consistency

Benefits:
- Users without Claude Code subscriptions don't need to install the dependency
- Reduces package size for users who don't use Claude Code
- Prevents installation failures if the package is unavailable
- Provides clear error messages when the package is needed but not installed

The implementation uses dynamic imports to load the SDK only when doGenerate() or doStream() is called, ensuring the provider can be instantiated without the package present.
2025-06-23 08:56:30 +03:00
Ben Vargas
5c726dc542 feat: add Claude Code provider support
Implements Claude Code as a new AI provider that uses the Claude Code CLI
without requiring API keys. This enables users to leverage Claude models
through their local Claude Code installation.

Key changes:
- Add complete AI SDK v1 implementation for Claude Code provider
  - Custom SDK with streaming/non-streaming support
  - Session management for conversation continuity
  - JSON extraction for object generation mode
  - Support for advanced settings (maxTurns, allowedTools, etc.)

- Integrate Claude Code into Task Master's provider system
  - Update ai-services-unified.js to handle keyless authentication
  - Add provider to supported-models.json with opus/sonnet models
  - Ensure correct maxTokens values are applied (opus: 32000, sonnet: 64000)

- Fix maxTokens configuration issue
  - Add max_tokens property to getAvailableModels() output
  - Update setModel() to properly handle claude-code models
  - Create update-config-tokens.js utility for init process

- Add comprehensive documentation
  - User guide with configuration examples
  - Advanced settings explanation and future integration options

The implementation maintains full backward compatibility with existing
providers while adding seamless Claude Code support to all Task Master
commands.
2025-06-23 08:56:28 +03:00
ejones40
21d988691b Add pyproject.toml as project root marker (#804)
* feat: Add pyproject.toml as project root marker - Added 'pyproject.toml' to the project markers array in findProjectRoot() - Enables Task Master to recognize Python projects using pyproject.toml - Improves project root detection for modern Python development workflows - Maintains compatibility with existing Node.js and Git-based detection

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-23 08:56:26 +03:00
Ralph Khreish
21839b1cd6 Fix/expand command tag corruption (#827)
* fix(expand): Fix tag corruption in expand command - Fix tag parameter passing through MCP expand-task flow - Add tag parameter to direct function and tool registration - Fix contextGatherer method name from _buildDependencyContext to _buildDependencyGraphs - Add comprehensive test coverage for tag handling in expand-task - Ensures tagged task structure is preserved during expansion - Prevents corruption when tag is undefined. Fixes expand command causing tag corruption in tagged task lists. All existing tests pass and new test coverage added.

* test(e2e): Add comprehensive tag-aware expand testing to verify tag corruption fix - Add new test section for feature-expand tag creation and testing - Verify tag preservation during expand, force expand, and expand --all operations - Test that master tag remains intact and feature-expand tag receives subtasks correctly - Fix file path references to use correct .taskmaster/tasks/tasks.json location - Fix config file check to use .taskmaster/config.json instead of .taskmasterconfig - All tag corruption verification tests pass successfully in E2E test

* fix(changeset): Update E2E test improvements changeset to properly reflect tag corruption fix verification

* chore(changeset): combine duplicate changesets for expand tag corruption fix

Merge eighty-breads-wonder.md into bright-llamas-enter.md to consolidate
the expand command fix and its comprehensive E2E testing enhancements
into a single changeset entry.

* Delete .changeset/eighty-breads-wonder.md

* Version Packages

* chore: fix package.json

* fix(expand): Enhance context handling in expandAllTasks function
- Added `tag` to context destructuring for better context management.
- Updated `readJSON` call to include `contextTag` for improved data integrity.
- Ensured the correct tag is passed during task expansion to prevent tag corruption.

---------

Co-authored-by: Parththipan Thaniperumkarunai <parththipan.thaniperumkarunai@milkmonkey.de>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-06-23 08:56:26 +03:00
Ralph Khreish
6160089b8e fix(bedrock): improve AWS credential handling and add model definitions (#826)
* fix(bedrock): improve AWS credential handling and add model definitions

- Change error to warning when AWS credentials are missing in environment
- Allow fallback to system configuration (aws config files or instance profiles)
- Remove hardcoded region and profile parameters in Bedrock client
- Add Claude 3.7 Sonnet and DeepSeek R1 model definitions for Bedrock
- Update config manager to properly handle Bedrock provider

* chore: cleanup and format and small refactor

---------

Co-authored-by: Ray Krueger <raykrueger@gmail.com>
2025-06-23 08:56:18 +03:00
Nathan Marley
82bb50619f fix: switch to ESM export to avoid mixed format (#633)
* fix: switch to ESM export to avoid mixed format

The CLI entrypoint was using `module.exports` alongside ESM `import` statements,
resulting in an invalid mixed module format. Replaced the CommonJS export with
a proper ESM `export` to maintain consistency and prevent module resolution issues.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-23 08:56:06 +03:00
Ralph Khreish
898f15e699 fix: providers config for azure, bedrock, and vertex (#822)
* fix: providers config for azure, bedrock, and vertex

* chore: improve changelog

* chore: fix CI
2025-06-23 08:56:02 +03:00
Joe Danziger
1a157567dc feat: Flexible brand rules management (#460)
* chore(docs): update docs and rules related to model management.

* feat(ai): Add OpenRouter AI provider support

Integrates the OpenRouter AI provider using the Vercel AI SDK adapter (@openrouter/ai-sdk-provider). This allows users to configure and utilize models available through the OpenRouter platform.

- Added src/ai-providers/openrouter.js with standard Vercel AI SDK wrapper functions (generateText, streamText, generateObject).

- Updated ai-services-unified.js to include the OpenRouter provider in the PROVIDER_FUNCTIONS map and API key resolution logic.

- Verified config-manager.js handles OpenRouter API key checks correctly.

- Users can configure OpenRouter models via .taskmasterconfig using the task-master models command or MCP models tool. Requires OPENROUTER_API_KEY.

- Enhanced error handling in ai-services-unified.js to provide clearer messages when generateObjectService fails due to lack of underlying tool support in the selected model/provider endpoint.

* feat(cli): Add --status/-s filter flag to show command and get-task MCP tool

Implements the ability to filter subtasks displayed by the `task-master show <id>` command using the `--status` (or `-s`) flag. This is also available in the MCP context.

- Modified `commands.js` to add the `--status` option to the `show` command definition.

- Updated `utils.js` (`findTaskById`) to handle the filtering logic and return original subtask counts/arrays when filtering.

- Updated `ui.js` (`displayTaskById`) to use the filtered subtasks for the table, display a summary line when filtering, and use the original subtask list for the progress bar calculation.

- Updated MCP `get_task` tool and `showTaskDirect` function to accept and pass the `status` parameter.

- Added changeset entry.

* fix(tasks): Improve next task logic to be subtask-aware

* fix(tasks): Enable removing multiple tasks/subtasks via comma-separated IDs

- Refactors the core `removeTask` function (`task-manager/remove-task.js`) to accept and iterate over comma-separated task/subtask IDs.

- Updates dependency cleanup and file regeneration logic to run once after processing all specified IDs.

- Adjusts the `remove-task` CLI command (`commands.js`) description and confirmation prompt to handle multiple IDs correctly.

- Fixes a bug in the CLI confirmation prompt where task/subtask titles were not being displayed correctly.

- Updates the `remove_task` MCP tool description to reflect the new multi-ID capability.

This addresses the previously known issue where only the first ID in a comma-separated list was processed.

Closes #140

* Update README.md (#342)

* Update Discord badge (#337)

* refactor(init): Improve robustness and dependencies; Update template deps for AI SDKs; Silence npm install in MCP; Improve conditional model setup logic; Refactor init.js flags; Tweak Getting Started text; Fix MCP server launch command; Update default model in config template

* Refactor: Improve MCP logging, update E2E & tests

Refactors MCP server logging and updates testing infrastructure.

- MCP Server:

  - Replaced manual logger wrappers with centralized `createLogWrapper` utility.

  - Updated direct function calls to use `{ session, mcpLog }` context.

  - Removed deprecated `model` parameter from analyze, expand-all, expand-task tools.

  - Adjusted MCP tool import paths and parameter descriptions.

- Documentation:

  - Modified `docs/configuration.md`.

  - Modified `docs/tutorial.md`.

- Testing:

  - E2E Script (`run_e2e.sh`):

    - Removed `set -e`.

    - Added LLM analysis function (`analyze_log_with_llm`) & integration.

    - Adjusted test run directory creation timing.

    - Added debug echo statements.

  - Deleted Unit Tests: Removed `ai-client-factory.test.js`, `ai-client-utils.test.js`, `ai-services.test.js`.

  - Modified Fixtures: Updated `scripts/task-complexity-report.json`.

- Dev Scripts:

  - Modified `scripts/dev.js`.

* chore(tests): Passes tests for merge candidate
- Adjusted the interactive model default choice to be 'no change' instead of 'cancel setup'
- E2E script has been perfected and works as designed provided there are all provider API keys .env in the root
- Fixes the entire test suite to make sure it passes with the new architecture.
- Fixes dependency command to properly show there is a validation failure if there is one.
- Refactored config-manager.test.js mocking strategy and fixed assertions to read the real supported-models.json
- Fixed rule-transformer.test.js assertion syntax and transformation logic adjusting replacement for search which was too broad.
- Skip unstable tests in utils.test.js (log, readJSON, writeJSON error paths) due to SIGABRT crash. These tests trigger a native crash (SIGABRT), likely stemming from a conflict between internal chalk usage within the functions and Jest's test environment, possibly related to ESM module handling.

* chore(wtf): removes chai. not sure how that even made it in here. also removes duplicate test in scripts/.

* fix: ensure API key detection properly reads .env in MCP context

Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env

Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env

Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works

* fix(update): pass projectRoot through update command flow

Modified ai-services-unified.js, update.js tool, and update-tasks.js direct function to correctly pass projectRoot. This enables the .env file API key fallback mechanism for the update command when running via MCP, ensuring consistent key resolution with the CLI context.

* fix(analyze-complexity): pass projectRoot through analyze-complexity flow

Modified analyze-task-complexity.js core function, direct function, and analyze.js tool to correctly pass projectRoot. Fixed import error in tools/index.js. Added debug logging to _resolveApiKey in ai-services-unified.js. This enables the .env API key fallback for analyze_project_complexity.

* fix(add-task): pass projectRoot and fix logging/refs

Modified add-task core, direct function, and tool to pass projectRoot for .env API key fallback. Fixed logFn reference error and removed deprecated reportProgress call in core addTask function. Verified working.

* fix(parse-prd): pass projectRoot and fix schema/logging

Modified parse-prd core, direct function, and tool to pass projectRoot for .env API key fallback. Corrected Zod schema used in generateObjectService call. Fixed logFn reference error in core parsePRD. Updated unit test mock for utils.js.

* fix(update-task): pass projectRoot and adjust parsing

Modified update-task-by-id core, direct function, and tool to pass projectRoot. Reverted parsing logic in core function to prioritize `{...}` extraction, resolving parsing errors. Fixed ReferenceError by correctly destructuring projectRoot.

* fix(update-subtask): pass projectRoot and allow updating done subtasks

Modified update-subtask-by-id core, direct function, and tool to pass projectRoot for .env API key fallback. Removed check preventing appending details to completed subtasks.

* fix(mcp, expand): pass projectRoot through expand/expand-all flows

Problem: expand_task & expand_all MCP tools failed with .env keys due to missing projectRoot propagation for API key resolution. Also fixed a ReferenceError: wasSilent is not defined in expandTaskDirect.

Solution: Modified core logic, direct functions, and MCP tools for expand-task and expand-all to correctly destructure projectRoot from arguments and pass it down through the context object to the AI service call (generateTextService). Fixed wasSilent scope in expandTaskDirect.

Verification: Tested expand_task successfully in MCP using .env keys. Reviewed expand_all flow for correct projectRoot propagation.

* chore: prettier

* fix(expand-all): add projectRoot to expandAllTasksDirect invokation.

* fix(update-tasks): Improve AI response parsing for 'update' command

Refactors the JSON array parsing logic within
in .

The previous logic primarily relied on extracting content from markdown
code blocks (json or javascript), which proved brittle when the AI
response included comments or non-JSON text within the block, leading to
parsing errors for the  command.

This change modifies the parsing strategy to first attempt extracting
content directly between the outermost '[' and ']' brackets. This is
more robust as it targets the expected array structure directly. If
bracket extraction fails, it falls back to looking for a strict json
code block, then prefix stripping, before attempting a raw parse.

This approach aligns with the successful parsing strategy used for
single-object responses in  and resolves the
parsing errors previously observed with the  command.

* refactor(mcp): introduce withNormalizedProjectRoot HOF for path normalization

Added HOF to mcp tools utils to normalize projectRoot from args/session. Refactored get-task tool to use HOF. Updated relevant documentation.

* refactor(mcp): apply withNormalizedProjectRoot HOF to update tool

Problem: The  MCP tool previously handled project root acquisition and path resolution within its  method, leading to potential inconsistencies and repetition.

Solution: Refactored the  tool () to utilize the new  Higher-Order Function (HOF) from .

Specific Changes:
- Imported  HOF.
- Updated the Zod schema for the  parameter to be optional, as the HOF handles deriving it from the session if not provided.
- Wrapped the entire  function body with the  HOF.
- Removed the manual call to  from within the  function body.
- Destructured the  from the  object received by the wrapped  function, ensuring it's the normalized path provided by the HOF.
- Used the normalized  variable when calling  and when passing arguments to .

This change standardizes project root handling for the  tool, simplifies its  method, and ensures consistent path normalization. This serves as the pattern for refactoring other MCP tools.

* fix: apply to all tools withNormalizedProjectRoot to fix projectRoot issues for linux and windows

* fix: add rest of tools that need wrapper

* chore: cleanup tools to stop using rootFolder and remove unused imports

* chore: more cleanup

* refactor: Improve update-subtask, consolidate utils, update config

This commit introduces several improvements and refactorings across MCP tools, core logic, and configuration.

**Major Changes:**

1.  **Refactor updateSubtaskById:**
    - Switched from generateTextService to generateObjectService for structured AI responses, using a Zod schema (subtaskSchema) for validation.
    - Revised prompts to have the AI generate relevant content based on user request and context (parent/sibling tasks), while explicitly preventing AI from handling timestamp/tag formatting.
    - Implemented **local timestamp generation (new Date().toISOString()) and formatting** (using <info added on ...> tags) within the function *after* receiving the AI response. This ensures reliable and correctly formatted details are appended.
    - Corrected logic to append only the locally formatted, AI-generated content block to the existing subtask.details.

2.  **Consolidate MCP Utilities:**
    - Moved/consolidated the withNormalizedProjectRoot HOF into mcp-server/src/tools/utils.js.
    - Updated MCP tools (like update-subtask.js) to import withNormalizedProjectRoot from the new location.

3.  **Refactor Project Initialization:**
    - Deleted the redundant mcp-server/src/core/direct-functions/initialize-project-direct.js file.
    - Updated mcp-server/src/core/task-master-core.js to import initializeProjectDirect from its correct location (./direct-functions/initialize-project.js).

**Other Changes:**

-   Updated .taskmasterconfig fallback model to claude-3-7-sonnet-20250219.
-   Clarified model cost representation in the models tool description (taskmaster.mdc and mcp-server/src/tools/models.js).

* fix: displayBanner logging when silentMode is active (#385)

* fix: improve error handling, test options, and model configuration

- Enhance error validation in parse-prd.js and update-tasks.js
- Fix bug where mcpLog was incorrectly passed as logWrapper
- Improve error messages and response formatting
- Add --skip-verification flag to E2E tests
- Update MCP server config that ships with init to match new API key structure
- Fix task force/append handling in parse-prd command
- Increase column width in update-tasks display

* chore: fixes parse prd to show loading indicator in cli.

* fix(parse-prd): suggested fix for mcpLog was incorrect. reverting to my previously working code.

* chore(init): No longer ships readme with task-master init (commented out for now). No longer looking for task-master-mcp, instead checked for task-master-ai - this should prevent the init sequence from needlessly adding another mcp server with task-master-mcp to the mpc.json which a ton of people probably ran into.

* chore: restores 3.7 sonnet as the main role.

* fix(add/remove-dependency): dependency mcp tools were failing due to hard-coded tasks path in generate task files.

* chore: removes tasks json backup that was temporarily created.

* fix(next): adjusts mcp tool response to correctly return the next task/subtask. Also adds nextSteps to the next task response.

* chore: prettier

* chore: readme typos

* fix(config): restores sonnet 3.7 as default main role.

* Version Packages

* hotfix: move production package to "dependencies" (#399)

* Version Packages

* Fix: issues with 0.13.0 not working (#402)

* Exit prerelease mode and version packages

* hotfix: move production package to "dependencies"

* Enter prerelease mode and version packages

* Enter prerelease mode and version packages

* chore: cleanup

* chore: improve pre.json and add pre-release workflow

* chore: fix package.json

* chore: cleanup

* chore: improve pre-release workflow

* chore: allow github actions to commit

* extract fileMap and conversionConfig into brand profile

* extract into brand profile

* add windsurf profile

* add remove brand rules function

* fix regex

* add rules command to add/remove rules for a specific brand

* fix post processing for roo

* allow multiples

* add cursor profile

* update test for new structure

* move rules to assets

* use assets/rules for rules files

* use standardized setupMCP function

* fix formatting

* fix formatting

* add logging

* fix escapes

* default to cursor

* allow init with certain rulesets; no more .windsurfrules

* update docs

* update log msg

* fix formatting

* keep mdc extension for cursor

* don't rewrite .mdc to .md inside the files

* fix roo init (add modes)

* fix cursor init (don't use roo transformation by default)

* use more generic function names

* update docs

* fix formatting

* update function names

* add changeset

* add rules to mcp initialize project

* register tool with mcp server

* update docs

* add integration test

* fix cursor initialization

* rule selection

* fix formatting

* fix MCP - remove yes flag

* add import

* update roo tests

* add/update tests

* remove test

* add rules command test

* update MCP responses, centralize rules profiles & helpers

* fix logging and MCP response messages

* fix formatting

* incorrect test

* fix tests

* update fileMap

* fix file extension transformations

* fix formatting

* add rules command test

* test already covered

* fix formatting

* move renaming logic into profiles

* make sure dir is deleted (DS_Store)

* add confirmation for rules removal

* add force flag for rules remove

* use force flag for test

* remove yes parameter

* fix formatting

* import brand profiles from rule-transformer.js

* update comment

* add interactive rules setup

* optimize

* only copy rules specifically listed in fileMap

* update comment

* add cline profile

* add brandDir to remove ambiguity and support Cline

* specify whether to create mcp config and filename

* add mcpConfigName value for parh

* fix formatting

* remove rules just for this repository - only include rules to be distributed

* update error message

* update "brand rules" to "rules"

* update to minor

* remove comment

* remove comments

* move to /src/utils

* optimize imports

* move rules-setup.js to /src/utils

* move rule-transformer.js to /src/utils

* move confirmation to /src/ui/confirm.js

* default to all rules

* use profile js for mcp config settings

* only run rules interactive setup if not provided via command line

* update comments

* initialize with all brands if nothing specified

* update var name

* clean up

* enumerate brands for brand rules

* update instructions

* add test to check for brand profiles

* fix quotes

* update semantics and terminology from 'brand rules' to 'rules profiles'

* fix formatting

* fix formatting

* update function name and remove copying of cursor rules, now handled by rules transformer

* update comment

* rename to mcp-config-setup.js

* use enums for rules actions

* add aggregate reporting for rules add command

* add missing log message

* use simpler path

* use base profile with modifications for each brand

* use displayName and don't select any defaults in setup

* add confirmation if removing ALL rules profiles, and add --force flag on rules remove

* Use profile-detection instead of rules-detection

* add newline at end of mcp config

* add proper formatting for mcp.json

* update rules

* update rules

* update rules

* add checks for other rules and other profile folder items before removing

* update confirmation for rules remove

* update docs

* update changeset

* fix for filepath at bottom of rule

* Update cline profile and add test; adjust other rules tests

* update changeset

* update changeset

* clarify init for all profiles if not specified

* update rule text

* revert text

* use "rule profiles" instead of "rules profiles"

* use standard tool mappings for windsurf

* add Trae support

* update changeset

* update wording

* update to 'rule profile'

* remove unneeded exports to optimize loc

* combine to /src/utils/profiles.js; add codex and claude code profiles

* rename function and add boxen

* add claude and codex integration tests

* organize tests into profiles folder

* mock fs for transformer tests

* update UI

* add cline and trae integration tests

* update test

* update function name

* update formatting

* Update change set with new profiles

* move profile integration tests to subdirectory

* properly create temp directories in /tmp folder

* fix formatting

* use taskmaster subfolder for the 2 TM rules

* update wording

* ensure subdirectory exists

* update rules from next

* update from next

* update taskmaster rule

* add details on new rules command and init

* fix mcp init

* fix MCP path to assets

* remove duplication

* remove duplication

* MCP server path fixes for rules command

* fix for CLI roo rules add/remove

* update tests

* fix formatting

* fix pattern for interactive rule profiles setup

* restore comments

* restore comments

* restore comments

* remove unused import, fix quotes

* add missing integration tests

* add VS Code profile and tests

* update docs and rules to include vscode profile

* add rules subdirectory support per-profile

* move profiles to /src

* fix formatting

* rename to remove ambiguity

* use --setup for rules interactive setup

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* change roo boomerang to orchestrator; update tests that don't use modes

* fix newline

* chore: cleanup

---------

Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: Yuval <yuvalbl@users.noreply.github.com>
Co-authored-by: Marijn van der Werf <marijn.vanderwerf@gmail.com>
Co-authored-by: Eyal Toledano <eutait@gmail.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-06-23 08:54:29 +03:00
Riccardo (Ricky) Esclapon
eb8a3a85a1 Update SWE scores (#657) 2025-06-23 08:52:35 +03:00
Joe Danziger
59a4ec9e1a Default to Cursor profile for MCP init when no rules specified (#846) 2025-06-22 21:24:09 +02:00
github-actions[bot]
ef1deec947 Version Packages (#842) 2025-06-22 00:00:00 +03:00
Ralph Khreish
b40139ca05 Release 0.18.0 (#840)
* Update SWE scores (#657)

* docs: Auto-update and format models.md

* feat: Flexible brand rules management (#460)

* chore(docs): update docs and rules related to model management.

* feat(ai): Add OpenRouter AI provider support

Integrates the OpenRouter AI provider using the Vercel AI SDK adapter (@openrouter/ai-sdk-provider). This allows users to configure and utilize models available through the OpenRouter platform.

- Added src/ai-providers/openrouter.js with standard Vercel AI SDK wrapper functions (generateText, streamText, generateObject).

- Updated ai-services-unified.js to include the OpenRouter provider in the PROVIDER_FUNCTIONS map and API key resolution logic.

- Verified config-manager.js handles OpenRouter API key checks correctly.

- Users can configure OpenRouter models via .taskmasterconfig using the task-master models command or MCP models tool. Requires OPENROUTER_API_KEY.

- Enhanced error handling in ai-services-unified.js to provide clearer messages when generateObjectService fails due to lack of underlying tool support in the selected model/provider endpoint.

* feat(cli): Add --status/-s filter flag to show command and get-task MCP tool

Implements the ability to filter subtasks displayed by the `task-master show <id>` command using the `--status` (or `-s`) flag. This is also available in the MCP context.

- Modified `commands.js` to add the `--status` option to the `show` command definition.

- Updated `utils.js` (`findTaskById`) to handle the filtering logic and return original subtask counts/arrays when filtering.

- Updated `ui.js` (`displayTaskById`) to use the filtered subtasks for the table, display a summary line when filtering, and use the original subtask list for the progress bar calculation.

- Updated MCP `get_task` tool and `showTaskDirect` function to accept and pass the `status` parameter.

- Added changeset entry.

* fix(tasks): Improve next task logic to be subtask-aware

* fix(tasks): Enable removing multiple tasks/subtasks via comma-separated IDs

- Refactors the core `removeTask` function (`task-manager/remove-task.js`) to accept and iterate over comma-separated task/subtask IDs.

- Updates dependency cleanup and file regeneration logic to run once after processing all specified IDs.

- Adjusts the `remove-task` CLI command (`commands.js`) description and confirmation prompt to handle multiple IDs correctly.

- Fixes a bug in the CLI confirmation prompt where task/subtask titles were not being displayed correctly.

- Updates the `remove_task` MCP tool description to reflect the new multi-ID capability.

This addresses the previously known issue where only the first ID in a comma-separated list was processed.

Closes #140

* Update README.md (#342)

* Update Discord badge (#337)

* refactor(init): Improve robustness and dependencies; Update template deps for AI SDKs; Silence npm install in MCP; Improve conditional model setup logic; Refactor init.js flags; Tweak Getting Started text; Fix MCP server launch command; Update default model in config template

* Refactor: Improve MCP logging, update E2E & tests

Refactors MCP server logging and updates testing infrastructure.

- MCP Server:

  - Replaced manual logger wrappers with centralized `createLogWrapper` utility.

  - Updated direct function calls to use `{ session, mcpLog }` context.

  - Removed deprecated `model` parameter from analyze, expand-all, expand-task tools.

  - Adjusted MCP tool import paths and parameter descriptions.

- Documentation:

  - Modified `docs/configuration.md`.

  - Modified `docs/tutorial.md`.

- Testing:

  - E2E Script (`run_e2e.sh`):

    - Removed `set -e`.

    - Added LLM analysis function (`analyze_log_with_llm`) & integration.

    - Adjusted test run directory creation timing.

    - Added debug echo statements.

  - Deleted Unit Tests: Removed `ai-client-factory.test.js`, `ai-client-utils.test.js`, `ai-services.test.js`.

  - Modified Fixtures: Updated `scripts/task-complexity-report.json`.

- Dev Scripts:

  - Modified `scripts/dev.js`.

* chore(tests): Passes tests for merge candidate
- Adjusted the interactive model default choice to be 'no change' instead of 'cancel setup'
- E2E script has been perfected and works as designed provided there are all provider API keys .env in the root
- Fixes the entire test suite to make sure it passes with the new architecture.
- Fixes dependency command to properly show there is a validation failure if there is one.
- Refactored config-manager.test.js mocking strategy and fixed assertions to read the real supported-models.json
- Fixed rule-transformer.test.js assertion syntax and transformation logic adjusting replacement for search which was too broad.
- Skip unstable tests in utils.test.js (log, readJSON, writeJSON error paths) due to SIGABRT crash. These tests trigger a native crash (SIGABRT), likely stemming from a conflict between internal chalk usage within the functions and Jest's test environment, possibly related to ESM module handling.

* chore(wtf): removes chai. not sure how that even made it in here. also removes duplicate test in scripts/.

* fix: ensure API key detection properly reads .env in MCP context

Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env

Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env

Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works

* fix(update): pass projectRoot through update command flow

Modified ai-services-unified.js, update.js tool, and update-tasks.js direct function to correctly pass projectRoot. This enables the .env file API key fallback mechanism for the update command when running via MCP, ensuring consistent key resolution with the CLI context.

* fix(analyze-complexity): pass projectRoot through analyze-complexity flow

Modified analyze-task-complexity.js core function, direct function, and analyze.js tool to correctly pass projectRoot. Fixed import error in tools/index.js. Added debug logging to _resolveApiKey in ai-services-unified.js. This enables the .env API key fallback for analyze_project_complexity.

* fix(add-task): pass projectRoot and fix logging/refs

Modified add-task core, direct function, and tool to pass projectRoot for .env API key fallback. Fixed logFn reference error and removed deprecated reportProgress call in core addTask function. Verified working.

* fix(parse-prd): pass projectRoot and fix schema/logging

Modified parse-prd core, direct function, and tool to pass projectRoot for .env API key fallback. Corrected Zod schema used in generateObjectService call. Fixed logFn reference error in core parsePRD. Updated unit test mock for utils.js.

* fix(update-task): pass projectRoot and adjust parsing

Modified update-task-by-id core, direct function, and tool to pass projectRoot. Reverted parsing logic in core function to prioritize `{...}` extraction, resolving parsing errors. Fixed ReferenceError by correctly destructuring projectRoot.

* fix(update-subtask): pass projectRoot and allow updating done subtasks

Modified update-subtask-by-id core, direct function, and tool to pass projectRoot for .env API key fallback. Removed check preventing appending details to completed subtasks.

* fix(mcp, expand): pass projectRoot through expand/expand-all flows

Problem: expand_task & expand_all MCP tools failed with .env keys due to missing projectRoot propagation for API key resolution. Also fixed a ReferenceError: wasSilent is not defined in expandTaskDirect.

Solution: Modified core logic, direct functions, and MCP tools for expand-task and expand-all to correctly destructure projectRoot from arguments and pass it down through the context object to the AI service call (generateTextService). Fixed wasSilent scope in expandTaskDirect.

Verification: Tested expand_task successfully in MCP using .env keys. Reviewed expand_all flow for correct projectRoot propagation.

* chore: prettier

* fix(expand-all): add projectRoot to expandAllTasksDirect invokation.

* fix(update-tasks): Improve AI response parsing for 'update' command

Refactors the JSON array parsing logic within
in .

The previous logic primarily relied on extracting content from markdown
code blocks (json or javascript), which proved brittle when the AI
response included comments or non-JSON text within the block, leading to
parsing errors for the  command.

This change modifies the parsing strategy to first attempt extracting
content directly between the outermost '[' and ']' brackets. This is
more robust as it targets the expected array structure directly. If
bracket extraction fails, it falls back to looking for a strict json
code block, then prefix stripping, before attempting a raw parse.

This approach aligns with the successful parsing strategy used for
single-object responses in  and resolves the
parsing errors previously observed with the  command.

* refactor(mcp): introduce withNormalizedProjectRoot HOF for path normalization

Added HOF to mcp tools utils to normalize projectRoot from args/session. Refactored get-task tool to use HOF. Updated relevant documentation.

* refactor(mcp): apply withNormalizedProjectRoot HOF to update tool

Problem: The  MCP tool previously handled project root acquisition and path resolution within its  method, leading to potential inconsistencies and repetition.

Solution: Refactored the  tool () to utilize the new  Higher-Order Function (HOF) from .

Specific Changes:
- Imported  HOF.
- Updated the Zod schema for the  parameter to be optional, as the HOF handles deriving it from the session if not provided.
- Wrapped the entire  function body with the  HOF.
- Removed the manual call to  from within the  function body.
- Destructured the  from the  object received by the wrapped  function, ensuring it's the normalized path provided by the HOF.
- Used the normalized  variable when calling  and when passing arguments to .

This change standardizes project root handling for the  tool, simplifies its  method, and ensures consistent path normalization. This serves as the pattern for refactoring other MCP tools.

* fix: apply to all tools withNormalizedProjectRoot to fix projectRoot issues for linux and windows

* fix: add rest of tools that need wrapper

* chore: cleanup tools to stop using rootFolder and remove unused imports

* chore: more cleanup

* refactor: Improve update-subtask, consolidate utils, update config

This commit introduces several improvements and refactorings across MCP tools, core logic, and configuration.

**Major Changes:**

1.  **Refactor updateSubtaskById:**
    - Switched from generateTextService to generateObjectService for structured AI responses, using a Zod schema (subtaskSchema) for validation.
    - Revised prompts to have the AI generate relevant content based on user request and context (parent/sibling tasks), while explicitly preventing AI from handling timestamp/tag formatting.
    - Implemented **local timestamp generation (new Date().toISOString()) and formatting** (using <info added on ...> tags) within the function *after* receiving the AI response. This ensures reliable and correctly formatted details are appended.
    - Corrected logic to append only the locally formatted, AI-generated content block to the existing subtask.details.

2.  **Consolidate MCP Utilities:**
    - Moved/consolidated the withNormalizedProjectRoot HOF into mcp-server/src/tools/utils.js.
    - Updated MCP tools (like update-subtask.js) to import withNormalizedProjectRoot from the new location.

3.  **Refactor Project Initialization:**
    - Deleted the redundant mcp-server/src/core/direct-functions/initialize-project-direct.js file.
    - Updated mcp-server/src/core/task-master-core.js to import initializeProjectDirect from its correct location (./direct-functions/initialize-project.js).

**Other Changes:**

-   Updated .taskmasterconfig fallback model to claude-3-7-sonnet-20250219.
-   Clarified model cost representation in the models tool description (taskmaster.mdc and mcp-server/src/tools/models.js).

* fix: displayBanner logging when silentMode is active (#385)

* fix: improve error handling, test options, and model configuration

- Enhance error validation in parse-prd.js and update-tasks.js
- Fix bug where mcpLog was incorrectly passed as logWrapper
- Improve error messages and response formatting
- Add --skip-verification flag to E2E tests
- Update MCP server config that ships with init to match new API key structure
- Fix task force/append handling in parse-prd command
- Increase column width in update-tasks display

* chore: fixes parse prd to show loading indicator in cli.

* fix(parse-prd): suggested fix for mcpLog was incorrect. reverting to my previously working code.

* chore(init): No longer ships readme with task-master init (commented out for now). No longer looking for task-master-mcp, instead checked for task-master-ai - this should prevent the init sequence from needlessly adding another mcp server with task-master-mcp to the mpc.json which a ton of people probably ran into.

* chore: restores 3.7 sonnet as the main role.

* fix(add/remove-dependency): dependency mcp tools were failing due to hard-coded tasks path in generate task files.

* chore: removes tasks json backup that was temporarily created.

* fix(next): adjusts mcp tool response to correctly return the next task/subtask. Also adds nextSteps to the next task response.

* chore: prettier

* chore: readme typos

* fix(config): restores sonnet 3.7 as default main role.

* Version Packages

* hotfix: move production package to "dependencies" (#399)

* Version Packages

* Fix: issues with 0.13.0 not working (#402)

* Exit prerelease mode and version packages

* hotfix: move production package to "dependencies"

* Enter prerelease mode and version packages

* Enter prerelease mode and version packages

* chore: cleanup

* chore: improve pre.json and add pre-release workflow

* chore: fix package.json

* chore: cleanup

* chore: improve pre-release workflow

* chore: allow github actions to commit

* extract fileMap and conversionConfig into brand profile

* extract into brand profile

* add windsurf profile

* add remove brand rules function

* fix regex

* add rules command to add/remove rules for a specific brand

* fix post processing for roo

* allow multiples

* add cursor profile

* update test for new structure

* move rules to assets

* use assets/rules for rules files

* use standardized setupMCP function

* fix formatting

* fix formatting

* add logging

* fix escapes

* default to cursor

* allow init with certain rulesets; no more .windsurfrules

* update docs

* update log msg

* fix formatting

* keep mdc extension for cursor

* don't rewrite .mdc to .md inside the files

* fix roo init (add modes)

* fix cursor init (don't use roo transformation by default)

* use more generic function names

* update docs

* fix formatting

* update function names

* add changeset

* add rules to mcp initialize project

* register tool with mcp server

* update docs

* add integration test

* fix cursor initialization

* rule selection

* fix formatting

* fix MCP - remove yes flag

* add import

* update roo tests

* add/update tests

* remove test

* add rules command test

* update MCP responses, centralize rules profiles & helpers

* fix logging and MCP response messages

* fix formatting

* incorrect test

* fix tests

* update fileMap

* fix file extension transformations

* fix formatting

* add rules command test

* test already covered

* fix formatting

* move renaming logic into profiles

* make sure dir is deleted (DS_Store)

* add confirmation for rules removal

* add force flag for rules remove

* use force flag for test

* remove yes parameter

* fix formatting

* import brand profiles from rule-transformer.js

* update comment

* add interactive rules setup

* optimize

* only copy rules specifically listed in fileMap

* update comment

* add cline profile

* add brandDir to remove ambiguity and support Cline

* specify whether to create mcp config and filename

* add mcpConfigName value for parh

* fix formatting

* remove rules just for this repository - only include rules to be distributed

* update error message

* update "brand rules" to "rules"

* update to minor

* remove comment

* remove comments

* move to /src/utils

* optimize imports

* move rules-setup.js to /src/utils

* move rule-transformer.js to /src/utils

* move confirmation to /src/ui/confirm.js

* default to all rules

* use profile js for mcp config settings

* only run rules interactive setup if not provided via command line

* update comments

* initialize with all brands if nothing specified

* update var name

* clean up

* enumerate brands for brand rules

* update instructions

* add test to check for brand profiles

* fix quotes

* update semantics and terminology from 'brand rules' to 'rules profiles'

* fix formatting

* fix formatting

* update function name and remove copying of cursor rules, now handled by rules transformer

* update comment

* rename to mcp-config-setup.js

* use enums for rules actions

* add aggregate reporting for rules add command

* add missing log message

* use simpler path

* use base profile with modifications for each brand

* use displayName and don't select any defaults in setup

* add confirmation if removing ALL rules profiles, and add --force flag on rules remove

* Use profile-detection instead of rules-detection

* add newline at end of mcp config

* add proper formatting for mcp.json

* update rules

* update rules

* update rules

* add checks for other rules and other profile folder items before removing

* update confirmation for rules remove

* update docs

* update changeset

* fix for filepath at bottom of rule

* Update cline profile and add test; adjust other rules tests

* update changeset

* update changeset

* clarify init for all profiles if not specified

* update rule text

* revert text

* use "rule profiles" instead of "rules profiles"

* use standard tool mappings for windsurf

* add Trae support

* update changeset

* update wording

* update to 'rule profile'

* remove unneeded exports to optimize loc

* combine to /src/utils/profiles.js; add codex and claude code profiles

* rename function and add boxen

* add claude and codex integration tests

* organize tests into profiles folder

* mock fs for transformer tests

* update UI

* add cline and trae integration tests

* update test

* update function name

* update formatting

* Update change set with new profiles

* move profile integration tests to subdirectory

* properly create temp directories in /tmp folder

* fix formatting

* use taskmaster subfolder for the 2 TM rules

* update wording

* ensure subdirectory exists

* update rules from next

* update from next

* update taskmaster rule

* add details on new rules command and init

* fix mcp init

* fix MCP path to assets

* remove duplication

* remove duplication

* MCP server path fixes for rules command

* fix for CLI roo rules add/remove

* update tests

* fix formatting

* fix pattern for interactive rule profiles setup

* restore comments

* restore comments

* restore comments

* remove unused import, fix quotes

* add missing integration tests

* add VS Code profile and tests

* update docs and rules to include vscode profile

* add rules subdirectory support per-profile

* move profiles to /src

* fix formatting

* rename to remove ambiguity

* use --setup for rules interactive setup

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* change roo boomerang to orchestrator; update tests that don't use modes

* fix newline

* chore: cleanup

---------

Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: Yuval <yuvalbl@users.noreply.github.com>
Co-authored-by: Marijn van der Werf <marijn.vanderwerf@gmail.com>
Co-authored-by: Eyal Toledano <eutait@gmail.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix: providers config for azure, bedrock, and vertex (#822)

* fix: providers config for azure, bedrock, and vertex

* chore: improve changelog

* chore: fix CI

* fix: switch to ESM export to avoid mixed format (#633)

* fix: switch to ESM export to avoid mixed format

The CLI entrypoint was using `module.exports` alongside ESM `import` statements,
resulting in an invalid mixed module format. Replaced the CommonJS export with
a proper ESM `export` to maintain consistency and prevent module resolution issues.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* fix: Fix external provider support (#726)

* fix(bedrock): improve AWS credential handling and add model definitions (#826)

* fix(bedrock): improve AWS credential handling and add model definitions

- Change error to warning when AWS credentials are missing in environment
- Allow fallback to system configuration (aws config files or instance profiles)
- Remove hardcoded region and profile parameters in Bedrock client
- Add Claude 3.7 Sonnet and DeepSeek R1 model definitions for Bedrock
- Update config manager to properly handle Bedrock provider

* chore: cleanup and format and small refactor

---------

Co-authored-by: Ray Krueger <raykrueger@gmail.com>

* docs: Auto-update and format models.md

* Version Packages

* chore: fix package.json

* Fix/expand command tag corruption (#827)

* fix(expand): Fix tag corruption in expand command - Fix tag parameter passing through MCP expand-task flow - Add tag parameter to direct function and tool registration - Fix contextGatherer method name from _buildDependencyContext to _buildDependencyGraphs - Add comprehensive test coverage for tag handling in expand-task - Ensures tagged task structure is preserved during expansion - Prevents corruption when tag is undefined. Fixes expand command causing tag corruption in tagged task lists. All existing tests pass and new test coverage added.

* test(e2e): Add comprehensive tag-aware expand testing to verify tag corruption fix - Add new test section for feature-expand tag creation and testing - Verify tag preservation during expand, force expand, and expand --all operations - Test that master tag remains intact and feature-expand tag receives subtasks correctly - Fix file path references to use correct .taskmaster/tasks/tasks.json location - Fix config file check to use .taskmaster/config.json instead of .taskmasterconfig - All tag corruption verification tests pass successfully in E2E test

* fix(changeset): Update E2E test improvements changeset to properly reflect tag corruption fix verification

* chore(changeset): combine duplicate changesets for expand tag corruption fix

Merge eighty-breads-wonder.md into bright-llamas-enter.md to consolidate
the expand command fix and its comprehensive E2E testing enhancements
into a single changeset entry.

* Delete .changeset/eighty-breads-wonder.md

* Version Packages

* chore: fix package.json

* fix(expand): Enhance context handling in expandAllTasks function
- Added `tag` to context destructuring for better context management.
- Updated `readJSON` call to include `contextTag` for improved data integrity.
- Ensured the correct tag is passed during task expansion to prevent tag corruption.

---------

Co-authored-by: Parththipan Thaniperumkarunai <parththipan.thaniperumkarunai@milkmonkey.de>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Add pyproject.toml as project root marker (#804)

* feat: Add pyproject.toml as project root marker - Added 'pyproject.toml' to the project markers array in findProjectRoot() - Enables Task Master to recognize Python projects using pyproject.toml - Improves project root detection for modern Python development workflows - Maintains compatibility with existing Node.js and Git-based detection

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* feat: add Claude Code provider support

Implements Claude Code as a new AI provider that uses the Claude Code CLI
without requiring API keys. This enables users to leverage Claude models
through their local Claude Code installation.

Key changes:
- Add complete AI SDK v1 implementation for Claude Code provider
  - Custom SDK with streaming/non-streaming support
  - Session management for conversation continuity
  - JSON extraction for object generation mode
  - Support for advanced settings (maxTurns, allowedTools, etc.)

- Integrate Claude Code into Task Master's provider system
  - Update ai-services-unified.js to handle keyless authentication
  - Add provider to supported-models.json with opus/sonnet models
  - Ensure correct maxTokens values are applied (opus: 32000, sonnet: 64000)

- Fix maxTokens configuration issue
  - Add max_tokens property to getAvailableModels() output
  - Update setModel() to properly handle claude-code models
  - Create update-config-tokens.js utility for init process

- Add comprehensive documentation
  - User guide with configuration examples
  - Advanced settings explanation and future integration options

The implementation maintains full backward compatibility with existing
providers while adding seamless Claude Code support to all Task Master
commands.

* fix(docs): correct invalid commands in claude-code usage examples

- Remove non-existent 'do', 'estimate', and 'analyze' commands
- Replace with actual Task Master commands: next, show, set-status
- Use correct syntax for parse-prd and analyze-complexity

* feat: make @anthropic-ai/claude-code an optional dependency

This change makes the Claude Code SDK package optional, preventing installation failures for users who don't need Claude Code functionality.

Changes:
- Added @anthropic-ai/claude-code to optionalDependencies in package.json
- Implemented lazy loading in language-model.js to only import the SDK when actually used
- Updated documentation to explain the optional installation requirement
- Applied formatting fixes to ensure code consistency

Benefits:
- Users without Claude Code subscriptions don't need to install the dependency
- Reduces package size for users who don't use Claude Code
- Prevents installation failures if the package is unavailable
- Provides clear error messages when the package is needed but not installed

The implementation uses dynamic imports to load the SDK only when doGenerate() or doStream() is called, ensuring the provider can be instantiated without the package present.

* test: add comprehensive tests for ClaudeCodeProvider

Addresses code review feedback about missing automated tests for the ClaudeCodeProvider.

## Changes

- Added unit tests for ClaudeCodeProvider class covering constructor, validateAuth, and getClient methods
- Added unit tests for ClaudeCodeLanguageModel testing lazy loading behavior and error handling
- Added integration tests verifying optional dependency behavior when @anthropic-ai/claude-code is not installed

## Test Coverage

1. **Unit Tests**:
   - ClaudeCodeProvider: Basic functionality, no API key requirement, client creation
   - ClaudeCodeLanguageModel: Model initialization, lazy loading, error messages, warning generation

2. **Integration Tests**:
   - Optional dependency behavior when package is not installed
   - Clear error messages for users about missing package
   - Provider instantiation works but usage fails gracefully

All tests pass and provide comprehensive coverage for the claude-code provider implementation.

* revert: remove maxTokens update functionality from init

This functionality was out of scope for the Claude Code provider PR.
The automatic updating of maxTokens values in config.json during
initialization is a general improvement that should be in a separate PR.

Additionally, Claude Code ignores maxTokens and temperature parameters
anyway, making this change irrelevant for the Claude Code integration.

Removed:
- scripts/modules/update-config-tokens.js
- Import and usage in scripts/init.js

* docs: add Claude Code support information to README

- Added Claude Code to the list of supported providers in Requirements section
- Noted that Claude Code requires no API key but needs Claude Code CLI
- Added example of configuring claude-code/sonnet model
- Created dedicated Claude Code Support section with key information
- Added link to detailed Claude Code setup documentation

This ensures users are aware of the Claude Code option as a no-API-key
alternative for using Claude models.

* style: apply biome formatting to test files

* fix(models): add missing --claude-code flag to models command

The models command was missing the --claude-code provider flag, preventing users from setting Claude Code models via CLI. While the backend already supported claude-code as a provider hint, there was no command-line flag to trigger it.

Changes:
- Added --claude-code option to models command alongside existing provider flags
- Updated provider flags validation to include claudeCode option
- Added claude-code to providerHint logic for all three model roles (main, research, fallback)
- Updated error message to include --claude-code in list of mutually exclusive flags
- Added example usage in help text

This allows users to properly set Claude Code models using commands like:
  task-master models --set-main sonnet --claude-code
  task-master models --set-main opus --claude-code

Without this flag, users would get "Model ID not found" errors when trying to set claude-code models, as the system couldn't determine the correct provider for generic model names like "sonnet" or "opus".

* chore: add changeset for Claude Code provider feature

* docs: Auto-update and format models.md

* readme: add troubleshooting note for MCP tools not working

* Feature/compatibleapisupport (#830)

* add compatible platform api support

* Adjust the code according to the suggestions

* Fully revised as requested: restored all required checks, improved compatibility, and converted all comments to English.

* feat: Add support for compatible API endpoints via baseURL

* chore: Add changeset for compatible API support

* chore: cleanup

* chore: improve changeset

* fix: package-lock.json

* fix: package-lock.json

---------

Co-authored-by: He-Xun <1226807142@qq.com>

* Rename Roo Code "Boomerang" role to "Orchestrator" (#831)

* feat: Enhanced project initialization with Git worktree detection (#743)

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* detect git worktree

* add changeset

* add aliases and git flags

* add changeset

* rename and update test

* add store tasks in git functionality

* update changeset

* fix newline

* remove unused import

* update command wording

* update command option text

* fix: update task by id (#834)

* store tasks in git by default (#835)

* Call rules interactive setup during init (#833)

* chore: rc version bump

* feat: Claude Code slash commands for Task Master (#774)

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* fix: expand-task (#755)

* docs: Update o3 model price (#751)

* docs: Auto-update and format models.md

* docs: Auto-update and format models.md

* feat: Add Claude Code task master commands

Adds Task Master slash commands for Claude Code under /project:tm/ namespace

---------

Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Volodymyr Zahorniak <7808206+zahorniak@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>

* feat: make more compatible with "o" family models (#839)

* docs: Auto-update and format models.md

* docs: Add comprehensive Azure OpenAI configuration documentation (#837)

* docs: Add comprehensive Azure OpenAI configuration documentation

- Add detailed Azure OpenAI configuration section with prerequisites, authentication, and setup options
- Include both global and per-model baseURL configuration examples
- Add comprehensive troubleshooting guide for common Azure OpenAI issues
- Update environment variables section with Azure OpenAI examples
- Add Azure OpenAI models to all model tables (Main, Research, Fallback)
- Include prominent Azure configuration example in main documentation
- Fix azureBaseURL format to use correct Azure OpenAI endpoint structure

Addresses common Azure OpenAI setup challenges and provides clear guidance for new users.

* refactor: Move Azure models from docs/models.md to scripts/modules/supported-models.json

- Remove Azure model entries from documentation tables
- Add Azure provider section to supported-models.json with gpt-4o, gpt-4o-mini, and gpt-4-1
- Maintain consistency with existing model configuration structure

* docs: Auto-update and format models.md

* Version Packages

* chore: format fix

---------

Co-authored-by: Riccardo (Ricky) Esclapon <32306488+ries9112@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: Yuval <yuvalbl@users.noreply.github.com>
Co-authored-by: Marijn van der Werf <marijn.vanderwerf@gmail.com>
Co-authored-by: Eyal Toledano <eutait@gmail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Nathan Marley <nathan@glowberrylabs.com>
Co-authored-by: Ray Krueger <raykrueger@gmail.com>
Co-authored-by: Parththipan Thaniperumkarunai <parththipan.thaniperumkarunai@milkmonkey.de>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: ejones40 <ethan.jones@fortyau.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
Co-authored-by: V4G4X <34249137+V4G4X@users.noreply.github.com>
Co-authored-by: He-Xun <1226807142@qq.com>
Co-authored-by: neno <github@meaning.systems>
Co-authored-by: Volodymyr Zahorniak <7808206+zahorniak@users.noreply.github.com>
Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
Co-authored-by: Jitesh Thakur <56656484+Jitha-afk@users.noreply.github.com>
2025-06-21 13:54:17 -07:00
Ralph Khreish
403d7b00ca chore: format fix 2025-06-21 23:35:23 +03:00
Ralph Khreish
b78614b44e Merge branch 'main' into next 2025-06-21 23:02:17 +03:00
github-actions[bot]
19d795d63f Version Packages 2025-06-21 23:01:03 +03:00
github-actions[bot]
07ec89ab17 docs: Auto-update and format models.md 2025-06-21 19:50:31 +00:00
Jitesh Thakur
eaa7f24280 docs: Add comprehensive Azure OpenAI configuration documentation (#837)
* docs: Add comprehensive Azure OpenAI configuration documentation

- Add detailed Azure OpenAI configuration section with prerequisites, authentication, and setup options
- Include both global and per-model baseURL configuration examples
- Add comprehensive troubleshooting guide for common Azure OpenAI issues
- Update environment variables section with Azure OpenAI examples
- Add Azure OpenAI models to all model tables (Main, Research, Fallback)
- Include prominent Azure configuration example in main documentation
- Fix azureBaseURL format to use correct Azure OpenAI endpoint structure

Addresses common Azure OpenAI setup challenges and provides clear guidance for new users.

* refactor: Move Azure models from docs/models.md to scripts/modules/supported-models.json

- Remove Azure model entries from documentation tables
- Add Azure provider section to supported-models.json with gpt-4o, gpt-4o-mini, and gpt-4-1
- Maintain consistency with existing model configuration structure
2025-06-21 21:50:20 +02:00
github-actions[bot]
b3d43c5992 docs: Auto-update and format models.md 2025-06-21 19:50:10 +00:00
Ralph Khreish
c5de4f8b68 feat: make more compatible with "o" family models (#839) 2025-06-21 21:50:00 +02:00
neno
b9299c5af0 feat: Claude Code slash commands for Task Master (#774)
* Fix Cursor deeplink installation with copy-paste instructions (#723)

* fix: expand-task (#755)

* docs: Update o3 model price (#751)

* docs: Auto-update and format models.md

* docs: Auto-update and format models.md

* feat: Add Claude Code task master commands

Adds Task Master slash commands for Claude Code under /project:tm/ namespace

---------

Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Volodymyr Zahorniak <7808206+zahorniak@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
2025-06-21 20:48:20 +02:00
github-actions[bot]
122a0465d8 chore: rc version bump 2025-06-21 02:43:13 +00:00
Joe Danziger
cf2c06697a Call rules interactive setup during init (#833) 2025-06-20 22:05:25 +02:00
Joe Danziger
727f1ec4eb store tasks in git by default (#835) 2025-06-20 18:49:38 +02:00
Ralph Khreish
648353794e fix: update task by id (#834) 2025-06-20 18:11:17 +02:00
Joe Danziger
a2a3229fd0 feat: Enhanced project initialization with Git worktree detection (#743)
* Fix Cursor deeplink installation with copy-paste instructions (#723)

* detect git worktree

* add changeset

* add aliases and git flags

* add changeset

* rename and update test

* add store tasks in git functionality

* update changeset

* fix newline

* remove unused import

* update command wording

* update command option text
2025-06-20 17:58:50 +02:00
Joe Danziger
b592dff8bc Rename Roo Code "Boomerang" role to "Orchestrator" (#831) 2025-06-20 17:20:14 +03:00
Ralph Khreish
e9d1bc2385 Feature/compatibleapisupport (#830)
* add compatible platform api support

* Adjust the code according to the suggestions

* Fully revised as requested: restored all required checks, improved compatibility, and converted all comments to English.

* feat: Add support for compatible API endpoints via baseURL

* chore: Add changeset for compatible API support

* chore: cleanup

* chore: improve changeset

* fix: package-lock.json

* fix: package-lock.json

---------

Co-authored-by: He-Xun <1226807142@qq.com>
2025-06-20 16:18:03 +02:00
V4G4X
030694bb96 readme: add troubleshooting note for MCP tools not working 2025-06-20 15:28:00 +02:00
github-actions[bot]
3e0f696c49 docs: Auto-update and format models.md 2025-06-20 13:25:33 +00:00
Ben Vargas
4b0c9d9af6 chore: add changeset for Claude Code provider feature 2025-06-20 16:25:22 +03:00
Ben Vargas
3fa91f56e5 fix(models): add missing --claude-code flag to models command
The models command was missing the --claude-code provider flag, preventing users from setting Claude Code models via CLI. While the backend already supported claude-code as a provider hint, there was no command-line flag to trigger it.

Changes:
- Added --claude-code option to models command alongside existing provider flags
- Updated provider flags validation to include claudeCode option
- Added claude-code to providerHint logic for all three model roles (main, research, fallback)
- Updated error message to include --claude-code in list of mutually exclusive flags
- Added example usage in help text

This allows users to properly set Claude Code models using commands like:
  task-master models --set-main sonnet --claude-code
  task-master models --set-main opus --claude-code

Without this flag, users would get "Model ID not found" errors when trying to set claude-code models, as the system couldn't determine the correct provider for generic model names like "sonnet" or "opus".
2025-06-20 16:25:22 +03:00
Ben Vargas
e69ac5d5cf style: apply biome formatting to test files 2025-06-20 16:25:22 +03:00
Ben Vargas
c60c9354a4 docs: add Claude Code support information to README
- Added Claude Code to the list of supported providers in Requirements section
- Noted that Claude Code requires no API key but needs Claude Code CLI
- Added example of configuring claude-code/sonnet model
- Created dedicated Claude Code Support section with key information
- Added link to detailed Claude Code setup documentation

This ensures users are aware of the Claude Code option as a no-API-key
alternative for using Claude models.
2025-06-20 16:25:22 +03:00
Ben Vargas
30b895be2c revert: remove maxTokens update functionality from init
This functionality was out of scope for the Claude Code provider PR.
The automatic updating of maxTokens values in config.json during
initialization is a general improvement that should be in a separate PR.

Additionally, Claude Code ignores maxTokens and temperature parameters
anyway, making this change irrelevant for the Claude Code integration.

Removed:
- scripts/modules/update-config-tokens.js
- Import and usage in scripts/init.js
2025-06-20 16:25:22 +03:00
Ben Vargas
9995075093 test: add comprehensive tests for ClaudeCodeProvider
Addresses code review feedback about missing automated tests for the ClaudeCodeProvider.

## Changes

- Added unit tests for ClaudeCodeProvider class covering constructor, validateAuth, and getClient methods
- Added unit tests for ClaudeCodeLanguageModel testing lazy loading behavior and error handling
- Added integration tests verifying optional dependency behavior when @anthropic-ai/claude-code is not installed

## Test Coverage

1. **Unit Tests**:
   - ClaudeCodeProvider: Basic functionality, no API key requirement, client creation
   - ClaudeCodeLanguageModel: Model initialization, lazy loading, error messages, warning generation

2. **Integration Tests**:
   - Optional dependency behavior when package is not installed
   - Clear error messages for users about missing package
   - Provider instantiation works but usage fails gracefully

All tests pass and provide comprehensive coverage for the claude-code provider implementation.
2025-06-20 16:25:22 +03:00
Ben Vargas
b62cb1bbe7 feat: make @anthropic-ai/claude-code an optional dependency
This change makes the Claude Code SDK package optional, preventing installation failures for users who don't need Claude Code functionality.

Changes:
- Added @anthropic-ai/claude-code to optionalDependencies in package.json
- Implemented lazy loading in language-model.js to only import the SDK when actually used
- Updated documentation to explain the optional installation requirement
- Applied formatting fixes to ensure code consistency

Benefits:
- Users without Claude Code subscriptions don't need to install the dependency
- Reduces package size for users who don't use Claude Code
- Prevents installation failures if the package is unavailable
- Provides clear error messages when the package is needed but not installed

The implementation uses dynamic imports to load the SDK only when doGenerate() or doStream() is called, ensuring the provider can be instantiated without the package present.
2025-06-20 16:25:22 +03:00
Ben Vargas
7defcba465 fix(docs): correct invalid commands in claude-code usage examples
- Remove non-existent 'do', 'estimate', and 'analyze' commands
- Replace with actual Task Master commands: next, show, set-status
- Use correct syntax for parse-prd and analyze-complexity
2025-06-20 16:25:22 +03:00
Ben Vargas
3e838ed34b feat: add Claude Code provider support
Implements Claude Code as a new AI provider that uses the Claude Code CLI
without requiring API keys. This enables users to leverage Claude models
through their local Claude Code installation.

Key changes:
- Add complete AI SDK v1 implementation for Claude Code provider
  - Custom SDK with streaming/non-streaming support
  - Session management for conversation continuity
  - JSON extraction for object generation mode
  - Support for advanced settings (maxTurns, allowedTools, etc.)

- Integrate Claude Code into Task Master's provider system
  - Update ai-services-unified.js to handle keyless authentication
  - Add provider to supported-models.json with opus/sonnet models
  - Ensure correct maxTokens values are applied (opus: 32000, sonnet: 64000)

- Fix maxTokens configuration issue
  - Add max_tokens property to getAvailableModels() output
  - Update setModel() to properly handle claude-code models
  - Create update-config-tokens.js utility for init process

- Add comprehensive documentation
  - User guide with configuration examples
  - Advanced settings explanation and future integration options

The implementation maintains full backward compatibility with existing
providers while adding seamless Claude Code support to all Task Master
commands.
2025-06-20 16:25:22 +03:00
ejones40
1b8c320c57 Add pyproject.toml as project root marker (#804)
* feat: Add pyproject.toml as project root marker - Added 'pyproject.toml' to the project markers array in findProjectRoot() - Enables Task Master to recognize Python projects using pyproject.toml - Improves project root detection for modern Python development workflows - Maintains compatibility with existing Node.js and Git-based detection

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-20 15:15:13 +02:00
Ralph Khreish
5da5b59bde Fix/expand command tag corruption (#827)
* fix(expand): Fix tag corruption in expand command - Fix tag parameter passing through MCP expand-task flow - Add tag parameter to direct function and tool registration - Fix contextGatherer method name from _buildDependencyContext to _buildDependencyGraphs - Add comprehensive test coverage for tag handling in expand-task - Ensures tagged task structure is preserved during expansion - Prevents corruption when tag is undefined. Fixes expand command causing tag corruption in tagged task lists. All existing tests pass and new test coverage added.

* test(e2e): Add comprehensive tag-aware expand testing to verify tag corruption fix - Add new test section for feature-expand tag creation and testing - Verify tag preservation during expand, force expand, and expand --all operations - Test that master tag remains intact and feature-expand tag receives subtasks correctly - Fix file path references to use correct .taskmaster/tasks/tasks.json location - Fix config file check to use .taskmaster/config.json instead of .taskmasterconfig - All tag corruption verification tests pass successfully in E2E test

* fix(changeset): Update E2E test improvements changeset to properly reflect tag corruption fix verification

* chore(changeset): combine duplicate changesets for expand tag corruption fix

Merge eighty-breads-wonder.md into bright-llamas-enter.md to consolidate
the expand command fix and its comprehensive E2E testing enhancements
into a single changeset entry.

* Delete .changeset/eighty-breads-wonder.md

* Version Packages

* chore: fix package.json

* fix(expand): Enhance context handling in expandAllTasks function
- Added `tag` to context destructuring for better context management.
- Updated `readJSON` call to include `contextTag` for improved data integrity.
- Ensured the correct tag is passed during task expansion to prevent tag corruption.

---------

Co-authored-by: Parththipan Thaniperumkarunai <parththipan.thaniperumkarunai@milkmonkey.de>
Co-authored-by: Parthy <52548018+mm-parthy@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-06-20 15:12:40 +02:00
Ralph Khreish
04f44a2d3d chore: fix package.json 2025-06-20 16:10:52 +03:00
github-actions[bot]
36fe838fd5 Version Packages 2025-06-20 16:10:52 +03:00
github-actions[bot]
415b1835d4 docs: Auto-update and format models.md 2025-06-20 13:05:31 +00:00
Ralph Khreish
78112277b3 fix(bedrock): improve AWS credential handling and add model definitions (#826)
* fix(bedrock): improve AWS credential handling and add model definitions

- Change error to warning when AWS credentials are missing in environment
- Allow fallback to system configuration (aws config files or instance profiles)
- Remove hardcoded region and profile parameters in Bedrock client
- Add Claude 3.7 Sonnet and DeepSeek R1 model definitions for Bedrock
- Update config manager to properly handle Bedrock provider

* chore: cleanup and format and small refactor

---------

Co-authored-by: Ray Krueger <raykrueger@gmail.com>
2025-06-20 15:05:20 +02:00
Ralph Khreish
2bb4260966 fix: Fix external provider support (#726) 2025-06-20 14:59:53 +02:00
Nathan Marley
3a2325a963 fix: switch to ESM export to avoid mixed format (#633)
* fix: switch to ESM export to avoid mixed format

The CLI entrypoint was using `module.exports` alongside ESM `import` statements,
resulting in an invalid mixed module format. Replaced the CommonJS export with
a proper ESM `export` to maintain consistency and prevent module resolution issues.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-20 14:12:36 +02:00
Ralph Khreish
1bd6d4f246 fix: providers config for azure, bedrock, and vertex (#822)
* fix: providers config for azure, bedrock, and vertex

* chore: improve changelog

* chore: fix CI
2025-06-20 13:13:53 +02:00
Joe Danziger
a09a2d0967 feat: Flexible brand rules management (#460)
* chore(docs): update docs and rules related to model management.

* feat(ai): Add OpenRouter AI provider support

Integrates the OpenRouter AI provider using the Vercel AI SDK adapter (@openrouter/ai-sdk-provider). This allows users to configure and utilize models available through the OpenRouter platform.

- Added src/ai-providers/openrouter.js with standard Vercel AI SDK wrapper functions (generateText, streamText, generateObject).

- Updated ai-services-unified.js to include the OpenRouter provider in the PROVIDER_FUNCTIONS map and API key resolution logic.

- Verified config-manager.js handles OpenRouter API key checks correctly.

- Users can configure OpenRouter models via .taskmasterconfig using the task-master models command or MCP models tool. Requires OPENROUTER_API_KEY.

- Enhanced error handling in ai-services-unified.js to provide clearer messages when generateObjectService fails due to lack of underlying tool support in the selected model/provider endpoint.

* feat(cli): Add --status/-s filter flag to show command and get-task MCP tool

Implements the ability to filter subtasks displayed by the `task-master show <id>` command using the `--status` (or `-s`) flag. This is also available in the MCP context.

- Modified `commands.js` to add the `--status` option to the `show` command definition.

- Updated `utils.js` (`findTaskById`) to handle the filtering logic and return original subtask counts/arrays when filtering.

- Updated `ui.js` (`displayTaskById`) to use the filtered subtasks for the table, display a summary line when filtering, and use the original subtask list for the progress bar calculation.

- Updated MCP `get_task` tool and `showTaskDirect` function to accept and pass the `status` parameter.

- Added changeset entry.

* fix(tasks): Improve next task logic to be subtask-aware

* fix(tasks): Enable removing multiple tasks/subtasks via comma-separated IDs

- Refactors the core `removeTask` function (`task-manager/remove-task.js`) to accept and iterate over comma-separated task/subtask IDs.

- Updates dependency cleanup and file regeneration logic to run once after processing all specified IDs.

- Adjusts the `remove-task` CLI command (`commands.js`) description and confirmation prompt to handle multiple IDs correctly.

- Fixes a bug in the CLI confirmation prompt where task/subtask titles were not being displayed correctly.

- Updates the `remove_task` MCP tool description to reflect the new multi-ID capability.

This addresses the previously known issue where only the first ID in a comma-separated list was processed.

Closes #140

* Update README.md (#342)

* Update Discord badge (#337)

* refactor(init): Improve robustness and dependencies; Update template deps for AI SDKs; Silence npm install in MCP; Improve conditional model setup logic; Refactor init.js flags; Tweak Getting Started text; Fix MCP server launch command; Update default model in config template

* Refactor: Improve MCP logging, update E2E & tests

Refactors MCP server logging and updates testing infrastructure.

- MCP Server:

  - Replaced manual logger wrappers with centralized `createLogWrapper` utility.

  - Updated direct function calls to use `{ session, mcpLog }` context.

  - Removed deprecated `model` parameter from analyze, expand-all, expand-task tools.

  - Adjusted MCP tool import paths and parameter descriptions.

- Documentation:

  - Modified `docs/configuration.md`.

  - Modified `docs/tutorial.md`.

- Testing:

  - E2E Script (`run_e2e.sh`):

    - Removed `set -e`.

    - Added LLM analysis function (`analyze_log_with_llm`) & integration.

    - Adjusted test run directory creation timing.

    - Added debug echo statements.

  - Deleted Unit Tests: Removed `ai-client-factory.test.js`, `ai-client-utils.test.js`, `ai-services.test.js`.

  - Modified Fixtures: Updated `scripts/task-complexity-report.json`.

- Dev Scripts:

  - Modified `scripts/dev.js`.

* chore(tests): Passes tests for merge candidate
- Adjusted the interactive model default choice to be 'no change' instead of 'cancel setup'
- E2E script has been perfected and works as designed provided there are all provider API keys .env in the root
- Fixes the entire test suite to make sure it passes with the new architecture.
- Fixes dependency command to properly show there is a validation failure if there is one.
- Refactored config-manager.test.js mocking strategy and fixed assertions to read the real supported-models.json
- Fixed rule-transformer.test.js assertion syntax and transformation logic adjusting replacement for search which was too broad.
- Skip unstable tests in utils.test.js (log, readJSON, writeJSON error paths) due to SIGABRT crash. These tests trigger a native crash (SIGABRT), likely stemming from a conflict between internal chalk usage within the functions and Jest's test environment, possibly related to ESM module handling.

* chore(wtf): removes chai. not sure how that even made it in here. also removes duplicate test in scripts/.

* fix: ensure API key detection properly reads .env in MCP context

Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env

Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env

Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works

* fix(update): pass projectRoot through update command flow

Modified ai-services-unified.js, update.js tool, and update-tasks.js direct function to correctly pass projectRoot. This enables the .env file API key fallback mechanism for the update command when running via MCP, ensuring consistent key resolution with the CLI context.

* fix(analyze-complexity): pass projectRoot through analyze-complexity flow

Modified analyze-task-complexity.js core function, direct function, and analyze.js tool to correctly pass projectRoot. Fixed import error in tools/index.js. Added debug logging to _resolveApiKey in ai-services-unified.js. This enables the .env API key fallback for analyze_project_complexity.

* fix(add-task): pass projectRoot and fix logging/refs

Modified add-task core, direct function, and tool to pass projectRoot for .env API key fallback. Fixed logFn reference error and removed deprecated reportProgress call in core addTask function. Verified working.

* fix(parse-prd): pass projectRoot and fix schema/logging

Modified parse-prd core, direct function, and tool to pass projectRoot for .env API key fallback. Corrected Zod schema used in generateObjectService call. Fixed logFn reference error in core parsePRD. Updated unit test mock for utils.js.

* fix(update-task): pass projectRoot and adjust parsing

Modified update-task-by-id core, direct function, and tool to pass projectRoot. Reverted parsing logic in core function to prioritize `{...}` extraction, resolving parsing errors. Fixed ReferenceError by correctly destructuring projectRoot.

* fix(update-subtask): pass projectRoot and allow updating done subtasks

Modified update-subtask-by-id core, direct function, and tool to pass projectRoot for .env API key fallback. Removed check preventing appending details to completed subtasks.

* fix(mcp, expand): pass projectRoot through expand/expand-all flows

Problem: expand_task & expand_all MCP tools failed with .env keys due to missing projectRoot propagation for API key resolution. Also fixed a ReferenceError: wasSilent is not defined in expandTaskDirect.

Solution: Modified core logic, direct functions, and MCP tools for expand-task and expand-all to correctly destructure projectRoot from arguments and pass it down through the context object to the AI service call (generateTextService). Fixed wasSilent scope in expandTaskDirect.

Verification: Tested expand_task successfully in MCP using .env keys. Reviewed expand_all flow for correct projectRoot propagation.

* chore: prettier

* fix(expand-all): add projectRoot to expandAllTasksDirect invokation.

* fix(update-tasks): Improve AI response parsing for 'update' command

Refactors the JSON array parsing logic within
in .

The previous logic primarily relied on extracting content from markdown
code blocks (json or javascript), which proved brittle when the AI
response included comments or non-JSON text within the block, leading to
parsing errors for the  command.

This change modifies the parsing strategy to first attempt extracting
content directly between the outermost '[' and ']' brackets. This is
more robust as it targets the expected array structure directly. If
bracket extraction fails, it falls back to looking for a strict json
code block, then prefix stripping, before attempting a raw parse.

This approach aligns with the successful parsing strategy used for
single-object responses in  and resolves the
parsing errors previously observed with the  command.

* refactor(mcp): introduce withNormalizedProjectRoot HOF for path normalization

Added HOF to mcp tools utils to normalize projectRoot from args/session. Refactored get-task tool to use HOF. Updated relevant documentation.

* refactor(mcp): apply withNormalizedProjectRoot HOF to update tool

Problem: The  MCP tool previously handled project root acquisition and path resolution within its  method, leading to potential inconsistencies and repetition.

Solution: Refactored the  tool () to utilize the new  Higher-Order Function (HOF) from .

Specific Changes:
- Imported  HOF.
- Updated the Zod schema for the  parameter to be optional, as the HOF handles deriving it from the session if not provided.
- Wrapped the entire  function body with the  HOF.
- Removed the manual call to  from within the  function body.
- Destructured the  from the  object received by the wrapped  function, ensuring it's the normalized path provided by the HOF.
- Used the normalized  variable when calling  and when passing arguments to .

This change standardizes project root handling for the  tool, simplifies its  method, and ensures consistent path normalization. This serves as the pattern for refactoring other MCP tools.

* fix: apply to all tools withNormalizedProjectRoot to fix projectRoot issues for linux and windows

* fix: add rest of tools that need wrapper

* chore: cleanup tools to stop using rootFolder and remove unused imports

* chore: more cleanup

* refactor: Improve update-subtask, consolidate utils, update config

This commit introduces several improvements and refactorings across MCP tools, core logic, and configuration.

**Major Changes:**

1.  **Refactor updateSubtaskById:**
    - Switched from generateTextService to generateObjectService for structured AI responses, using a Zod schema (subtaskSchema) for validation.
    - Revised prompts to have the AI generate relevant content based on user request and context (parent/sibling tasks), while explicitly preventing AI from handling timestamp/tag formatting.
    - Implemented **local timestamp generation (new Date().toISOString()) and formatting** (using <info added on ...> tags) within the function *after* receiving the AI response. This ensures reliable and correctly formatted details are appended.
    - Corrected logic to append only the locally formatted, AI-generated content block to the existing subtask.details.

2.  **Consolidate MCP Utilities:**
    - Moved/consolidated the withNormalizedProjectRoot HOF into mcp-server/src/tools/utils.js.
    - Updated MCP tools (like update-subtask.js) to import withNormalizedProjectRoot from the new location.

3.  **Refactor Project Initialization:**
    - Deleted the redundant mcp-server/src/core/direct-functions/initialize-project-direct.js file.
    - Updated mcp-server/src/core/task-master-core.js to import initializeProjectDirect from its correct location (./direct-functions/initialize-project.js).

**Other Changes:**

-   Updated .taskmasterconfig fallback model to claude-3-7-sonnet-20250219.
-   Clarified model cost representation in the models tool description (taskmaster.mdc and mcp-server/src/tools/models.js).

* fix: displayBanner logging when silentMode is active (#385)

* fix: improve error handling, test options, and model configuration

- Enhance error validation in parse-prd.js and update-tasks.js
- Fix bug where mcpLog was incorrectly passed as logWrapper
- Improve error messages and response formatting
- Add --skip-verification flag to E2E tests
- Update MCP server config that ships with init to match new API key structure
- Fix task force/append handling in parse-prd command
- Increase column width in update-tasks display

* chore: fixes parse prd to show loading indicator in cli.

* fix(parse-prd): suggested fix for mcpLog was incorrect. reverting to my previously working code.

* chore(init): No longer ships readme with task-master init (commented out for now). No longer looking for task-master-mcp, instead checked for task-master-ai - this should prevent the init sequence from needlessly adding another mcp server with task-master-mcp to the mpc.json which a ton of people probably ran into.

* chore: restores 3.7 sonnet as the main role.

* fix(add/remove-dependency): dependency mcp tools were failing due to hard-coded tasks path in generate task files.

* chore: removes tasks json backup that was temporarily created.

* fix(next): adjusts mcp tool response to correctly return the next task/subtask. Also adds nextSteps to the next task response.

* chore: prettier

* chore: readme typos

* fix(config): restores sonnet 3.7 as default main role.

* Version Packages

* hotfix: move production package to "dependencies" (#399)

* Version Packages

* Fix: issues with 0.13.0 not working (#402)

* Exit prerelease mode and version packages

* hotfix: move production package to "dependencies"

* Enter prerelease mode and version packages

* Enter prerelease mode and version packages

* chore: cleanup

* chore: improve pre.json and add pre-release workflow

* chore: fix package.json

* chore: cleanup

* chore: improve pre-release workflow

* chore: allow github actions to commit

* extract fileMap and conversionConfig into brand profile

* extract into brand profile

* add windsurf profile

* add remove brand rules function

* fix regex

* add rules command to add/remove rules for a specific brand

* fix post processing for roo

* allow multiples

* add cursor profile

* update test for new structure

* move rules to assets

* use assets/rules for rules files

* use standardized setupMCP function

* fix formatting

* fix formatting

* add logging

* fix escapes

* default to cursor

* allow init with certain rulesets; no more .windsurfrules

* update docs

* update log msg

* fix formatting

* keep mdc extension for cursor

* don't rewrite .mdc to .md inside the files

* fix roo init (add modes)

* fix cursor init (don't use roo transformation by default)

* use more generic function names

* update docs

* fix formatting

* update function names

* add changeset

* add rules to mcp initialize project

* register tool with mcp server

* update docs

* add integration test

* fix cursor initialization

* rule selection

* fix formatting

* fix MCP - remove yes flag

* add import

* update roo tests

* add/update tests

* remove test

* add rules command test

* update MCP responses, centralize rules profiles & helpers

* fix logging and MCP response messages

* fix formatting

* incorrect test

* fix tests

* update fileMap

* fix file extension transformations

* fix formatting

* add rules command test

* test already covered

* fix formatting

* move renaming logic into profiles

* make sure dir is deleted (DS_Store)

* add confirmation for rules removal

* add force flag for rules remove

* use force flag for test

* remove yes parameter

* fix formatting

* import brand profiles from rule-transformer.js

* update comment

* add interactive rules setup

* optimize

* only copy rules specifically listed in fileMap

* update comment

* add cline profile

* add brandDir to remove ambiguity and support Cline

* specify whether to create mcp config and filename

* add mcpConfigName value for parh

* fix formatting

* remove rules just for this repository - only include rules to be distributed

* update error message

* update "brand rules" to "rules"

* update to minor

* remove comment

* remove comments

* move to /src/utils

* optimize imports

* move rules-setup.js to /src/utils

* move rule-transformer.js to /src/utils

* move confirmation to /src/ui/confirm.js

* default to all rules

* use profile js for mcp config settings

* only run rules interactive setup if not provided via command line

* update comments

* initialize with all brands if nothing specified

* update var name

* clean up

* enumerate brands for brand rules

* update instructions

* add test to check for brand profiles

* fix quotes

* update semantics and terminology from 'brand rules' to 'rules profiles'

* fix formatting

* fix formatting

* update function name and remove copying of cursor rules, now handled by rules transformer

* update comment

* rename to mcp-config-setup.js

* use enums for rules actions

* add aggregate reporting for rules add command

* add missing log message

* use simpler path

* use base profile with modifications for each brand

* use displayName and don't select any defaults in setup

* add confirmation if removing ALL rules profiles, and add --force flag on rules remove

* Use profile-detection instead of rules-detection

* add newline at end of mcp config

* add proper formatting for mcp.json

* update rules

* update rules

* update rules

* add checks for other rules and other profile folder items before removing

* update confirmation for rules remove

* update docs

* update changeset

* fix for filepath at bottom of rule

* Update cline profile and add test; adjust other rules tests

* update changeset

* update changeset

* clarify init for all profiles if not specified

* update rule text

* revert text

* use "rule profiles" instead of "rules profiles"

* use standard tool mappings for windsurf

* add Trae support

* update changeset

* update wording

* update to 'rule profile'

* remove unneeded exports to optimize loc

* combine to /src/utils/profiles.js; add codex and claude code profiles

* rename function and add boxen

* add claude and codex integration tests

* organize tests into profiles folder

* mock fs for transformer tests

* update UI

* add cline and trae integration tests

* update test

* update function name

* update formatting

* Update change set with new profiles

* move profile integration tests to subdirectory

* properly create temp directories in /tmp folder

* fix formatting

* use taskmaster subfolder for the 2 TM rules

* update wording

* ensure subdirectory exists

* update rules from next

* update from next

* update taskmaster rule

* add details on new rules command and init

* fix mcp init

* fix MCP path to assets

* remove duplication

* remove duplication

* MCP server path fixes for rules command

* fix for CLI roo rules add/remove

* update tests

* fix formatting

* fix pattern for interactive rule profiles setup

* restore comments

* restore comments

* restore comments

* remove unused import, fix quotes

* add missing integration tests

* add VS Code profile and tests

* update docs and rules to include vscode profile

* add rules subdirectory support per-profile

* move profiles to /src

* fix formatting

* rename to remove ambiguity

* use --setup for rules interactive setup

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* change roo boomerang to orchestrator; update tests that don't use modes

* fix newline

* chore: cleanup

---------

Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: Yuval <yuvalbl@users.noreply.github.com>
Co-authored-by: Marijn van der Werf <marijn.vanderwerf@gmail.com>
Co-authored-by: Eyal Toledano <eutait@gmail.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-06-20 10:09:36 +02:00
github-actions[bot]
02e0db09df docs: Auto-update and format models.md 2025-06-20 07:59:03 +00:00
Riccardo (Ricky) Esclapon
3bcce8d70e Update SWE scores (#657) 2025-06-20 09:58:53 +02:00
Ralph Khreish
8852831807 Merge pull request #810 from eyaltoledano/changeset-release/main
Version Packages
2025-06-18 21:35:39 +03:00
Ralph Khreish
661d3e04ba chore: fix package.json 2025-06-18 21:14:27 +03:00
github-actions[bot]
0dba2cb2da Version Packages 2025-06-18 16:02:39 +00:00
Ralph Khreish
9ee7a94056 Release 0.17.1 (#790)
* fix(contextGatherer): cannot read properties of undefined reading forEach (#789)

* docs: Update configuration.md (#782)

---------

Co-authored-by: Bartu OZEL <bartuozel@gmail.com>
2025-06-18 19:02:16 +03:00
Bartu OZEL
636fb3f680 docs: Update configuration.md (#782) 2025-06-16 20:12:54 +02:00
Ralph Khreish
8cde6c2708 fix(contextGatherer): cannot read properties of undefined reading forEach (#789) 2025-06-16 10:32:34 +02:00
Ralph Khreish
246acd1035 Merge Release 0.17.0 pull request #780 from eyaltoledano/changeset-release/main
Version Packages
2025-06-15 03:16:16 +02:00
Ralph Khreish
de5acbc6c9 chore: fix formatting 2025-06-15 04:12:13 +03:00
Ralph Khreish
664eb5b896 cleanup release 2025-06-15 04:10:51 +03:00
github-actions[bot]
dbaf492bdb Version Packages 2025-06-15 00:59:24 +00:00
Ralph Khreish
0c8a0b81a0 Merge pull request #779 from eyaltoledano/next
Release 0.17.0
2025-06-15 02:59:01 +02:00
github-actions[bot]
46d4f273f5 docs: Auto-update and format models.md 2025-06-15 00:50:10 +00:00
github-actions[bot]
aa7396d65e Version Packages 2025-06-15 03:47:56 +03:00
Eyal Toledano
5119cd2d8e v017 polish (#778)
* fix(research, tasks): Make research command and task updates tag-aware

* refactor(tasks): Prevent automatic task file generation across other locations

This commit refactors several core task management functions to prevent them from automatically regenerating individual task files after modifying the main `tasks.json`.

Previously, operations like `add-task`, `clear-subtasks`, `expand-task`, and `update-task-by-id` would immediately trigger `generateTaskFiles`. This could be slow and was often unnecessary.

The calls to `generateTaskFiles` have been removed or commented out from the core task functions. Users should now run `task-master generate` explicitly to update their individual task files.

Additionally, this commit includes fixes to the `move` command to make it fully tag-aware.

* fix: move and clear subtasks mcp commands

* chore: fix format

* chore: fix unit tests

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-15 03:47:56 +03:00
github-actions[bot]
44eba3f7d1 chore: rc version bump 2025-06-15 03:47:56 +03:00
Eyal Toledano
e82b093dce docs: Update taskmaster.mdc and dev_workflow.mdc with missing CLI fla… (#775)
* docs: Update taskmaster.mdc and dev_workflow.mdc with missing CLI flags and enhanced workflow guidance

- Add missing --tag flags to commands that were implemented but not documented
- Add missing --file flags to tag management commands
- Add --bedrock flag to models command documentation
- Synchronize CLI documentation with actual implementation in commands.js
- Enhance dev_workflow.mdc with comprehensive tagged task lists guidance
- Add patterns for when to introduce tags (git branching, team collaboration, experiments)
- Consolidate and refine changesets for upcoming release

* chore: package-lock fixup

* chore: fix format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-15 03:47:56 +03:00
Ralph Khreish
ad3acd874d chore: rc version bump (#776)
* Version Packages

* chore: update package-lock.json

* chore: fix format

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eyal Toledano <eyal@microangel.so>
2025-06-15 03:47:56 +03:00
github-actions[bot]
52022d370b chore: rc version bump 2025-06-15 03:47:56 +03:00
Eyal Toledano
957af5253b chore: v017 linting (#773) 2025-06-15 03:47:28 +03:00
Ralph Khreish
c0b3f432a6 chore: v0.17 features and improvements (#771)
* chore: task management and small bug fix.

* chore: task management

* feat: implement research command with enhanced context gathering - Add comprehensive research command with AI-powered queries - Implement ContextGatherer utility for reusable context extraction - Support multiple context types: tasks, files, custom text, project tree - Add fuzzy search integration for automatic task discovery - Implement detailed token breakdown display with syntax highlighting - Add enhanced UI with boxed output and code block formatting - Support different detail levels (low, medium, high) for responses - Include project-specific context for more relevant AI responses - Add token counting with gpt-tokens library integration - Create reusable patterns for future context-aware commands - Task 94.4 completed

* docs: add context gathering rule and update existing rules

- Create comprehensive context_gathering.mdc rule documenting ContextGatherer utility patterns, FuzzyTaskSearch integration, token breakdown display, code block syntax highlighting, and enhanced result display patterns
- Update new_features.mdc to include context gathering step
- Update commands.mdc with context-aware command pattern
- Update ui.mdc with enhanced display patterns and syntax highlighting
- Update utilities.mdc to document new context gathering utilities
- Update glossary.mdc to include new context_gathering rule
- Establishes standardized patterns for building intelligent, context-aware commands that can leverage project knowledge for better AI assistance

* feat(fuzzy): improves fuzzy search to introspect into subtasks as well. might still need improvement.

* fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks.

* fix(move-task): Fix critical bugs in task move functionality

- Fixed parent-to-parent task moves where original task would remain as duplicate
- Fixed moving tasks to become subtasks of empty parents (validation errors)
- Fixed moving subtasks between different parent tasks
- Improved comma-separated batch moves with proper error handling
- Updated MCP tool to use core logic instead of custom implementation
- Resolves task duplication issues and enables proper task hierarchy reorganization

* feat(research): Add subtasks to fuzzy search and follow-up questions

- Enhanced fuzzy search to include subtasks in discovery - Added interactive follow-up question functionality using inquirer
- Improved context discovery by including both tasks and subtasks
- Follow-up option for research with default to 'n' for quick workflow

* chore: removes task004 chat that had like 11k lines lol.

* chore: formatting

* feat(show): add comma-separated ID support for multi-task viewing

- Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations.
- New features include multiple task retrieval, smart display logic, interactive action menu with batch operations, MCP array response for AI agent efficiency, and support for mixed parent tasks and subtasks.
- Implementation includes updated CLI show command, enhanced MCP get_task tool, modified showTaskDirect function, and maintained full backward compatibility.
- Documentation updated across all relevant files.

Benefits include faster context gathering for AI agents, improved workflow with interactive batch operations, better UX with responsive layout, and enhanced API efficiency.

* feat(research): Adds MCP tool for  command

- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.

* chore: task management

* chore: task management and removes mistakenly staged changes

* fix(move): Fix move command bug that left duplicate tasks

- Fixed logic in moveTaskToNewId function that was incorrectly treating task-to-task moves as subtask creation instead of task replacement
- Updated moveTaskToNewId to properly handle replacing existing destination tasks instead of just placeholders
- The move command now correctly replaces destination tasks and cleans up properly without leaving duplicates

- Task Management: Moved task 93 (Google Vertex AI Provider) to position 88, Moved task 94 (Azure OpenAI Provider) to position 89, Updated task dependencies and regenerated task files, Cleaned up orphaned task files automatically
- All important validations remain in place: Prevents moving tasks to themselves, Prevents moving parent tasks to their own subtasks, Prevents circular dependencies
- Resolves the issue where moving tasks would leave both source and destination tasks in tasks.json and file system

* chore: formatting

* feat: Add .taskmaster directory (#619)

* chore: apply requested changes from next branch (#629)

* chore: rc version bump

* chore: cleanup migration-guide

* fix: bedrock set model and other fixes (#641)

* Fix: MCP log errors (#648)

* fix: projectRoot duplicate .taskmaster directory (#655)

* Version Packages

* chore: add package-lock.json

* Version Packages

* Version Packages

* fix: markdown format (#622)

* Version Packages

* Version Packages

* Fixed the Typo in cursor rules Issue:#675 (#677)

Fixed the typo in the Api keys

* Add one-click MCP server installation for Cursor (#671)

* Update README.md - Remove trailing commas (#673)

JSON doesn't allow for trailing commas, so these need to be removed in order for this to work

* chore: rc version bump

* fix: findTasksPath function

* fix: update MCP tool

* feat(ui): replace emoji complexity indicators with clean filled circle characters

Replace 🟢, 🟡, 🔴 emojis with ● character in getComplexityWithColor function

Update corresponding unit tests to expect ● instead of emojis

Improves UI continuity

* fix(ai-providers): change generateObject mode from 'tool' to 'auto' for better provider compatibility

Fixes Perplexity research role failing with 'tool-mode object generation' error

The hardcoded 'tool' mode was incompatible with providers like Perplexity that support structured JSON output but not function calling/tool use

Using 'auto' mode allows the AI SDK to choose the best approach for each provider

* Adds qwen3-235n-a22b:free to supported models. Closes #687)

* chore: adds a warning when custom openrouter model is a free model which suffers from lower rate limits, restricted context, and, worst of all, no access to tool_use.

* refactor: enhance add-task fuzzy search and fix duplicate banner display

- **Remove hardcoded category system** in add-task that always matched 'Task management'
- **Eliminate arbitrary limits** in fuzzy search results (5→25 high relevance, 3→10 medium relevance, 8→20 detailed tasks)
- **Improve semantic weighting** in Fuse.js search (details=3, description=2, title=1.5) for better relevance
- **Fix duplicate banner issue** by removing console.clear() and redundant displayBanner() calls from UI functions
- **Enhance context generation** to rely on semantic similarity rather than rigid pattern matching
- **Preserve terminal history** to address GitHub issue #553 about eating terminal lines
- **Remove displayBanner() calls** from: displayHelp, displayNextTask, displayTaskById, displayComplexityReport, set-task-status, clear-subtasks, dependency-manager functions

The add-task system now provides truly relevant task context based on semantic similarity rather than arbitrary categories and limits, while maintaining a cleaner terminal experience.

Changes span: add-task.js, ui.js, set-task-status.js, clear-subtasks.js, list-tasks.js, dependency-manager.js

Closes #553

* chore: changeset

* chore: passes tests and linting

* chore: more linting

* ninja(sync): add sync-readme command for GitHub README export with UTM tracking and professional markdown formatting. Experimental

* chore: changeset adjustment

* docs: Auto-update and format models.md

* chore: updates readme with npm download badges and mentions AI Jason who is joining the taskmaster core team.

* chore: fixes urls in readme npm packages

* chore: fixes urls in readme npm packages again

* fix: readme typo

* readme: fix twitter urls.

* readme: removes the taskmaster list output which is too overwhelming given its size with subtasks. may re-add later. fixes likely issues in the json for manual config in cursor and windsurf in the readme.

* chore: small readme nitpicks

* chore: adjusts changeset from minor to patch to avoid version bump to 0.17

* readme: moves up the documentation links higher up in the readme. same with the cursor one-click install.

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* solve merge conflics with next. not gonna deal with these much longer.

* chore: update task files during rebase

* chore: task management

* feat: implement research command with enhanced context gathering - Add comprehensive research command with AI-powered queries - Implement ContextGatherer utility for reusable context extraction - Support multiple context types: tasks, files, custom text, project tree - Add fuzzy search integration for automatic task discovery - Implement detailed token breakdown display with syntax highlighting - Add enhanced UI with boxed output and code block formatting - Support different detail levels (low, medium, high) for responses - Include project-specific context for more relevant AI responses - Add token counting with gpt-tokens library integration - Create reusable patterns for future context-aware commands - Task 94.4 completed

* fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks.

* fix(move-task): Fix critical bugs in task move functionality

- Fixed parent-to-parent task moves where original task would remain as duplicate
- Fixed moving tasks to become subtasks of empty parents (validation errors)
- Fixed moving subtasks between different parent tasks
- Improved comma-separated batch moves with proper error handling
- Updated MCP tool to use core logic instead of custom implementation
- Resolves task duplication issues and enables proper task hierarchy reorganization

* chore: removes task004 chat that had like 11k lines lol.

* feat(show): add comma-separated ID support for multi-task viewing

- Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations.
- New features include multiple task retrieval, smart display logic, interactive action menu with batch operations, MCP array response for AI agent efficiency, and support for mixed parent tasks and subtasks.
- Implementation includes updated CLI show command, enhanced MCP get_task tool, modified showTaskDirect function, and maintained full backward compatibility.
- Documentation updated across all relevant files.

Benefits include faster context gathering for AI agents, improved workflow with interactive batch operations, better UX with responsive layout, and enhanced API efficiency.

* feat(research): Adds MCP tool for  command

- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.

* chore: task management

* fix(move): Fix move command bug that left duplicate tasks

- Fixed logic in moveTaskToNewId function that was incorrectly treating task-to-task moves as subtask creation instead of task replacement
- Updated moveTaskToNewId to properly handle replacing existing destination tasks instead of just placeholders
- The move command now correctly replaces destination tasks and cleans up properly without leaving duplicates

- Task Management: Moved task 93 (Google Vertex AI Provider) to position 88, Moved task 94 (Azure OpenAI Provider) to position 89, Updated task dependencies and regenerated task files, Cleaned up orphaned task files automatically
- All important validations remain in place: Prevents moving tasks to themselves, Prevents moving parent tasks to their own subtasks, Prevents circular dependencies
- Resolves the issue where moving tasks would leave both source and destination tasks in tasks.json and file system

* chore: moves to new task master config setup

* feat: add comma-separated status filtering to list-tasks

- supports multiple statuses like 'blocked,deferred' with comprehensive test coverage and backward compatibility

- also adjusts biome.json to stop bitching about templating.

* chore: linting ffs

* fix(generate): Fix generate command creating tasks in legacy location

- Update generate command default output directory from 'tasks' to '.taskmaster/tasks'
- Fix path.dirname() usage to properly derive output directory from tasks file location
- Update MCP tool description and documentation to reflect new structure
- Disable Biome linting rules for noUnusedTemplateLiteral and useArrowFunction
- Fixes issue where generate command was creating task files in the old 'tasks/' directory instead of the new '.taskmaster/tasks/' structure after the refactor

* chore: task management

* chore: task management some more

* fix(get-task): makes the projectRoot argument required to prevent errors when getting tasks.

* feat(tags): Implement tagged task lists migration system (Part 1/2)

This commit introduces the foundational infrastructure for tagged task lists,
enabling multi-context task management without remote storage to prevent merge conflicts.

CORE ARCHITECTURE:
• Silent migration system transforms tasks.json from old format { "tasks": [...] }
  to new tagged format { "master": { "tasks": [...] } }
• Tag resolution layer provides complete backward compatibility - existing code continues to work
• Automatic configuration and state management for seamless user experience

SILENT MIGRATION SYSTEM:
• Automatic detection and migration of legacy tasks.json format
• Complete project migration: tasks.json + config.json + state.json
• Transparent tag resolution returns old format to maintain compatibility
• Zero breaking changes - all existing functionality preserved

CONFIGURATION MANAGEMENT:
• Added global.defaultTag setting (defaults to 'master')
• New tags section with gitIntegration placeholders for future features
• Automatic config.json migration during first run
• Proper state.json creation with migration tracking

USER EXPERIENCE:
• Clean, one-time FYI notice after migration (no emojis, professional styling)
• Notice appears after 'Suggested Next Steps' and is tracked in state.json
• Silent operation - users unaware migration occurred unless explicitly shown

TECHNICAL IMPLEMENTATION:
• Enhanced readJSON() with automatic migration detection and processing
• New utility functions: getCurrentTag(), resolveTag(), getTasksForTag(), setTasksForTag()
• Complete migration orchestration via performCompleteTagMigration()
• Robust error handling and fallback mechanisms

BACKWARD COMPATIBILITY:
• 100% backward compatibility maintained
• Existing CLI commands and MCP tools continue to work unchanged
• Legacy tasks.json format automatically upgraded on first read
• All existing workflows preserved

TESTING VERIFIED:
• Complete migration from legacy state works correctly
• Config.json properly updated with tagged system settings
• State.json created with correct initial values
• Migration notice system functions as designed
• All existing functionality continues to work normally

Part 2 will implement tag management commands (add-tag, use-tag, list-tags)
and MCP tool updates for full tagged task system functionality.

Related: Task 103 - Implement Tagged Task Lists System for Multi-Context Task Management

* docs: Update documentation and rules for tagged task lists system

- Updated task-structure.md with comprehensive tagged format explanation
- Updated all .cursor/rules/*.mdc files to reflect tagged system
- Completed subtask 103.16: Update Documentation for Tagged Task Lists System

* feat(mcp): Add tagInfo to responses and integrate ContextGatherer

Enhances the MCP server to include 'tagInfo' (currentTag, availableTags) in all tool responses, providing better client-side context.

- Introduces a new 'ContextGatherer' utility to standardize the collection of file, task, and project context for AI-powered commands. This refactors several task-manager modules ('expand-task', 'research', 'update-task', etc.) to use the new utility.

- Fixes an issue in 'get-task' and 'get-tasks' MCP tools where the 'projectRoot' was not being passed correctly, preventing tag information from being included in their responses.

- Adds subtask '103.17' to track the implementation of the task template importing feature.

- Updates documentation ('.cursor/rules', 'docs/') to align with the new tagged task system and context gatherer logic.

* fix: include tagInfo in AI service responses for MCP tools

- Update all core functions that call AI services to extract and return tagInfo
- Update all direct functions to include tagInfo in MCP response data
- Fixes issue where add_task, expand_task, and other AI commands were not including current tag and available tags information
- tagInfo includes currentTag from state.json and availableTags list
- Ensures tagged task lists system information is properly propagated through the full chain: AI service -> core function -> direct function -> MCP client

* fix(move-task): Update move functionality for tagged task system compatibility

- incorporate GitHub commit fixes and resolve readJSON data handling

* feat(tagged-tasks): Complete core tag management system implementation

- Implements comprehensive tagged task lists system for multi-context task management including core tag management functions (Task 103.11), MCP integration updates, and foundational infrastructure for tagged task operations. Features tag CRUD operations, validation, metadata tracking, deep task copying, and full backward compatibility.

* fix(core): Fixed move-task.js writing _rawTaggedData directly, updated writeJSON to filter tag fields, fixed CLI move command missing projectRoot, added ensureTagMetadata utility

* fix(tasks): ensure list tasks triggers silent migration if necessary.

* feat(tags): Complete show and add-task command tag support
- show command: Added --tag flag, fixed projectRoot passing to UI functions
- add-task command: Already had proper tag support and projectRoot handling
- Both commands now work correctly with tagged task lists system
- Migration logic works properly when viewing and adding tasks
- Updated subtask 103.5 with progress on high-priority command fixes

* fix(tags): Clean up rogue created properties and fix taskCount calculation
- Enhanced writeJSON to automatically filter rogue created/description properties from tag objects
- Fixed tags command error by making taskCount calculation dynamic instead of hardcoded
- Cleaned up existing rogue created property in master tag through forced write operation
- All created properties now properly located in metadata objects only
- Tags command working perfectly with proper task count display
- Data integrity maintained with automatic cleanup during write operations

* fix(tags): Resolve critical tag deletion and migration notice bugs

Major Issues Fixed:

1. Tag Deletion Bug: Fixed critical issue where creating subtasks would delete other tags

   - Root cause: writeJSON function wasn't accepting projectRoot/tag parameters

   - Fixed writeJSON signature and logic to handle tagged data structure

   - Added proper merging of resolved tag data back into full tagged structure

2. Persistent Migration Notice: Fixed FYI notice showing after every command

   - Root cause: markMigrationForNotice was resetting migrationNoticeShown to false

   - Fixed migration logic to only trigger on actual legacy->tagged migrations

   - Added proper _rawTaggedData checks to prevent false migration detection

3. Data Corruption Prevention: Enhanced data integrity safeguards

   - Fixed writeJSON to filter out internal properties

   - Added automatic cleanup of rogue properties

   - Improved hasTaggedStructure detection logic

Commands Fixed: add-subtask, remove-subtask, and all commands now preserve tags correctly

* fix(tags): Resolve tag deletion bug in remove-task command

Refactored the core 'removeTask' function to be fully tag-aware, preventing data corruption.

- The function now correctly reads the full tagged data structure by prioritizing '_rawTaggedData' instead of operating on a resolved single-tag view.

- All subsequent operations (task removal, dependency cleanup, file writing) now correctly reference the full multi-tag data object, preserving the integrity of 'tasks.json'.

- This resolves the critical bug where removing a task would delete all other tags.

* fix(tasks): Ensure new task IDs are sequential within the target tag

Modified the ID generation logic in 'add-task.js' to calculate the next task ID based on the highest ID within the specified tag, rather than globally across all tags.

This fixes a critical bug where creating a task in a new tag would result in a high, non-sequential ID, such as ID 105 for the first task in a tag.

* fix(commands): Add missing context parameters to dependency and remove-subtask commands

- Add projectRoot and tag context to all dependency commands
- Add projectRoot and tag context to remove-subtask command
- Add --tag option to remove-subtask command
- Fixes critical bug where remove-subtask was deleting other tags due to missing context
- All dependency and subtask commands now properly handle tagged task lists

* feat(tags): Add --tag flag support to core commands for multi-context task management
- parse-prd now supports creating tasks in specific contexts
- Fixed tag preservation logic to prevent data loss
- analyze-complexity generates tag-specific reports
- Non-existent tags created automatically
- Enables rapid prototyping and parallel development workflows

* feat(tags): Complete tagged task lists system with enhanced use-tag command

- Multi-context task management with full CLI support
- Enhanced use-tag command shows next available task after switching
- Universal --tag flag support across all commands
- Seamless migration with zero disruption
- Complete tag management suite (add, delete, rename, copy, list)
- Smart confirmation logic and data integrity protection
- State management and configuration integration
- Real-world use cases for teams, features, and releases

* feat(tags): Complete tag support for remaining CLI commands

- Add --tag flag to update, move, and set-status commands
- Ensure all task operation commands now support tag context
- Fix missing tag context passing to core functions
- Complete comprehensive tag-aware command coverage

* feat(ui): add tag indicator to all CLI commands
- shows 🏷️ tag: tagname for complete context visibility across 15+ commands

* fix(ui): resolve dependency 'Not found' issue when filtering

- now correctly displays dependencies that exist but are filtered out of view

* feat(research): Add comprehensive AI-powered research command with interactive follow-ups, save functionality, intelligent context gathering, fuzzy task discovery, multi-source context support, enhanced display with syntax highlighting, clean inquirer menus, comprehensive help, and MCP integration with saveTo parameter

* feat(tags): Implement full MCP support for Tagged Task Lists and update-task append mode

* chore: task management

* feat(research): Enhance research command with follow-up menu, save functionality, and fix ContextGatherer token counting

* feat(git-workflow): Add automatic git branch-tag integration

- Implement automatic tag creation when switching to new git branches

- Add branch-tag mapping system for seamless context switching

- Enable auto-switch of task contexts based on current git branch

- Provide isolated task contexts per branch to prevent merge conflicts

- Add configuration support for enabling/disabling git workflow features

- Fix ES module compatibility issues in git-utils module

- Maintain zero migration impact with automatic 'master' tag creation

- Support parallel development with branch-specific task contexts

The git workflow system automatically detects branch changes and creates corresponding empty task tags, enabling developers to maintain separate task contexts for different features/branches while preventing task-related merge conflicts during collaborative development.

Resolves git workflow integration requirements for multi-context development.

* feat(git-workflow): Simplify git integration with --from-branch option

- Remove automatic git workflow and branch-tag switching - we are not ready for it yet

- Add --from-branch option to add-tag command for manual tag creation from git branch

- Remove git workflow configuration from config.json and assets

- Disable automatic tag switching functions in git-utils.js

- Add createTagFromBranch function for branch-based tag creation

- Support both CLI and MCP interfaces for --from-branch functionality

- Fix ES module imports in git-utils.js and utils.js

- Maintain user control over tag contexts without forced automation

The simplified approach allows users to create tags from their current git branch when desired, without the complexity and rigidity of automatic branch-tag synchronization. Users maintain full control over their tag contexts while having convenient tools for git-based workflows when needed.

* docs: Update rule files to reflect simplified git integration approach

- Remove automatic git workflow features, update to manual --from-branch option, change Part 2 references to completed status

* fix(commands): Fix add-tag --from-branch requiring tagName argument
- Made tagName optional when using --from-branch - Added validation for either tagName or --from-branch
- Fixes 'missing required argument' error with --from-branch option

* fix(mcp): Prevent tag deletion on subtask update

Adds a safety net to the writeJSON utility to prevent data loss when updating subtasks via the MCP server.

The MCP process was inadvertently causing the _rawTaggedData property, which holds the complete multi-tag structure, to be lost. When writeJSON received the data for only a single tag, it would overwrite the entire tasks.json file, deleting all other tags.

This fix makes writeJSON more robust. If it receives data that looks like a single, resolved tag without the complete structure, it re-reads the full tasks.json file from disk. It then carefully merges the updated data back into the correct tag within the full structure, preserving all other tags.

* fix: resolve all remaining test failures and improve test reliability

- Fix clear-subtasks test by implementing deep copy of mock data to prevent mutation issues between tests
- Fix add-task test by uncommenting and properly configuring generateTaskFiles call with correct parameters
- Fix analyze-task-complexity tests by properly mocking fs.writeFileSync with shared mock function
- Update test expectations to match actual function signatures and data structures
- Improve mock setup consistency across all test suites
- Ensure all tests now pass (329 total: 318 passed, 11 skipped, 0 failed)

* chore: task management

---------

Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ibrahim H. <bitsnaps@yahoo.fr>
Co-authored-by: Saksham Goel <sakshamgoel1107@gmail.com>
Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Aaron Gabriel Neyer <ag@unforced.org>
2025-06-15 03:47:28 +03:00
github-actions[bot]
12bed2b307 docs: Auto-update and format models.md 2025-06-15 03:47:28 +03:00
Volodymyr Zahorniak
d76bea49b3 docs: Update o3 model price (#751) 2025-06-15 03:47:28 +03:00
Ralph Khreish
0849c0c2ce fix: expand-task (#755) 2025-06-15 03:47:28 +03:00
Joe Danziger
5ec1f61c13 Fix Cursor deeplink installation with copy-paste instructions (#723) 2025-06-15 03:47:28 +03:00
Eyal Toledano
292c2caf7f Merge pull request #722 from eyaltoledano/changeset-release/main
Version Packages
2025-06-08 17:43:43 -04:00
github-actions[bot]
526d64fb8a Version Packages 2025-06-08 20:39:20 +00:00
Ralph Khreish
1b86ce6c83 Merge pull request #721 from eyaltoledano/next 2025-06-08 22:38:49 +02:00
Eyal Toledano
8a86ec538e Merge pull request #717 from eyaltoledano/v016-last-touches
V016 last touches
2025-06-08 16:20:32 -04:00
Eyal Toledano
9e7387952d readme: moves up the documentation links higher up in the readme. same with the cursor one-click install. 2025-06-08 15:59:49 -04:00
Eyal Toledano
ab05f550b3 chore: adjusts changeset from minor to patch to avoid version bump to 0.17 2025-06-08 15:32:31 -04:00
Ralph Khreish
cf01fbedcf Merge pull request #686 from eyaltoledano/next 2025-06-08 19:37:46 +02:00
Ralph Khreish
d2bcbee0c2 chore: small readme nitpicks 2025-06-08 13:49:40 +02:00
Eyal Toledano
72171bd4ba Merge pull request #702 from eyaltoledano/readme-fixes-2
readme: removes the taskmaster list output
2025-06-07 23:23:01 -04:00
Eyal Toledano
9ad517231a readme: removes the taskmaster list output which is too overwhelming given its size with subtasks. may re-add later. fixes likely issues in the json for manual config in cursor and windsurf in the readme. 2025-06-07 23:21:17 -04:00
Eyal Toledano
7db3b47a47 Merge pull request #701 from eyaltoledano/readme-npm-badges
chore: updates readme with npm download badges and mentions AI Jason who is joining the taskmaster core team.
2025-06-07 23:17:02 -04:00
Eyal Toledano
3de785a99c readme: fix twitter urls. 2025-06-07 23:10:08 -04:00
Eyal Toledano
8188fdd832 fix: readme typo 2025-06-07 23:09:16 -04:00
Eyal Toledano
3fadc2f1ef chore: fixes urls in readme npm packages again 2025-06-07 23:07:12 -04:00
Eyal Toledano
dd36111367 chore: fixes urls in readme npm packages 2025-06-07 23:06:26 -04:00
Eyal Toledano
c58ab8963c chore: updates readme with npm download badges and mentions AI Jason who is joining the taskmaster core team. 2025-06-07 23:02:36 -04:00
github-actions[bot]
3eeb4721aa docs: Auto-update and format models.md 2025-06-08 02:15:32 +00:00
Eyal Toledano
7ea905f2c5 Merge pull request #699 from eyaltoledano/0.16.2-touchups
0.16.2 touchups
2025-06-07 22:15:19 -04:00
Eyal Toledano
51dd4f625b chore: changeset adjustment 2025-06-07 22:13:11 -04:00
Eyal Toledano
2e55757b26 ninja(sync): add sync-readme command for GitHub README export with UTM tracking and professional markdown formatting. Experimental 2025-06-07 22:07:35 -04:00
Eyal Toledano
54bfc72baa chore: more linting 2025-06-07 20:32:37 -04:00
Eyal Toledano
faae0b419d chore: passes tests and linting 2025-06-07 20:30:51 -04:00
Eyal Toledano
27edbd8f3f chore: changeset 2025-06-07 20:28:28 -04:00
Eyal Toledano
b1390e4ddf refactor: enhance add-task fuzzy search and fix duplicate banner display
- **Remove hardcoded category system** in add-task that always matched 'Task management'
- **Eliminate arbitrary limits** in fuzzy search results (5→25 high relevance, 3→10 medium relevance, 8→20 detailed tasks)
- **Improve semantic weighting** in Fuse.js search (details=3, description=2, title=1.5) for better relevance
- **Fix duplicate banner issue** by removing console.clear() and redundant displayBanner() calls from UI functions
- **Enhance context generation** to rely on semantic similarity rather than rigid pattern matching
- **Preserve terminal history** to address GitHub issue #553 about eating terminal lines
- **Remove displayBanner() calls** from: displayHelp, displayNextTask, displayTaskById, displayComplexityReport, set-task-status, clear-subtasks, dependency-manager functions

The add-task system now provides truly relevant task context based on semantic similarity rather than arbitrary categories and limits, while maintaining a cleaner terminal experience.

Changes span: add-task.js, ui.js, set-task-status.js, clear-subtasks.js, list-tasks.js, dependency-manager.js

Closes #553
2025-06-07 20:23:55 -04:00
Eyal Toledano
cc04d53720 chore: adds a warning when custom openrouter model is a free model which suffers from lower rate limits, restricted context, and, worst of all, no access to tool_use. 2025-06-07 18:54:11 -04:00
Eyal Toledano
bfd86eb9cc Adds qwen3-235n-a22b:free to supported models. Closes #687) 2025-06-07 18:42:11 -04:00
Eyal Toledano
9eb3842f04 fix(ai-providers): change generateObject mode from 'tool' to 'auto' for better provider compatibility
Fixes Perplexity research role failing with 'tool-mode object generation' error

The hardcoded 'tool' mode was incompatible with providers like Perplexity that support structured JSON output but not function calling/tool use

Using 'auto' mode allows the AI SDK to choose the best approach for each provider
2025-06-07 15:02:48 -04:00
Eyal Toledano
bf2053e140 feat(ui): replace emoji complexity indicators with clean filled circle characters
Replace 🟢, 🟡, 🔴 emojis with ● character in getComplexityWithColor function

Update corresponding unit tests to expect ● instead of emojis

Improves UI continuity
2025-06-07 12:57:45 -04:00
Ralph Khreish
ee0be04302 fix: update MCP tool 2025-06-07 13:29:03 +02:00
Ralph Khreish
c0707fc399 chore: upgrade fast mcp to latest version 2025-06-07 13:29:03 +02:00
Ralph Khreish
1ece6f1904 fix: findTasksPath function 2025-06-07 13:29:03 +02:00
github-actions[bot]
f4a9ad1095 chore: rc version bump 2025-06-06 18:51:19 +00:00
Aaron Gabriel Neyer
cba86510d3 Update README.md - Remove trailing commas (#673)
JSON doesn't allow for trailing commas, so these need to be removed in order for this to work
2025-06-05 19:08:24 +02:00
Joe Danziger
86ea6d1dbc Add one-click MCP server installation for Cursor (#671) 2025-06-05 19:08:15 +02:00
Saksham Goel
a22d2a45b5 Fixed the Typo in cursor rules Issue:#675 (#677)
Fixed the typo in the Api keys
2025-06-05 19:06:01 +02:00
Ralph Khreish
d73c8e17ec Merge pull request #661 from eyaltoledano/chore/update.next
Update next from main branch
2025-06-03 18:13:22 +02:00
Ralph Khreish
4f23751d25 chore: update package-lock.json 2025-06-03 18:12:02 +02:00
Ibrahim H.
7d5c028ca0 fix: markdown format (#622) 2025-06-03 15:54:13 +02:00
github-actions[bot]
f18df6da19 Version Packages 2025-06-03 15:14:34 +02:00
github-actions[bot]
1754a31372 Version Packages 2025-06-03 15:13:26 +02:00
Ralph Khreish
3096ccdfb3 chore: add package-lock.json 2025-06-03 15:13:26 +02:00
github-actions[bot]
6464bb11e5 Version Packages 2025-06-03 15:13:26 +02:00
Ralph Khreish
edaa5fe0d5 fix: projectRoot duplicate .taskmaster directory (#655) 2025-06-03 15:12:50 +02:00
Ralph Khreish
41d9dbbe6d Merge pull request #650 from eyaltoledano/changeset-release/main 2025-06-03 01:40:34 +02:00
github-actions[bot]
6e0d866756 Version Packages 2025-06-02 23:26:36 +00:00
Ralph Khreish
926aa61a4e Merge pull request #642 from eyaltoledano/next
Release 0.16.1
2025-06-03 01:26:12 +02:00
Ralph Khreish
9b4168bb4e Fix: MCP log errors (#648) 2025-06-03 01:09:29 +02:00
Ralph Khreish
ad612763ff fix: bedrock set model and other fixes (#641) 2025-06-02 14:44:35 +02:00
Ralph Khreish
293b59bac6 Merge pull request #630 from eyaltoledano/changeset-release/main
Version Packages
2025-06-01 17:49:18 +02:00
Ralph Khreish
1809c4ed7b chore: add package-lock.json 2025-06-01 11:48:11 -04:00
github-actions[bot]
6e406958c1 Version Packages 2025-06-01 15:24:59 +00:00
Ralph Khreish
074b7ec0bc Merge pull request #625 from eyaltoledano/next 2025-06-01 17:24:37 +02:00
Ralph Khreish
e0438c8fb8 chore: cleanup migration-guide 2025-06-01 01:08:31 -04:00
github-actions[bot]
1f6694fb3d chore: rc version bump 2025-06-01 04:20:35 +00:00
Ralph Khreish
b0dfcf345e chore: apply requested changes from next branch (#629) 2025-06-01 06:19:55 +02:00
Ralph Khreish
3f64202c9f feat: Add .taskmaster directory (#619) 2025-05-31 16:21:03 +02:00
Ralph Khreish
669b744ced Feat/add nvmrc (#612)
* feat: Add .nvmrc and align engines to Node 20

* chore: set nvm to 22, engines to 18

* chore: format

* chore: add changeset

---------

Co-authored-by: Amir Golan <amirgolan@Amirs-MacBook-Pro.local>
2025-05-28 15:02:15 +02:00
Nathan Marley
f058543888 Replace prettier with biome (#531) 2025-05-28 14:47:16 +02:00
Ralph Khreish
acd5c1ea3d chore: add contributing.md (#611) 2025-05-28 00:59:14 +02:00
github-actions[bot]
682b54e103 docs: Auto-update and format models.md 2025-05-27 22:42:42 +00:00
Ralph Khreish
6a8a68e1a3 Feat/add.azure.and.other.providers (#607)
* fix: claude-4 not having the right max_tokens

* feat: add bedrock support

* chore: fix package-lock.json

* fix: rename baseUrl to baseURL

* feat: add azure support

* fix: final touches of azure integration

* feat: add google vertex provider

* chore: fix tests and refactor task-manager.test.js

* chore: move task 92 to 94
2025-05-28 00:42:31 +02:00
Ralph Khreish
80735f9e60 feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution (#604)
* feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution

- Added support for the TASK_MASTER_PROJECT_ROOT environment variable in MCP configuration, establishing a clear precedence order for project root resolution.
- Updated utility functions to prioritize the environment variable, followed by args.projectRoot and session-based resolution.
- Enhanced error handling and logging for project root determination.
- Introduced new tasks for comprehensive testing and documentation updates related to the new configuration options.

* chore: fix CI issues
2025-05-28 00:32:34 +02:00
github-actions[bot]
48732d5423 docs: Auto-update and format models.md 2025-05-25 22:13:23 -04:00
Eyal Toledano
2d520de269 fix(add-task): removes stdout in add-task which will crash MCP server (#593)
* fix(add-task): fixes an isse in which stdout leaks out of add-task causing the mcp server to crash if used.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-25 22:13:23 -04:00
celgost
b60e1cf835 revamping readme (#522) 2025-05-24 17:21:15 +02:00
Ralph Khreish
d1e45ff50e Merge pull request #589 from eyaltoledano/changeset-release/main
Version Packages
2025-05-24 16:25:26 +02:00
github-actions[bot]
1513858da4 Version Packages 2025-05-24 14:07:53 +00:00
Ralph Khreish
59dcf4bd64 Release 0.15.0
Release 0.15.0
2025-05-24 16:07:24 +02:00
github-actions[bot]
a09ba021c5 chore: rc version bump 2025-05-24 00:44:47 +00:00
Eyal Toledano
e906166141 Merge pull request #567 from eyaltoledano/parse-prd-research
v0.15 improvements & new features
2025-05-23 20:42:41 -04:00
Eyal Toledano
231e569e84 Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7 2025-05-23 20:33:45 -04:00
Eyal Toledano
09add37423 feat(models): Add comprehensive Ollama model validation and interactive setup - Add 'Custom Ollama model' option to interactive setup (--setup) - Implement live validation against local Ollama instance via /api/tags - Support configurable Ollama endpoints from .taskmasterconfig - Add robust error handling for server connectivity and model existence - Enhance user experience with clear validation feedback - Support both MCP server and CLI interfaces 2025-05-23 20:20:39 -04:00
Eyal Toledano
91fc779714 chore: adjusts changesets and an import. 2025-05-23 17:41:25 -04:00
Eyal Toledano
8c69c0aafd Task management, research, improvements for 24, 41 and 51 2025-05-23 17:30:25 -04:00
Eyal Toledano
43ad75c7fa chore: formatting 2025-05-23 14:44:53 -04:00
Eyal Toledano
a59dd037cf chore: changeset for Claude Code rules. depends on us adding it as an init option from the other PR. 2025-05-23 13:23:26 -04:00
Eyal Toledano
3293c7858b feat: adds AGENTS.md to the assets/ folder so we can add it into the project if the user selects Claude Code as the IDE of choice in the init sequence (to be done in another PR) 2025-05-23 13:17:45 -04:00
Eyal Toledano
b371808524 fix(models): Adjusts the Claude 4 models and introduces the llms-install.md file to enable AI agents to install the Taskmaster MCP server programmatically. 2025-05-23 12:59:14 -04:00
Shrey Paharia
86d8f00af8 Add next task to set status for mcp server (#558) 2025-05-22 11:09:36 +02:00
Eyal Toledano
0c55ce0165 chore: linting and prettier 2025-05-22 04:17:06 -04:00
Eyal Toledano
5a91941913 removes changeset for set/mark which i didnt add in the end 2025-05-22 04:15:10 -04:00
Eyal Toledano
04af16de27 feat(move-tasks): Implement move command for tasks and subtasks
Adds a new CLI command and MCP tool to reorganize tasks and subtasks within the hierarchy. Features include:
- Moving tasks between different positions in the task list
- Converting tasks to subtasks and vice versa
- Moving subtasks between parents
- Moving multiple tasks at once with comma-separated IDs
- Creating placeholder tasks when moving to new IDs
- Validation to prevent accidental data loss

This is particularly useful for resolving merge conflicts when multiple team members create tasks on different branches.
2025-05-22 04:14:22 -04:00
Eyal Toledano
edf0f23005 update changesets 2025-05-22 03:03:25 -04:00
Eyal Toledano
e0e1155260 fix(parse-prd): Fix parameter naming inconsistency in CLI parse-prd command 2025-05-22 02:59:32 -04:00
Eyal Toledano
70f4054f26 feat(parse-prd): Add research flag to parse-prd command for enhanced PRD analysis. Significantly improves parse PRD system prompt when used with research. 2025-05-22 02:57:51 -04:00
Eyal Toledano
34c769bcd0 feat(analyze): add task ID filtering to analyze-complexity command
Enhance analyze-complexity to support analyzing specific tasks by ID or range:
- Add --id option for comma-separated task IDs
- Add --from/--to options for analyzing tasks within a range
- Implement intelligent merging with existing reports
- Update CLI, MCP tools, and direct functions for consistent support
- Add changeset documenting the feature
2025-05-22 01:49:41 -04:00
Eyal Toledano
34df2c8bbd feat: automatically create tasks.json when missing (Task #68)
This commit implements automatic tasks.json file creation when it doesn't exist:

- When tasks.json is missing or invalid, create a new one with { tasks: [] }
- Allows adding tasks immediately after initializing a project without parsing a PRD
- Replaces error with informative feedback about file creation
- Enables smoother workflow for new projects or directories

This change improves user experience by removing the requirement to parse a PRD
before adding the first task to a newly initialized project. Closes #494
2025-05-22 01:18:27 -04:00
Eyal Toledano
5e9bc28abe feat(add-task): enhance dependency detection with semantic search
This commit significantly improves the  functionality by implementing
fuzzy semantic search to find contextually relevant dependencies:

- Add Fuse.js for powerful fuzzy search capability with weighted multi-field matching
- Implement score-based relevance ranking with high/medium relevance tiers
- Enhance context generation to include detailed information about similar tasks
- Fix context shadowing issue that prevented detailed task information from
  reaching the AI model
- Add informative CLI output showing semantic search results and dependency patterns
- Improve formatting of dependency information in prompts with task titles

The result is that newly created tasks are automatically placed within the correct
dependency structure without manual intervention, with the AI having much better
context about which tasks are most relevant to the new one being created.

This significantly improves the user experience by reducing the need to manually
update task dependencies after creation, all without increasing token usage or costs.
2025-05-22 01:09:40 -04:00
Eyal Toledano
d2e64318e2 fix(ai-services): add logic for API key checking in fallback sequence 2025-05-21 22:49:25 -04:00
Eyal Toledano
4c835264ac task management 2025-05-21 21:23:39 -04:00
github-actions[bot]
c882f89a8c Version Packages 2025-05-20 18:40:38 +02:00
Ralph Khreish
20e1b72a17 Merge pull request #549 from eyaltoledano/changeset-release/main
Version Packages
2025-05-20 00:34:13 +02:00
github-actions[bot]
db631f43a5 Version Packages 2025-05-19 22:31:08 +00:00
Ralph Khreish
3b9402f1f8 Merge Release 0.14.0 #529
Release 0.14.0
2025-05-20 00:30:46 +02:00
Ralph Khreish
c8c0fc2a57 fix: improve ollama object to telemetry structure (#546) 2025-05-19 23:05:45 +02:00
HR
60b8e97a1c fix: roomodes typo (#544) 2025-05-19 17:00:06 +02:00
github-actions[bot]
3a6d6dd671 chore: rc version bump 2025-05-18 08:08:54 +00:00
Ralph Khreish
f4a83ec047 feat: add ollama support (#536) 2025-05-18 10:07:31 +02:00
Eyal Toledano
0699f64299 Merge pull request #442 from eyaltoledano/telemetry
feat(telemetry): Implement AI usage telemetry pattern and apply to ad…
2025-05-17 22:34:01 -04:00
Eyal Toledano
60b8f5faa3 fix(expand-task): Ensure advanced parsing logic works and trimmed AI response properly if any jsonToParse modifications need to be made on initial parse of response. 2025-05-17 22:26:37 -04:00
Eyal Toledano
cd6e42249e fix(parse-prd): simplifies append and force variable names across the chain to avoid confusion. parse-prd append tested on MCP and the fix is good to go. Also adjusts e2e test to properly capture costs. 2025-05-17 20:10:53 -04:00
Eyal Toledano
fcd80623b6 linting 2025-05-17 18:43:15 -04:00
Eyal Toledano
026815353f fix(ai): Correctly imports generateText in openai.js, adds specific cause and reason for OpenRouter failures in the openrouter.js catch, performs complexity analysis on all tm tasks, adds new tasks to further improve the maxTokens to take input and output maximum into account. Adjusts default fallback max tokens so 3.5 does not fail. 2025-05-17 18:42:57 -04:00
Eyal Toledano
8a3b611fc2 fix(telemetry): renames _aggregateTelemetry to aggregateTelemetry to avoid confusion about it being a private function (it's not) 2025-05-17 17:48:45 -04:00
Eyal Toledano
6ba42b53dc fix: dupe export 2025-05-16 18:17:33 -04:00
Eyal Toledano
3e304232ab Solves merge conflicts with origin/next. 2025-05-16 18:15:11 -04:00
Eyal Toledano
70fa5b0031 fix(config): adjusts getUserId to optionally create/fill in the (currently hardcoded) userId to the telemetry object if it is not found. This prevents the telemetry call from landing as null for users who may have a taskmasterconfig but no userId in the globals. 2025-05-16 17:41:48 -04:00
github-actions[bot]
314c0de8c4 chore: rc version bump 2025-05-16 21:37:00 +00:00
Ralph Khreish
58b417a8ce Add complexity score to task (#528)
* feat: added complexity score handling to list tasks

* feat: added handling for complexity score in find task by id

* test: remove console dir

* chore: add changeset

* format: fixed formatting issues

* ref: reorder imports

* feat: updated handling for findTaskById to take complexityReport as input

* test: fix findTaskById complexity report testcases

* fix: added handling for complexity report path

* chore: add changeset

* fix: moved complexity report handling to list tasks rather than list tasks direct

* fix: add complexity handling to next task in list command

* fix: added handling for show cli

* fix: fixed next cli command handling

* fix: fixed handling for complexity report path in mcp

* feat: added handling to get-task

* feat: added handling for next-task in mcp

* feat: add handling for report path override

* chore: remove unecessary changeset

* ref: remove unecessary comments

* feat: update list and find next task

* fix: fixed running tests

* fix: fixed findTaskById

* fix: fixed findTaskById and tests

* fix: fixed addComplexityToTask util

* fix: fixed mcp server project root input

* chore: cleanup

---------

Co-authored-by: Shrey Paharia <shreypaharia@gmail.com>
2025-05-16 23:24:25 +02:00
Ralph Khreish
a8dabf4485 fix: remove cache from list-tasks and next-task mcp calls (#527)
* fix: remove cache from list-tasks and next-task mcp calls

* chore: remove cached function

* chore: add changeset
2025-05-16 22:54:03 +02:00
Ralph Khreish
bc19bc7927 Merge remote-tracking branch 'origin/next' into telemetry 2025-05-16 18:16:58 +02:00
Ralph Khreish
da317f2607 fix: error handling of task status settings (#523)
* fix: error handling of task status settings

* fix: update import path

---------

Co-authored-by: shenysun <shenysun@163.com>
2025-05-16 15:47:01 +02:00
Ralph Khreish
ed17cb0e0a feat: implement baseUrls on all ai providers(#521) 2025-05-16 15:34:29 +02:00
Ralph Khreish
e96734a6cc fix: updateTask enableSilentMode is not defined (#517)
- Closes #412
2025-05-15 22:56:52 +02:00
Ralph Khreish
17294ff259 Fix: Correct version resolution for banner and update check (#511)
* Fix: Correct version resolution for banner and update check

Resolves issues where the tool's version was displayed as 'unknown'.

- Modified 'displayBanner' in 'ui.js' and 'checkForUpdate' in 'commands.js' to read package.json relative to their own script locations using import.meta.url.
- This ensures the correct local version is identified for both the main banner display and the update notification mechanism.
- Restored a missing closing brace in 'ui.js' to fix a SyntaxError.

* fix: refactor and cleanup

* fix: chores and cleanup and testing

* chore: cleanup

* fix: add changeset

---------

Co-authored-by: Christer Soederlund <christer.soderlund@gmail.com>
2025-05-15 22:41:16 +02:00
Lars Bell
a96215a359 Update .taskmasterconfig (#435)
* Update .taskmasterconfig

Max tokens in 3.5 is lower.  With the current number get this error:

Service call failed for role fallback (Provider: anthropic, Model: claude-3-5-sonnet-20240620): max_tokens: 120000 > 8192, which is the maximum allowed number of output tokens for claude-3-5-sonnet-20240620

* Fix fallback model ID format and update maxTokens in Taskmaster configuration

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-15 13:01:21 +02:00
Ralph Khreish
0a611843b5 fix: Inline comments in .env.example conflicting with env variable values (#501)
* fix: Update API key format in env.example to use quotes for consistency

* chore: add changelog
2025-05-15 01:32:49 +02:00
Kayvan Sylvan
a1f8d52474 chore: rename log level environment variable to TASKMASTER_LOG_LEVEL (#417)
* chore: rename log level environment variable to `TASKMASTER_LOG_LEVEL`

### CHANGES
- Update environment variable from `LOG_LEVEL` to `TASKMASTER_LOG_LEVEL`.
- Reflect change in documentation for clarity.
- Adjust variable name in script and test files.
- Maintain default log level as `info`.

* fix: add changeset

* chore: rename `LOG_LEVEL` to `TASKMASTER_LOG_LEVEL` for consistency

### CHANGES
- Update environment variable name to `TASKMASTER_LOG_LEVEL` in documentation.
- Reflect rename in configuration rules for clarity.
- Maintain consistency across project configuration settings.
2025-05-15 01:09:41 +02:00
Eyal Toledano
da636f6681 fix(e2e): further improves the end to end script to take into account the changes made for each AI provider as it now responds with an obejct not just the result straight up. 2025-05-14 19:04:47 -04:00
Eyal Toledano
ca5ec03cd8 fix(ai,tasks): Enhance AI provider robustness and task processing
This commit introduces several improvements to AI interactions and
task management functionalities:

- AI Provider Enhancements (for Telemetry & Robustness):
    - :
        - Added a check in  to ensure
          is a string, throwing an error if not. This prevents downstream
           errors (e.g., in ).
    - , , :
        - Standardized return structures for their respective
          and  functions to consistently include /
          and  fields. This aligns them with other providers (like
          Anthropic, Google, Perplexity) for consistent telemetry data
          collection, as part of implementing subtask 77.14 and similar work.

- Task Expansion ():
    - Updated  to be more explicit
      about using an empty array  for empty  to
      better guide AI output.
    - Implemented a pre-emptive cleanup step in
      to replace malformed  with
      before JSON parsing. This improves resilience to AI output quirks,
      particularly observed with Perplexity.

- Adjusts issue in commands.js where successfulRemovals would be undefined. It's properly invoked from the result variable now.

- Updates supported models for Gemini
These changes address issues observed during E2E tests, enhance the
reliability of AI-driven task analysis and expansion, and promote
consistent telemetry data across multiple AI providers.
2025-05-14 19:04:03 -04:00
Ralph Khreish
c47deeb869 Merge remote-tracking branch 'origin/main' into next 2025-05-15 00:29:54 +02:00
github-actions[bot]
dd90c9cb5d Version Packages 2025-05-15 00:29:11 +02:00
Ralph Khreish
c7042845d6 chore: improve CI to better accomodate pre-releases for testing (#507) 2025-05-15 00:28:06 +02:00
Eyal Toledano
79a41543d5 fix(ai): Align Perplexity provider with standard telemetry response structure
This commit updates the Perplexity AI provider () to ensure its functions return data in a structure consistent with other providers and the expectations of the unified AI service layer ().

Specifically:
-  now returns an object  instead of only the text string.
-  now returns an object  instead of only the result object.

These changes ensure that  can correctly extract both the primary AI-generated content and the token usage data for telemetry purposes when Perplexity models are used. This resolves issues encountered during E2E testing where complexity analysis (which can use Perplexity for its research role) failed due to unexpected response formats.

The  function was already compliant.
2025-05-14 11:46:35 -04:00
Joe Danziger
efce37469b Fix duplicate output on CLI help screen (#496)
* remove duplication

* add changeset

* fix formatting
2025-05-14 13:12:15 +02:00
Joe Danziger
4117f71c18 Fix CLI --force flag on parse-prd command 2025-05-13 22:06:09 +02:00
Eyal Toledano
9f4bac8d6a fix(ai): Improve AI object response handling in parse-prd
This commit updates  to more robustly handle responses from .

Previously, the module strictly expected the AI-generated object to be nested under . This change ensures that it now first checks if  itself contains the expected task data object, and then falls back to checking .

This enhancement increases compatibility with varying AI provider response structures, similar to the improvements recently made in .
2025-05-13 13:21:51 -04:00
Eyal Toledano
e53d5e1577 feat(ai): Enhance Google provider telemetry and AI object response handling
This commit introduces two key improvements:

1.  **Google Provider Telemetry:**
    - Updated  to include token usage data (, ) in the responses from  and .
    - This aligns the Google provider with others for consistent AI usage telemetry.

2.  **Robust AI Object Response Handling:**
    - Modified  to more flexibly handle responses from .
    - The add-task module now check for the AI-generated object in both  and , improving compatibility with different AI provider response structures (e.g., Gemini).

These changes enhance the reliability of AI interactions, particularly with the Google provider, and ensure accurate telemetry collection.
2025-05-13 12:13:35 -04:00
Eyal Toledano
59230c4d91 chore: task management and formatting. 2025-05-09 14:12:21 -04:00
Eyal Toledano
04b6a3cb21 feat(telemetry): Integrate AI usage telemetry into analyze-complexity
This commit applies the standard telemetry pattern to the analyze-task-complexity command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/analyze-task-complexity.js):
    -   The call to generateTextService now includes commandName: 'analyze-complexity' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the complexity report JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { report: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/analyze-task-complexity.js):
    -   The call to the core analyzeTaskComplexity function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:34:00 -04:00
Eyal Toledano
37178ff1b9 feat(telemetry): Integrate AI usage telemetry into update-subtask
This commit applies the standard telemetry pattern to the update-subtask command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-subtask-by-id.js):
    -   The call to generateTextService now includes commandName: 'update-subtask' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for the appended content.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { updatedSubtask: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-subtask-by-id.js):
    -   The call to the core updateSubtaskById function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:04:25 -04:00
Eyal Toledano
bbc8b9cc1f feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the update-tasks command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-tasks.js):
    -   The call to generateTextService now includes commandName: 'update-tasks' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { success: true, updatedTasks: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-tasks.js):
    -   The call to the core updateTasks function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 18:51:29 -04:00
Eyal Toledano
c955431753 feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the  command and its corresponding MCP tool.

Key Changes:

1.  **Core Logic ():**
    -   The call to  now includes  and .
    -   The full response  is captured.
    -    (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (),  is called with the .
    -   The function now returns .

2.  **Direct Function ():**
    -   The call to the core  function now passes the necessary context for telemetry (, ).
    -   The successful response object now correctly extracts  and includes it in the  field returned to the MCP client.
2025-05-08 18:37:41 -04:00
Eyal Toledano
21c3cb8cda feat(telemetry): Integrate telemetry for expand-all, aggregate results
This commit implements AI usage telemetry for the `expand-all-tasks` command/tool and refactors its CLI output for clarity and consistency.

Key Changes:

1.  **Telemetry Integration for `expand-all-tasks` (Subtask 77.8):**\n    -   The `expandAllTasks` core logic (`scripts/modules/task-manager/expand-all-tasks.js`) now calls the `expandTask` function for each eligible task and collects the individual `telemetryData` returned.\n    -   A new helper function `_aggregateTelemetry` (in `utils.js`) is used to sum up token counts and costs from all individual expansions into a single `telemetryData` object for the entire `expand-all` operation.\n    -   The `expandAllTasksDirect` wrapper (`mcp-server/src/core/direct-functions/expand-all-tasks.js`) now receives and passes this aggregated `telemetryData` in the MCP response.\n    -   For CLI usage, `displayAiUsageSummary` is called once with the aggregated telemetry.

2.  **Improved CLI Output for `expand-all`:**\n    -   The `expandAllTasks` core function now handles displaying a final "Expansion Summary" box (showing Attempted, Expanded, Skipped, Failed counts) directly after the aggregated telemetry summary.\n    -   This consolidates all summary output within the core function for better flow and removes redundant logging from the command action in `scripts/modules/commands.js`.\n    -   The summary box border is green for success and red if any expansions failed.

3.  **Code Refinements:**\n    -   Ensured `chalk` and `boxen` are imported in `expand-all-tasks.js` for the new summary box.\n    -   Minor adjustments to logging messages for clarity.
2025-05-08 18:22:00 -04:00
Eyal Toledano
ab84afd036 feat(telemetry): Integrate usage telemetry for expand-task, fix return types
This commit integrates AI usage telemetry for the `expand-task` command/tool and resolves issues related to incorrect return type handling and logging.

Key Changes:

1.  **Telemetry Integration for `expand-task` (Subtask 77.7):**\n    -   Applied the standard telemetry pattern to the `expandTask` core logic (`scripts/modules/task-manager/expand-task.js`) and the `expandTaskDirect` wrapper (`mcp-server/src/core/direct-functions/expand-task.js`).\n    -   AI service calls now pass `commandName` and `outputType`.\n    -   Core function returns `{ task, telemetryData }`.\n    -   Direct function correctly extracts `task` and passes `telemetryData` in the MCP response `data` field.\n    -   Telemetry summary is now displayed in the CLI output for the `expand` command.

2.  **Fix AI Service Return Type Handling (`ai-services-unified.js`):**\n    -   Corrected the `_unifiedServiceRunner` function to properly handle the return objects from provider-specific functions (`generateText`, `generateObject`).\n    -   It now correctly extracts `providerResponse.text` or `providerResponse.object` into the `mainResult` field based on `serviceType`, resolving the "text.trim is not a function" error encountered during `expand-task`.

3.  **Log Cleanup:**\n    -   Removed various redundant or excessive `console.log` statements across multiple files (as indicated by recent changes) to reduce noise and improve clarity, particularly for MCP interactions.
2025-05-08 16:02:23 -04:00
Eyal Toledano
f89d2aacc0 feat(telemetry): Integrate AI usage telemetry into parse-prd
Implements AI usage telemetry capture and propagation for the  command and MCP tool, following the established telemetry pattern.

Key changes:

-   **Core ():**
    -   Modified the  call to include  and .
    -   Updated to receive  from .
    -   Adjusted to return an object .
    -   Added a call to  to show telemetry data in the CLI output when not in MCP mode.

-   **Direct Function ():**
    -   Updated the call to the core  function to pass , , and .
    -   Modified to correctly handle the new return structure from the core function.
    -   Ensures  received from the core function is included in the  field of the successful MCP response.

-   **MCP Tool ():**
    -   No changes required; existing  correctly passes through the  object containing .

-   **CLI Command ():**
    -   The  command's action now relies on the core  function to handle CLI success messages and telemetry display.

This ensures that AI usage for the  functionality is tracked and can be displayed or logged as appropriate for both CLI and MCP interactions.
2025-05-07 14:22:42 -04:00
Eyal Toledano
0288311965 fix(parse-prd): resolves issue preventing --append flag from properly working in the CLI context. Adds changeset. 2025-05-07 14:17:41 -04:00
Eyal Toledano
8ae772086d fix(next): adjusts CLI output for next when the result is a subtask. previously incorrect suggested creating subtasks for the subtask. 2025-05-07 14:07:50 -04:00
Eyal Toledano
2b3ae8bf89 tests: adjusts the tests to properly pass. 2025-05-07 13:54:01 -04:00
Eyal Toledano
245c3cb398 feat(telemetry): Implement AI usage telemetry pattern and apply to add-task
This commit introduces a standardized pattern for capturing and propagating AI usage telemetry (cost, tokens, model used) across the Task Master stack and applies it to the 'add-task' functionality.

Key changes include:

- **Telemetry Pattern Definition:**
  - Added  defining the integration pattern for core logic, direct functions, MCP tools, and CLI commands.
  - Updated related rules (, ,
 Usage: mcp [OPTIONS] COMMAND [ARGS]...

 MCP development tools

╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --help          Show this message and exit.                                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ version   Show the MCP version.                                                                                                            │
│ dev       Run a MCP server with the MCP Inspector.                                                                                         │
│ run       Run a MCP server.                                                                                                                │
│ install   Install a MCP server in the Claude desktop app.                                                                                  │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯, , ) to reference the new telemetry rule.

- **Core Telemetry Implementation ():**
  - Refactored the unified AI service to generate and return a  object alongside the main AI result.
  - Fixed an MCP server startup crash by removing redundant local loading of  and instead using the  imported from  for cost calculations.
  - Added  to the  object.

- ** Integration:**
  - Modified  (core) to receive  from the AI service, return it, and call the new UI display function for CLI output.
  - Updated  to receive  from the core function and include it in the  payload of its response.
  - Ensured  (MCP tool) correctly passes the  through via .
  - Updated  to correctly pass context (, ) to the core  function and rely on it for CLI telemetry display.

- **UI Enhancement:**
  - Added  function to  to show telemetry details in the CLI.

- **Project Management:**
  - Added subtasks 77.6 through 77.12 to track the rollout of this telemetry pattern to other AI-powered commands (, , , , , , ).

This establishes the foundation for tracking AI usage across the application.
2025-05-07 13:41:25 -04:00
Ralph Khreish
09d839fff5 Merge pull request #405 from eyaltoledano/changeset-release/main
Version Packages
2025-05-03 20:46:10 +02:00
github-actions[bot]
90068348d3 Version Packages 2025-05-03 18:13:24 +00:00
Ralph Khreish
02e347d2d7 Merge pull request #404 from eyaltoledano/next
Release 0.13.2
2025-05-03 20:13:05 +02:00
Ralph Khreish
0527c363e3 Merge remote-tracking branch 'origin/main' into next 2025-05-03 19:32:07 +02:00
Ralph Khreish
735135efe9 chore: allow github actions to commit 2025-05-03 19:24:00 +02:00
Ralph Khreish
4fee667a05 chore: improve pre-release workflow 2025-05-03 19:07:42 +02:00
Ralph Khreish
01963af2cb Fix: issues with 0.13.0 not working (#402)
* Exit prerelease mode and version packages

* hotfix: move production package to "dependencies"

* Enter prerelease mode and version packages

* Enter prerelease mode and version packages

* chore: cleanup

* chore: improve pre.json and add pre-release workflow

* chore: fix package.json

* chore: cleanup
2025-05-03 18:55:18 +02:00
Ralph Khreish
0633895f3b Version Packages (#401)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-05-03 17:02:05 +02:00
github-actions[bot]
10442c1119 Version Packages 2025-05-03 14:56:40 +00:00
Ralph Khreish
734a4fdcfc hotfix: move production package to "dependencies" (#399) 2025-05-03 16:56:17 +02:00
Ralph Khreish
8dace2186c Merge pull request #390 from eyaltoledano/changeset-release/main
Version Packages
2025-05-03 10:17:11 +02:00
github-actions[bot]
095e373843 Version Packages 2025-05-03 08:14:02 +00:00
Ralph Khreish
0bc9bac392 Merge pull request #369 from eyaltoledano/next
Release 0.13.0
2025-05-03 10:13:43 +02:00
Eyal Toledano
0a45f4329c Merge pull request #389 from eyaltoledano/v013-final
fix(config): restores sonnet 3.7 as default main role.
2025-05-03 02:59:44 -04:00
Eyal Toledano
c4b2f7e514 fix(config): restores sonnet 3.7 as default main role. 2025-05-03 02:28:40 -04:00
Eyal Toledano
9684beafc3 Merge pull request #388 from eyaltoledano/readme-init-typo
chore: readme typos
2025-05-03 02:19:49 -04:00
Eyal Toledano
302b916045 chore: readme typos 2025-05-03 02:17:52 -04:00
Eyal Toledano
e7f18f65b9 Merge pull request #387 from eyaltoledano/v0.13-touchups
fix: improve error handling, test options, and model configuration

Final polish for v0.13.x
2025-05-03 02:12:40 -04:00
Eyal Toledano
655c7c225a chore: prettier 2025-05-03 02:09:35 -04:00
Eyal Toledano
e1218b3747 fix(next): adjusts mcp tool response to correctly return the next task/subtask. Also adds nextSteps to the next task response. 2025-05-03 02:06:50 -04:00
Eyal Toledano
ffa621a37c chore: removes tasks json backup that was temporarily created. 2025-05-03 01:33:03 -04:00
Eyal Toledano
cd32fd9edf fix(add/remove-dependency): dependency mcp tools were failing due to hard-coded tasks path in generate task files. 2025-05-03 01:31:16 -04:00
Eyal Toledano
590e4bd66d chore: restores 3.7 sonnet as the main role. 2025-05-03 00:35:24 -04:00
Eyal Toledano
70d3f2f103 chore(init): No longer ships readme with task-master init (commented out for now). No longer looking for task-master-mcp, instead checked for task-master-ai - this should prevent the init sequence from needlessly adding another mcp server with task-master-mcp to the mpc.json which a ton of people probably ran into. 2025-05-03 00:33:21 -04:00
Eyal Toledano
424aae10ed fix(parse-prd): suggested fix for mcpLog was incorrect. reverting to my previously working code. 2025-05-03 00:10:58 -04:00
Eyal Toledano
a48d1f13e2 chore: fixes parse prd to show loading indicator in cli. 2025-05-03 00:04:45 -04:00
Eyal Toledano
25ca1a45a0 fix: improve error handling, test options, and model configuration
- Enhance error validation in parse-prd.js and update-tasks.js
- Fix bug where mcpLog was incorrectly passed as logWrapper
- Improve error messages and response formatting
- Add --skip-verification flag to E2E tests
- Update MCP server config that ships with init to match new API key structure
- Fix task force/append handling in parse-prd command
- Increase column width in update-tasks display
2025-05-02 23:11:39 -04:00
Ralph Khreish
2e17437da3 fix: displayBanner logging when silentMode is active (#385) 2025-05-03 01:06:29 +02:00
Eyal Toledano
1f44ea5299 Merge pull request #378 from eyaltoledano/wsl-windows-fix
WSL + Windows Fix
2025-05-02 17:51:54 -04:00
Eyal Toledano
d63964a10e refactor: Improve update-subtask, consolidate utils, update config
This commit introduces several improvements and refactorings across MCP tools, core logic, and configuration.

**Major Changes:**

1.  **Refactor updateSubtaskById:**
    - Switched from generateTextService to generateObjectService for structured AI responses, using a Zod schema (subtaskSchema) for validation.
    - Revised prompts to have the AI generate relevant content based on user request and context (parent/sibling tasks), while explicitly preventing AI from handling timestamp/tag formatting.
    - Implemented **local timestamp generation (new Date().toISOString()) and formatting** (using <info added on ...> tags) within the function *after* receiving the AI response. This ensures reliable and correctly formatted details are appended.
    - Corrected logic to append only the locally formatted, AI-generated content block to the existing subtask.details.

2.  **Consolidate MCP Utilities:**
    - Moved/consolidated the withNormalizedProjectRoot HOF into mcp-server/src/tools/utils.js.
    - Updated MCP tools (like update-subtask.js) to import withNormalizedProjectRoot from the new location.

3.  **Refactor Project Initialization:**
    - Deleted the redundant mcp-server/src/core/direct-functions/initialize-project-direct.js file.
    - Updated mcp-server/src/core/task-master-core.js to import initializeProjectDirect from its correct location (./direct-functions/initialize-project.js).

**Other Changes:**

-   Updated .taskmasterconfig fallback model to claude-3-7-sonnet-20250219.
-   Clarified model cost representation in the models tool description (taskmaster.mdc and mcp-server/src/tools/models.js).
2025-05-02 17:48:59 -04:00
Ralph Khreish
33559e368c chore: more cleanup 2025-05-02 23:33:34 +02:00
Ralph Khreish
9f86306766 chore: cleanup tools to stop using rootFolder and remove unused imports 2025-05-02 21:50:35 +02:00
Ralph Khreish
8f8a3dc45d fix: add rest of tools that need wrapper 2025-05-02 19:56:13 +02:00
Ralph Khreish
d18351dc38 fix: apply to all tools withNormalizedProjectRoot to fix projectRoot issues for linux and windows 2025-05-02 18:32:12 +02:00
Eyal Toledano
9d437f8594 refactor(mcp): apply withNormalizedProjectRoot HOF to update tool
Problem: The  MCP tool previously handled project root acquisition and path resolution within its  method, leading to potential inconsistencies and repetition.

Solution: Refactored the  tool () to utilize the new  Higher-Order Function (HOF) from .

Specific Changes:
- Imported  HOF.
- Updated the Zod schema for the  parameter to be optional, as the HOF handles deriving it from the session if not provided.
- Wrapped the entire  function body with the  HOF.
- Removed the manual call to  from within the  function body.
- Destructured the  from the  object received by the wrapped  function, ensuring it's the normalized path provided by the HOF.
- Used the normalized  variable when calling  and when passing arguments to .

This change standardizes project root handling for the  tool, simplifies its  method, and ensures consistent path normalization. This serves as the pattern for refactoring other MCP tools.
2025-05-02 02:14:32 -04:00
Eyal Toledano
ad89253e31 refactor(mcp): introduce withNormalizedProjectRoot HOF for path normalization
Added HOF to mcp tools utils to normalize projectRoot from args/session. Refactored get-task tool to use HOF. Updated relevant documentation.
2025-05-02 01:54:24 -04:00
Eyal Toledano
70c5097553 Merge pull request #377 from eyaltoledano/fix-update-tasks-parsing
fix(update-tasks): Improve AI response parsing for 'update' command
2025-05-02 00:42:35 -04:00
Eyal Toledano
c9e4558a19 fix(update-tasks): Improve AI response parsing for 'update' command
Refactors the JSON array parsing logic within
in .

The previous logic primarily relied on extracting content from markdown
code blocks (json or javascript), which proved brittle when the AI
response included comments or non-JSON text within the block, leading to
parsing errors for the  command.

This change modifies the parsing strategy to first attempt extracting
content directly between the outermost '[' and ']' brackets. This is
more robust as it targets the expected array structure directly. If
bracket extraction fails, it falls back to looking for a strict json
code block, then prefix stripping, before attempting a raw parse.

This approach aligns with the successful parsing strategy used for
single-object responses in  and resolves the
parsing errors previously observed with the  command.
2025-05-02 00:37:41 -04:00
Eyal Toledano
cd4d8e335f MCP ENV fallback to read API keys in .env if not found in mcp.json
Problem:

- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
-This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env
- All AI commands (core functions, direct functions, mcp tools) have been fixed to ensure they pass `projectRoot` from the mcp tool up to the direct function and through to the core function such that it can use that root to access the user's .env file in the correct location (instead of trying to find it in the server's process.env which is useless).

Should have a big impact across the board for all users who were having API related issues
2025-05-01 23:52:17 -04:00
Eyal Toledano
16297058bb fix(expand-all): add projectRoot to expandAllTasksDirect invokation. 2025-05-01 22:47:50 -04:00
Eyal Toledano
ae2d43de29 chore: prettier 2025-05-01 22:43:36 -04:00
Eyal Toledano
f5585e6c31 fix(mcp, expand): pass projectRoot through expand/expand-all flows
Problem: expand_task & expand_all MCP tools failed with .env keys due to missing projectRoot propagation for API key resolution. Also fixed a ReferenceError: wasSilent is not defined in expandTaskDirect.

Solution: Modified core logic, direct functions, and MCP tools for expand-task and expand-all to correctly destructure projectRoot from arguments and pass it down through the context object to the AI service call (generateTextService). Fixed wasSilent scope in expandTaskDirect.

Verification: Tested expand_task successfully in MCP using .env keys. Reviewed expand_all flow for correct projectRoot propagation.
2025-05-01 22:37:33 -04:00
Eyal Toledano
303b13e3d4 fix(update-subtask): pass projectRoot and allow updating done subtasks
Modified update-subtask-by-id core, direct function, and tool to pass projectRoot for .env API key fallback. Removed check preventing appending details to completed subtasks.
2025-05-01 17:59:54 -04:00
Eyal Toledano
1862ca2360 fix(update-task): pass projectRoot and adjust parsing
Modified update-task-by-id core, direct function, and tool to pass projectRoot. Reverted parsing logic in core function to prioritize `{...}` extraction, resolving parsing errors. Fixed ReferenceError by correctly destructuring projectRoot.
2025-05-01 17:46:33 -04:00
Eyal Toledano
ad1c234b4e fix(parse-prd): pass projectRoot and fix schema/logging
Modified parse-prd core, direct function, and tool to pass projectRoot for .env API key fallback. Corrected Zod schema used in generateObjectService call. Fixed logFn reference error in core parsePRD. Updated unit test mock for utils.js.
2025-05-01 17:11:51 -04:00
Eyal Toledano
d07f8fddc5 fix(add-task): pass projectRoot and fix logging/refs
Modified add-task core, direct function, and tool to pass projectRoot for .env API key fallback. Fixed logFn reference error and removed deprecated reportProgress call in core addTask function. Verified working.
2025-05-01 14:53:15 -04:00
Eyal Toledano
c7158d4910 fix(analyze-complexity): pass projectRoot through analyze-complexity flow
Modified analyze-task-complexity.js core function, direct function, and analyze.js tool to correctly pass projectRoot. Fixed import error in tools/index.js. Added debug logging to _resolveApiKey in ai-services-unified.js. This enables the .env API key fallback for analyze_project_complexity.
2025-05-01 14:18:44 -04:00
Eyal Toledano
2a07d366be fix(update): pass projectRoot through update command flow
Modified ai-services-unified.js, update.js tool, and update-tasks.js direct function to correctly pass projectRoot. This enables the .env file API key fallback mechanism for the update command when running via MCP, ensuring consistent key resolution with the CLI context.
2025-05-01 13:45:11 -04:00
Eyal Toledano
40df57f969 fix: ensure API key detection properly reads .env in MCP context
Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env

Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env

Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works
2025-05-01 13:23:52 -04:00
Eyal Toledano
d4a2e34b3b Merge pull request #240 from eyaltoledano/better-ai-model-management
- introduces model management features across CLI and MCP
- introduces an interactive model setup
- introduces API key verification checks across CLI and MCP
- introduces Gemini support
- introduces OpenAI support
- introduces xAI support
- introduces OpenRouter support
- introduces custom model support via OpenRouter and soon Ollama
- introduces `--research` flag to the `add-task` command to hit up research model right away
- introduces `--status`  and `-s` flag for the `show` command (and `get-task` MCP tool) to filter subtasks by any status
- bunch of small fixes and a few stealth additions
- refactors test suite to work with new structure
- introduces AI powered E2E test for testing all Taskmaster CLI commands
2025-04-30 22:13:46 -04:00
Eyal Toledano
d67b21fd43 chore(wtf): removes chai. not sure how that even made it in here. also removes duplicate test in scripts/. 2025-04-30 22:06:04 -04:00
Eyal Toledano
b1beae3042 chore(tests): Passes tests for merge candidate
- Adjusted the interactive model default choice to be 'no change' instead of 'cancel setup'
- E2E script has been perfected and works as designed provided there are all provider API keys .env in the root
- Fixes the entire test suite to make sure it passes with the new architecture.
- Fixes dependency command to properly show there is a validation failure if there is one.
- Refactored config-manager.test.js mocking strategy and fixed assertions to read the real supported-models.json
- Fixed rule-transformer.test.js assertion syntax and transformation logic adjusting replacement for search which was too broad.
- Skip unstable tests in utils.test.js (log, readJSON, writeJSON error paths) due to SIGABRT crash. These tests trigger a native crash (SIGABRT), likely stemming from a conflict between internal chalk usage within the functions and Jest's test environment, possibly related to ESM module handling.
2025-04-30 22:02:02 -04:00
Eyal Toledano
d2f761c652 fix merge conflicts to prep for merge with branch next
- Enhance E2E testing and LLM analysis report and:
  - Add --analyze-log flag to run_e2e.sh to re-run LLM analysis on existing logs.
  - Add test:e2e and analyze-log scripts to package.json for easier execution.

- Correct display errors and dependency validation output:
  - Update chalk usage in add-task.js to use bracket notation (chalk[color]) compatible with v5, resolving 'chalk.keyword is not a function' error.
  - Modify fix-dependencies command output to show red failure box with issue count instead of green success box when validation fails.

- Refactor interactive model setup:
  - Verify inclusion of 'No change' option during interactive model setup flow (task-master models --setup).

- Update model definitions:
  - Add max_tokens field for gpt-4o in supported-models.json.

- Remove unused scripts:
  - Delete prepare-package.js and rule-transformer.test.js.

Release candidate
2025-04-29 01:54:42 -04:00
Eyal Toledano
4cf7e8a74a Refactor: Improve MCP logging, update E2E & tests
Refactors MCP server logging and updates testing infrastructure.

- MCP Server:

  - Replaced manual logger wrappers with centralized `createLogWrapper` utility.

  - Updated direct function calls to use `{ session, mcpLog }` context.

  - Removed deprecated `model` parameter from analyze, expand-all, expand-task tools.

  - Adjusted MCP tool import paths and parameter descriptions.

- Documentation:

  - Modified `docs/configuration.md`.

  - Modified `docs/tutorial.md`.

- Testing:

  - E2E Script (`run_e2e.sh`):

    - Removed `set -e`.

    - Added LLM analysis function (`analyze_log_with_llm`) & integration.

    - Adjusted test run directory creation timing.

    - Added debug echo statements.

  - Deleted Unit Tests: Removed `ai-client-factory.test.js`, `ai-client-utils.test.js`, `ai-services.test.js`.

  - Modified Fixtures: Updated `scripts/task-complexity-report.json`.

- Dev Scripts:

  - Modified `scripts/dev.js`.
2025-04-28 14:38:01 -04:00
Eyal Toledano
5f504fafb8 refactor(init): Improve robustness and dependencies; Update template deps for AI SDKs; Silence npm install in MCP; Improve conditional model setup logic; Refactor init.js flags; Tweak Getting Started text; Fix MCP server launch command; Update default model in config template 2025-04-28 04:08:10 -04:00
Marijn van der Werf
e69a47d382 Update Discord badge (#337) 2025-04-28 08:39:52 +02:00
Yuval
89bb62d44b Update README.md (#342) 2025-04-28 08:38:43 +02:00
Eyal Toledano
5aea93d4c0 fix(tasks): Enable removing multiple tasks/subtasks via comma-separated IDs
- Refactors the core `removeTask` function (`task-manager/remove-task.js`) to accept and iterate over comma-separated task/subtask IDs.

- Updates dependency cleanup and file regeneration logic to run once after processing all specified IDs.

- Adjusts the `remove-task` CLI command (`commands.js`) description and confirmation prompt to handle multiple IDs correctly.

- Fixes a bug in the CLI confirmation prompt where task/subtask titles were not being displayed correctly.

- Updates the `remove_task` MCP tool description to reflect the new multi-ID capability.

This addresses the previously known issue where only the first ID in a comma-separated list was processed.

Closes #140
2025-04-28 00:42:05 -04:00
Eyal Toledano
66ac9ab9f6 fix(tasks): Improve next task logic to be subtask-aware 2025-04-28 00:27:19 -04:00
Eyal Toledano
ca7b0457f1 feat(cli): Add --status/-s filter flag to show command and get-task MCP tool
Implements the ability to filter subtasks displayed by the `task-master show <id>` command using the `--status` (or `-s`) flag. This is also available in the MCP context.

- Modified `commands.js` to add the `--status` option to the `show` command definition.

- Updated `utils.js` (`findTaskById`) to handle the filtering logic and return original subtask counts/arrays when filtering.

- Updated `ui.js` (`displayTaskById`) to use the filtered subtasks for the table, display a summary line when filtering, and use the original subtask list for the progress bar calculation.

- Updated MCP `get_task` tool and `showTaskDirect` function to accept and pass the `status` parameter.

- Added changeset entry.
2025-04-27 18:50:47 -04:00
Eyal Toledano
87d97bba00 feat(ai): Add OpenRouter AI provider support
Integrates the OpenRouter AI provider using the Vercel AI SDK adapter (@openrouter/ai-sdk-provider). This allows users to configure and utilize models available through the OpenRouter platform.

- Added src/ai-providers/openrouter.js with standard Vercel AI SDK wrapper functions (generateText, streamText, generateObject).

- Updated ai-services-unified.js to include the OpenRouter provider in the PROVIDER_FUNCTIONS map and API key resolution logic.

- Verified config-manager.js handles OpenRouter API key checks correctly.

- Users can configure OpenRouter models via .taskmasterconfig using the task-master models command or MCP models tool. Requires OPENROUTER_API_KEY.

- Enhanced error handling in ai-services-unified.js to provide clearer messages when generateObjectService fails due to lack of underlying tool support in the selected model/provider endpoint.
2025-04-27 18:23:56 -04:00
Eyal Toledano
3516efdc3b chore(docs): update docs and rules related to model management. 2025-04-27 17:32:59 -04:00
Eyal Toledano
c8722b0a7a feat(models): implement custom model support for ollama/openrouter
Adds the ability for users to specify custom model IDs for Ollama and OpenRouter providers, bypassing the internal supported model list.

    - Introduces --ollama and --openrouter flags for the 'task-master models --set-<role>' command.
    - Updates the interactive 'task-master models --setup' to include options for entering custom Ollama/OpenRouter IDs.
    - Implements live validation against the OpenRouter API when a custom OpenRouter ID is provided.
    - Refines the model setting logic to prioritize explicit provider flags/choices.
    - Adds warnings when custom models are set.
    - Updates the changeset file.
2025-04-27 17:25:54 -04:00
Eyal Toledano
ed79d4f473 feat(ai): Add xAI provider and Grok models
Integrates the xAI provider into the unified AI service layer, allowing the use of Grok models (e.g., grok-3, grok-3-mini).

    Changes include:
    - Added  dependency.
    - Created  with implementations for generateText, streamText, and generateObject (stubbed).
    - Updated  to include the xAI provider in the function map.
    - Updated  to recognize the 'xai' provider and the  environment variable.
    - Updated  to include known Grok models and their capabilities (object generation marked as likely unsupported).
2025-04-27 14:47:50 -04:00
Eyal Toledano
2517bc112c feat(ai): Integrate OpenAI provider and enhance model config
- Add OpenAI provider implementation using @ai-sdk/openai.\n- Update `models` command/tool to display API key status for configured providers.\n- Implement model-specific `maxTokens` override logic in `config-manager.js` using `supported-models.json`.\n- Improve AI error message parsing in `ai-services-unified.js` for better clarity.
2025-04-27 03:56:23 -04:00
Eyal Toledano
842eaf7224 feat(ai): Add Google Gemini provider support and fix config loading 2025-04-27 01:24:38 -04:00
Eyal Toledano
96aeeffc19 fix(cli): Correctly pass manual task data in add-task command
The add-task command handler in commands.js was incorrectly passing null for the manualTaskData parameter to the core addTask function. This caused the core function to always fall back to the AI generation path, even when only manual flags like --title and --description were provided. This commit updates the call to pass the correctly constructed manualTaskData object, ensuring that manual task creation via the CLI works as intended without unnecessarily calling the AI service.
2025-04-26 18:30:02 -04:00
itsgreyum
5a2371b7cc Fix --tasks to --num-tasks in ui (#328) 2025-04-26 19:26:08 +02:00
Eyal Toledano
b47f189cc2 chore: Remove unused imports across modules
Removes unused import statements identified after the major refactoring of the AI service layer and other components. This cleanup improves code clarity and removes unnecessary dependencies.

Unused imports removed from:

- **`mcp-server/src/core/direct-functions/analyze-task-complexity.js`:**

    - Removed `path`

- **`mcp-server/src/core/direct-functions/complexity-report.js`:**

    - Removed `path`

- **`mcp-server/src/core/direct-functions/expand-all-tasks.js`:**

    - Removed `path`, `fs`

- **`mcp-server/src/core/direct-functions/generate-task-files.js`:**

    - Removed `path`

- **`mcp-server/src/core/direct-functions/parse-prd.js`:**

    - Removed `os`, `findTasksJsonPath`

- **`mcp-server/src/core/direct-functions/update-tasks.js`:**

    - Removed `isSilentMode`

- **`mcp-server/src/tools/add-task.js`:**

    - Removed `createContentResponse`, `executeTaskMasterCommand`

- **`mcp-server/src/tools/analyze.js`:**

    - Removed `getProjectRootFromSession` (as `projectRoot` is now required in args)

- **`mcp-server/src/tools/expand-task.js`:**

    - Removed `path`

- **`mcp-server/src/tools/initialize-project.js`:**

    - Removed `createContentResponse`

- **`mcp-server/src/tools/parse-prd.js`:**

    - Removed `findPRDDocumentPath`, `resolveTasksOutputPath` (logic moved or handled by `resolveProjectPaths`)

- **`mcp-server/src/tools/update.js`:**

    - Removed `getProjectRootFromSession` (as `projectRoot` is now required in args)

- **`scripts/modules/commands.js`:**

    - Removed `exec`, `readline`

    - Removed AI config getters (`getMainModelId`, etc.)

    - Removed MCP helpers (`getMcpApiKeyStatus`)

- **`scripts/modules/config-manager.js`:**

    - Removed `ZodError`, `readJSON`, `writeJSON`

- **`scripts/modules/task-manager/analyze-task-complexity.js`:**

    - Removed AI config getters (`getMainModelId`, etc.)

- **`scripts/modules/task-manager/expand-all-tasks.js`:**

    - Removed `fs`, `path`, `writeJSON`

- **`scripts/modules/task-manager/models.js`:**

    - Removed `VALID_PROVIDERS`

- **`scripts/modules/task-manager/update-subtask-by-id.js`:**

    - Removed AI config getters (`getMainModelId`, etc.)

- **`scripts/modules/task-manager/update-tasks.js`:**

    - Removed AI config getters (`getMainModelId`, etc.)

- **`scripts/modules/ui.js`:**

    - Removed `getDebugFlag`

- **`scripts/modules/utils.js`:**

    - Removed `ZodError`
2025-04-25 15:11:55 -04:00
Eyal Toledano
36d559db26 docs: Update documentation for new AI/config architecture and finalize cleanup
This commit updates all relevant documentation (READMEs, docs/*, .cursor/rules) to accurately reflect the finalized unified AI service architecture and the new configuration system (.taskmasterconfig + .env/mcp.json). It also includes the final code cleanup steps related to the refactoring.

Key Changes:

1.  **Documentation Updates:**

    *   Revised `README.md`, `README-task-master.md`, `assets/scripts_README.md`, `docs/configuration.md`, and `docs/tutorial.md` to explain the new configuration split (.taskmasterconfig vs .env/mcp.json).

    *   Updated MCP configuration examples in READMEs and tutorials to only include API keys in the `env` block.

    *   Added/updated examples for using the `--research` flag in `docs/command-reference.md`, `docs/examples.md`, and `docs/tutorial.md`.

    *   Updated `.cursor/rules/ai_services.mdc`, `.cursor/rules/architecture.mdc`, `.cursor/rules/dev_workflow.mdc`, `.cursor/rules/mcp.mdc`, `.cursor/rules/taskmaster.mdc`, `.cursor/rules/utilities.mdc`, and `.cursor/rules/new_features.mdc` to align with the new architecture, removing references to old patterns/files.

    *   Removed internal rule links from user-facing rules (`taskmaster.mdc`, `dev_workflow.mdc`, `self_improve.mdc`).

    *   Deleted outdated example file `docs/ai-client-utils-example.md`.

2.  **Final Code Refactor & Cleanup:**

    *   Corrected `update-task-by-id.js` by removing the last import from the old `ai-services.js`.

    *   Refactored `update-subtask-by-id.js` to correctly use the unified service and logger patterns.

    *   Removed the obsolete export block from `mcp-server/src/core/task-master-core.js`.

    *   Corrected logger implementation in `update-tasks.js` for CLI context.

    *   Updated API key mapping in `config-manager.js` and `ai-services-unified.js`.

3.  **Configuration Files:**

    *   Updated API keys in `.cursor/mcp.json`, replacing `GROK_API_KEY` with `XAI_API_KEY`.

    *   Updated `.env.example` with current API key names.

    *   Added `azureOpenaiBaseUrl` to `.taskmasterconfig` example.

4.  **Task Management:**

    *   Marked documentation subtask 61.10 as 'done'.

    *   Includes various other task content/status updates from the diff summary.

5.  **Changeset:**

    *   Added `.changeset/cuddly-zebras-matter.md` for user-facing `expand`/`expand-all` improvements.

This commit concludes the major architectural refactoring (Task 61) and ensures the documentation accurately reflects the current system.
2025-04-25 14:43:12 -04:00
Eyal Toledano
afb47584bd feat(refactor): Finalize AI service migration and cleanup obsolete files
This commit completes the major refactoring initiative (Task 61) to migrate all AI-interacting task management functions to the unified service layer (`ai-services-unified.js`) and standardized configuration (`config-manager.js`).

Key Changes:

1.  **Refactor `update-task-by-id` & `update-subtask-by-id`:**

    *   Replaced direct AI client logic and config fetching with calls to `generateTextService`.

    *   Preserved original prompt logic while ensuring JSON output format is requested.

    *   Implemented robust manual JSON parsing and Zod validation for text-based AI responses.

    *   Corrected logger implementation (`logFn`/`isMCP`/`report` pattern) for both CLI and MCP contexts.

    *   Ensured correct passing of `session` context to the unified service.

    *   Refactored associated direct function wrappers (`updateTaskByIdDirect`, `updateSubtaskByIdDirect`) to remove AI client initialization and call core logic appropriately.

2.  **CLI Environment Loading:**

    *   Added `dotenv.config()` to `scripts/dev.js` to ensure consistent loading of the `.env` file for CLI operations.

3.  **Obsolete Code Removal:**

    *   Deleted unused helper files:

        *   `scripts/modules/task-manager/get-subtasks-from-ai.js`

        *   `scripts/modules/task-manager/generate-subtask-prompt.js`

        *   `scripts/modules/ai-services.js`

        *   `scripts/modules/ai-client-factory.js`

        *   `mcp-server/src/core/utils/ai-client-utils.js`

    *   Removed corresponding imports/exports from `scripts/modules/task-manager.js` and `mcp-server/src/core/task-master-core.js`.

4.  **Verification:**

    *   Successfully tested `update-task` and `update-subtask` via both CLI and MCP after refactoring.

5.  **Task Management:**

    *   Marked subtasks 61.38, 61.39, 61.40, 61.41, and 61.33 as 'done'.

    *   Includes other task content/status updates as reflected in the diff.

This completes the migration of core AI features to the new architecture, enhancing maintainability and flexibility.
2025-04-25 13:24:15 -04:00
Eyal Toledano
3721359782 refactor(tasks): Align update-tasks with unified AI service and remove obsolete helpers
Completes the refactoring of the AI-interacting task management functions by aligning `update-tasks.js` with the unified service architecture and removing now-unused helper files.

Key Changes:

- **`update-tasks.js` Refactoring:**

    - Replaced direct AI client calls and AI-specific config fetching with a call to `generateTextService` from `ai-services-unified.js`.

    - Preserved the original system and user prompts requesting a JSON array output.

    - Implemented manual JSON parsing (`parseUpdatedTasksFromText`) with Zod validation to handle the text response reliably.

    - Updated the core function signature to accept the standard `context` object (`{ session, mcpLog }`).

    - Corrected logger implementation to handle both MCP (`mcpLog`) and CLI (`consoleLog`) contexts appropriately.

- **Related Component Updates:**

    - Refactored `mcp-server/src/core/direct-functions/update-tasks.js` to use the standard direct function pattern (logger wrapper, silent mode, call core function with context).

    - Verified `mcp-server/src/tools/update.js` correctly passes arguments and context.

    - Verified `scripts/modules/commands.js` (update command) correctly calls the refactored core function.

- **Obsolete File Cleanup:**

    - Removed the now-unused `scripts/modules/task-manager/get-subtasks-from-ai.js` file and its export, as its functionality was integrated into `expand-task.js`.

    - Removed the now-unused `scripts/modules/task-manager/generate-subtask-prompt.js` file and its export for the same reason.

- **Task Management:**

    - Marked subtasks 61.38, 61.39, and 61.41 as complete.

This commit finalizes the alignment of `updateTasks`, `updateTaskById`, `expandTask`, `expandAllTasks`, `analyzeTaskComplexity`, `addTask`, and `parsePRD` with the unified AI service and configuration management patterns.
2025-04-25 04:09:14 -04:00
Eyal Toledano
ef782ff5bd refactor(expand/all): Implement additive expansion and complexity report integration
Refactors the `expandTask` and `expandAllTasks` features to complete subtask 61.38 and enhance functionality based on subtask 61.37's refactor.

Key Changes:

- **Additive Expansion (`expandTask`, `expandAllTasks`):**

    - Modified `expandTask` default behavior to append newly generated subtasks to any existing ones.

    - Added a `force` flag (passed down from CLI/MCP via `--force` option/parameter) to `expandTask` and `expandAllTasks`. When `force` is true, existing subtasks are cleared before generating new ones.

    - Updated relevant CLI command (`expand`), MCP tool (`expand_task`, `expand_all`), and direct function wrappers (`expandTaskDirect`, `expandAllTasksDirect`) to handle and pass the `force` flag.

- **Complexity Report Integration (`expandTask`):**

    - `expandTask` now reads `scripts/task-complexity-report.json`.

    - If an analysis entry exists for the target task:

        - `recommendedSubtasks` is used to determine the number of subtasks to generate (unless `--num` is explicitly provided).

        - `expansionPrompt` is used as the primary prompt content for the AI.

        - `reasoning` is appended to any additional context provided.

    - If no report entry exists or the report is missing, it falls back to default subtask count (from config) and standard prompt generation.

- **`expandAllTasks` Orchestration:**

    - Refactored `expandAllTasks` to primarily iterate through eligible tasks (pending/in-progress, considering `force` flag and existing subtasks) and call the updated `expandTask` function for each.

    - Removed redundant logic (like complexity reading or explicit subtask clearing) now handled within `expandTask`.

    - Ensures correct context (`session`, `mcpLog`) and flags (`useResearch`, `force`) are passed down.

- **Configuration & Cleanup:**

    - Updated `.cursor/mcp.json` with new Perplexity/Anthropic API keys (old ones invalidated).

    - Completed refactoring of `expandTask` started in 61.37, confirming usage of `generateTextService` and appropriate prompts.

- **Task Management:**

    - Marked subtask 61.37 as complete.

    - Updated `.changeset/cuddly-zebras-matter.md` to reflect user-facing changes.

These changes finalize the refactoring of the task expansion features, making them more robust, configurable via complexity analysis, and aligned with the unified AI service architecture.
2025-04-25 02:57:08 -04:00
Eyal Toledano
99b1a0ad7a refactor(expand): Align expand-task with unified AI service
Refactored the `expandTask` feature (`scripts/modules/task-manager/expand-task.js`) and related components (`commands.js`, `mcp-server/src/tools/expand-task.js`, `mcp-server/src/core/direct-functions/expand-task.js`) to integrate with the unified AI service layer (`ai-services-unified.js`) and configuration management (`config-manager.js`).

The refactor involved:

- Removing direct AI client calls and configuration fetching from `expand-task.js`.

- Attempting to use `generateObjectService` for structured subtask generation. This failed due to provider-specific errors (Perplexity internal errors, Anthropic schema translation issues).

- Reverting the core AI interaction to use `generateTextService`, asking the LLM to format its response as JSON containing a "subtasks" array.

- Re-implementing manual JSON parsing and Zod validation (`parseSubtasksFromText`) to handle the text response reliably.

- Updating prompt generation functions (`generateMainSystemPrompt`, `generateMainUserPrompt`, `generateResearchUserPrompt`) to request the correct JSON object structure within the text response.

- Ensuring the `expandTaskDirect` function handles pre-checks (force flag, task status) and correctly passes the `session` context and logger wrapper to the core `expandTask` function.

- Correcting duplicate imports in `commands.js`.

- Validating the refactored feature works correctly via both CLI (`task-master expand --id <id>`) and MCP (`expand_task` tool) for main and research roles.

This aligns the task expansion feature with the new architecture while using the more robust text generation approach due to current limitations with structured output services. Closes subtask 61.37.
2025-04-25 01:26:42 -04:00
Eyal Toledano
70cc15bc87 refactor(analyze): Align complexity analysis with unified AI service
Refactored the  feature and related components (CLI command, MCP tool, direct function) to integrate with the unified AI service layer ().

Initially,  was implemented to leverage structured output generation. However, this approach encountered persistent errors:
- Perplexity provider returned internal server errors.
- Anthropic provider failed with schema type and model errors.

Due to the unreliability of  for this specific use case, the core AI interaction within  was reverted to use . Basic manual JSON parsing and cleanup logic for the text response were reintroduced.

Key changes include:
- Removed direct AI client initialization (Anthropic, Perplexity).
- Removed direct fetching of AI model configuration parameters.
- Removed manual AI retry/fallback/streaming logic.
- Replaced direct AI calls with a call to .
- Updated  wrapper to pass session context correctly.
- Updated  MCP tool for correct path resolution and argument passing.
- Updated  CLI command for correct path resolution.
- Preserved core functionality: task loading/filtering, report generation, CLI summary display.

Both the CLI command ([INFO] Initialized Perplexity client with OpenAI compatibility layer
[INFO] Initialized Perplexity client with OpenAI compatibility layer
Analyzing task complexity from: tasks/tasks.json
Output report will be saved to: scripts/task-complexity-report.json
Analyzing task complexity and generating expansion recommendations...
[INFO] Reading tasks from tasks/tasks.json...
[INFO] Found 62 total tasks in the task file.
[INFO] Skipping 31 tasks marked as done/cancelled/deferred. Analyzing 31 active tasks.
Skipping 31 tasks marked as done/cancelled/deferred. Analyzing 31 active tasks.
[INFO] Claude API attempt 1/2
[ERROR] Error in Claude API call: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Non-overload Claude API error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
Claude API error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Error during AI analysis: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Error analyzing task complexity: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}) and the MCP tool () have been verified to work correctly with this revised approach.
2025-04-24 22:33:33 -04:00
Ralph Khreish
ce51b0d3ef Merge pull request #326 from eyaltoledano/main
Get next branch up to speed
2025-04-25 01:08:13 +02:00
Marijn van der Werf
a82284a2db Fix discord badge in readme (#325) 2025-04-25 01:05:57 +02:00
Eyal Toledano
205a11e82c fix(config): Improve config-manager.js for MCP server integration
- Fixed MCP server initialization warnings by refactoring config-manager.js to handle missing project roots silently during startup

- Added project root tracking (loadedConfigRoot) to improve config caching and prevent unnecessary reloads

- Modified _loadAndValidateConfig to return defaults without warnings when no explicitRoot provided

- Improved getConfig to only update cache when loading config with a specific project root

- Ensured warning messages still appear when explicitly specified roots have missing/invalid configs

- Prevented console output during MCP startup that was causing JSON parsing errors

- Verified parse_prd and other MCP tools still work correctly with the new config loading approach.

- Replaces test perplexity api key in mcp.json and rolls it. It's invalid now.
2025-04-24 13:34:51 -04:00
Eyal Toledano
be3f68e777 refactor(tasks): Align add-task with unified AI service and add research flag 2025-04-24 01:59:41 -04:00
Eyal Toledano
90c6c1e587 fix(ai, config): Correct Anthropic API calls and improve model config UI
Resolves persistent 404 'Not Found' errors when calling Anthropic models via the Vercel AI SDK. The primary issue was likely related to incorrect or missing API headers.

- Refactors Anthropic provider (src/ai-providers/anthropic.js) to use the standard 'anthropic-version' header instead of potentially outdated/incorrect beta headers when creating the client instance.

- Updates the default fallback model ID in .taskmasterconfig to 'claude-3-5-sonnet-20241022'.

- Fixes the interactive model setup (task-master models --setup) in scripts/modules/commands.js to correctly filter and default the main model selection.

- Improves the cost display in the 'task-master models' command output to explicitly show 'Free' for models with zero cost.

- Updates description for the 'id' parameter in the 'set_task_status' MCP tool definition for clarity.

- Updates list of models and costs
2025-04-24 00:29:36 -04:00
Eyal Toledano
6cb213ebbd eat(models): Add MCP support for models command and improve configuration docs
This commit implements several related improvements to the models command and configuration system:

- Added MCP support for the models command:
  - Created new direct function implementation in models.js
  - Registered modelsDirect in task-master-core.js for proper export
  - Added models tool registration in tools/index.js
  - Ensured project name replacement when copying .taskmasterconfig in init.js

- Improved .taskmasterconfig copying during project initialization:
  - Added copyTemplateFile() call in createProjectStructure()
  - Ensured project name is properly replaced in the config

- Restructured tool registration in logical workflow groups:
  - Organized registration into 6 functional categories
  - Improved command ordering to follow typical workflow
  - Added clear group comments for maintainability

- Enhanced documentation in cursor rules:
  - Updated dev_workflow.mdc with clearer config management instructions
  - Added comprehensive models command reference to taskmaster.mdc
  - Clarified CLI vs MCP usage patterns and options
  - Added warning against manual .taskmasterconfig editing
2025-04-23 15:47:33 -04:00
Ralph Khreish
bd0ee1b6e3 Merge pull request #308 from eyaltoledano/changeset-release/main
Version Packages
2025-04-23 02:01:57 +02:00
github-actions[bot]
8ed651c165 Version Packages 2025-04-23 00:00:43 +00:00
Ralph Khreish
2829194d3c fix: dependency manager & friend fixes (#307) 2025-04-23 02:00:27 +02:00
neno
2acba945c0 🦘 Direct Integration of Roo Code Support (#285)
* Direct Integration of Roo Code Support

## Overview

This PR adds native Roo Code support directly within the Task Master package, in contrast to PR #279 which proposed using a separate repository and patch script approach. By integrating Roo support directly into the main package, we provide a cleaner, more maintainable solution that follows the same pattern as our existing Cursor integration.

## Key Changes

1. **Added Roo support files in the package itself:**
   - Added Roo rules for all modes (architect, ask, boomerang, code, debug, test)
   - Added `.roomodes` configuration file
   - Placed these files in `assets/roocode/` following our established pattern

2. **Enhanced init.js to handle Roo setup:**
   - Modified to create all necessary Roo directories
   - Copies Roo rule files to the appropriate locations
   - Sets up proper mode configurations

3. **Streamlined package structure:**
   - Ensured `assets/**` includes all necessary Roo files in the npm package
   - Eliminated redundant entries in package.json
   - Updated prepare-package.js to verify all required files

4. **Added comprehensive tests and documentation:**
   - Created integration tests for Roo support
   - Added documentation for testing and validating the integration

## Implementation Philosophy

Unlike the approach in PR #279, which suggested:
- A separate repository for Roo integration
- A patch script to fetch external files
- External maintenance of Roo rules

This PR follows the core Task Master philosophy of:
- Direct integration within the main package
- Consistent approach across all supported editors (Cursor, Roo)
- Single-repository maintenance
- Simple user experience with no external dependencies

## Testing

The integration can be tested with:
```bash
npm test -- -t "Roo"
```

## Impact

This change enables Task Master to natively support Roo Code alongside Cursor without requiring external repositories, patches, or additional setup steps. Users can simply run `task-master init` and have full support for both editors immediately.

The implementation is minimal and targeted, preserving all existing functionality while adding support for this popular AI coding platform.

* Update roo-files-inclusion.test.js

* Update README.md

* Address PR feedback: move docs to contributor-docs, fix package.json references, regenerate package-lock.json

@Crunchyman-ralph Thank you for the feedback! I've made the requested changes:

1.  Moved testing-roo-integration.md to the contributor-docs folder
2.  Removed manual package.json changes and used changeset instead
3.  Fixed package references and regenerated package-lock.json
4.  All tests are now passing

Regarding architectural concerns:

- **Rule duplication**: I agree this is an opportunity for improvement. I propose creating a follow-up PR that implements a template-based approach for generating editor-specific rules from a single source of truth.

- **Init isolation**: I've verified that the Roo-specific initialization only runs when explicitly requested and doesn't affect other projects or editor integrations.

- **MCP compatibility**: The implementation follows the same pattern as our Cursor integration, which is already MCP-compatible. I've tested this by [describe your testing approach here].

Let me know if you'd like any additional changes!

* Address PR feedback: move docs to contributor-docs, fix package.json references, regenerate package-lock.json

@Crunchyman-ralph Thank you for the feedback! I've made the requested changes:

1.  Moved testing-roo-integration.md to the contributor-docs folder
2.  Removed manual package.json changes and used changeset instead
3.  Fixed package references and regenerated package-lock.json
4.  All tests are now passing

Regarding architectural concerns:

- **Rule duplication**: I agree this is an opportunity for improvement. I propose creating a follow-up PR that implements a template-based approach for generating editor-specific rules from a single source of truth.

- **Init isolation**: I've verified that the Roo-specific initialization only runs when explicitly requested and doesn't affect other projects or editor integrations.

- **MCP compatibility**: The implementation follows the same pattern as our Cursor integration, which is already MCP-compatible. I've tested this by [describe your testing approach here].

Let me know if you'd like any additional changes!

* feat: Add procedural generation of Roo rules from Cursor rules

* fixed prettier CI issue

* chore: update gitignore to exclude test files

* removing the old way to source the cursor derived roo rules

* resolving remaining conflicts

* resolving conflict 2

* Update package-lock.json

* fixing prettier

---------

Co-authored-by: neno-is-ooo <204701868+neno-is-ooo@users.noreply.github.com>
2025-04-23 00:15:01 +02:00
Eyal Toledano
78a5376796 fix(mcp): prevents the mcp from failing due to the newly introduced ConfigurationError object thrown if .taskmasterconfig is not present. I'll need to implement MCP tools for model to manage models from MCP and be able to create it. 2025-04-22 16:09:33 -04:00
Eyal Toledano
b3b424be93 refactor(ai): Implement unified AI service layer and fix subtask update
- Unified Service: Introduced 'scripts/modules/ai-services-unified.js' to centralize AI interactions using provider modules ('src/ai-providers/') and the Vercel AI SDK.

- Provider Modules: Implemented 'anthropic.js' and 'perplexity.js' wrappers for Vercel SDK.

- 'updateSubtaskById' Fix: Refactored the AI call within 'updateSubtaskById' to use 'generateTextService' from the unified layer, resolving runtime errors related to parameter passing and streaming. This serves as the pattern for refactoring other AI calls in 'scripts/modules/task-manager/'.

- Task Status: Marked Subtask 61.19 as 'done'.

- Rules: Added new 'ai-services.mdc' rule.

This centralizes AI logic, replacing previous direct SDK calls and custom implementations. API keys are resolved via 'resolveEnvVariable' within the service layer. The refactoring of 'updateSubtaskById' establishes the standard approach for migrating other AI-dependent functions in the task manager module to use the unified service.

Relates to Task 61.
2025-04-22 02:42:04 -04:00
Eyal Toledano
c90578b6da fix(config): erroneous 256k token limit. 2025-04-21 22:52:11 -04:00
Eyal Toledano
3a3ad9f4fe woops: removes api key from mcp.json + rolls it. it's now invalid. 2025-04-21 22:47:27 -04:00
Eyal Toledano
abdc15eab2 chore(rules): adjusts rules based on the new config approach. 2025-04-21 22:44:40 -04:00
Eyal Toledano
515dcae965 refactor(config)!: Enforce .taskmasterconfig and remove env var overrides
BREAKING CHANGE: Taskmaster now requires a `.taskmasterconfig` file for model/parameter settings. Environment variables (except API keys) are no longer used for overrides.

- Throws an error if `.taskmasterconfig` is missing, guiding user to run `task-master models --setup`." -m "- Removed env var checks from config getters in `config-manager.js`." -m "- Updated `env.example` to remove obsolete variables." -m "- Refined missing config file error message in `commands.js`.
2025-04-21 22:25:04 -04:00
Eyal Toledano
a40805adf7 fix(cli): Fix interactive model setup (models --setup)
The interactive model setup triggered by `task-master models --setup` was previously attempting to call non-existent setter functions (`setMainModel`, etc.) in `config-manager.js`, leading to errors and preventing configuration updates.

This commit refactors the `--setup` logic within the `models` command handler in `scripts/modules/commands.js`. It now correctly:

- Loads the current configuration using `getConfig()`." -m "- Updates the appropriate sections of the loaded configuration object based on user selections from `inquirer`." -m "- Saves the modified configuration using the existing `writeConfig()` function from `config-manager.js`." -m "- Handles disabling the fallback model correctly."
2025-04-21 21:43:10 -04:00
Eyal Toledano
4a9f6cd5f5 refactor: Standardize configuration and environment variable access
This commit centralizes configuration and environment variable access across various modules by consistently utilizing getters from scripts/modules/config-manager.js. This replaces direct access to process.env and the global CONFIG object, leading to improved consistency, maintainability, testability, and better handling of session-specific configurations within the MCP context.

Key changes include:

- Centralized Getters: Replaced numerous instances of process.env.* and CONFIG.* with corresponding getter functions (e.g., getLogLevel, getMainModelId, getResearchMaxTokens, getMainTemperature, isApiKeySet, getDebugFlag, getDefaultSubtasks).

- Session Awareness: Ensured that the session object is passed to config getters where necessary, particularly within AI service calls (ai-services.js, add-task.js) and error handling (ai-services.js), allowing for session-specific environment overrides.

- API Key Checks: Standardized API key availability checks using isApiKeySet() instead of directly checking process.env.* (e.g., for Perplexity in commands.js and ai-services.js).

- Client Instantiation Cleanup: Removed now-redundant/obsolete local client instantiation functions (getAnthropicClient, getPerplexityClient) from ai-services.js and the global Anthropic client initialization from dependency-manager.js. Client creation should now rely on the config manager and factory patterns.

- Consistent Debug Flag Usage: Standardized calls to getDebugFlag() in commands.js, removing potentially unnecessary null arguments.

- Accurate Progress Calculation: Updated AI stream progress reporting (ai-services.js, add-task.js) to use getMainMaxTokens(session) for more accurate calculations.

- Minor Cleanup: Removed unused  import from scripts/modules/commands.js.

Specific module updates:

- :

  - Uses getLogLevel() instead of process.env.LOG_LEVEL.

- :

  - Replaced direct env/config access for model IDs, tokens, temperature, API keys, and default subtasks with appropriate getters.

  - Passed session to handleClaudeError.

  - Removed local getPerplexityClient and getAnthropicClient functions.

  - Updated progress calculations to use getMainMaxTokens(session).

- :

  - Uses isApiKeySet('perplexity') for API key checks.

  - Uses getDebugFlag() consistently for debug checks.

  - Removed unused  import.

- :

  - Removed global Anthropic client initialization.

- :

  - Uses config getters (getResearch..., getMain...) for Perplexity and Claude API call parameters, preserving customEnv override logic.

This refactoring also resolves a potential SyntaxError: Identifier 'getPerplexityClient' has already been declared by removing the duplicated/obsolete function definition previously present in ai-services.js.
2025-04-21 21:30:12 -04:00
Eyal Toledano
d46547a80f refactor(config): Standardize env var access and config getters
This commit focuses on standardizing configuration and API key access patterns across key modules as part of subtask 61.34.

Key changes include:

- Refactored `ai-services.js` to remove global AI clients and use `resolveEnvVariable` for API key checks. Client instantiation now relies on `getAnthropicClient`/`getPerplexityClient` accepting a session object.

- Refactored `task-manager.js` (`analyzeTaskComplexity` function) to use the unified `generateTextService` from `ai-services-unified.js`, removing direct AI client calls.

- Replaced direct `process.env` access for model parameters and other configurations (`PERPLEXITY_MODEL`, `CONFIG.*`) in `task-manager.js` with calls to the appropriate getters from `config-manager.js` (e.g., `getResearchModelId(session)`, `getMainMaxTokens(session)`).

- Ensured `utils.js` (`resolveEnvVariable`) correctly handles potentially undefined session objects.

- Updated function signatures where necessary to propagate the `session` object for correct context-aware configuration/key retrieval.

This moves towards the goal of using `ai-client-factory.js` and `ai-services-unified.js` as the standard pattern for AI interactions and centralizing configuration management through `config-manager.js`.
2025-04-21 17:48:30 -04:00
Ralph Khreish
bcb885e0ba chore: update package.json in next branch 2025-04-20 22:39:48 +02:00
Eyal Toledano
538b874582 feat(config): Implement new config system and resolve refactoring errors Introduced config-manager.js and new utilities (resolveEnvVariable, findProjectRoot). Removed old global CONFIG object from utils.js. Updated .taskmasterconfig, mcp.json, and .env.example. Added generateComplexityAnalysisPrompt to ui.js. Removed unused updateSubtaskById from task-manager.js. Resolved SyntaxError and ReferenceError issues across commands.js, ui.js, task-manager.js, and ai-services.js by replacing CONFIG references with config-manager getters (getDebugFlag, getProjectName, getDefaultSubtasks, isApiKeySet). Refactored 'models' command to use getConfig/writeConfig. Simplified version checking. This stabilizes the codebase after initial Task 61 refactoring, fixing CLI errors and enabling subsequent work on Subtasks 61.34 and 61.35. 2025-04-20 01:09:30 -04:00
Eyal Toledano
11b8d1bda5 feat(ai-client-factory): Add xAI and OpenRouter provider support, enhance tests
- Integrate  for Grok models and  for OpenRouter into the AI client factory ().
- Install necessary provider dependencies (, , and other related  packages, updated  core).
- Update environment variable checks () and client creation logic () for the new providers.
- Add and correct unit tests in  to cover xAI and OpenRouter instantiation, error handling, and environment variable resolution.
- Corrected mock paths and names in tests to align with official package names.
- Verify all tests (28 total) pass for .
- Confirm test coverage remains high (~90%) after additions.
2025-04-19 17:00:47 -04:00
Eyal Toledano
d181c40a95 chore: skips 3 failing tests, must come back to them, and some task management. 2025-04-16 01:09:31 -04:00
Eyal Toledano
1ab836f191 feat(config): Add Fallback Model and Expanded Provider Support
Introduces a configurable fallback model and adds support for additional AI provider API keys in the environment setup.

- **Add Fallback Model Configuration (.taskmasterconfig):**
  - Implemented a new  section in .
  - Configured  as the default fallback model, enhancing resilience if the primary model fails.

- **Update Default Model Configuration (.taskmasterconfig):**
  - Changed the default  model to .
  - Changed the default  model to .

- **Add API Key Examples (assets/env.example):**
  - Added example environment variables for:
    -  (for OpenAI/OpenRouter)
    -  (for Google Gemini)
    -  (for XAI Grok)
  - Included format comments for clarity.
2025-04-16 00:45:02 -04:00
Eyal Toledano
d84c2486e4 fix(config): Improve config manager flexibility & test mocks
Refactored `config-manager.js` to handle different execution contexts (CLI vs. MCP) and fixed related Jest tests.

- Modified `readConfig` and `writeConfig` to accept an optional `explicitRoot` parameter, allowing explicit path specification (e.g., from MCP) while retaining automatic project root finding for CLI usage.

- Updated getter/setter functions (`getMainProvider`, `setMainModel`, etc.) to accept and propagate the `explicitRoot`.

- Resolved Jest testing issues for dynamic imports by using `jest.unstable_mockModule` for `fs` and `chalk` dependencies *before* the dynamic `import()`.

- Corrected console error assertions in tests to match exact logged messages.

- Updated `.cursor/rules/tests.mdc` with guidelines for `jest.unstable_mockModule` and precise console assertions.
2025-04-16 00:45:02 -04:00
Eyal Toledano
329839aeb8 fix: Correct TTY check for AI progress indicator in CLI
Addresses `process.stdout.clearLine is not a function` error when running AI-dependent commands non-interactively (e.g., `update-subtask`).

Adds `process.stdout.isTTY` check before attempting to use terminal-specific output manipulations.

feat: Implement initial config manager for AI models

Adds `scripts/modules/config-manager.js` to handle reading/writing model selections from/to `.taskmasterconfig`.

Implements core functions: findProjectRoot, read/writeConfig, validateModel, get/setModel.

Defines valid model lists. Completes initial work for Subtask 61.1.
2025-04-16 00:45:02 -04:00
Eyal Toledano
c7fefb0549 fix(ai-services): Prevent TTY errors during AI streaming output
The  function used terminal manipulation functions
(like , ) for the CLI
streaming progress indicator. This caused errors when Task Master commands
involving AI streaming were run in non-interactive terminals (e.g., via
output redirection, some CI environments, or integrated terminals).

This commit adds a check for  to the condition
that controls the display of the CLI progress indicator, ensuring these
functions are only called when standard output is a fully interactive TTY.
2025-04-16 00:45:02 -04:00
Eyal Toledano
cde23946e9 chore: task management 2025-04-16 00:45:02 -04:00
Eyal Toledano
1ceb545d86 chore: formatting 2025-04-16 00:45:02 -04:00
Eyal Toledano
9a482789f7 feat(ai): Enhance Perplexity research calls & fix docs examples
Improves the quality and relevance of research-backed AI operations:
- Tweaks Perplexity AI calls to use max input tokens (8700), temperature 0.1, high context size, and day-fresh search recency.
- Adds a system prompt to guide Perplexity research output.

Docs:
- Updates CLI examples in taskmaster.mdc to use ANSI-C quoting ($'...') for multi-line prompts, ensuring they work correctly in bash/zsh.
2025-04-16 00:45:02 -04:00
921 changed files with 190118 additions and 29485 deletions

View File

@@ -2,13 +2,16 @@
"$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
"changelog": [
"@changesets/changelog-github",
{ "repo": "eyaltoledano/claude-task-master" }
{
"repo": "eyaltoledano/claude-task-master"
}
],
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
"ignore": [
"docs",
"@tm/claude-code-plugin"
]
}

View File

@@ -0,0 +1,32 @@
{
"name": "taskmaster",
"owner": {
"name": "Hamster",
"email": "ralph@tryhamster.com"
},
"metadata": {
"description": "Official marketplace for Taskmaster AI - AI-powered task management for ambitious development",
"version": "1.0.0"
},
"plugins": [
{
"name": "taskmaster",
"source": "./packages/claude-code-plugin",
"description": "AI-powered task management system for ambitious development workflows with intelligent orchestration, complexity analysis, and automated coordination",
"author": {
"name": "Hamster"
},
"homepage": "https://github.com/eyaltoledano/claude-task-master",
"repository": "https://github.com/eyaltoledano/claude-task-master",
"keywords": [
"task-management",
"ai",
"workflow",
"orchestration",
"automation",
"mcp"
],
"category": "productivity"
}
]
}

View File

@@ -0,0 +1,147 @@
# Task Master Commands for Claude Code
Complete guide to using Task Master through Claude Code's slash commands.
## Overview
All Task Master functionality is available through the `/project:tm/` namespace with natural language support and intelligent features.
## Quick Start
```bash
# Install Task Master
/project:tm/setup/quick-install
# Initialize project
/project:tm/init/quick
# Parse requirements
/project:tm/parse-prd requirements.md
# Start working
/project:tm/next
```
## Command Structure
Commands are organized hierarchically to match Task Master's CLI:
- Main commands at `/project:tm/[command]`
- Subcommands for specific operations `/project:tm/[command]/[subcommand]`
- Natural language arguments accepted throughout
## Complete Command Reference
### Setup & Configuration
- `/project:tm/setup/install` - Full installation guide
- `/project:tm/setup/quick-install` - One-line install
- `/project:tm/init` - Initialize project
- `/project:tm/init/quick` - Quick init with -y
- `/project:tm/models` - View AI config
- `/project:tm/models/setup` - Configure AI
### Task Generation
- `/project:tm/parse-prd` - Generate from PRD
- `/project:tm/parse-prd/with-research` - Enhanced parsing
- `/project:tm/generate` - Create task files
### Task Management
- `/project:tm/list` - List with natural language filters
- `/project:tm/list/with-subtasks` - Hierarchical view
- `/project:tm/list/by-status <status>` - Filter by status
- `/project:tm/show <id>` - Task details
- `/project:tm/add-task` - Create task
- `/project:tm/update` - Update tasks
- `/project:tm/remove-task` - Delete task
### Status Management
- `/project:tm/set-status/to-pending <id>`
- `/project:tm/set-status/to-in-progress <id>`
- `/project:tm/set-status/to-done <id>`
- `/project:tm/set-status/to-review <id>`
- `/project:tm/set-status/to-deferred <id>`
- `/project:tm/set-status/to-cancelled <id>`
### Task Analysis
- `/project:tm/analyze-complexity` - AI analysis
- `/project:tm/complexity-report` - View report
- `/project:tm/expand <id>` - Break down task
- `/project:tm/expand/all` - Expand all complex
### Dependencies
- `/project:tm/add-dependency` - Add dependency
- `/project:tm/remove-dependency` - Remove dependency
- `/project:tm/validate-dependencies` - Check issues
- `/project:tm/fix-dependencies` - Auto-fix
### Workflows
- `/project:tm/workflows/smart-flow` - Adaptive workflows
- `/project:tm/workflows/pipeline` - Chain commands
- `/project:tm/workflows/auto-implement` - AI implementation
### Utilities
- `/project:tm/status` - Project dashboard
- `/project:tm/next` - Next task recommendation
- `/project:tm/utils/analyze` - Project analysis
- `/project:tm/learn` - Interactive help
## Key Features
### Natural Language Support
All commands understand natural language:
```
/project:tm/list pending high priority
/project:tm/update mark 23 as done
/project:tm/add-task implement OAuth login
```
### Smart Context
Commands analyze project state and provide intelligent suggestions based on:
- Current task status
- Dependencies
- Team patterns
- Project phase
### Visual Enhancements
- Progress bars and indicators
- Status badges
- Organized displays
- Clear hierarchies
## Common Workflows
### Daily Development
```
/project:tm/workflows/smart-flow morning
/project:tm/next
/project:tm/set-status/to-in-progress <id>
/project:tm/set-status/to-done <id>
```
### Task Breakdown
```
/project:tm/show <id>
/project:tm/expand <id>
/project:tm/list/with-subtasks
```
### Sprint Planning
```
/project:tm/analyze-complexity
/project:tm/workflows/pipeline init → expand/all → status
```
## Migration from Old Commands
| Old | New |
|-----|-----|
| `/project:task-master:list` | `/project:tm/list` |
| `/project:task-master:complete` | `/project:tm/set-status/to-done` |
| `/project:workflows:auto-implement` | `/project:tm/workflows/auto-implement` |
## Tips
1. Use `/project:tm/` + Tab for command discovery
2. Natural language is supported everywhere
3. Commands provide smart defaults
4. Chain commands for automation
5. Check `/project:tm/learn` for interactive help

View File

@@ -0,0 +1,38 @@
---
allowed-tools: Bash(gh issue view:*), Bash(gh search:*), Bash(gh issue list:*), Bash(gh api:*), Bash(gh issue comment:*)
description: Find duplicate GitHub issues
---
Find up to 3 likely duplicate issues for a given GitHub issue.
To do this, follow these steps precisely:
1. Use an agent to check if the Github issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicates comment that you made earlier. If so, do not proceed.
2. Use an agent to view a Github issue, and ask the agent to return a summary of the issue
3. Then, launch 5 parallel agents to search Github for duplicates of this issue, using diverse keywords and search approaches, using the summary from #1
4. Next, feed the results from #1 and #2 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed.
5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates)
Notes (be sure to tell this to your agents, too):
- Use `gh` to interact with Github, rather than web fetch
- Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.)
- Make a todo list first
- For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates):
---
Found 3 possible duplicate issues:
1. <link to issue>
2. <link to issue>
3. <link to issue>
This issue will be automatically closed as a duplicate in 3 days.
- If your issue is a duplicate, please close it and 👍 the existing issue instead
- To prevent auto-closure, add a comment or 👎 this comment
🤖 Generated with \[Task Master Bot\]
---

10
.coderabbit.yaml Normal file
View File

@@ -0,0 +1,10 @@
reviews:
profile: assertive
poem: false
auto_review:
base_branches:
- rc
- beta
- alpha
- production
- next

View File

@@ -1,17 +1,20 @@
{
"mcpServers": {
"taskmaster-ai": {
"task-master-ai": {
"command": "node",
"args": ["./mcp-server/server.js"],
"args": ["./dist/mcp-server.js"],
"env": {
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
"MODEL": "claude-3-7-sonnet-20250219",
"PERPLEXITY_MODEL": "sonar-pro",
"MAX_TOKENS": 64000,
"TEMPERATURE": 0.2,
"DEFAULT_SUBTASKS": 5,
"DEFAULT_PRIORITY": "medium"
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"GROQ_API_KEY": "GROQ_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE",
"GITHUB_API_KEY": "GITHUB_API_KEY_HERE"
}
}
}

View File

@@ -0,0 +1,155 @@
---
description: Guidelines for managing Task Master AI providers and models.
globs:
alwaysApply: false
---
# Task Master AI Provider Management
This rule guides AI assistants on how to view, configure, and interact with the different AI providers and models supported by Task Master. For internal implementation details of the service layer, see [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc).
- **Primary Interaction:**
- Use the `models` MCP tool or the `task-master models` CLI command to manage AI configurations. See [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for detailed command/tool usage.
- **Configuration Roles:**
- Task Master uses three roles for AI models:
- `main`: Primary model for general tasks (generation, updates).
- `research`: Model used when the `--research` flag or `research: true` parameter is used (typically models with web access or specialized knowledge).
- `fallback`: Model used if the primary (`main`) model fails.
- Each role is configured with a specific `provider:modelId` pair (e.g., `openai:gpt-4o`).
- **Viewing Configuration & Available Models:**
- To see the current model assignments for each role and list all models available for assignment:
- **MCP Tool:** `models` (call with no arguments or `listAvailableModels: true`)
- **CLI Command:** `task-master models`
- The output will show currently assigned models and a list of others, prefixed with their provider (e.g., `google:gemini-2.5-pro-exp-03-25`).
- **Setting Models for Roles:**
- To assign a model to a role:
- **MCP Tool:** `models` with `setMain`, `setResearch`, or `setFallback` parameters.
- **CLI Command:** `task-master models` with `--set-main`, `--set-research`, or `--set-fallback` flags.
- **Crucially:** When providing the model ID to *set*, **DO NOT include the `provider:` prefix**. Use only the model ID itself.
- ✅ **DO:** `models(setMain='gpt-4o')` or `task-master models --set-main=gpt-4o`
- ❌ **DON'T:** `models(setMain='openai:gpt-4o')` or `task-master models --set-main=openai:gpt-4o`
- The tool/command will automatically determine the provider based on the model ID.
- **Setting Custom Models (Ollama/OpenRouter):**
- To set a model ID not in the internal list for Ollama or OpenRouter:
- **MCP Tool:** Use `models` with `set<Role>` and **also** `ollama: true` or `openrouter: true`.
- Example: `models(setMain='my-custom-ollama-model', ollama=true)`
- Example: `models(setMain='some-openrouter-model', openrouter=true)`
- **CLI Command:** Use `task-master models` with `--set-<role>` and **also** `--ollama` or `--openrouter`.
- Example: `task-master models --set-main=my-custom-ollama-model --ollama`
- Example: `task-master models --set-main=some-openrouter-model --openrouter`
- **Interactive Setup:** Use `task-master models --setup` and select the `Ollama (Enter Custom ID)` or `OpenRouter (Enter Custom ID)` options.
- **OpenRouter Validation:** When setting a custom OpenRouter model, Taskmaster attempts to validate the ID against the live OpenRouter API.
- **Ollama:** No live validation occurs for custom Ollama models; ensure the model is available on your Ollama server.
- **Supported Providers & Required API Keys:**
- Task Master integrates with various providers via the Vercel AI SDK.
- **API keys are essential** for most providers and must be configured correctly.
- **Key Locations** (See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) - Configuration Management):
- **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`.
- **CLI:** Set keys in a `.env` file in the project root.
- **Provider List & Keys:**
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
- **`google`**: Requires `GOOGLE_API_KEY`.
- **`openai`**: Requires `OPENAI_API_KEY`.
- **`perplexity`**: Requires `PERPLEXITY_API_KEY`.
- **`xai`**: Requires `XAI_API_KEY`.
- **`mistral`**: Requires `MISTRAL_API_KEY`.
- **`azure`**: Requires `AZURE_OPENAI_API_KEY` and `AZURE_OPENAI_ENDPOINT`.
- **`openrouter`**: Requires `OPENROUTER_API_KEY`.
- **`ollama`**: Might require `OLLAMA_API_KEY` (not currently supported) *and* `OLLAMA_BASE_URL` (default: `http://localhost:11434/api`). *Check specific setup.*
- **Troubleshooting:**
- If AI commands fail (especially in MCP context):
1. **Verify API Key:** Ensure the correct API key for the *selected provider* (check `models` output) exists in the appropriate location (`.cursor/mcp.json` env or `.env`).
2. **Check Model ID:** Ensure the model ID set for the role is valid (use `models` listAvailableModels/`task-master models`).
3. **Provider Status:** Check the status of the external AI provider's service.
4. **Restart MCP:** If changes were made to configuration or provider code, restart the MCP server.
## Adding a New AI Provider (Vercel AI SDK Method)
Follow these steps to integrate a new AI provider that has an official Vercel AI SDK adapter (`@ai-sdk/<provider>`):
1. **Install Dependency:**
- Install the provider-specific package:
```bash
npm install @ai-sdk/<provider-name>
```
2. **Create Provider Module:**
- Create a new file in `src/ai-providers/` named `<provider-name>.js`.
- Use existing modules (`openai.js`, `anthropic.js`, etc.) as a template.
- **Import:**
- Import the provider's `create<ProviderName>` function from `@ai-sdk/<provider-name>`.
- Import `generateText`, `streamText`, `generateObject` from the core `ai` package.
- Import the `log` utility from `../../scripts/modules/utils.js`.
- **Implement Core Functions:**
- `generate<ProviderName>Text(params)`:
- Accepts `params` (apiKey, modelId, messages, etc.).
- Instantiate the client: `const client = create<ProviderName>({ apiKey });`
- Call `generateText({ model: client(modelId), ... })`.
- Return `result.text`.
- Include basic validation and try/catch error handling.
- `stream<ProviderName>Text(params)`:
- Similar structure to `generateText`.
- Call `streamText({ model: client(modelId), ... })`.
- Return the full stream result object.
- Include basic validation and try/catch.
- `generate<ProviderName>Object(params)`:
- Similar structure.
- Call `generateObject({ model: client(modelId), schema, messages, ... })`.
- Return `result.object`.
- Include basic validation and try/catch.
- **Export Functions:** Export the three implemented functions (`generate<ProviderName>Text`, `stream<ProviderName>Text`, `generate<ProviderName>Object`).
3. **Integrate with Unified Service:**
- Open `scripts/modules/ai-services-unified.js`.
- **Import:** Add `import * as <providerName> from '../../src/ai-providers/<provider-name>.js';`
- **Map:** Add an entry to the `PROVIDER_FUNCTIONS` map:
```javascript
'<provider-name>': {
generateText: <providerName>.generate<ProviderName>Text,
streamText: <providerName>.stream<ProviderName>Text,
generateObject: <providerName>.generate<ProviderName>Object
},
```
4. **Update Configuration Management:**
- Open `scripts/modules/config-manager.js`.
- **`MODEL_MAP`:** Add the new `<provider-name>` key to the `MODEL_MAP` loaded from `supported-models.json` (or ensure the loading handles new providers dynamically if `supported-models.json` is updated first).
- **`VALID_PROVIDERS`:** Ensure the new `<provider-name>` is included in the `VALID_PROVIDERS` array (this should happen automatically if derived from `MODEL_MAP` keys).
- **API Key Handling:**
- Update the `keyMap` in `_resolveApiKey` and `isApiKeySet` with the correct environment variable name (e.g., `PROVIDER_API_KEY`).
- Update the `switch` statement in `getMcpApiKeyStatus` to check the corresponding key in `mcp.json` and its placeholder value.
- Add a case to the `switch` statement in `getMcpApiKeyStatus` for the new provider, including its placeholder string if applicable.
- **Ollama Exception:** If adding Ollama or another provider *not* requiring an API key, add a specific check at the beginning of `isApiKeySet` and `getMcpApiKeyStatus` to return `true` immediately for that provider.
5. **Update Supported Models List:**
- Edit `scripts/modules/supported-models.json`.
- Add a new key for the `<provider-name>`.
- Add an array of model objects under the provider key, each including:
- `id`: The specific model identifier (e.g., `claude-3-opus-20240229`).
- `name`: A user-friendly name (optional).
- `swe_score`, `cost_per_1m_tokens`: (Optional) Add performance/cost data if available.
- `allowed_roles`: An array of roles (`"main"`, `"research"`, `"fallback"`) the model is suitable for.
- `max_tokens`: (Optional but recommended) The maximum token limit for the model.
6. **Update Environment Examples:**
- Add the new `PROVIDER_API_KEY` to `.env.example`.
- Add the new `PROVIDER_API_KEY` with its placeholder (`YOUR_PROVIDER_API_KEY_HERE`) to the `env` section for `taskmaster-ai` in `.cursor/mcp.json.example` (if it exists) or update instructions.
7. **Add Unit Tests:**
- Create `tests/unit/ai-providers/<provider-name>.test.js`.
- Mock the `@ai-sdk/<provider-name>` module and the core `ai` module functions (`generateText`, `streamText`, `generateObject`).
- Write tests for each exported function (`generate<ProviderName>Text`, etc.) to verify:
- Correct client instantiation.
- Correct parameters passed to the mocked Vercel AI SDK functions.
- Correct handling of results.
- Error handling (missing API key, SDK errors).
8. **Documentation:**
- Update any relevant documentation (like `README.md` or other rules) mentioning supported providers or configuration.
*(Note: For providers **without** an official Vercel AI SDK adapter, the process would involve directly using the provider's own SDK or API within the `src/ai-providers/<provider-name>.js` module and manually constructing responses compatible with the unified service layer, which is significantly more complex.)*

View File

@@ -0,0 +1,102 @@
---
description: Guidelines for interacting with the unified AI service layer.
globs: scripts/modules/ai-services-unified.js, scripts/modules/task-manager/*.js, scripts/modules/commands.js
---
# AI Services Layer Guidelines
This document outlines the architecture and usage patterns for interacting with Large Language Models (LLMs) via Task Master's unified AI service layer (`ai-services-unified.js`). The goal is to centralize configuration, provider selection, API key management, fallback logic, and error handling.
**Core Components:**
* **Configuration (`.taskmasterconfig` & [`config-manager.js`](mdc:scripts/modules/config-manager.js)):**
* Defines the AI provider and model ID for different **roles** (`main`, `research`, `fallback`).
* Stores parameters like `maxTokens` and `temperature` per role.
* Managed via the `task-master models --setup` CLI command.
* [`config-manager.js`](mdc:scripts/modules/config-manager.js) provides **getters** (e.g., `getMainProvider()`, `getParametersForRole()`) to access these settings. Core logic should **only** use these getters for *non-AI related application logic* (e.g., `getDefaultSubtasks`). The unified service fetches necessary AI parameters internally based on the `role`.
* **API keys** are **NOT** stored here; they are resolved via `resolveEnvVariable` (in [`utils.js`](mdc:scripts/modules/utils.js)) from `.env` (for CLI) or the MCP `session.env` object (for MCP calls). See [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc).
* **Unified Service (`ai-services-unified.js`):**
* Exports primary interaction functions: `generateTextService`, `generateObjectService`. (Note: `streamTextService` exists but has known reliability issues with some providers/payloads).
* Contains the core `_unifiedServiceRunner` logic.
* Internally uses `config-manager.js` getters to determine the provider/model/parameters based on the requested `role`.
* Implements the **fallback sequence** (e.g., main -> fallback -> research) if the primary provider/model fails.
* Constructs the `messages` array required by the Vercel AI SDK.
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
* Returns a structured object containing the primary AI result (`mainResult`) and telemetry data (`telemetryData`). See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for details on how this telemetry data is propagated and handled.
* **Provider Implementations (`src/ai-providers/*.js`):**
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).
**Usage Pattern (from Core Logic like `task-manager/*.js`):**
1. **Import Service:** Import `generateTextService` or `generateObjectService` from `../ai-services-unified.js`.
```javascript
// Preferred for most tasks (especially with complex JSON)
import { generateTextService } from '../ai-services-unified.js';
// Use if structured output is reliable for the specific use case
// import { generateObjectService } from '../ai-services-unified.js';
```
2. **Prepare Parameters:** Construct the parameters object for the service call.
* `role`: **Required.** `'main'`, `'research'`, or `'fallback'`. Determines the initial provider/model/parameters used by the unified service.
* `session`: **Required if called from MCP context.** Pass the `session` object received by the direct function wrapper. The unified service uses `session.env` to find API keys.
* `systemPrompt`: Your system instruction string.
* `prompt`: The user message string (can be long, include stringified data, etc.).
* (For `generateObjectService` only): `schema` (Zod schema), `objectName`.
3. **Call Service:** Use `await` to call the service function.
```javascript
// Example using generateTextService (most common)
try {
const resultText = await generateTextService({
role: useResearch ? 'research' : 'main', // Determine role based on logic
session: context.session, // Pass session from context object
systemPrompt: "You are...",
prompt: userMessageContent
});
// Process the raw text response (e.g., parse JSON, use directly)
// ...
} catch (error) {
// Handle errors thrown by the unified service (if all fallbacks/retries fail)
report('error', `Unified AI service call failed: ${error.message}`);
throw error;
}
// Example using generateObjectService (use cautiously)
try {
const resultObject = await generateObjectService({
role: 'main',
session: context.session,
schema: myZodSchema,
objectName: 'myDataObject',
systemPrompt: "You are...",
prompt: userMessageContent
});
// resultObject is already a validated JS object
// ...
} catch (error) {
report('error', `Unified AI service call failed: ${error.message}`);
throw error;
}
```
4. **Handle Results/Errors:** Process the returned text/object or handle errors thrown by the unified service layer.
**Key Implementation Rules & Gotchas:**
* ✅ **DO**: Centralize **all** LLM calls through `generateTextService` or `generateObjectService`.
* ✅ **DO**: Determine the appropriate `role` (`main`, `research`, `fallback`) in your core logic and pass it to the service.
* ✅ **DO**: Pass the `session` object (received in the `context` parameter, especially from direct function wrappers) to the service call when in MCP context.
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP).
* ✅ **DO**: Ensure `.taskmasterconfig` exists and has valid provider/model IDs for the roles you intend to use (manage via `task-master models --setup`).
* ✅ **DO**: Use `generateTextService` and implement robust manual JSON parsing (with Zod validation *after* parsing) when structured output is needed, as `generateObjectService` has shown unreliability with some providers/schemas.
* ❌ **DON'T**: Import or call anything from the old `ai-services.js`, `ai-client-factory.js`, or `ai-client-utils.js` files.
* ❌ **DON'T**: Initialize AI clients (Anthropic, Perplexity, etc.) directly within core logic (`task-manager/`) or MCP direct functions.
* ❌ **DON'T**: Fetch AI-specific parameters (model ID, max tokens, temp) using `config-manager.js` getters *for the AI call*. Pass the `role` instead.
* ❌ **DON'T**: Implement fallback or retry logic outside `ai-services-unified.js`.
* ❌ **DON'T**: Handle API key resolution outside the service layer (it uses `utils.js` internally).
* ⚠️ **generateObjectService Caution**: Be aware of potential reliability issues with `generateObjectService` across different providers and complex schemas. Prefer `generateTextService` + manual parsing as a more robust alternative for structured data needs.

View File

@@ -3,7 +3,6 @@ description: Describes the high-level architecture of the Task Master CLI applic
globs: scripts/modules/*.js
alwaysApply: false
---
# Application Architecture Overview
- **Modular Structure**: The Task Master CLI is built using a modular architecture, with distinct modules responsible for different aspects of the application. This promotes separation of concerns, maintainability, and testability.
@@ -14,161 +13,106 @@ alwaysApply: false
- **Purpose**: Defines and registers all CLI commands using Commander.js.
- **Responsibilities** (See also: [`commands.mdc`](mdc:.cursor/rules/commands.mdc)):
- Parses command-line arguments and options.
- Invokes appropriate functions from other modules to execute commands (e.g., calls `initializeProject` from `init.js` for the `init` command).
- Handles user input and output related to command execution.
- Implements input validation and error handling for CLI commands.
- **Key Components**:
- `programInstance` (Commander.js `Command` instance): Manages command definitions.
- `registerCommands(programInstance)`: Function to register all application commands.
- Command action handlers: Functions executed when a specific command is invoked, delegating to core modules.
- Invokes appropriate core logic functions from `scripts/modules/`.
- Handles user input/output for CLI.
- Implements CLI-specific validation.
- **[`task-manager.js`](mdc:scripts/modules/task-manager.js): Task Data Management**
- **Purpose**: Manages task data, including loading, saving, creating, updating, deleting, and querying tasks.
- **[`task-manager.js`](mdc:scripts/modules/task-manager.js) & `task-manager/` directory: Task Data & Core Logic**
- **Purpose**: Contains core functions for task data manipulation (CRUD), AI interactions, and related logic.
- **Responsibilities**:
- Reads and writes task data to `tasks.json` file.
- Implements functions for task CRUD operations (Create, Read, Update, Delete).
- Handles task parsing from PRD documents using AI.
- Manages task expansion and subtask generation.
- Updates task statuses and properties.
- Implements task listing and display logic.
- Performs task complexity analysis using AI.
- **Key Functions**:
- `readTasks(tasksPath)` / `writeTasks(tasksPath, tasksData)`: Load and save task data.
- `parsePRD(prdFilePath, outputPath, numTasks)`: Parses PRD document to create tasks.
- `expandTask(taskId, numSubtasks, useResearch, prompt, force)`: Expands a task into subtasks.
- `setTaskStatus(tasksPath, taskIdInput, newStatus)`: Updates task status.
- `listTasks(tasksPath, statusFilter, withSubtasks)`: Lists tasks with filtering and subtask display options.
- `analyzeComplexity(tasksPath, reportPath, useResearch, thresholdScore)`: Analyzes task complexity.
- Reading/writing `tasks.json` with tagged task lists support.
- Implementing functions for task CRUD, parsing PRDs, expanding tasks, updating status, etc.
- **Tagged Task Lists**: Handles task organization across multiple contexts (tags) like "master", branch names, or project phases.
- **Tag Resolution**: Provides backward compatibility by resolving tagged format to legacy format transparently.
- **Delegating AI interactions** to the `ai-services-unified.js` layer.
- Accessing non-AI configuration via `config-manager.js` getters.
- **Key Files**: Individual files within `scripts/modules/task-manager/` handle specific actions (e.g., `add-task.js`, `expand-task.js`).
- **[`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js): Dependency Management**
- **Purpose**: Manages task dependencies, including adding, removing, validating, and fixing dependency relationships.
- **Responsibilities**:
- Adds and removes task dependencies.
- Validates dependency relationships to prevent circular dependencies and invalid references.
- Fixes invalid dependencies by removing non-existent or self-referential dependencies.
- Provides functions to check for circular dependencies.
- **Key Functions**:
- `addDependency(tasksPath, taskId, dependencyId)`: Adds a dependency between tasks.
- `removeDependency(tasksPath, taskId, dependencyId)`: Removes a dependency.
- `validateDependencies(tasksPath)`: Validates task dependencies.
- `fixDependencies(tasksPath)`: Fixes invalid task dependencies.
- `isCircularDependency(tasks, taskId, dependencyChain)`: Detects circular dependencies.
- **Purpose**: Manages task dependencies.
- **Responsibilities**: Add/remove/validate/fix dependencies across tagged task contexts.
- **[`ui.js`](mdc:scripts/modules/ui.js): User Interface Components**
- **Purpose**: Handles all user interface elements, including displaying information, formatting output, and providing user feedback.
- **Responsibilities**:
- Displays task lists, task details, and command outputs in a formatted way.
- Uses `chalk` for colored output and `boxen` for boxed messages.
- Implements table display using `cli-table3`.
- Shows loading indicators using `ora`.
- Provides helper functions for status formatting, dependency display, and progress reporting.
- Suggests next actions to the user after command execution.
- **Key Functions**:
- `displayTaskList(tasks, statusFilter, withSubtasks)`: Displays a list of tasks in a table.
- `displayTaskDetails(task)`: Displays detailed information for a single task.
- `displayComplexityReport(reportPath)`: Displays the task complexity report.
- `startLoadingIndicator(message)` / `stopLoadingIndicator(indicator)`: Manages loading indicators.
- `getStatusWithColor(status)`: Returns status string with color formatting.
- `formatDependenciesWithStatus(dependencies, allTasks, inTable)`: Formats dependency list with status indicators.
- **Purpose**: Handles CLI output formatting (tables, colors, boxes, spinners).
- **Responsibilities**: Displaying tasks, reports, progress, suggestions, and migration notices for tagged systems.
- **[`ai-services.js`](mdc:scripts/modules/ai-services.js) (Conceptual): AI Integration**
- **Purpose**: Abstracts interactions with AI models (like Anthropic Claude and Perplexity AI) for various features. *Note: This module might be implicitly implemented within `task-manager.js` and `utils.js` or could be explicitly created for better organization as the project evolves.*
- **Responsibilities**:
- Handles API calls to AI services.
- Manages prompts and parameters for AI requests.
- Parses AI responses and extracts relevant information.
- Implements logic for task complexity analysis, task expansion, and PRD parsing using AI.
- **Potential Functions**:
- `getAIResponse(prompt, model, maxTokens, temperature)`: Generic function to interact with AI model.
- `analyzeTaskComplexityWithAI(taskDescription)`: Sends task description to AI for complexity analysis.
- `expandTaskWithAI(taskDescription, numSubtasks, researchContext)`: Generates subtasks using AI.
- `parsePRDWithAI(prdContent)`: Extracts tasks from PRD content using AI.
- **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js): Unified AI Service Layer**
- **Purpose**: Centralized interface for all LLM interactions using Vercel AI SDK.
- **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)):
- Exports `generateTextService`, `generateObjectService`.
- Handles provider/model selection based on `role` and `.taskmasterconfig`.
- Resolves API keys (from `.env` or `session.env`).
- Implements fallback and retry logic.
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
- **[`utils.js`](mdc:scripts/modules/utils.js): Utility Functions and Configuration**
- **Purpose**: Provides reusable utility functions and global configuration settings used across the **CLI application**.
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
- **Responsibilities**: Interact directly with Vercel AI SDK adapters.
- **[`config-manager.js`](mdc:scripts/modules/config-manager.js): Configuration Management**
- **Purpose**: Loads, validates, and provides access to configuration.
- **Responsibilities** (See also: [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)):
- Manages global configuration settings loaded from environment variables and defaults.
- Implements logging utility with different log levels and output formatting.
- Provides file system operation utilities (read/write JSON files).
- Includes string manipulation utilities (e.g., `truncate`, `sanitizePrompt`).
- Offers task-specific utility functions (e.g., `formatTaskId`, `findTaskById`, `taskExists`).
- Implements graph algorithms like cycle detection for dependency management.
- **Silent Mode Control**: Provides `enableSilentMode` and `disableSilentMode` functions to control log output.
- **Key Components**:
- `CONFIG`: Global configuration object.
- `log(level, ...args)`: Logging function.
- `readJSON(filepath)` / `writeJSON(filepath, data)`: File I/O utilities for JSON files.
- `truncate(text, maxLength)`: String truncation utility.
- `formatTaskId(id)` / `findTaskById(tasks, taskId)`: Task ID and search utilities.
- `findCycles(subtaskId, dependencyMap)`: Cycle detection algorithm.
- `enableSilentMode()` / `disableSilentMode()`: Control console logging output.
- Reads and merges `.taskmasterconfig` with defaults.
- Provides getters (e.g., `getMainProvider`, `getLogLevel`, `getDefaultSubtasks`) for accessing settings.
- **Tag Configuration**: Manages `global.defaultTag` and `tags` section for tag system settings.
- **Note**: Does **not** store or directly handle API keys (keys are in `.env` or MCP `session.env`).
- **[`utils.js`](mdc:scripts/modules/utils.js): Core Utility Functions**
- **Purpose**: Low-level, reusable CLI utilities.
- **Responsibilities** (See also: [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)):
- Logging (`log` function), File I/O (`readJSON`, `writeJSON`), String utils (`truncate`).
- Task utils (`findTaskById`), Dependency utils (`findCycles`).
- API Key Resolution (`resolveEnvVariable`).
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
- **Tagged Task Lists**: Silent migration system, tag resolution, current tag management.
- **Migration System**: `performCompleteTagMigration`, `migrateConfigJson`, `createStateJson`.
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
- **Purpose**: Provides an MCP (Model Context Protocol) interface for Task Master, allowing integration with external tools like Cursor. Uses FastMCP framework.
- **Purpose**: Provides MCP interface using FastMCP.
- **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)):
- Registers Task Master functionalities as tools consumable via MCP.
- Handles MCP requests via tool `execute` methods defined in `mcp-server/src/tools/*.js`.
- Tool `execute` methods call corresponding **direct function wrappers**.
- Tool `execute` methods use `getProjectRootFromSession` (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to determine the project root from the client session and pass it to the direct function.
- **Direct function wrappers (`*Direct` functions in `mcp-server/src/core/direct-functions/*.js`) contain the main logic for handling MCP requests**, including path resolution, argument validation, caching, and calling core Task Master functions.
- Direct functions use `findTasksJsonPath` (from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js)) to locate `tasks.json` based on the provided `projectRoot`.
- **Silent Mode Implementation**: Direct functions use `enableSilentMode` and `disableSilentMode` to prevent logs from interfering with JSON responses.
- **Async Operations**: Uses `AsyncOperationManager` to handle long-running operations in the background.
- **Project Initialization**: Provides `initialize_project` command for setting up new projects from within integrated clients.
- Tool `execute` methods use `handleApiResult` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) to process the result from the direct function and format the final MCP response.
- Uses CLI execution via `executeTaskMasterCommand` as a fallback only when necessary.
- **Implements Robust Path Finding**: The utility [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) (specifically `getProjectRootFromSession`) and [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js) (specifically `findTasksJsonPath`) work together. The tool gets the root via session, passes it to the direct function, which uses `findTasksJsonPath` to locate the specific `tasks.json` file within that root.
- **Implements Caching**: Utilizes a caching layer (`ContextManager` with `lru-cache`). Caching logic is invoked *within* the direct function wrappers using the `getCachedOrExecute` utility for performance-sensitive read operations.
- Standardizes response formatting and data filtering using utilities in [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
- **Resource Management**: Provides access to static and dynamic resources.
- **Key Components**:
- `mcp-server/src/index.js`: Main server class definition with FastMCP initialization, resource registration, and server lifecycle management.
- `mcp-server/src/server.js`: Main server setup and initialization.
- `mcp-server/src/tools/`: Directory containing individual tool definitions. Each tool's `execute` method orchestrates the call to core logic and handles the response.
- `mcp-server/src/tools/utils.js`: Provides MCP-specific utilities like `handleApiResult`, `processMCPResponseData`, `getCachedOrExecute`, and **`getProjectRootFromSession`**.
- `mcp-server/src/core/utils/`: Directory containing utility functions specific to the MCP server, like **`path-utils.js` for resolving `tasks.json` within a given root** and **`async-manager.js` for handling background operations**.
- `mcp-server/src/core/direct-functions/`: Directory containing individual files for each **direct function wrapper (`*Direct`)**. These files contain the primary logic for MCP tool execution.
- `mcp-server/src/core/resources/`: Directory containing resource handlers for task templates, workflow definitions, and other static/dynamic data exposed to LLM clients.
- [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js): Acts as an import/export hub, collecting and exporting direct functions from the `direct-functions` directory and MCP utility functions.
- **Naming Conventions**:
- **Files** use **kebab-case**: `list-tasks.js`, `set-task-status.js`, `parse-prd.js`
- **Direct Functions** use **camelCase** with `Direct` suffix: `listTasksDirect`, `setTaskStatusDirect`, `parsePRDDirect`
- **Tool Registration Functions** use **camelCase** with `Tool` suffix: `registerListTasksTool`, `registerSetTaskStatusTool`
- **MCP Tool Names** use **snake_case**: `list_tasks`, `set_task_status`, `parse_prd_document`
- **Resource Handlers** use **camelCase** with pattern URI: `@mcp.resource("tasks://templates/{template_id}")`
- **AsyncOperationManager**:
- **Purpose**: Manages background execution of long-running operations.
- **Location**: `mcp-server/src/core/utils/async-manager.js`
- **Key Features**:
- Operation tracking with unique IDs using UUID
- Status management (pending, running, completed, failed)
- Progress reporting forwarded from background tasks
- Operation history with automatic cleanup of completed operations
- Context preservation (log, session, reportProgress)
- Robust error handling for background tasks
- **Usage**: Used for CPU-intensive operations like task expansion and PRD parsing
- Registers tools (`mcp-server/src/tools/*.js`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling.
- The HOF provides a normalized `args.projectRoot` to the `execute` method.
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`), passing the normalized `projectRoot` and other args.
- Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session.
- Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`.
- **Tagged Task Lists**: MCP tools fully support the tagged format with complete tag management capabilities.
- Manages MCP caching and response formatting.
- **[`init.js`](mdc:scripts/init.js): Project Initialization Logic**
- **Purpose**: Contains the core logic for setting up a new Task Master project structure.
- **Responsibilities**:
- Creates necessary directories (`.cursor/rules`, `scripts`, `tasks`).
- Copies template files (`.env.example`, `.gitignore`, rule files, `dev.js`, etc.).
- Creates or merges `package.json` with required dependencies and scripts.
- Sets up MCP configuration (`.cursor/mcp.json`).
- Optionally initializes a git repository and installs dependencies.
- Handles user prompts for project details *if* called without skip flags (`-y`).
- **Key Function**:
- `initializeProject(options)`: The main function exported and called by the `init` command's action handler in [`commands.js`](mdc:scripts/modules/commands.js). It receives parsed options directly.
- **Note**: This script is used as a module and no longer handles its own argument parsing or direct execution via a separate `bin` file.
- **Purpose**: Sets up new Task Master project structure.
- **Responsibilities**: Creates directories, copies templates, manages `package.json`, sets up `.cursor/mcp.json`, initializes state.json for tagged system.
- **Data Flow and Module Dependencies**:
## Tagged Task Lists System Architecture
- **Commands Initiate Actions**: User commands entered via the CLI (parsed by `commander` based on definitions in [`commands.js`](mdc:scripts/modules/commands.js)) are the entry points for most operations.
- **Command Handlers Delegate to Core Logic**: Action handlers within [`commands.js`](mdc:scripts/modules/commands.js) call functions in core modules like [`task-manager.js`](mdc:scripts/modules/task-manager.js), [`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js), and [`init.js`](mdc:scripts/init.js) (for the `init` command) to perform the actual work.
- **UI for Presentation**: [`ui.js`](mdc:scripts/modules/ui.js) is used by command handlers and task/dependency managers to display information to the user. UI functions primarily consume data and format it for output, without modifying core application state.
- **Utilities for Common Tasks**: [`utils.js`](mdc:scripts/modules/utils.js) provides helper functions used by all other modules for configuration, logging, file operations, and common data manipulations.
- **AI Services Integration**: AI functionalities (complexity analysis, task expansion, PRD parsing) are invoked from [`task-manager.js`](mdc:scripts/modules/task-manager.js) and potentially [`commands.js`](mdc:scripts/modules/commands.js), likely using functions that would reside in a dedicated `ai-services.js` module or be integrated within `utils.js` or `task-manager.js`.
- **MCP Server Interaction**: External tools interact with the `mcp-server`. MCP Tool `execute` methods use `getProjectRootFromSession` to find the project root, then call direct function wrappers (in `mcp-server/src/core/direct-functions/`) passing the root in `args`. These wrappers handle path finding for `tasks.json` (using `path-utils.js`), validation, caching, call the core logic from `scripts/modules/` (passing logging context via the standard wrapper pattern detailed in mcp.mdc), and return a standardized result. The final MCP response is formatted by `mcp-server/src/tools/utils.js`. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details.
**Data Structure**: Task Master now uses a tagged task lists system where the `tasks.json` file contains multiple named task lists as top-level keys:
```json
{
"master": {
"tasks": [/* standard task objects */]
},
"feature-branch": {
"tasks": [/* separate task context */]
}
}
```
**Key Components:**
- **Silent Migration**: Automatically transforms legacy `{"tasks": [...]}` format to tagged format `{"master": {"tasks": [...]}}` on first read
- **Tag Resolution Layer**: Provides 100% backward compatibility by intercepting tagged format and returning legacy format to existing code
- **Configuration Integration**: `global.defaultTag` and `tags` section in config.json manage tag system settings
- **State Management**: `.taskmaster/state.json` tracks current tag, migration status, and tag-branch mappings
- **Migration Notice**: User-friendly notification system for seamless migration experience
**Backward Compatibility**: All existing CLI commands and MCP tools continue to work unchanged. The tag resolution layer ensures that existing code receives the expected legacy format while the underlying storage uses the new tagged structure.
- **Data Flow and Module Dependencies (Updated)**:
- **CLI**: `bin/task-master.js` -> `scripts/dev.js` (loads `.env`) -> `scripts/modules/commands.js` -> Core Logic (`scripts/modules/*`) -> **Tag Resolution Layer** -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **MCP**: External Tool -> `mcp-server/server.js` -> Tool (`mcp-server/src/tools/*`) -> Direct Function (`mcp-server/src/core/direct-functions/*`) -> Core Logic (`scripts/modules/*`) -> **Tag Resolution Layer** -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **Configuration**: Core logic needing non-AI settings calls `config-manager.js` getters (passing `session.env` via `explicitRoot` if from MCP). Unified AI Service internally calls `config-manager.js` getters (using `role`) for AI params and `utils.js` (`resolveEnvVariable` with `session.env`) for API keys.
## Silent Mode Implementation Pattern in MCP Direct Functions
@@ -284,6 +228,7 @@ By following these patterns consistently, direct functions will properly manage
- **Integration Tests**: Located in `tests/integration/`, test interactions between modules
- **End-to-End Tests**: Located in `tests/e2e/`, test complete workflows from a user perspective
- **Test Fixtures**: Located in `tests/fixtures/`, provide reusable test data
- **Tagged System Tests**: Test migration, tag resolution, and multi-context functionality
- **Module Design for Testability**:
- **Explicit Dependencies**: Functions accept their dependencies as parameters rather than using globals
@@ -292,12 +237,14 @@ By following these patterns consistently, direct functions will properly manage
- **Clear Module Interfaces**: Each module has well-defined exports that can be mocked in tests
- **Callback Isolation**: Callbacks are defined as separate functions for easier testing
- **Stateless Design**: Modules avoid maintaining internal state where possible
- **Tag Resolution Testing**: Test both tagged and legacy format handling
- **Mock Integration Patterns**:
- **External Libraries**: Libraries like `fs`, `commander`, and `@anthropic-ai/sdk` are mocked at module level
- **Internal Modules**: Application modules are mocked with appropriate spy functions
- **Testing Function Callbacks**: Callbacks are extracted from mock call arguments and tested in isolation
- **UI Elements**: Output functions from `ui.js` are mocked to verify display calls
- **Tagged Data Mocking**: Test both legacy and tagged task data structures
- **Testing Flow**:
- Module dependencies are mocked (following Jest's hoisting behavior)
@@ -305,6 +252,7 @@ By following these patterns consistently, direct functions will properly manage
- Spy functions are set up on module methods
- Tests call the functions under test and verify behavior
- Mocks are reset between test cases to maintain isolation
- Tagged system behavior is tested for both migration and normal operation
- **Benefits of this Architecture**:
@@ -313,8 +261,11 @@ By following these patterns consistently, direct functions will properly manage
- **Mocking Support**: The clear dependency boundaries make mocking straightforward
- **Test Isolation**: Each component can be tested without affecting others
- **Callback Testing**: Function callbacks can be extracted and tested independently
- **Multi-Context Testing**: Tagged system enables testing different task contexts independently
- **Reusability**: Utility functions and UI components can be reused across different parts of the application.
- **Scalability**: New features can be added as new modules or by extending existing ones without significantly impacting other parts of the application.
- **Multi-Context Support**: Tagged task lists enable working across different contexts (branches, environments, phases) without conflicts.
- **Backward Compatibility**: Seamless migration and tag resolution ensure existing workflows continue unchanged.
- **Clarity**: The modular structure provides a clear separation of concerns, making the codebase easier to navigate and understand for developers.
This architectural overview should help AI models understand the structure and organization of the Task Master CLI codebase, enabling them to more effectively assist with code generation, modification, and understanding.
@@ -336,6 +287,7 @@ Follow these steps to add MCP support for an existing Task Master command (see [
- Call core logic.
- Return `{ success: true/false, data/error, fromCache: boolean }`.
- Export the wrapper function.
- **Note**: Tag-aware MCP tools are fully implemented with complete tag management support.
3. **Update `task-master-core.js` with Import/Export**: Add imports/exports for the new `*Direct` function.
@@ -362,23 +314,8 @@ The `initialize_project` command provides a way to set up a new Task Master proj
- **MCP Tool**: `initialize_project`
- **Functionality**:
- Creates necessary directories and files for a new project
- Sets up `tasks.json` and initial task files
- Sets up `tasks.json` with tagged structure and initial task files
- Configures project metadata (name, description, version)
- Initializes state.json for tag system
- Handles shell alias creation if requested
- Works in both interactive and non-interactive modes
## Async Operation Management
The AsyncOperationManager provides background task execution capabilities:
- **Location**: `mcp-server/src/core/utils/async-manager.js`
- **Key Components**:
- `asyncOperationManager` singleton instance
- `addOperation(operationFn, args, context)` method
- `getStatus(operationId)` method
- **Usage Flow**:
1. Client calls an MCP tool that may take time to complete
2. Tool uses AsyncOperationManager to run the operation in background
3. Tool returns immediate response with operation ID
4. Client polls `get_operation_status` tool with the ID
5. Once completed, client can access operation results
- Works in both interactive and non-interactive modes

View File

@@ -34,8 +34,8 @@ While this document details the implementation of Task Master's **CLI commands**
- **Command Handler Organization**:
- ✅ DO: Keep action handlers concise and focused
- ✅ DO: Extract core functionality to appropriate modules
- ✅ DO: Have the action handler import and call the relevant function(s) from core modules (e.g., `task-manager.js`, `init.js`), passing the parsed `options`.
- ✅ DO: Perform basic parameter validation (e.g., checking for required options) within the action handler or at the start of the called core function.
- ✅ DO: Have the action handler import and call the relevant functions from core modules, like `task-manager.js` or `init.js`, passing the parsed `options`.
- ✅ DO: Perform basic parameter validation, such as checking for required options, within the action handler or at the start of the called core function.
- ❌ DON'T: Implement business logic in command handlers
## Best Practices for Removal/Delete Commands
@@ -44,7 +44,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **Confirmation Prompts**:
- ✅ **DO**: Include a confirmation prompt by default for destructive operations
- ✅ **DO**: Provide a `--yes` or `-y` flag to skip confirmation for scripting/automation
- ✅ **DO**: Provide a `--yes` or `-y` flag to skip confirmation, useful for scripting or automation
- ✅ **DO**: Show what will be deleted in the confirmation message
- ❌ **DON'T**: Perform destructive operations without user confirmation unless explicitly overridden
@@ -78,7 +78,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **File Path Handling**:
- ✅ **DO**: Use `path.join()` to construct file paths
- ✅ **DO**: Follow established naming conventions for tasks (e.g., `task_001.txt`)
- ✅ **DO**: Follow established naming conventions for tasks, like `task_001.txt`
- ✅ **DO**: Check if files exist before attempting to delete them
- ✅ **DO**: Handle file deletion errors gracefully
- ❌ **DON'T**: Construct paths with string concatenation
@@ -166,10 +166,10 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- ✅ DO: Use descriptive, action-oriented names
- **Option Names**:
- ✅ DO: Use kebab-case for long-form option names (`--output-format`)
- ✅ DO: Provide single-letter shortcuts when appropriate (`-f, --file`)
- ✅ DO: Use kebab-case for long-form option names, like `--output-format`
- ✅ DO: Provide single-letter shortcuts when appropriate, like `-f, --file`
- ✅ DO: Use consistent option names across similar commands
- ❌ DON'T: Use different names for the same concept (`--file` in one command, `--path` in another)
- ❌ DON'T: Use different names for the same concept, such as `--file` in one command and `--path` in another
```javascript
// ✅ DO: Use consistent option naming
@@ -181,7 +181,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.option('-p, --path <dir>', 'Output directory') // Should be --output
```
> **Note**: Although options are defined with kebab-case (`--num-tasks`), Commander.js stores them internally as camelCase properties. Access them in code as `options.numTasks`, not `options['num-tasks']`.
> **Note**: Although options are defined with kebab-case, like `--num-tasks`, Commander.js stores them internally as camelCase properties. Access them in code as `options.numTasks`, not `options['num-tasks']`.
- **Boolean Flag Conventions**:
- ✅ DO: Use positive flags with `--skip-` prefix for disabling behavior
@@ -210,7 +210,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **Required Parameters**:
- ✅ DO: Check that required parameters are provided
- ✅ DO: Provide clear error messages when parameters are missing
- ✅ DO: Use early returns with process.exit(1) for validation failures
- ✅ DO: Use early returns with `process.exit(1)` for validation failures
```javascript
// ✅ DO: Validate required parameters early
@@ -221,7 +221,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
```
- **Parameter Type Conversion**:
- ✅ DO: Convert string inputs to appropriate types (numbers, booleans)
- ✅ DO: Convert string inputs to appropriate types, such as numbers or booleans
- ✅ DO: Handle conversion errors gracefully
```javascript
@@ -254,7 +254,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
const taskId = parseInt(options.id, 10);
if (isNaN(taskId) || taskId <= 0) {
console.error(chalk.red(`Error: Invalid task ID: ${options.id}. Task ID must be a positive integer.`));
console.log(chalk.yellow('Usage example: task-master update-task --id=\'23\' --prompt=\'Update with new information.\nEnsure proper error handling.\''));
console.log(chalk.yellow("Usage example: task-master update-task --id='23' --prompt='Update with new information.\\nEnsure proper error handling.'"));
process.exit(1);
}
@@ -329,6 +329,60 @@ When implementing commands that delete or remove data (like `remove-task` or `re
};
```
## Context-Aware Command Pattern
For AI-powered commands that benefit from project context, follow the research command pattern:
- **Context Integration**:
- ✅ DO: Use `ContextGatherer` utility for multi-source context extraction
- ✅ DO: Support task IDs, file paths, custom context, and project tree
- ✅ DO: Implement fuzzy search for automatic task discovery
- ✅ DO: Display detailed token breakdown for transparency
```javascript
// ✅ DO: Follow this pattern for context-aware commands
programInstance
.command('research')
.description('Perform AI-powered research queries with project context')
.argument('<prompt>', 'Research prompt to investigate')
.option('-i, --id <ids>', 'Comma-separated task/subtask IDs to include as context')
.option('-f, --files <paths>', 'Comma-separated file paths to include as context')
.option('-c, --context <text>', 'Additional custom context')
.option('--tree', 'Include project file tree structure')
.option('-d, --detail <level>', 'Output detail level: low, medium, high', 'medium')
.action(async (prompt, options) => {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown and execute AI call
// Implementation continues...
});
```
## Error Handling
- **Exception Management**:
@@ -392,9 +446,9 @@ When implementing commands that delete or remove data (like `remove-task` or `re
process.on('uncaughtException', (err) => {
// Handle Commander-specific errors
if (err.code === 'commander.unknownOption') {
const option = err.message.match(/'([^']+)'/)?.[1];
const option = err.message.match(/'([^']+)'/)?.[1]; // Safely extract option name
console.error(chalk.red(`Error: Unknown option '${option}'`));
console.error(chalk.yellow(`Run 'task-master <command> --help' to see available options`));
console.error(chalk.yellow("Run 'task-master <command> --help' to see available options"));
process.exit(1);
}
@@ -464,12 +518,12 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.option('-f, --file <path>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-p, --parent <id>', 'ID of the parent task (required)')
.option('-i, --task-id <id>', 'Existing task ID to convert to subtask')
.option('-t, --title <title>', 'Title for the new subtask (when not converting)')
.option('-d, --description <description>', 'Description for the new subtask (when not converting)')
.option('--details <details>', 'Implementation details for the new subtask (when not converting)')
.option('-t, --title <title>', 'Title for the new subtask, required if not converting')
.option('-d, --description <description>', 'Description for the new subtask, optional')
.option('--details <details>', 'Implementation details for the new subtask, optional')
.option('--dependencies <ids>', 'Comma-separated list of subtask IDs this subtask depends on')
.option('--status <status>', 'Initial status for the subtask', 'pending')
.option('--skip-generate', 'Skip regenerating task files')
.option('--generate', 'Regenerate task files after adding subtask')
.action(async (options) => {
// Validate required parameters
if (!options.parent) {
@@ -489,9 +543,9 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.command('remove-subtask')
.description('Remove a subtask from its parent task, optionally converting it to a standalone task')
.option('-f, --file <path>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-i, --id <id>', 'ID of the subtask to remove in format "parentId.subtaskId" (required)')
.option('-c, --convert', 'Convert the subtask to a standalone task')
.option('--skip-generate', 'Skip regenerating task files')
.option('-i, --id <id>', 'ID of the subtask to remove in format parentId.subtaskId, required')
.option('-c, --convert', 'Convert the subtask to a standalone task instead of deleting')
.option('--generate', 'Regenerate task files after removing subtask')
.action(async (options) => {
// Implementation with detailed error handling
})
@@ -513,7 +567,8 @@ When implementing commands that delete or remove data (like `remove-task` or `re
// ✅ DO: Implement version checking function
async function checkForUpdate() {
// Implementation details...
return { currentVersion, latestVersion, needsUpdate };
// Example return structure:
return { currentVersion, latestVersion, updateAvailable };
}
// ✅ DO: Implement semantic version comparison
@@ -553,7 +608,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
// After command execution, check if an update is available
const updateInfo = await updateCheckPromise;
if (updateInfo.needsUpdate) {
if (updateInfo.updateAvailable) {
displayUpgradeNotification(updateInfo.currentVersion, updateInfo.latestVersion);
}
} catch (error) {
@@ -578,11 +633,11 @@ function showAddSubtaskHelp() {
' --dependencies <ids> Comma-separated list of dependency IDs\n' +
' -s, --status <status> Status for the new subtask (default: "pending")\n' +
' -f, --file <file> Path to the tasks file (default: "tasks/tasks.json")\n' +
' --skip-generate Skip regenerating task files\n\n' +
' --generate Regenerate task files after adding subtask\n\n' +
chalk.cyan('Examples:') + '\n' +
' task-master add-subtask --parent=\'5\' --task-id=\'8\'\n' +
' task-master add-subtask -p \'5\' -t \'Implement login UI\' -d \'Create the login form\'\n' +
' task-master add-subtask -p \'5\' -t \'Handle API Errors\' --details $\'Handle 401 Unauthorized.\nHandle 500 Server Error.\'',
' task-master add-subtask -p \'5\' -t \'Handle API Errors\' --details "Handle 401 Unauthorized.\\nHandle 500 Server Error." --generate',
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
));
}
@@ -597,7 +652,7 @@ function showRemoveSubtaskHelp() {
' -i, --id <id> Subtask ID(s) to remove in format "parentId.subtaskId" (can be comma-separated, required)\n' +
' -c, --convert Convert the subtask to a standalone task instead of deleting it\n' +
' -f, --file <file> Path to the tasks file (default: "tasks/tasks.json")\n' +
' --skip-generate Skip regenerating task files\n\n' +
' --generate Regenerate task files after removing subtask\n\n' +
chalk.cyan('Examples:') + '\n' +
' task-master remove-subtask --id=\'5.2\'\n' +
' task-master remove-subtask --id=\'5.2,6.3,7.1\'\n' +

View File

@@ -0,0 +1,268 @@
---
description: Standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
globs:
alwaysApply: false
---
# Context Gathering Patterns and Utilities
This document outlines the standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
## Core Context Gathering Utility
The `ContextGatherer` class (`scripts/modules/utils/contextGatherer.js`) provides a centralized, reusable utility for extracting context from multiple sources:
### **Key Features**
- **Multi-source Context**: Tasks, files, custom text, project file tree
- **Token Counting**: Detailed breakdown using `gpt-tokens` library
- **Format Support**: Different output formats (research, chat, system-prompt)
- **Error Handling**: Graceful handling of missing files, invalid task IDs
- **Performance**: File size limits, depth limits for tree generation
### **Usage Pattern**
```javascript
import { ContextGatherer } from '../utils/contextGatherer.js';
// Initialize with project paths
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// Gather context with detailed token breakdown
const result = await gatherer.gather({
tasks: ['15', '16.2'], // Task and subtask IDs
files: ['src/api.js', 'README.md'], // File paths
customContext: 'Additional context text',
includeProjectTree: true, // Include file tree
format: 'research', // Output format
includeTokenCounts: true // Get detailed token breakdown
});
// Access results
const contextString = result.context;
const tokenBreakdown = result.tokenBreakdown;
```
### **Token Breakdown Structure**
```javascript
{
customContext: { tokens: 150, characters: 800 },
tasks: [
{ id: '15', type: 'task', title: 'Task Title', tokens: 245, characters: 1200 },
{ id: '16.2', type: 'subtask', title: 'Subtask Title', tokens: 180, characters: 900 }
],
files: [
{ path: 'src/api.js', tokens: 890, characters: 4500, size: '4.5 KB' }
],
projectTree: { tokens: 320, characters: 1600 },
total: { tokens: 1785, characters: 8000 }
}
```
## Fuzzy Search Integration
The `FuzzyTaskSearch` class (`scripts/modules/utils/fuzzyTaskSearch.js`) provides intelligent task discovery:
### **Key Features**
- **Semantic Matching**: Uses Fuse.js for similarity scoring
- **Purpose Categories**: Pattern-based task categorization
- **Relevance Scoring**: High/medium/low relevance thresholds
- **Context-Aware**: Different search configurations for different use cases
### **Usage Pattern**
```javascript
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
// Initialize with tasks data and context
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
// Find relevant tasks
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
// Get task IDs for context gathering
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
## Implementation Patterns for Commands
### **1. Context-Aware Command Structure**
```javascript
// In command action handler
async function commandAction(prompt, options) {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown (for CLI)
if (outputFormat === 'text') {
displayDetailedTokenBreakdown(contextResult.tokenBreakdown);
}
// 6. Use context in AI call
const aiResult = await generateTextService(role, session, systemPrompt, userPrompt);
// 7. Display results with enhanced formatting
displayResults(aiResult, contextResult.tokenBreakdown);
}
```
### **2. Token Display Pattern**
```javascript
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
// Build context breakdown
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
if (tokenBreakdown.files?.length > 0) {
const fileDetails = tokenBreakdown.files.map(file =>
` ${file.path}: ${file.tokens.toLocaleString()} (${file.size})`
).join('\n');
sections.push(`Files (${tokenBreakdown.files.reduce((sum, f) => sum + f.tokens, 0).toLocaleString()}):\n${fileDetails}`);
}
// Add prompts breakdown
sections.push(`Prompts: system ${systemTokens.toLocaleString()}, user ${userTokens.toLocaleString()}`);
// Display in clean box
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **3. Enhanced Result Display Pattern**
```javascript
function displayResults(result, query, detailLevel, tokenBreakdown) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and highlight code blocks
const processedResult = processCodeBlocks(result);
// Main content in clean box
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Research complete'));
}
```
## Code Block Enhancement
### **Syntax Highlighting Pattern**
```javascript
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
## Integration Guidelines
### **When to Use Context Gathering**
- ✅ **DO**: Use for AI-powered commands that benefit from project context
- ✅ **DO**: Use when users might want to reference specific tasks or files
- ✅ **DO**: Use for research, analysis, or generation commands
- ❌ **DON'T**: Use for simple CRUD operations that don't need AI context
### **Performance Considerations**
- ✅ **DO**: Set reasonable file size limits (50KB default)
- ✅ **DO**: Limit project tree depth (3-5 levels)
- ✅ **DO**: Provide token counts to help users understand context size
- ✅ **DO**: Allow users to control what context is included
### **Error Handling**
- ✅ **DO**: Gracefully handle missing files with warnings
- ✅ **DO**: Validate task IDs and provide helpful error messages
- ✅ **DO**: Continue processing even if some context sources fail
- ✅ **DO**: Provide fallback behavior when context gathering fails
### **Future Command Integration**
Commands that should consider adopting this pattern:
- `analyze-complexity` - Could benefit from file context
- `expand-task` - Could use related task context
- `update-task` - Could reference similar tasks for consistency
- `add-task` - Could use project context for better task generation
## Export Patterns
### **Context Gatherer Module**
```javascript
export {
ContextGatherer,
createContextGatherer // Factory function
};
```
### **Fuzzy Search Module**
```javascript
export {
FuzzyTaskSearch,
PURPOSE_CATEGORIES,
RELEVANCE_THRESHOLDS
};
```
This context gathering system provides a foundation for building more intelligent, context-aware commands that can leverage project knowledge to provide better AI-powered assistance.

View File

@@ -1,24 +1,205 @@
---
description: Guide for using Task Master to manage task-driven development workflows
description: Guide for using Taskmaster to manage task-driven development workflows
globs: **/*
alwaysApply: true
---
# Task Master Development Workflow
# Taskmaster Development Workflow
This guide outlines the typical process for using Task Master to manage software development projects.
This guide outlines the standard process for using Taskmaster to manage software development projects. It is written as a set of instructions for you, the AI agent.
- **Your Default Stance**: For most projects, the user can work directly within the `master` task context. Your initial actions should operate on this default context unless a clear pattern for multi-context work emerges.
- **Your Goal**: Your role is to elevate the user's workflow by intelligently introducing advanced features like **Tagged Task Lists** when you detect the appropriate context. Do not force tags on the user; suggest them as a helpful solution to a specific need.
## The Basic Loop
The fundamental development cycle you will facilitate is:
1. **`list`**: Show the user what needs to be done.
2. **`next`**: Help the user decide what to work on.
3. **`show <id>`**: Provide details for a specific task.
4. **`expand <id>`**: Break down a complex task into smaller, manageable subtasks.
5. **Implement**: The user writes the code and tests.
6. **`update-subtask`**: Log progress and findings on behalf of the user.
7. **`set-status`**: Mark tasks and subtasks as `done` as work is completed.
8. **Repeat**.
All your standard command executions should operate on the user's current task context, which defaults to `master`.
---
## Standard Development Workflow Process
### Simple Workflow (Default Starting Point)
For new projects or when users are getting started, operate within the `master` tag context:
- Start new projects by running `initialize_project` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json with tagged structure
- Configure rule sets during initialization with `--rules` flag (e.g., `task-master init --rules cursor,windsurf`) or manage them later with `task-master rules add/remove` commands
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Analyze task complexity with `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- View specific task details using `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id> --force --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags like `--force` (to replace existing subtasks) and `--research`
- Implement code following task details, dependencies, and project standards
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
---
## Leveling Up: Agent-Led Multi-Context Workflows
While the basic workflow is powerful, your primary opportunity to add value is by identifying when to introduce **Tagged Task Lists**. These patterns are your tools for creating a more organized and efficient development environment for the user, especially if you detect agentic or parallel development happening across the same session.
**Critical Principle**: Most users should never see a difference in their experience. Only introduce advanced workflows when you detect clear indicators that the project has evolved beyond simple task management.
### When to Introduce Tags: Your Decision Patterns
Here are the patterns to look for. When you detect one, you should propose the corresponding workflow to the user.
#### Pattern 1: Simple Git Feature Branching
This is the most common and direct use case for tags.
- **Trigger**: The user creates a new git branch (e.g., `git checkout -b feature/user-auth`).
- **Your Action**: Propose creating a new tag that mirrors the branch name to isolate the feature's tasks from `master`.
- **Your Suggested Prompt**: *"I see you've created a new branch named 'feature/user-auth'. To keep all related tasks neatly organized and separate from your main list, I can create a corresponding task tag for you. This helps prevent merge conflicts in your `tasks.json` file later. Shall I create the 'feature-user-auth' tag?"*
- **Tool to Use**: `task-master add-tag --from-branch`
#### Pattern 2: Team Collaboration
- **Trigger**: The user mentions working with teammates (e.g., "My teammate Alice is handling the database schema," or "I need to review Bob's work on the API.").
- **Your Action**: Suggest creating a separate tag for the user's work to prevent conflicts with shared master context.
- **Your Suggested Prompt**: *"Since you're working with Alice, I can create a separate task context for your work to avoid conflicts. This way, Alice can continue working with the master list while you have your own isolated context. When you're ready to merge your work, we can coordinate the tasks back to master. Shall I create a tag for your current work?"*
- **Tool to Use**: `task-master add-tag my-work --copy-from-current --description="My tasks while collaborating with Alice"`
#### Pattern 3: Experiments or Risky Refactors
- **Trigger**: The user wants to try something that might not be kept (e.g., "I want to experiment with switching our state management library," or "Let's refactor the old API module, but I want to keep the current tasks as a reference.").
- **Your Action**: Propose creating a sandboxed tag for the experimental work.
- **Your Suggested Prompt**: *"This sounds like a great experiment. To keep these new tasks separate from our main plan, I can create a temporary 'experiment-zustand' tag for this work. If we decide not to proceed, we can simply delete the tag without affecting the main task list. Sound good?"*
- **Tool to Use**: `task-master add-tag experiment-zustand --description="Exploring Zustand migration"`
#### Pattern 4: Large Feature Initiatives (PRD-Driven)
This is a more structured approach for significant new features or epics.
- **Trigger**: The user describes a large, multi-step feature that would benefit from a formal plan.
- **Your Action**: Propose a comprehensive, PRD-driven workflow.
- **Your Suggested Prompt**: *"This sounds like a significant new feature. To manage this effectively, I suggest we create a dedicated task context for it. Here's the plan: I'll create a new tag called 'feature-xyz', then we can draft a Product Requirements Document (PRD) together to scope the work. Once the PRD is ready, I'll automatically generate all the necessary tasks within that new tag. How does that sound?"*
- **Your Implementation Flow**:
1. **Create an empty tag**: `task-master add-tag feature-xyz --description "Tasks for the new XYZ feature"`. You can also start by creating a git branch if applicable, and then create the tag from that branch.
2. **Collaborate & Create PRD**: Work with the user to create a detailed PRD file (e.g., `.taskmaster/docs/feature-xyz-prd.txt`).
3. **Parse PRD into the new tag**: `task-master parse-prd .taskmaster/docs/feature-xyz-prd.txt --tag feature-xyz`
4. **Prepare the new task list**: Follow up by suggesting `analyze-complexity` and `expand-all` for the newly created tasks within the `feature-xyz` tag.
#### Pattern 5: Version-Based Development
Tailor your approach based on the project maturity indicated by tag names.
- **Prototype/MVP Tags** (`prototype`, `mvp`, `poc`, `v0.x`):
- **Your Approach**: Focus on speed and functionality over perfection
- **Task Generation**: Create tasks that emphasize "get it working" over "get it perfect"
- **Complexity Level**: Lower complexity, fewer subtasks, more direct implementation paths
- **Research Prompts**: Include context like "This is a prototype - prioritize speed and basic functionality over optimization"
- **Example Prompt Addition**: *"Since this is for the MVP, I'll focus on tasks that get core functionality working quickly rather than over-engineering."*
- **Production/Mature Tags** (`v1.0+`, `production`, `stable`):
- **Your Approach**: Emphasize robustness, testing, and maintainability
- **Task Generation**: Include comprehensive error handling, testing, documentation, and optimization
- **Complexity Level**: Higher complexity, more detailed subtasks, thorough implementation paths
- **Research Prompts**: Include context like "This is for production - prioritize reliability, performance, and maintainability"
- **Example Prompt Addition**: *"Since this is for production, I'll ensure tasks include proper error handling, testing, and documentation."*
### Advanced Workflow (Tag-Based & PRD-Driven)
**When to Transition**: Recognize when the project has evolved (or has initiated a project which existing code) beyond simple task management. Look for these indicators:
- User mentions teammates or collaboration needs
- Project has grown to 15+ tasks with mixed priorities
- User creates feature branches or mentions major initiatives
- User initializes Taskmaster on an existing, complex codebase
- User describes large features that would benefit from dedicated planning
**Your Role in Transition**: Guide the user to a more sophisticated workflow that leverages tags for organization and PRDs for comprehensive planning.
#### Master List Strategy (High-Value Focus)
Once you transition to tag-based workflows, the `master` tag should ideally contain only:
- **High-level deliverables** that provide significant business value
- **Major milestones** and epic-level features
- **Critical infrastructure** work that affects the entire project
- **Release-blocking** items
**What NOT to put in master**:
- Detailed implementation subtasks (these go in feature-specific tags' parent tasks)
- Refactoring work (create dedicated tags like `refactor-auth`)
- Experimental features (use `experiment-*` tags)
- Team member-specific tasks (use person-specific tags)
#### PRD-Driven Feature Development
**For New Major Features**:
1. **Identify the Initiative**: When user describes a significant feature
2. **Create Dedicated Tag**: `add_tag feature-[name] --description="[Feature description]"`
3. **Collaborative PRD Creation**: Work with user to create comprehensive PRD in `.taskmaster/docs/feature-[name]-prd.txt`
4. **Parse & Prepare**:
- `parse_prd .taskmaster/docs/feature-[name]-prd.txt --tag=feature-[name]`
- `analyze_project_complexity --tag=feature-[name] --research`
- `expand_all --tag=feature-[name] --research`
5. **Add Master Reference**: Create a high-level task in `master` that references the feature tag
**For Existing Codebase Analysis**:
When users initialize Taskmaster on existing projects:
1. **Codebase Discovery**: Use your native tools for producing deep context about the code base. You may use `research` tool with `--tree` and `--files` to collect up to date information using the existing architecture as context.
2. **Collaborative Assessment**: Work with user to identify improvement areas, technical debt, or new features
3. **Strategic PRD Creation**: Co-author PRDs that include:
- Current state analysis (based on your codebase research)
- Proposed improvements or new features
- Implementation strategy considering existing code
4. **Tag-Based Organization**: Parse PRDs into appropriate tags (`refactor-api`, `feature-dashboard`, `tech-debt`, etc.)
5. **Master List Curation**: Keep only the most valuable initiatives in master
The parse-prd's `--append` flag enables the user to parse multiple PRDs within tags or across tags. PRDs should be focused and the number of tasks they are parsed into should be strategically chosen relative to the PRD's complexity and level of detail.
### Workflow Transition Examples
**Example 1: Simple → Team-Based**
```
User: "Alice is going to help with the API work"
Your Response: "Great! To avoid conflicts, I'll create a separate task context for your work. Alice can continue with the master list while you work in your own context. When you're ready to merge, we can coordinate the tasks back together."
Action: add_tag my-api-work --copy-from-current --description="My API tasks while collaborating with Alice"
```
**Example 2: Simple → PRD-Driven**
```
User: "I want to add a complete user dashboard with analytics, user management, and reporting"
Your Response: "This sounds like a major feature that would benefit from detailed planning. Let me create a dedicated context for this work and we can draft a PRD together to ensure we capture all requirements."
Actions:
1. add_tag feature-dashboard --description="User dashboard with analytics and management"
2. Collaborate on PRD creation
3. parse_prd dashboard-prd.txt --tag=feature-dashboard
4. Add high-level "User Dashboard" task to master
```
**Example 3: Existing Project → Strategic Planning**
```
User: "I just initialized Taskmaster on my existing React app. It's getting messy and I want to improve it."
Your Response: "Let me research your codebase to understand the current architecture, then we can create a strategic plan for improvements."
Actions:
1. research "Current React app architecture and improvement opportunities" --tree --files=src/
2. Collaborate on improvement PRD based on findings
3. Create tags for different improvement areas (refactor-components, improve-state-management, etc.)
4. Keep only major improvement initiatives in master
```
---
## Primary Interaction: MCP Server vs. CLI
Task Master offers two primary ways to interact:
Taskmaster offers two primary ways to interact:
1. **MCP Server (Recommended for Integrated Tools)**:
- For AI agents and integrated development environments (like Cursor), interacting via the **MCP server is the preferred method**.
- The MCP server exposes Task Master functionality through a set of tools (e.g., `get_tasks`, `add_subtask`).
- The MCP server exposes Taskmaster functionality through a set of tools (e.g., `get_tasks`, `add_subtask`).
- This method offers better performance, structured data exchange, and richer error handling compared to CLI parsing.
- Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details on the MCP architecture and available tools.
- A comprehensive list and description of MCP tools and their corresponding CLI commands can be found in [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
- **Restart the MCP server** if core logic in `scripts/modules` or MCP tool/direct function definitions change.
- **Note**: MCP tools fully support tagged task lists with complete tag management capabilities.
2. **`task-master` CLI (For Users & Fallback)**:
- The global `task-master` command provides a user-friendly interface for direct terminal interaction.
@@ -26,56 +207,44 @@ Task Master offers two primary ways to interact:
- Install globally with `npm install -g task-master-ai` or use locally via `npx task-master-ai ...`.
- The CLI commands often mirror the MCP tools (e.g., `task-master list` corresponds to `get_tasks`).
- Refer to [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for a detailed command reference.
- **Tagged Task Lists**: CLI fully supports the new tagged system with seamless migration.
## Standard Development Workflow Process
## How the Tag System Works (For Your Reference)
- Start new projects by running `init` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Analyze task complexity with `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- Clarify tasks by checking task files in tasks/ directory or asking for user input
- View specific task details using `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags
- Clear existing subtasks if needed using `clear_subtasks` / `task-master clear-subtasks --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before regenerating
- Implement code following task details, dependencies, and project standards
- Verify tasks according to test strategies before marking as complete (See [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Add new subtasks as needed using `add_subtask` / `task-master add-subtask --parent=<id> --title="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Append notes or details to subtasks using `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='Add implementation notes here...\nMore details...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Generate task files with `generate` / `task-master generate` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) after updating tasks.json
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
- Respect dependency chains and task priorities when selecting work
- Report progress regularly using `get_tasks` / `task-master list`
- **Data Structure**: Tasks are organized into separate contexts (tags) like "master", "feature-branch", or "v2.0".
- **Silent Migration**: Existing projects automatically migrate to use a "master" tag with zero disruption.
- **Context Isolation**: Tasks in different tags are completely separate. Changes in one tag do not affect any other tag.
- **Manual Control**: The user is always in control. There is no automatic switching. You facilitate switching by using `use-tag <name>`.
- **Full CLI & MCP Support**: All tag management commands are available through both the CLI and MCP tools for you to use. Refer to [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for a full command list.
---
## Task Complexity Analysis
- Run `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for comprehensive analysis
- Run `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for comprehensive analysis
- Review complexity report via `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for a formatted, readable version.
- Focus on tasks with highest complexity scores (8-10) for detailed breakdown
- Use analysis results to determine appropriate subtask allocation
- Note that reports are automatically used by the `expand` tool/command
- Note that reports are automatically used by the `expand_task` tool/command
## Task Breakdown Process
- For tasks with complexity analysis, use `expand_task` / `task-master expand --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Otherwise use `expand_task` / `task-master expand --id=<id> --num=<number>`
- Add `--research` flag to leverage Perplexity AI for research-backed expansion
- Use `--prompt="<context>"` to provide additional context when needed
- Review and adjust generated subtasks as necessary
- Use `--all` flag with `expand` or `expand_all` to expand multiple pending tasks at once
- If subtasks need regeneration, clear them first with `clear_subtasks` / `task-master clear-subtasks` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Use `expand_task` / `task-master expand --id=<id>`. It automatically uses the complexity report if found, otherwise generates default number of subtasks.
- Use `--num=<number>` to specify an explicit number of subtasks, overriding defaults or complexity report recommendations.
- Add `--research` flag to leverage Perplexity AI for research-backed expansion.
- Add `--force` flag to clear existing subtasks before generating new ones (default is to append).
- Use `--prompt="<context>"` to provide additional context when needed.
- Review and adjust generated subtasks as necessary.
- Use `expand_all` tool or `task-master expand --all` to expand multiple pending tasks at once, respecting flags like `--force` and `--research`.
- If subtasks need complete replacement (regardless of the `--force` flag on `expand`), clear them first with `clear_subtasks` / `task-master clear-subtasks --id=<id>`.
## Implementation Drift Handling
- When implementation differs significantly from planned approach
- When future tasks need modification due to current implementation choices
- When new dependencies or requirements emerge
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update multiple future tasks.
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update a single specific task.
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...' --research` to update multiple future tasks.
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...' --research` to update a single specific task.
## Task Status Management
@@ -97,28 +266,49 @@ Task Master offers two primary ways to interact:
- **details**: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
- **testStrategy**: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
- **subtasks**: List of smaller, more specific tasks (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
- Refer to [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc) for more details on the task data structure.
- Refer to task structure details (previously linked to `tasks.mdc`).
## Environment Variables Configuration
## Configuration Management (Updated)
- Task Master behavior is configured via environment variables:
- **ANTHROPIC_API_KEY** (Required): Your Anthropic API key for Claude.
- **MODEL**: Claude model to use (e.g., `claude-3-opus-20240229`).
- **MAX_TOKENS**: Maximum tokens for AI responses.
- **TEMPERATURE**: Temperature for AI model responses.
- **DEBUG**: Enable debug logging (`true`/`false`).
- **LOG_LEVEL**: Console output level (`debug`, `info`, `warn`, `error`).
- **DEFAULT_SUBTASKS**: Default number of subtasks for `expand`.
- **DEFAULT_PRIORITY**: Default priority for new tasks.
- **PROJECT_NAME**: Project name used in metadata.
- **PROJECT_VERSION**: Project version used in metadata.
- **PERPLEXITY_API_KEY**: API key for Perplexity AI (for `--research` flags).
- **PERPLEXITY_MODEL**: Perplexity model to use (e.g., `sonar-medium-online`).
- See [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for default values and examples.
Taskmaster configuration is managed through two main mechanisms:
1. **`.taskmaster/config.json` File (Primary):**
* Located in the project root directory.
* Stores most configuration settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default subtasks/priority, project name, etc.
* **Tagged System Settings**: Includes `global.defaultTag` (defaults to "master") and `tags` section for tag management configuration.
* **Managed via `task-master models --setup` command.** Do not edit manually unless you know what you are doing.
* **View/Set specific models via `task-master models` command or `models` MCP tool.**
* Created automatically when you run `task-master models --setup` for the first time or during tagged system migration.
2. **Environment Variables (`.env` / `mcp.json`):**
* Used **only** for sensitive API keys and specific endpoint URLs.
* Place API keys (one per provider) in a `.env` file in the project root for CLI usage.
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
3. **`.taskmaster/state.json` File (Tagged System State):**
* Tracks current tag context and migration status.
* Automatically created during tagged system migration.
* Contains: `currentTag`, `lastSwitched`, `migrationNoticeShown`.
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.
## Rules Management
Taskmaster supports multiple AI coding assistant rule sets that can be configured during project initialization or managed afterward:
- **Available Profiles**: Claude Code, Cline, Codex, Cursor, Roo Code, Trae, Windsurf (claude, cline, codex, cursor, roo, trae, windsurf)
- **During Initialization**: Use `task-master init --rules cursor,windsurf` to specify which rule sets to include
- **After Initialization**: Use `task-master rules add <profiles>` or `task-master rules remove <profiles>` to manage rule sets
- **Interactive Setup**: Use `task-master rules setup` to launch an interactive prompt for selecting rule profiles
- **Default Behavior**: If no `--rules` flag is specified during initialization, all available rule profiles are included
- **Rule Structure**: Each profile creates its own directory (e.g., `.cursor/rules`, `.roo/rules`) with appropriate configuration files
## Determining the Next Task
- Run `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to show the next task to work on
- Run `next_task` / `task-master next` to show the next task to work on.
- The command identifies tasks with all dependencies satisfied
- Tasks are prioritized by priority level, dependency count, and ID
- The command shows comprehensive task information including:
@@ -133,7 +323,7 @@ Task Master offers two primary ways to interact:
## Viewing Specific Task Details
- Run `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to view a specific task
- Run `get_task` / `task-master show <id>` to view a specific task.
- Use dot notation for subtasks: `task-master show 1.2` (shows subtask 2 of task 1)
- Displays comprehensive information similar to the next command, but for a specific task
- For parent tasks, shows all subtasks and their current status
@@ -143,13 +333,32 @@ Task Master offers two primary ways to interact:
## Managing Task Dependencies
- Use `add_dependency` / `task-master add-dependency --id=<id> --depends-on=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to add a dependency
- Use `remove_dependency` / `task-master remove-dependency --id=<id> --depends-on=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to remove a dependency
- Use `add_dependency` / `task-master add-dependency --id=<id> --depends-on=<id>` to add a dependency.
- Use `remove_dependency` / `task-master remove-dependency --id=<id> --depends-on=<id>` to remove a dependency.
- The system prevents circular dependencies and duplicate dependency entries
- Dependencies are checked for existence before being added or removed
- Task files are automatically regenerated after dependency changes
- Dependencies are visualized with status indicators in task listings and files
## Task Reorganization
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
- This command supports several use cases:
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
- The system includes validation to prevent data loss:
- Allows moving to non-existent IDs by creating placeholder tasks
- Prevents moving to existing task IDs that have content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- The system maintains proper parent-child relationships and dependency integrity
- Task files are automatically regenerated after the move operation
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
## Iterative Subtask Implementation
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
@@ -164,14 +373,14 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
* Gather *all* relevant details from this exploration phase.
3. **Log the Plan:**
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'`.
* Provide the *complete and detailed* findings from the exploration phase in the prompt. Include file paths, line numbers, proposed diffs, reasoning, and any potential challenges identified. Do not omit details. The goal is to create a rich, timestamped log within the subtask's `details`.
4. **Verify the Plan:**
* Run `get_task` / `task-master show <subtaskId>` again to confirm that the detailed implementation plan has been successfully appended to the subtask's details.
5. **Begin Implementation:**
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress`.
* Start coding based on the logged plan.
6. **Refine and Log Progress (Iteration 2+):**
@@ -189,7 +398,7 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
7. **Review & Update Rules (Post-Implementation):**
* Once the implementation for the subtask is functionally complete, review all code changes and the relevant chat history.
* Identify any new or modified code patterns, conventions, or best practices established during the implementation.
* Create new or update existing Cursor rules in the `.cursor/rules/` directory to capture these patterns, following the guidelines in [`cursor_rules.mdc`](mdc:.cursor/rules/cursor_rules.mdc) and [`self_improve.mdc`](mdc:.cursor/rules/self_improve.mdc).
* Create new or update existing rules following internal guidelines (previously linked to `cursor_rules.mdc` and `self_improve.mdc`).
8. **Mark Task Complete:**
* After verifying the implementation and updating any necessary rules, mark the subtask as completed: `set_task_status` / `task-master set-status --id=<subtaskId> --status=done`.
@@ -198,10 +407,10 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
* Stage the relevant code changes and any updated/new rule files (`git add .`).
* Craft a comprehensive Git commit message summarizing the work done for the subtask, including both code implementation and any rule adjustments.
* Execute the commit command directly in the terminal (e.g., `git commit -m 'feat(module): Implement feature X for subtask <subtaskId>\n\n- Details about changes...\n- Updated rule Y for pattern Z'`).
* Consider if a Changeset is needed according to [`changeset.mdc`](mdc:.cursor/rules/changeset.mdc). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
* Consider if a Changeset is needed according to internal versioning guidelines (previously linked to `changeset.mdc`). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
10. **Proceed to Next Subtask:**
* Identify the next subtask in the dependency chain (e.g., using `next_task` / `task-master next`) and repeat this iterative process starting from step 1.
* Identify the next subtask (e.g., using `next_task` / `task-master next`).
## Code Analysis & Refactoring Techniques

View File

@@ -0,0 +1,404 @@
---
description: Git workflow integrated with Task Master for feature development and collaboration
globs: "**/*"
alwaysApply: true
---
# Git Workflow with Task Master Integration
## **Branch Strategy**
### **Main Branch Protection**
- **main** branch contains production-ready code
- All feature development happens on task-specific branches
- Direct commits to main are prohibited
- All changes merge via Pull Requests
### **Task Branch Naming**
```bash
# ✅ DO: Use consistent task branch naming
task-001 # For Task 1
task-004 # For Task 4
task-015 # For Task 15
# ❌ DON'T: Use inconsistent naming
feature/user-auth
fix-database-issue
random-branch-name
```
## **Tagged Task Lists Integration**
Task Master's **tagged task lists system** provides significant benefits for Git workflows:
### **Multi-Context Development**
- **Branch-Specific Tasks**: Each branch can have its own task context using tags
- **Merge Conflict Prevention**: Tasks in different tags are completely isolated
- **Context Switching**: Seamlessly switch between different development contexts
- **Parallel Development**: Multiple team members can work on separate task contexts
### **Migration and Compatibility**
- **Seamless Migration**: Existing projects automatically migrate to use a "master" tag
- **Zero Disruption**: All existing Git workflows continue unchanged
- **Backward Compatibility**: Legacy projects work exactly as before
### **Manual Git Integration**
- **Manual Tag Creation**: Use `--from-branch` option to create tags from current git branch
- **Manual Context Switching**: Explicitly switch tag contexts as needed for different branches
- **Simplified Integration**: Focused on manual control rather than automatic workflows
## **Workflow Overview**
```mermaid
flowchart TD
A[Start: On main branch] --> B[Pull latest changes]
B --> C[Create task branch<br/>git checkout -b task-XXX]
C --> D[Set task status: in-progress]
D --> E[Get task context & expand if needed<br/>Tasks automatically use current tag]
E --> F[Identify next subtask]
F --> G[Set subtask: in-progress]
G --> H[Research & collect context<br/>update_subtask with findings]
H --> I[Implement subtask]
I --> J[Update subtask with completion]
J --> K[Set subtask: done]
K --> L[Git commit subtask]
L --> M{More subtasks?}
M -->|Yes| F
M -->|No| N[Run final tests]
N --> O[Commit tests if added]
O --> P[Push task branch]
P --> Q[Create Pull Request]
Q --> R[Human review & merge]
R --> S[Switch to main & pull]
S --> T[Delete task branch]
T --> U[Ready for next task]
style A fill:#e1f5fe
style C fill:#f3e5f5
style G fill:#fff3e0
style L fill:#e8f5e8
style Q fill:#fce4ec
style R fill:#f1f8e9
style U fill:#e1f5fe
```
## **Complete Task Development Workflow**
### **Phase 1: Task Preparation**
```bash
# 1. Ensure you're on main branch and pull latest
git checkout main
git pull origin main
# 2. Check current branch status
git branch # Verify you're on main
# 3. Create task-specific branch
git checkout -b task-004 # For Task 4
# 4. Set task status in Task Master (tasks automatically use current tag context)
# Use: set_task_status tool or `task-master set-status --id=4 --status=in-progress`
```
### **Phase 2: Task Analysis & Planning**
```bash
# 5. Get task context and expand if needed (uses current tag automatically)
# Use: get_task tool or `task-master show 4`
# Use: expand_task tool or `task-master expand --id=4 --research --force` (if complex)
# 6. Identify next subtask to work on
# Use: next_task tool or `task-master next`
```
### **Phase 3: Subtask Implementation Loop**
For each subtask, follow this pattern:
```bash
# 7. Mark subtask as in-progress
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=in-progress`
# 8. Gather context and research (if needed)
# Use: update_subtask tool with research flag or:
# `task-master update-subtask --id=4.1 --prompt="Research findings..." --research`
# 9. Collect code context through AI exploration
# Document findings in subtask using update_subtask
# 10. Implement the subtask
# Write code, tests, documentation
# 11. Update subtask with completion details
# Use: update_subtask tool or:
# `task-master update-subtask --id=4.1 --prompt="Implementation complete..."`
# 12. Mark subtask as done
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=done`
# 13. Commit the subtask implementation
git add .
git commit -m "feat(task-4): Complete subtask 4.1 - [Subtask Title]
- Implementation details
- Key changes made
- Any important notes
Subtask 4.1: [Brief description of what was accomplished]
Relates to Task 4: [Main task title]"
```
### **Phase 4: Task Completion**
```bash
# 14. When all subtasks are complete, run final testing
# Create test file if needed, ensure all tests pass
npm test # or jest, or manual testing
# 15. If tests were added/modified, commit them
git add .
git commit -m "test(task-4): Add comprehensive tests for Task 4
- Unit tests for core functionality
- Integration tests for API endpoints
- All tests passing
Task 4: [Main task title] - Testing complete"
# 16. Push the task branch
git push origin task-004
# 17. Create Pull Request
# Title: "Task 4: [Task Title]"
# Description should include:
# - Task overview
# - Subtasks completed
# - Testing approach
# - Any breaking changes or considerations
```
### **Phase 5: PR Merge & Cleanup**
```bash
# 18. Human reviews and merges PR into main
# 19. Switch back to main and pull merged changes
git checkout main
git pull origin main
# 20. Delete the feature branch (optional cleanup)
git branch -d task-004
git push origin --delete task-004
```
## **Commit Message Standards**
### **Subtask Commits**
```bash
# ✅ DO: Consistent subtask commit format
git commit -m "feat(task-4): Complete subtask 4.1 - Initialize Express server
- Set up Express.js with TypeScript configuration
- Added CORS and body parsing middleware
- Implemented health check endpoints
- Basic error handling middleware
Subtask 4.1: Initialize project with npm and install dependencies
Relates to Task 4: Setup Express.js Server Project"
# ❌ DON'T: Vague or inconsistent commits
git commit -m "fixed stuff"
git commit -m "working on task"
```
### **Test Commits**
```bash
# ✅ DO: Separate test commits when substantial
git commit -m "test(task-4): Add comprehensive tests for Express server setup
- Unit tests for middleware configuration
- Integration tests for health check endpoints
- Mock tests for database connection
- All tests passing with 95% coverage
Task 4: Setup Express.js Server Project - Testing complete"
```
### **Commit Type Prefixes**
- `feat(task-X):` - New feature implementation
- `fix(task-X):` - Bug fixes
- `test(task-X):` - Test additions/modifications
- `docs(task-X):` - Documentation updates
- `refactor(task-X):` - Code refactoring
- `chore(task-X):` - Build/tooling changes
## **Task Master Commands Integration**
### **Essential Commands for Git Workflow**
```bash
# Task management (uses current tag context automatically)
task-master show <id> # Get task/subtask details
task-master next # Find next task to work on
task-master set-status --id=<id> --status=<status>
task-master update-subtask --id=<id> --prompt="..." --research
# Task expansion (for complex tasks)
task-master expand --id=<id> --research --force
# Progress tracking
task-master list # View all tasks and status
task-master list --status=in-progress # View active tasks
```
### **MCP Tool Equivalents**
When using Cursor or other MCP-integrated tools:
- `get_task` instead of `task-master show`
- `next_task` instead of `task-master next`
- `set_task_status` instead of `task-master set-status`
- `update_subtask` instead of `task-master update-subtask`
## **Branch Management Rules**
### **Branch Protection**
```bash
# ✅ DO: Always work on task branches
git checkout -b task-005
# Make changes
git commit -m "..."
git push origin task-005
# ❌ DON'T: Commit directly to main
git checkout main
git commit -m "..." # NEVER do this
```
### **Keeping Branches Updated**
```bash
# ✅ DO: Regularly sync with main (for long-running tasks)
git checkout task-005
git fetch origin
git rebase origin/main # or merge if preferred
# Resolve any conflicts and continue
```
## **Pull Request Guidelines**
### **PR Title Format**
```
Task <ID>: <Task Title>
Examples:
Task 4: Setup Express.js Server Project
Task 7: Implement User Authentication
Task 12: Add Stripe Payment Integration
```
### **PR Description Template**
```markdown
## Task Overview
Brief description of the main task objective.
## Subtasks Completed
- [x] 4.1: Initialize project with npm and install dependencies
- [x] 4.2: Configure TypeScript, ESLint and Prettier
- [x] 4.3: Create basic Express app with middleware and health check route
## Implementation Details
- Key architectural decisions made
- Important code changes
- Any deviations from original plan
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests passing
- [ ] Manual testing completed
## Breaking Changes
List any breaking changes or migration requirements.
## Related Tasks
Mention any dependent tasks or follow-up work needed.
```
## **Conflict Resolution**
### **Task Conflicts with Tagged System**
```bash
# With tagged task lists, merge conflicts are significantly reduced:
# 1. Different branches can use different tag contexts
# 2. Tasks in separate tags are completely isolated
# 3. Use Task Master's move functionality to reorganize if needed
# Manual git integration available:
# - Use `task-master add-tag --from-branch` to create tags from current branch
# - Manually switch contexts with `task-master use-tag <name>`
# - Simple, predictable workflow without automatic behavior
```
### **Code Conflicts**
```bash
# Standard Git conflict resolution
git fetch origin
git rebase origin/main
# Resolve conflicts in files
git add .
git rebase --continue
```
## **Emergency Procedures**
### **Hotfixes**
```bash
# For urgent production fixes:
git checkout main
git pull origin main
git checkout -b hotfix-urgent-issue
# Make minimal fix
git commit -m "hotfix: Fix critical production issue
- Specific fix description
- Minimal impact change
- Requires immediate deployment"
git push origin hotfix-urgent-issue
# Create emergency PR for immediate review
```
### **Task Abandonment**
```bash
# If task needs to be abandoned or significantly changed:
# 1. Update task status
task-master set-status --id=<id> --status=cancelled
# 2. Clean up branch
git checkout main
git branch -D task-<id>
git push origin --delete task-<id>
# 3. Document reasoning in task
task-master update-task --id=<id> --prompt="Task cancelled due to..."
```
## **Tagged System Benefits for Git Workflows**
### **Multi-Team Development**
- **Isolated Contexts**: Different teams can work on separate tag contexts without conflicts
- **Feature Branches**: Each feature branch can have its own task context
- **Release Management**: Separate tags for different release versions or environments
### **Merge Conflict Prevention**
- **Context Separation**: Tasks in different tags don't interfere with each other
- **Clean Merges**: Reduced likelihood of task-related merge conflicts
- **Parallel Development**: Multiple developers can work simultaneously without task conflicts
### **Manual Git Integration**
- **Branch-Based Tag Creation**: Use `--from-branch` option to create tags from current git branch
- **Manual Context Management**: Explicitly switch tag contexts as needed
- **Predictable Workflow**: Simple, manual control without automatic behavior
---
**References:**
- [Task Master Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Architecture Guidelines](mdc:.cursor/rules/architecture.mdc)
- [Task Master Commands](mdc:.cursor/rules/taskmaster.mdc)

View File

@@ -3,24 +3,24 @@ description: Glossary of other Cursor rules
globs: **/*
alwaysApply: true
---
# Glossary of Task Master Cursor Rules
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
- **[`architecture.mdc`](mdc:.cursor/rules/architecture.mdc)**: Describes the high-level architecture of the Task Master CLI application.
- **[`architecture.mdc`](mdc:.cursor/rules/architecture.mdc)**: Describes the high-level architecture of the Task Master CLI application, including the new tagged task lists system.
- **[`changeset.mdc`](mdc:.cursor/rules/changeset.mdc)**: Guidelines for using Changesets (npm run changeset) to manage versioning and changelogs.
- **[`commands.mdc`](mdc:.cursor/rules/commands.mdc)**: Guidelines for implementing CLI commands using Commander.js.
- **[`cursor_rules.mdc`](mdc:.cursor/rules/cursor_rules.mdc)**: Guidelines for creating and maintaining Cursor rules to ensure consistency and effectiveness.
- **[`dependencies.mdc`](mdc:.cursor/rules/dependencies.mdc)**: Guidelines for managing task dependencies and relationships.
- **[`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)**: Guide for using Task Master to manage task-driven development workflows.
- **[`dependencies.mdc`](mdc:.cursor/rules/dependencies.mdc)**: Guidelines for managing task dependencies and relationships across tagged task contexts.
- **[`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)**: Guide for using Task Master to manage task-driven development workflows with tagged task lists support.
- **[`glossary.mdc`](mdc:.cursor/rules/glossary.mdc)**: This file; provides a glossary of other Cursor rules.
- **[`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)**: Guidelines for implementing and interacting with the Task Master MCP Server.
- **[`new_features.mdc`](mdc:.cursor/rules/new_features.mdc)**: Guidelines for integrating new features into the Task Master CLI.
- **[`new_features.mdc`](mdc:.cursor/rules/new_features.mdc)**: Guidelines for integrating new features into the Task Master CLI with tagged system considerations.
- **[`self_improve.mdc`](mdc:.cursor/rules/self_improve.mdc)**: Guidelines for continuously improving Cursor rules based on emerging code patterns and best practices.
- **[`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)**: Comprehensive reference for Taskmaster MCP tools and CLI commands.
- **[`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)**: Guidelines for implementing task management operations.
- **[`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)**: Comprehensive reference for Taskmaster MCP tools and CLI commands with tagged task lists information.
- **[`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)**: Guidelines for implementing task management operations with tagged task lists system support.
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
- **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions including tagged task lists utilities.
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.

View File

@@ -3,7 +3,6 @@ description: Guidelines for implementing and interacting with the Task Master MC
globs: mcp-server/src/**/*, scripts/modules/**/*
alwaysApply: false
---
# Task Master MCP Server Guidelines
This document outlines the architecture and implementation patterns for the Task Master Model Context Protocol (MCP) server, designed for integration with tools like Cursor.
@@ -90,69 +89,54 @@ When implementing a new direct function in `mcp-server/src/core/direct-functions
```
5. **Handling Logging Context (`mcpLog`)**:
- **Requirement**: Core functions that use the internal `report` helper function (common in `task-manager.js`, `dependency-manager.js`, etc.) expect the `options` object to potentially contain an `mcpLog` property. This `mcpLog` object **must** have callable methods for each log level (e.g., `mcpLog.info(...)`, `mcpLog.error(...)`).
- **Challenge**: The `log` object provided by FastMCP to the direct function's context, while functional, might not perfectly match this expected structure or could change in the future. Passing it directly can lead to runtime errors like `mcpLog[level] is not a function`.
- **Solution: The Logger Wrapper Pattern**: To reliably bridge the FastMCP `log` object and the core function's `mcpLog` expectation, use a simple wrapper object within the direct function:
- **Requirement**: Core functions (like those in `task-manager.js`) may accept an `options` object containing an optional `mcpLog` property. If provided, the core function expects this object to have methods like `mcpLog.info(...)`, `mcpLog.error(...)`.
- **Solution: The Logger Wrapper Pattern**: When calling a core function from a direct function, pass the `log` object provided by FastMCP *wrapped* in the standard `logWrapper` object. This ensures the core function receives a logger with the expected method structure.
```javascript
// Standard logWrapper pattern within a Direct Function
const logWrapper = {
info: (message, ...args) => log.info(message, ...args),
warn: (message, ...args) => log.warn(message, ...args),
error: (message, ...args) => log.error(message, ...args),
debug: (message, ...args) => log.debug && log.debug(message, ...args), // Handle optional debug
success: (message, ...args) => log.info(message, ...args) // Map success to info if needed
debug: (message, ...args) => log.debug && log.debug(message, ...args),
success: (message, ...args) => log.info(message, ...args)
};
// ... later when calling the core function ...
await coreFunction(
// ... other arguments ...
tasksPath,
taskId,
{
mcpLog: logWrapper, // Pass the wrapper object
session
session // Also pass session if needed by core logic or AI service
},
'json' // Pass 'json' output format if supported by core function
);
```
- **Critical For JSON Output Format**: Passing the `logWrapper` as `mcpLog` serves a dual purpose:
1. **Prevents Runtime Errors**: It ensures the `mcpLog[level](...)` calls within the core function succeed
2. **Controls Output Format**: In functions like `updateTaskById` and `updateSubtaskById`, the presence of `mcpLog` in the options triggers setting `outputFormat = 'json'` (instead of 'text'). This prevents UI elements (spinners, boxes) from being generated, which would break the JSON response.
- **Proven Solution**: This pattern has successfully fixed multiple issues in our MCP tools (including `update-task` and `update-subtask`), where direct passing of the `log` object or omitting `mcpLog` led to either runtime errors or JSON parsing failures from UI output.
- **When To Use**: Implement this wrapper in any direct function that calls a core function with an `options` object that might use `mcpLog` for logging or output format control.
- **Why it Works**: The `logWrapper` explicitly defines the `.info()`, `.warn()`, `.error()`, etc., methods that the core function's `report` helper needs, ensuring the `mcpLog[level](...)` call succeeds. It simply forwards the logging calls to the actual FastMCP `log` object.
- **Combined with Silent Mode**: Remember that using the `logWrapper` for `mcpLog` is **necessary *in addition* to using `enableSilentMode()` / `disableSilentMode()`** (see next point). The wrapper handles structured logging *within* the core function, while silent mode suppresses direct `console.log` and UI elements (spinners, boxes) that would break the MCP JSON response.
- **JSON Output**: Passing `mcpLog` (via the wrapper) often triggers the core function to use a JSON-friendly output format, suppressing spinners/boxes.
- ✅ **DO**: Implement this pattern in direct functions calling core functions that might use `mcpLog`.
6. **Silent Mode Implementation**:
- ✅ **DO**: Import silent mode utilities at the top: `import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';`
- ✅ **DO**: Ensure core Task Master functions called from direct functions do **not** pollute `stdout` with console output (banners, spinners, logs) that would break MCP's JSON communication.
- **Preferred**: Modify the core function to accept an `outputFormat: 'json'` parameter and check it internally before printing UI elements. Pass `'json'` from the direct function.
- **Required Fallback/Guarantee**: If the core function cannot be modified or its output suppression is unreliable, **wrap the core function call** within the direct function using `enableSilentMode()` / `disableSilentMode()` in a `try/finally` block. This guarantees no console output interferes with the MCP response.
- ✅ **DO**: Use `isSilentMode()` function to check global silent mode status if needed (rare in direct functions), NEVER access the global `silentMode` variable directly.
- ❌ **DON'T**: Wrap AI client initialization or AI API calls in `enable/disableSilentMode`; their logging is controlled via the `log` object (passed potentially within the `logWrapper` for core functions).
- ❌ **DON'T**: Assume a core function is silent just because it *should* be. Verify or use the `enable/disableSilentMode` wrapper.
- **Example (Direct Function Guaranteeing Silence and using Log Wrapper)**:
- ✅ **DO**: Import silent mode utilities: `import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';`
- ✅ **DO**: Wrap core function calls *within direct functions* using `enableSilentMode()` / `disableSilentMode()` in a `try/finally` block if the core function might produce console output (spinners, boxes, direct `console.log`) that isn't reliably controlled by passing `{ mcpLog }` or an `outputFormat` parameter.
- ✅ **DO**: Always disable silent mode in the `finally` block.
- ❌ **DON'T**: Wrap calls to the unified AI service (`generateTextService`, `generateObjectService`) in silent mode; their logging is handled internally.
- **Example (Direct Function Guaranteeing Silence & using Log Wrapper)**:
```javascript
export async function coreWrapperDirect(args, log, context = {}) {
const { session } = context;
const tasksPath = findTasksJsonPath(args, log);
// Create the logger wrapper
const logWrapper = { /* ... as defined above ... */ };
const logWrapper = { /* ... */ };
enableSilentMode(); // Ensure silence for direct console output
try {
// Call core function, passing wrapper and 'json' format
const result = await coreFunction(
tasksPath,
args.param1,
{ mcpLog: logWrapper, session },
'json' // Explicitly request JSON format if supported
);
tasksPath,
args.param1,
{ mcpLog: logWrapper, session }, // Pass context
'json' // Request JSON format if supported
);
return { success: true, data: result };
} catch (error) {
log.error(`Error: ${error.message}`);
// Return standardized error object
return { success: false, error: { /* ... */ } };
} finally {
disableSilentMode(); // Critical: Always disable in finally
@@ -163,32 +147,6 @@ When implementing a new direct function in `mcp-server/src/core/direct-functions
7. **Debugging MCP/Core Logic Interaction**:
- ✅ **DO**: If an MCP tool fails with unclear errors (like JSON parsing failures), run the equivalent `task-master` CLI command in the terminal. The CLI often provides more detailed error messages originating from the core logic (e.g., `ReferenceError`, stack traces) that are obscured by the MCP layer.
### Specific Guidelines for AI-Based Direct Functions
Direct functions that interact with AI (e.g., `addTaskDirect`, `expandTaskDirect`) have additional responsibilities:
- **Context Parameter**: These functions receive an additional `context` object as their third parameter. **Critically, this object should only contain `{ session }`**. Do NOT expect or use `reportProgress` from this context.
```javascript
export async function yourAIDirect(args, log, context = {}) {
const { session } = context; // Only expect session
// ...
}
```
- **AI Client Initialization**:
- ✅ **DO**: Use the utilities from [`mcp-server/src/core/utils/ai-client-utils.js`](mdc:mcp-server/src/core/utils/ai-client-utils.js) (e.g., `getAnthropicClientForMCP(session, log)`) to get AI client instances. These correctly use the `session` object to resolve API keys.
- ✅ **DO**: Wrap client initialization in a try/catch block and return a specific `AI_CLIENT_ERROR` on failure.
- **AI Interaction**:
- ✅ **DO**: Build prompts using helper functions where appropriate (e.g., from `ai-prompt-helpers.js`).
- ✅ **DO**: Make the AI API call using appropriate helpers (e.g., `_handleAnthropicStream`). Pass the `log` object to these helpers for internal logging. **Do NOT pass `reportProgress`**.
- ✅ **DO**: Parse the AI response using helpers (e.g., `parseTaskJsonResponse`) and handle parsing errors with a specific code (e.g., `RESPONSE_PARSING_ERROR`).
- **Calling Core Logic**:
- ✅ **DO**: After successful AI interaction, call the relevant core Task Master function (from `scripts/modules/`) if needed (e.g., `addTaskDirect` calls `addTask`).
- ✅ **DO**: Pass necessary data, including potentially the parsed AI results, to the core function.
- ✅ **DO**: If the core function can produce console output, call it with an `outputFormat: 'json'` argument (or similar, depending on the function) to suppress CLI output. Ensure the core function is updated to respect this. Use `enableSilentMode/disableSilentMode` around the core function call as a fallback if `outputFormat` is not supported or insufficient.
- **Progress Indication**:
- ❌ **DON'T**: Call `reportProgress` within the direct function.
- ✅ **DO**: If intermediate progress status is needed *within* the long-running direct function, use standard logging: `log.info('Progress: Processing AI response...')`.
## Tool Definition and Execution
### Tool Structure
@@ -221,151 +179,78 @@ server.addTool({
The `execute` function receives validated arguments and the FastMCP context:
```javascript
// Standard signature
execute: async (args, context) => {
// Tool implementation
}
// Destructured signature (recommended)
execute: async (args, { log, reportProgress, session }) => {
execute: async (args, { log, session }) => {
// Tool implementation
}
```
- **args**: The first parameter contains all the validated parameters defined in the tool's schema.
- **context**: The second parameter is an object containing `{ log, reportProgress, session }` provided by FastMCP.
- ✅ **DO**: Use `{ log, session }` when calling direct functions.
- ⚠️ **WARNING**: Avoid passing `reportProgress` down to direct functions due to client compatibility issues. See Progress Reporting Convention below.
- **args**: Validated parameters.
- **context**: Contains `{ log, session }` from FastMCP. (Removed `reportProgress`).
### Standard Tool Execution Pattern
### Standard Tool Execution Pattern with Path Normalization (Updated)
The `execute` method within each MCP tool (in `mcp-server/src/tools/*.js`) should follow this standard pattern:
To ensure consistent handling of project paths across different client environments (Windows, macOS, Linux, WSL) and input formats (e.g., `file:///...`, URI encoded paths), all MCP tool `execute` methods that require access to the project root **MUST** be wrapped with the `withNormalizedProjectRoot` Higher-Order Function (HOF).
1. **Log Entry**: Log the start of the tool execution with relevant arguments.
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`. Crucially, the third argument (context) passed to the direct function should **only include `{ log, session }`**. **Do NOT pass `reportProgress`**.
```javascript
// Example call to a non-AI direct function
const result = await someDirectFunction({ ...args, projectRoot }, log);
// Example call to an AI-based direct function
const resultAI = await someAIDirect({ ...args, projectRoot }, log, { session });
```
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
6. **Return**: Return the formatted response object provided by `handleApiResult`.
This HOF, defined in [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js), performs the following before calling the tool's core logic:
1. **Determines the Raw Root:** It prioritizes `args.projectRoot` if provided by the client, otherwise it calls `getRawProjectRootFromSession` to extract the path from the session.
2. **Normalizes the Path:** It uses the `normalizeProjectRoot` helper to decode URIs, strip `file://` prefixes, fix potential Windows drive letter prefixes (e.g., `/C:/`), convert backslashes (`\`) to forward slashes (`/`), and resolve the path to an absolute path suitable for the server's OS.
3. **Injects Normalized Path:** It updates the `args` object by replacing the original `projectRoot` (or adding it) with the normalized, absolute path.
4. **Executes Original Logic:** It calls the original `execute` function body, passing the updated `args` object.
**Implementation Example:**
```javascript
// Example execute method structure for a tool calling an AI-based direct function
import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
import { someAIDirectFunction } from '../core/task-master-core.js';
// In mcp-server/src/tools/your-tool.js
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot // <<< Import HOF
} from './utils.js';
import { yourDirectFunction } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; // If needed
// ... inside server.addTool({...})
execute: async (args, { log, session }) => { // Note: reportProgress is omitted here
try {
log.info(`Starting AI tool execution with args: ${JSON.stringify(args)}`);
export function registerYourTool(server) {
server.addTool({
name: "your_tool",
description: "...".
parameters: z.object({
// ... other parameters ...
projectRoot: z.string().optional().describe('...') // projectRoot is optional here, HOF handles fallback
}),
// Wrap the entire execute function
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
// args.projectRoot is now guaranteed to be normalized and absolute
const { /* other args */, projectRoot } = args;
// 1. Get Project Root
let rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder && args.projectRoot) { // Fallback if needed
rootFolder = args.projectRoot;
log.info(`Using project root from args as fallback: ${rootFolder}`);
}
try {
log.info(`Executing your_tool with normalized root: ${projectRoot}`);
// 2. Call AI-Based Direct Function (passing only log and session in context)
const result = await someAIDirectFunction({
...args,
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
}, log, { session }); // Pass session here, NO reportProgress
// Resolve paths using the normalized projectRoot
let tasksPath = findTasksJsonPath({ projectRoot, file: args.file }, log);
// 3. Handle and Format Response
return handleApiResult(result, log);
// Call direct function, passing normalized projectRoot if needed by direct func
const result = await yourDirectFunction(
{
/* other args */,
projectRoot // Pass it if direct function needs it
},
log,
{ session }
);
} catch (error) {
log.error(`Error during AI tool execution: ${error.message}`);
return createErrorResponse(error.message);
}
return handleApiResult(result, log);
} catch (error) {
log.error(`Error in your_tool: ${error.message}`);
return createErrorResponse(error.message);
}
}) // End HOF wrap
});
}
```
### Using AsyncOperationManager for Background Tasks
For tools that execute potentially long-running operations *where the AI call is just one part* (e.g., `expand-task`, `update`), use the AsyncOperationManager. The `add-task` command, as refactored, does *not* require this in the MCP tool layer because the direct function handles the primary AI work and returns the final result synchronously from the perspective of the MCP tool.
For tools that *do* use `AsyncOperationManager`:
```javascript
import { AsyncOperationManager } from '../utils/async-operation-manager.js'; // Correct path assuming utils location
import { getProjectRootFromSession, createContentResponse, createErrorResponse } from './utils.js';
import { someIntensiveDirect } from '../core/task-master-core.js';
// ... inside server.addTool({...})
execute: async (args, { log, session }) => { // Note: reportProgress omitted
try {
log.info(`Starting background operation with args: ${JSON.stringify(args)}`);
// 1. Get Project Root
let rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder && args.projectRoot) {
rootFolder = args.projectRoot;
log.info(`Using project root from args as fallback: ${rootFolder}`);
}
// Create operation description
const operationDescription = `Expanding task ${args.id}...`; // Example
// 2. Start async operation using AsyncOperationManager
const operation = AsyncOperationManager.createOperation(
operationDescription,
async (reportProgressCallback) => { // This callback is provided by AsyncOperationManager
// This runs in the background
try {
// Report initial progress *from the manager's callback*
reportProgressCallback({ progress: 0, status: 'Starting operation...' });
// Call the direct function (passing only session context)
const result = await someIntensiveDirect(
{ ...args, projectRoot: rootFolder },
log,
{ session } // Pass session, NO reportProgress
);
// Report final progress *from the manager's callback*
reportProgressCallback({
progress: 100,
status: result.success ? 'Operation completed' : 'Operation failed',
result: result.data, // Include final data if successful
error: result.error // Include error object if failed
});
return result; // Return the direct function's result
} catch (error) {
// Handle errors within the async task
reportProgressCallback({
progress: 100,
status: 'Operation failed critically',
error: { message: error.message, code: error.code || 'ASYNC_OPERATION_FAILED' }
});
throw error; // Re-throw for the manager to catch
}
}
);
// 3. Return immediate response with operation ID
return {
status: 202, // StatusCodes.ACCEPTED
body: {
success: true,
message: 'Operation started',
operationId: operation.id
}
};
} catch (error) {
log.error(`Error starting background operation: ${error.message}`);
return createErrorResponse(`Failed to start operation: ${error.message}`); // Use standard error response
}
}
```
By using this HOF, the core logic within the `execute` method and any downstream functions (like `findTasksJsonPath` or direct functions) can reliably expect `args.projectRoot` to be a clean, absolute path suitable for the server environment.
### Project Initialization Tool
@@ -417,19 +302,13 @@ log.error(`Error occurred: ${error.message}`, { stack: error.stack });
log.info('Progress: 50% - AI call initiated...'); // Example progress logging
```
### Progress Reporting Convention
- ⚠️ **DEPRECATED within Direct Functions**: The `reportProgress` function passed in the `context` object should **NOT** be called from within `*Direct` functions. Doing so can cause client-side validation errors due to missing/incorrect `progressToken` handling.
- ✅ **DO**: For tools using `AsyncOperationManager`, use the `reportProgressCallback` function *provided by the manager* within the background task definition (as shown in the `AsyncOperationManager` example above) to report progress updates for the *overall operation*.
- ✅ **DO**: If finer-grained progress needs to be indicated *during* the execution of a `*Direct` function (whether called directly or via `AsyncOperationManager`), use `log.info()` statements (e.g., `log.info('Progress: Parsing AI response...')`).
### Session Usage Convention
## Session Usage Convention
The `session` object (destructured from `context`) contains authenticated session data and client information.
- **Authentication**: Access user-specific data (`session.userId`, etc.) if authentication is implemented.
- **Project Root**: The primary use in Task Master is accessing `session.roots` to determine the client's project root directory via the `getProjectRootFromSession` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)). See the Standard Tool Execution Pattern above.
- **Environment Variables**: The `session.env` object is critical for AI tools. Pass the `session` object to the `*Direct` function's context, and then to AI client utility functions (like `getAnthropicClientForMCP`) which will extract API keys and other relevant environment settings (e.g., `MODEL`, `MAX_TOKENS`) from `session.env`.
- **Environment Variables**: The `session.env` object provides access to environment variables set in the MCP client configuration (e.g., `.cursor/mcp.json`). This is the **primary mechanism** for the unified AI service layer (`ai-services-unified.js`) to securely access **API keys** when called from MCP context.
- **Capabilities**: Can be used to check client capabilities (`session.clientCapabilities`).
## Direct Function Wrappers (`*Direct`)
@@ -438,24 +317,25 @@ These functions, located in `mcp-server/src/core/direct-functions/`, form the co
- **Purpose**: Bridge MCP tools and core Task Master modules (`scripts/modules/*`). Handle AI interactions if applicable.
- **Responsibilities**:
- Receive `args` (including the `projectRoot` determined by the tool), `log` object, and optionally a `context` object (containing **only `{ session }` if needed).
- **Find `tasks.json`**: Use `findTasksJsonPath(args, log)` from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js).
- Validate arguments specific to the core logic.
- **Handle AI Logic (if applicable)**: Initialize AI clients (using `session` from context), build prompts, make AI calls, parse responses.
- **Implement Caching (if applicable)**: Use `getCachedOrExecute` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) for read operations.
- **Call Core Logic**: Call the underlying function from the core Task Master modules, passing necessary data (including AI results if applicable).
- ✅ **DO**: Pass `outputFormat: 'json'` (or similar) to the core function if it might produce console output.
- ✅ **DO**: Wrap the core function call with `enableSilentMode/disableSilentMode` if necessary.
- Handle errors gracefully (AI errors, core logic errors, file errors).
- Return a standardized result object: `{ success: boolean, data?: any, error?: { code: string, message: string }, fromCache?: boolean }`.
- ❌ **DON'T**: Call `reportProgress`. Use `log.info` for progress indication if needed.
- Receive `args` (including `projectRoot`), `log`, and optionally `{ session }` context.
- Find `tasks.json` using `findTasksJsonPath`.
- Validate arguments.
- **Implement Caching (if applicable)**: Use `getCachedOrExecute`.
- **Call Core Logic**: Invoke function from `scripts/modules/*`.
- Pass `outputFormat: 'json'` if applicable.
- Wrap with `enableSilentMode/disableSilentMode` if needed.
- Pass `{ mcpLog: logWrapper, session }` context if core logic needs it.
- Handle errors.
- Return standardized result object.
- ❌ **DON'T**: Call `reportProgress`.
- ❌ **DON'T**: Initialize AI clients or call AI services directly.
## Key Principles
- **Prefer Direct Function Calls**: MCP tools should always call `*Direct` wrappers instead of `executeTaskMasterCommand`.
- **Standardized Execution Flow**: Follow the pattern: MCP Tool -> `getProjectRootFromSession` -> `*Direct` Function -> Core Logic / AI Logic.
- **Path Resolution via Direct Functions**: The `*Direct` function is responsible for finding the exact `tasks.json` path using `findTasksJsonPath`, relying on the `projectRoot` passed in `args`.
- **AI Logic in Direct Functions**: For AI-based tools, the `*Direct` function handles AI client initialization, calls, and parsing, using the `session` object passed in its context.
- **AI Logic in Core Modules**: AI interactions (prompt building, calling unified service) reside within the core logic functions (`scripts/modules/*`), not direct functions.
- **Silent Mode in Direct Functions**: Wrap *core function* calls (from `scripts/modules`) with `enableSilentMode()` and `disableSilentMode()` if they produce console output not handled by `outputFormat`. Do not wrap AI calls.
- **Selective Async Processing**: Use `AsyncOperationManager` in the *MCP Tool layer* for operations involving multiple steps or long waits beyond a single AI call (e.g., file processing + AI call + file writing). Simple AI calls handled entirely within the `*Direct` function (like `addTaskDirect`) may not need it at the tool layer.
- **No `reportProgress` in Direct Functions**: Do not pass or use `reportProgress` within `*Direct` functions. Use `log.info()` for internal progress or report progress from the `AsyncOperationManager` callback in the MCP tool layer.
@@ -480,7 +360,7 @@ Follow these steps to add MCP support for an existing Task Master command (see [
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`. Ensure the core function can suppress console output (e.g., via an `outputFormat` parameter).
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
- Import necessary core functions, `findTasksJsonPath`, silent mode utilities, and potentially AI client/prompt utilities.
- Implement `async function yourCommandDirect(args, log, context = {})` using **camelCase** with `Direct` suffix. **Remember `context` should only contain `{ session }` if needed (for AI keys/config).**
@@ -642,3 +522,8 @@ Follow these steps to add MCP support for an existing Task Master command (see [
// Add more functions as implemented
};
```
## Telemetry Integration
- Direct functions calling core logic that involves AI should receive and pass through `telemetryData` within their successful `data` payload. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the standard pattern.
- MCP tools use `handleApiResult`, which ensures the `data` object (potentially including `telemetryData`) from the direct function is correctly included in the final response.

View File

@@ -3,7 +3,6 @@ description: Guidelines for integrating new features into the Task Master CLI
globs: scripts/modules/*.js
alwaysApply: false
---
# Task Master Feature Integration Guidelines
## Feature Placement Decision Process
@@ -25,11 +24,22 @@ alwaysApply: false
The standard pattern for adding a feature follows this workflow:
1. **Core Logic**: Implement the business logic in the appropriate module (e.g., [`task-manager.js`](mdc:scripts/modules/task-manager.js)).
2. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc).
3. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
4. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
5. **Configuration**: Update any configuration in [`utils.js`](mdc:scripts/modules/utils.js) if needed, following [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc).
6. **Documentation**: Update help text and documentation in [dev_workflow.mdc](mdc:scripts/modules/dev_workflow.mdc)
2. **Context Gathering (If Applicable)**:
- For AI-powered commands that benefit from project context, use the standardized context gathering patterns from [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc).
- Import `ContextGatherer` and `FuzzyTaskSearch` utilities for reusable context extraction.
- Support multiple context types: tasks, files, custom text, project tree.
- Implement detailed token breakdown display for transparency.
3. **AI Integration (If Applicable)**:
- Import necessary service functions (e.g., `generateTextService`, `streamTextService`) from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`).
- Call the service function.
- Handle the response (direct text or stream object).
- **Important**: Prefer `generateTextService` for calls sending large context (like stringified JSON) where incremental display is not needed. See [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc) for detailed usage patterns and cautions.
4. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc). Consider enhanced formatting with syntax highlighting for code blocks.
5. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
6. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
7. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
8. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
## Critical Checklist for New Features
@@ -190,6 +200,8 @@ The standard pattern for adding a feature follows this workflow:
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
- **Telemetry Integration**: Ensure AI calls correctly handle and propagate `telemetryData` as described in [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc).
```javascript
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
/**
@@ -211,7 +223,29 @@ export {
```
```javascript
// 2. UI COMPONENTS: Add display function to ui.js
// 2. AI Integration: Add import and use necessary service functions
import { generateTextService } from './ai-services-unified.js';
// Example usage:
async function handleAIInteraction() {
const role = 'user';
const session = 'exampleSession';
const systemPrompt = 'You are a helpful assistant.';
const prompt = 'What is the capital of France?';
const result = await generateTextService(role, session, systemPrompt, prompt);
console.log(result);
}
// Export from the module
export {
// ... existing exports ...
handleAIInteraction,
};
```
```javascript
// 3. UI COMPONENTS: Add display function to ui.js
/**
* Display archive operation results
* @param {string} archivePath - Path to the archive file
@@ -232,7 +266,7 @@ export {
```
```javascript
// 3. COMMAND INTEGRATION: Add to commands.js
// 4. COMMAND INTEGRATION: Add to commands.js
import { archiveTasks } from './task-manager.js';
import { displayArchiveResults } from './ui.js';
@@ -452,7 +486,7 @@ npm test
For each new feature:
1. Add help text to the command definition
2. Update [`dev_workflow.mdc`](mdc:scripts/modules/dev_workflow.mdc) with command reference
2. Update [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) with command reference
3. Consider updating [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) if the feature significantly changes module responsibilities.
Follow the existing command reference format:
@@ -495,14 +529,24 @@ Integrating Task Master commands with the MCP server (for use by tools like Curs
4. **Create MCP Tool (`mcp-server/src/tools/`)**:
- Create a new file (e.g., `your-command.js`) using **kebab-case**.
- Import `zod`, `handleApiResult`, `createErrorResponse`, **`getProjectRootFromSession`**, and your `yourCommandDirect` function.
- Import `zod`, `handleApiResult`, **`withNormalizedProjectRoot` HOF**, and your `yourCommandDirect` function.
- Implement `registerYourCommandTool(server)`.
- Define the tool `name` using **snake_case** (e.g., `your_command`).
- Define the `parameters` using `zod`. **Crucially, define `projectRoot` as optional**: `projectRoot: z.string().optional().describe(...)`. Include `file` if applicable.
- Implement the standard `async execute(args, { log, reportProgress, session })` method:
- Get `rootFolder` using `getProjectRootFromSession` (with fallback to `args.projectRoot`).
- Call `yourCommandDirect({ ...args, projectRoot: rootFolder }, log)`.
- Pass the result to `handleApiResult(result, log, 'Error Message')`.
- **Define parameters**: Make `projectRoot` optional (`z.string().optional().describe(...)`) as the HOF handles fallback.
- Consider if this operation should run in the background using `AsyncOperationManager`.
- Implement the standard `execute` method **wrapped with `withNormalizedProjectRoot`**:
```javascript
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
// args.projectRoot is now normalized
const { projectRoot /*, other args */ } = args;
// ... resolve tasks path if needed using normalized projectRoot ...
const result = await yourCommandDirect(
{ /* other args */, projectRoot /* if needed by direct func */ },
log,
{ session }
);
return handleApiResult(result, log);
})
```
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.
@@ -590,3 +634,287 @@ When implementing project initialization commands:
});
}
```
## Feature Planning
- **Core Logic First**:
- ✅ DO: Implement core logic in `scripts/modules/` before CLI or MCP interfaces
- ✅ DO: Consider tagged task lists system compatibility from the start
- ✅ DO: Design functions to work with both legacy and tagged data formats
- ✅ DO: Use tag resolution functions (`getTasksForTag`, `setTasksForTag`) for task data access
- ❌ DON'T: Directly manipulate tagged data structure in new features
```javascript
// ✅ DO: Design tagged-aware core functions
async function newFeatureCore(tasksPath, featureParams, options = {}) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Perform feature logic on tasks array
const result = performFeatureLogic(tasks, featureParams);
// Save back using tag resolution
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
return result;
}
```
- **Backward Compatibility**:
- ✅ DO: Ensure new features work with existing projects seamlessly
- ✅ DO: Test with both legacy and tagged task data formats
- ✅ DO: Support silent migration during feature usage
- ❌ DON'T: Break existing workflows when adding tagged system features
## CLI Command Implementation
- **Command Structure**:
- ✅ DO: Follow the established pattern in [`commands.js`](mdc:scripts/modules/commands.js)
- ✅ DO: Use Commander.js for argument parsing
- ✅ DO: Include comprehensive help text and examples
- ✅ DO: Support tagged task context awareness
```javascript
// ✅ DO: Implement CLI commands with tagged system awareness
program
.command('new-feature')
.description('Description of the new feature with tagged task lists support')
.option('-t, --tag <tag>', 'Specify tag context (defaults to current tag)')
.option('-p, --param <value>', 'Feature-specific parameter')
.option('--force', 'Force operation without confirmation')
.action(async (options) => {
try {
const projectRoot = findProjectRoot();
if (!projectRoot) {
console.error('Not in a Task Master project directory');
process.exit(1);
}
// Use specified tag or current tag
const targetTag = options.tag || getCurrentTag() || 'master';
const result = await newFeatureCore(
path.join(projectRoot, '.taskmaster', 'tasks', 'tasks.json'),
{ param: options.param },
{
force: options.force,
targetTag: targetTag,
outputFormat: 'text'
}
);
console.log('Feature executed successfully');
} catch (error) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
});
```
- **Error Handling**:
- ✅ DO: Provide clear error messages for common failures
- ✅ DO: Handle tagged system migration errors gracefully
- ✅ DO: Include suggestion for resolution when possible
- ✅ DO: Exit with appropriate codes for scripting
## MCP Tool Implementation
- **Direct Function Pattern**:
- ✅ DO: Create direct function wrappers in `mcp-server/src/core/direct-functions/`
- ✅ DO: Follow silent mode patterns to prevent console output interference
- ✅ DO: Use `findTasksJsonPath` for consistent path resolution
- ✅ DO: Ensure tagged system compatibility
```javascript
// ✅ DO: Implement MCP direct functions with tagged awareness
export async function newFeatureDirect(args, log, context = {}) {
try {
const tasksPath = findTasksJsonPath(args, log);
// Enable silent mode for clean MCP responses
enableSilentMode();
try {
const result = await newFeatureCore(
tasksPath,
{ param: args.param },
{
force: args.force,
targetTag: args.tag || 'master', // Support tag specification
mcpLog: log,
session: context.session,
outputFormat: 'json'
}
);
return {
success: true,
data: result,
fromCache: false
};
} finally {
disableSilentMode();
}
} catch (error) {
log.error(`Error in newFeatureDirect: ${error.message}`);
return {
success: false,
error: { code: 'FEATURE_ERROR', message: error.message },
fromCache: false
};
}
}
```
- **Tool Registration**:
- ✅ DO: Create tool definitions in `mcp-server/src/tools/`
- ✅ DO: Use Zod for parameter validation
- ✅ DO: Include optional tag parameter for multi-context support
- ✅ DO: Follow established naming conventions
```javascript
// ✅ DO: Register MCP tools with tagged system support
export function registerNewFeatureTool(server) {
server.addTool({
name: "new_feature",
description: "Description of the new feature with tagged task lists support",
inputSchema: z.object({
param: z.string().describe("Feature-specific parameter"),
tag: z.string().optional().describe("Target tag context (defaults to current tag)"),
force: z.boolean().optional().describe("Force operation without confirmation"),
projectRoot: z.string().optional().describe("Project root directory")
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const result = await newFeatureDirect(
{ ...args, projectRoot: args.projectRoot },
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
return handleApiResult({
success: false,
error: { code: 'EXECUTION_ERROR', message: error.message }
}, log);
}
})
});
}
```
## Testing Strategy
- **Unit Tests**:
- ✅ DO: Test core logic independently with both data formats
- ✅ DO: Mock file system operations appropriately
- ✅ DO: Test tag resolution behavior
- ✅ DO: Verify migration compatibility
```javascript
// ✅ DO: Test new features with tagged system awareness
describe('newFeature', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should work with legacy task format', async () => {
const legacyData = { tasks: [/* test data */] };
fs.readFileSync.mockReturnValue(JSON.stringify(legacyData));
const result = await newFeatureCore('/test/tasks.json', { param: 'test' });
expect(result).toBeDefined();
// Test legacy format handling
});
it('should work with tagged task format', async () => {
const taggedData = {
master: { tasks: [/* test data */] },
feature: { tasks: [/* test data */] }
};
fs.readFileSync.mockReturnValue(JSON.stringify(taggedData));
const result = await newFeatureCore('/test/tasks.json', { param: 'test' });
expect(result).toBeDefined();
// Test tagged format handling
});
it('should handle tag migration during feature usage', async () => {
const legacyData = { tasks: [/* test data */] };
fs.readFileSync.mockReturnValue(JSON.stringify(legacyData));
await newFeatureCore('/test/tasks.json', { param: 'test' });
// Verify migration occurred
expect(fs.writeFileSync).toHaveBeenCalledWith(
'/test/tasks.json',
expect.stringContaining('"master"')
);
});
});
```
- **Integration Tests**:
- ✅ DO: Test CLI and MCP interfaces with real task data
- ✅ DO: Verify end-to-end workflows across tag contexts
- ✅ DO: Test error scenarios and recovery
## Documentation Updates
- **Rule Updates**:
- ✅ DO: Update relevant `.cursor/rules/*.mdc` files
- ✅ DO: Include tagged system considerations in architecture docs
- ✅ DO: Add examples showing multi-context usage
- ✅ DO: Update workflow documentation as needed
- **User Documentation**:
- ✅ DO: Add feature documentation to `/docs` folder
- ✅ DO: Include tagged system usage examples
- ✅ DO: Update command reference documentation
- ✅ DO: Provide migration notes if relevant
## Migration Considerations
- **Silent Migration Support**:
- ✅ DO: Ensure new features trigger migration when needed
- ✅ DO: Handle migration errors gracefully in feature code
- ✅ DO: Test feature behavior with pre-migration projects
- ❌ DON'T: Assume projects are already migrated
- **Tag Context Handling**:
- ✅ DO: Default to current tag when not specified
- ✅ DO: Support explicit tag selection in advanced features
- ✅ DO: Validate tag existence before operations
- ✅ DO: Provide clear messaging about tag context
## Performance Considerations
- **Efficient Tag Operations**:
- ✅ DO: Minimize file I/O operations per feature execution
- ✅ DO: Cache tag resolution results when appropriate
- ✅ DO: Use streaming for large task datasets
- ❌ DON'T: Load all tags when only one is needed
- **Memory Management**:
- ✅ DO: Process large task lists efficiently
- ✅ DO: Clean up temporary data structures
- ✅ DO: Avoid keeping all tag data in memory simultaneously
## Deployment and Versioning
- **Changesets**:
- ✅ DO: Create appropriate changesets for new features
- ✅ DO: Use semantic versioning (minor for new features)
- ✅ DO: Include tagged system information in release notes
- ✅ DO: Document breaking changes if any
- **Feature Flags**:
- ✅ DO: Consider feature flags for experimental functionality
- ✅ DO: Ensure tagged system features work with flags
- ✅ DO: Provide clear documentation about flag usage
By following these guidelines, new features will integrate smoothly with the Task Master ecosystem while supporting the enhanced tagged task lists system for multi-context development workflows.

View File

@@ -69,5 +69,4 @@ alwaysApply: true
- Update references to external docs
- Maintain links between related rules
- Document breaking changes
Follow [cursor_rules.mdc](mdc:.cursor/rules/cursor_rules.mdc) for proper rule formatting and structure.
Follow [cursor_rules.mdc](mdc:.cursor/rules/cursor_rules.mdc) for proper rule formatting and structure.

229
.cursor/rules/tags.mdc Normal file
View File

@@ -0,0 +1,229 @@
---
description:
globs: scripts/modules/*
alwaysApply: false
---
# Tagged Task Lists Command Patterns
This document outlines the standardized patterns that **ALL** Task Master commands must follow to properly support the tagged task lists system.
## Core Principles
- **Every command** that reads or writes tasks.json must be tag-aware
- **Consistent tag resolution** across all commands using `getCurrentTag(projectRoot)`
- **Proper context passing** to core functions with `{ projectRoot, tag }`
- **Standardized CLI options** with `--tag <tag>` flag
## Required Imports
All command files must import `getCurrentTag`:
```javascript
// ✅ DO: Import getCurrentTag in commands.js
import {
log,
readJSON,
writeJSON,
findProjectRoot,
getCurrentTag
} from './utils.js';
// ✅ DO: Import getCurrentTag in task-manager files
import {
readJSON,
writeJSON,
getCurrentTag
} from '../utils.js';
```
## CLI Command Pattern
Every CLI command that operates on tasks must follow this exact pattern:
```javascript
// ✅ DO: Standard tag-aware CLI command pattern
programInstance
.command('command-name')
.description('Command description')
.option('-f, --file <file>', 'Path to the tasks file', TASKMASTER_TASKS_FILE)
.option('--tag <tag>', 'Specify tag context for task operations') // REQUIRED
.action(async (options) => {
// 1. Find project root
const projectRoot = findProjectRoot();
if (!projectRoot) {
console.error(chalk.red('Error: Could not find project root.'));
process.exit(1);
}
// 2. Resolve tag using standard pattern
const tag = options.tag || getCurrentTag(projectRoot) || 'master';
// 3. Call core function with proper context
await coreFunction(
tasksPath,
// ... other parameters ...
{ projectRoot, tag } // REQUIRED context object
);
});
```
## Core Function Pattern
All core functions in `scripts/modules/task-manager/` must follow this pattern:
```javascript
// ✅ DO: Standard tag-aware core function pattern
async function coreFunction(
tasksPath,
// ... other parameters ...
context = {} // REQUIRED context parameter
) {
const { projectRoot, tag } = context;
// Use tag-aware readJSON/writeJSON
const data = readJSON(tasksPath, projectRoot, tag);
// ... function logic ...
writeJSON(tasksPath, data, projectRoot, tag);
}
```
## Tag Resolution Priority
The tag resolution follows this exact priority order:
1. **Explicit `--tag` flag**: `options.tag`
2. **Current active tag**: `getCurrentTag(projectRoot)`
3. **Default fallback**: `'master'`
```javascript
// ✅ DO: Standard tag resolution pattern
const tag = options.tag || getCurrentTag(projectRoot) || 'master';
```
## Commands Requiring Updates
### High Priority (Core Task Operations)
- [x] `add-task` - ✅ Fixed
- [x] `list` - ✅ Fixed
- [x] `update-task` - ✅ Fixed
- [x] `update-subtask` - ✅ Fixed
- [x] `set-status` - ✅ Already correct
- [x] `remove-task` - ✅ Already correct
- [x] `remove-subtask` - ✅ Fixed
- [x] `add-subtask` - ✅ Already correct
- [x] `clear-subtasks` - ✅ Fixed
- [x] `move-task` - ✅ Already correct
### Medium Priority (Analysis & Expansion)
- [x] `expand` - ✅ Fixed
- [ ] `next` - ✅ Fixed
- [ ] `show` (get-task) - Needs checking
- [ ] `analyze-complexity` - Needs checking
- [ ] `generate` - ✅ Fixed
### Lower Priority (Utilities)
- [ ] `research` - Needs checking
- [ ] `complexity-report` - Needs checking
- [ ] `validate-dependencies` - ✅ Fixed
- [ ] `fix-dependencies` - ✅ Fixed
- [ ] `add-dependency` - ✅ Fixed
- [ ] `remove-dependency` - ✅ Fixed
## MCP Integration Pattern
MCP direct functions must also follow the tag-aware pattern:
```javascript
// ✅ DO: Tag-aware MCP direct function
export async function coreActionDirect(args, log, context = {}) {
const { session } = context;
const { projectRoot, tag } = args; // MCP passes these in args
try {
const result = await coreAction(
tasksPath,
// ... other parameters ...
{ projectRoot, tag, session, mcpLog: logWrapper }
);
return { success: true, data: result };
} catch (error) {
return { success: false, error: { code: 'ERROR_CODE', message: error.message } };
}
}
```
## File Generation Tag-Aware Naming
The `generate` command must use tag-aware file naming:
```javascript
// ✅ DO: Tag-aware file naming
const taskFileName = targetTag === 'master'
? `task_${task.id.toString().padStart(3, '0')}.txt`
: `task_${task.id.toString().padStart(3, '0')}_${targetTag}.txt`;
```
**Examples:**
- Master tag: `task_001.txt`, `task_002.txt`
- Other tags: `task_001_feature.txt`, `task_002_feature.txt`
## Common Anti-Patterns
```javascript
// ❌ DON'T: Missing getCurrentTag import
import { readJSON, writeJSON } from '../utils.js'; // Missing getCurrentTag
// ❌ DON'T: Hard-coded tag resolution
const tag = options.tag || 'master'; // Missing getCurrentTag
// ❌ DON'T: Missing --tag option
.option('-f, --file <file>', 'Path to tasks file') // Missing --tag option
// ❌ DON'T: Missing context parameter
await coreFunction(tasksPath, param1, param2); // Missing { projectRoot, tag }
// ❌ DON'T: Incorrect readJSON/writeJSON calls
const data = readJSON(tasksPath); // Missing projectRoot and tag
writeJSON(tasksPath, data); // Missing projectRoot and tag
```
## Validation Checklist
For each command, verify:
- [ ] Imports `getCurrentTag` from utils.js
- [ ] Has `--tag <tag>` CLI option
- [ ] Uses standard tag resolution: `options.tag || getCurrentTag(projectRoot) || 'master'`
- [ ] Finds `projectRoot` with error handling
- [ ] Passes `{ projectRoot, tag }` context to core functions
- [ ] Core functions accept and use context parameter
- [ ] Uses `readJSON(tasksPath, projectRoot, tag)` and `writeJSON(tasksPath, data, projectRoot, tag)`
## Testing Tag Resolution
Test each command with:
```bash
# Test with explicit tag
node bin/task-master command-name --tag test-tag
# Test with active tag (should use current active tag)
node bin/task-master use-tag test-tag
node bin/task-master command-name
# Test with master tag (default)
node bin/task-master use-tag master
node bin/task-master command-name
```
## Migration Strategy
1. **Audit Phase**: Systematically check each command against the checklist
2. **Fix Phase**: Apply the standard patterns to non-compliant commands
3. **Test Phase**: Verify tag resolution works correctly
4. **Document Phase**: Update command documentation with tag support
This ensures consistent, predictable behavior across all Task Master commands and prevents tag deletion bugs.

View File

@@ -3,14 +3,15 @@ description: Comprehensive reference for Taskmaster MCP tools and CLI commands.
globs: **/*
alwaysApply: true
---
# Taskmaster Tool & Command Reference
This document provides a detailed reference for interacting with Taskmaster, covering both the recommended MCP tools (for integrations like Cursor) and the corresponding `task-master` CLI commands (for direct user interaction or fallback).
This document provides a detailed reference for interacting with Taskmaster, covering both the recommended MCP tools, suitable for integrations like Cursor, and the corresponding `task-master` CLI commands, designed for direct user interaction or fallback.
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for MCP implementation details and [`commands.mdc`](mdc:.cursor/rules/commands.mdc) for CLI implementation guidelines.
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback.
**Important:** Several MCP tools involve AI processing and are long-running operations that may take up to a minute to complete. When using these tools, always inform users that the operation is in progress and to wait patiently for results. The AI-powered tools include: `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
**Important:** Several MCP tools involve AI processing... The AI-powered tools include `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
**🏷️ Tagged Task Lists System:** Task Master now supports **tagged task lists** for multi-context task management. This allows you to maintain separate, isolated lists of tasks for different features, branches, or experiments. Existing projects are seamlessly migrated to use a default "master" tag. Most commands now support a `--tag <name>` flag to specify which context to operate on. If omitted, commands use the currently active tag.
---
@@ -24,34 +25,68 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key CLI Options:**
* `--name <name>`: `Set the name for your project in Taskmaster's configuration.`
* `--description <text>`: `Provide a brief description for your project.`
* `--version <version>`: `Set the initial version for your project (e.g., '0.1.0').`
* `--version <version>`: `Set the initial version for your project, e.g., '0.1.0'.`
* `--no-git`: `Skip initializing a Git repository entirely.`
* `-y, --yes`: `Initialize Taskmaster quickly using default settings without interactive prompts.`
* **Usage:** Run this once at the beginning of a new project.
* **MCP Variant Description:** `Set up the basic Taskmaster file structure and configuration in the current directory for a new project by running the 'task-master init' command.`
* **Key MCP Parameters/Options:**
* `projectName`: `Set the name for your project.` (CLI: `--name <name>`)
* `projectDescription`: `Provide a brief description for your project.` (CLI: `--description <text>`)
* `projectVersion`: `Set the initial version for your project (e.g., '0.1.0').` (CLI: `--version <version>`)
* `projectVersion`: `Set the initial version for your project, e.g., '0.1.0'.` (CLI: `--version <version>`)
* `authorName`: `Author name.` (CLI: `--author <author>`)
* `skipInstall`: `Skip installing dependencies (default: false).` (CLI: `--skip-install`)
* `addAliases`: `Add shell aliases (tm, taskmaster) (default: false).` (CLI: `--aliases`)
* `yes`: `Skip prompts and use defaults/provided arguments (default: false).` (CLI: `-y, --yes`)
* `skipInstall`: `Skip installing dependencies. Default is false.` (CLI: `--skip-install`)
* `addAliases`: `Add shell aliases tm and taskmaster. Default is false.` (CLI: `--aliases`)
* `noGit`: `Skip initializing a Git repository entirely. Default is false.` (CLI: `--no-git`)
* `yes`: `Skip prompts and use defaults/provided arguments. Default is false.` (CLI: `-y, --yes`)
* **Usage:** Run this once at the beginning of a new project, typically via an integrated tool like Cursor. Operates on the current working directory of the MCP server.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in scripts/example_prd.txt.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in .taskmaster/templates/example_prd.txt.
* **Tagging:** Use the `--tag` option to parse the PRD into a specific, non-default tag context. If the tag doesn't exist, it will be created automatically. Example: `task-master parse-prd spec.txt --tag=new-feature`.
### 2. Parse PRD (`parse_prd`)
* **MCP Tool:** `parse_prd`
* **CLI Command:** `task-master parse-prd [file] [options]`
* **Description:** `Parse a Product Requirements Document (PRD) or text file with Taskmaster to automatically generate an initial set of tasks in tasks.json.`
* **Description:** `Parse a Product Requirements Document, PRD, or text file with Taskmaster to automatically generate an initial set of tasks in tasks.json.`
* **Key Parameters/Options:**
* `input`: `Path to your PRD or requirements text file that Taskmaster should parse for tasks.` (CLI: `[file]` positional or `-i, --input <file>`)
* `output`: `Specify where Taskmaster should save the generated 'tasks.json' file (default: 'tasks/tasks.json').` (CLI: `-o, --output <file>`)
* `output`: `Specify where Taskmaster should save the generated 'tasks.json' file. Defaults to '.taskmaster/tasks/tasks.json'.` (CLI: `-o, --output <file>`)
* `numTasks`: `Approximate number of top-level tasks Taskmaster should aim to generate from the document.` (CLI: `-n, --num-tasks <number>`)
* `force`: `Use this to allow Taskmaster to overwrite an existing 'tasks.json' without asking for confirmation.` (CLI: `-f, --force`)
* **Usage:** Useful for bootstrapping a project from an existing requirements document.
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD (libraries, database schemas, frameworks, tech stacks, etc.) while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress. If the user does not have a PRD, suggest discussing their idea and then use the example PRD in scripts/example_prd.txt as a template for creating the PRD based on their idea, for use with parse-prd.
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD, such as libraries, database schemas, frameworks, tech stacks, etc., while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress. If the user does not have a PRD, suggest discussing their idea and then use the example PRD in `.taskmaster/templates/example_prd.txt` as a template for creating the PRD based on their idea, for use with `parse-prd`.
---
## AI Model Configuration
### 2. Manage Models (`models`)
* **MCP Tool:** `models`
* **CLI Command:** `task-master models [options]`
* **Description:** `View the current AI model configuration or set specific models for different roles (main, research, fallback). Allows setting custom model IDs for Ollama and OpenRouter.`
* **Key MCP Parameters/Options:**
* `setMain <model_id>`: `Set the primary model ID for task generation/updates.` (CLI: `--set-main <model_id>`)
* `setResearch <model_id>`: `Set the model ID for research-backed operations.` (CLI: `--set-research <model_id>`)
* `setFallback <model_id>`: `Set the model ID to use if the primary fails.` (CLI: `--set-fallback <model_id>`)
* `ollama <boolean>`: `Indicates the set model ID is a custom Ollama model.` (CLI: `--ollama`)
* `openrouter <boolean>`: `Indicates the set model ID is a custom OpenRouter model.` (CLI: `--openrouter`)
* `listAvailableModels <boolean>`: `If true, lists available models not currently assigned to a role.` (CLI: No direct equivalent; CLI lists available automatically)
* `projectRoot <string>`: `Optional. Absolute path to the project root directory.` (CLI: Determined automatically)
* **Key CLI Options:**
* `--set-main <model_id>`: `Set the primary model.`
* `--set-research <model_id>`: `Set the research model.`
* `--set-fallback <model_id>`: `Set the fallback model.`
* `--ollama`: `Specify that the provided model ID is for Ollama (use with --set-*).`
* `--openrouter`: `Specify that the provided model ID is for OpenRouter (use with --set-*). Validates against OpenRouter API.`
* `--bedrock`: `Specify that the provided model ID is for AWS Bedrock (use with --set-*).`
* `--setup`: `Run interactive setup to configure models, including custom Ollama/OpenRouter IDs.`
* **Usage (MCP):** Call without set flags to get current config. Use `setMain`, `setResearch`, or `setFallback` with a valid model ID to update the configuration. Use `listAvailableModels: true` to get a list of unassigned models. To set a custom model, provide the model ID and set `ollama: true` or `openrouter: true`.
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
* **Notes:** Configuration is stored in `.taskmaster/config.json` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live.
* **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them.
* **Model costs:** The costs in supported models are expressed in dollars. An input/output value of 3 is $3.00. A value of 0.8 is $0.80.
* **Warning:** DO NOT MANUALLY EDIT THE .taskmaster/config.json FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback.
---
@@ -63,9 +98,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master list [options]`
* **Description:** `List your Taskmaster tasks, optionally filtering by status and showing subtasks.`
* **Key Parameters/Options:**
* `status`: `Show only Taskmaster tasks matching this status (e.g., 'pending', 'done').` (CLI: `-s, --status <status>`)
* `status`: `Show only Taskmaster tasks matching this status (or multiple statuses, comma-separated), e.g., 'pending' or 'done,in-progress'.` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks indented under their parent tasks in the list.` (CLI: `--with-subtasks`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to list tasks from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Get an overview of the project status, often used at the start of a work session.
### 4. Get Next Task (`next_task`)
@@ -74,18 +110,21 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master next [options]`
* **Description:** `Ask Taskmaster to show the next available task you can work on, based on status and completed dependencies.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to use. Defaults to the current active tag.` (CLI: `--tag <name>`)
* **Usage:** Identify what to work on next according to the plan.
### 5. Get Task Details (`get_task`)
* **MCP Tool:** `get_task`
* **CLI Command:** `task-master show [id] [options]`
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.`
* **Description:** `Display detailed information for one or more specific Taskmaster tasks or subtasks by ID.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task (e.g., '15') or subtask (e.g., '15.2') you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Understand the full details, implementation notes, and test strategy for a specific task before starting work.
* `id`: `Required. The ID of the Taskmaster task (e.g., '15'), subtask (e.g., '15.2'), or a comma-separated list of IDs ('1,5,10.2') you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
* `tag`: `Specify which tag context to get the task(s) from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Understand the full details for a specific task. When multiple IDs are provided, a summary table is shown.
* **CRITICAL INFORMATION** If you need to collect information from multiple tasks, use comma-separated IDs (i.e. 1,2,3) to receive an array of tasks. Do not needlessly get tasks one at a time if you need to get many as that is wasteful.
---
@@ -97,10 +136,12 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master add-task [options]`
* **Description:** `Add a new task to Taskmaster by describing it; AI will structure it.`
* **Key Parameters/Options:**
* `prompt`: `Required. Describe the new task you want Taskmaster to create (e.g., "Implement user authentication using JWT").` (CLI: `-p, --prompt <text>`)
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start (e.g., '12,14').` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task ('high', 'medium', 'low'; default: 'medium').` (CLI: `--priority <priority>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `prompt`: `Required. Describe the new task you want Taskmaster to create, e.g., "Implement user authentication using JWT".` (CLI: `-p, --prompt <text>`)
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start, e.g., '12,14'.` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task: 'high', 'medium', or 'low'. Default is 'medium'.` (CLI: `--priority <priority>`)
* `research`: `Enable Taskmaster to use the research role for potentially more informed task creation.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to add the task to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Quickly add newly identified tasks during development.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -112,13 +153,14 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id` / `parent`: `Required. The ID of the Taskmaster task that will be the parent.` (MCP: `id`, CLI: `-p, --parent <id>`)
* `taskId`: `Use this if you want to convert an existing top-level Taskmaster task into a subtask of the specified parent.` (CLI: `-i, --task-id <id>`)
* `title`: `Required (if not using taskId). The title for the new subtask Taskmaster should create.` (CLI: `-t, --title <title>`)
* `title`: `Required if not using taskId. The title for the new subtask Taskmaster should create.` (CLI: `-t, --title <title>`)
* `description`: `A brief description for the new subtask.` (CLI: `-d, --description <text>`)
* `details`: `Provide implementation notes or details for the new subtask.` (CLI: `--details <text>`)
* `dependencies`: `Specify IDs of other tasks or subtasks (e.g., '15', '16.1') that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask (default: 'pending').` (CLI: `-s, --status <status>`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after adding the subtask.` (CLI: `--skip-generate`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `dependencies`: `Specify IDs of other tasks or subtasks, e.g., '15' or '16.1', that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask. Default is 'pending'.` (CLI: `-s, --status <status>`)
* `generate`: `Enable Taskmaster to regenerate markdown task files after adding the subtask.` (CLI: `--generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Break down tasks manually or reorganize existing tasks.
### 8. Update Tasks (`update`)
@@ -127,10 +169,11 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master update [options]`
* **Description:** `Update multiple upcoming tasks in Taskmaster based on new context or changes, starting from a specific task ID.`
* **Key Parameters/Options:**
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher (and not 'done') will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks (e.g., "We are now using React Query instead of Redux Toolkit for data fetching").` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates based on external knowledge (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher that are not 'done' will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks, e.g., "We are now using React Query instead of Redux Toolkit for data fetching".` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks. Example CLI: `task-master update --from='18' --prompt='Switching to React Query.\nNeed to refactor data fetching...'`
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -138,13 +181,15 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `update_task`
* **CLI Command:** `task-master update-task [options]`
* **Description:** `Modify a specific Taskmaster task (or subtask) by its ID, incorporating new information or changes.`
* **Description:** `Modify a specific Taskmaster task by ID, incorporating new information or changes. By default, this replaces the existing task details.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster task (e.g., '15') or subtask (e.g., '15.2') you want to update.` (CLI: `-i, --id <id>`)
* `id`: `Required. The specific ID of the Taskmaster task, e.g., '15', you want to update.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Refine a specific task based on new understanding or feedback. Example CLI: `task-master update-task --id='15' --prompt='Clarification: Use PostgreSQL instead of MySQL.\nUpdate schema details...'`
* `append`: `If true, appends the prompt content to the task's details with a timestamp, rather than replacing them. Behaves like update-subtask.` (CLI: `--append`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Refine a specific task based on new understanding. Use `--append` to log progress without creating subtasks.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 10. Update Subtask (`update_subtask`)
@@ -153,22 +198,24 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master update-subtask [options]`
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content. Intended for iterative implementation logging.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster subtask (e.g., '15.2') you want to add information to.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Provide the information or notes Taskmaster should append to the subtask's details. Ensure this adds *new* information not already present.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Add implementation notes, code snippets, or clarifications to a subtask during development. Before calling, review the subtask's current details to append only fresh insights, helping to build a detailed log of the implementation journey and avoid redundancy. Example CLI: `task-master update-subtask --id='15.2' --prompt='Discovered that the API requires header X.\nImplementation needs adjustment...'`
* `id`: `Required. The ID of the Taskmaster subtask, e.g., '5.2', to update with new information.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. The information, findings, or progress notes to append to the subtask's details with a timestamp.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the subtask belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Log implementation progress, findings, and discoveries during subtask development. Each update is timestamped and appended to preserve the implementation journey.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 11. Set Task Status (`set_task_status`)
* **MCP Tool:** `set_task_status`
* **CLI Command:** `task-master set-status [options]`
* **Description:** `Update the status of one or more Taskmaster tasks or subtasks (e.g., 'pending', 'in-progress', 'done').`
* **Description:** `Update the status of one or more Taskmaster tasks or subtasks, e.g., 'pending', 'in-progress', 'done'.`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s) (e.g., '15', '15.2', '16,17.1') to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set (e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled').` (CLI: `-s, --status <status>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s), e.g., '15', '15.2', or '16,17.1', to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set, e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled'.` (CLI: `-s, --status <status>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Mark progress as tasks move through the development cycle.
### 12. Remove Task (`remove_task`)
@@ -177,9 +224,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master remove-task [options]`
* **Description:** `Permanently remove a task or subtask from the Taskmaster tasks list.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task (e.g., '5') or subtask (e.g., '5.2') to permanently remove.` (CLI: `-i, --id <id>`)
* `id`: `Required. The ID of the Taskmaster task, e.g., '5', or subtask, e.g., '5.2', to permanently remove.` (CLI: `-i, --id <id>`)
* `yes`: `Skip the confirmation prompt and immediately delete the task.` (CLI: `-y, --yes`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Permanently delete tasks or subtasks that are no longer needed in the project.
* **Notes:** Use with caution as this operation cannot be undone. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you just want to exclude a task from active planning but keep it for reference. The command automatically cleans up dependency references in other tasks.
@@ -191,28 +239,30 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `expand_task`
* **CLI Command:** `task-master expand [options]`
* **Description:** `Use Taskmaster's AI to break down a complex task (or all tasks) into smaller, manageable subtasks.`
* **Description:** `Use Taskmaster's AI to break down a complex task into smaller, manageable subtasks. Appends subtasks by default.`
* **Key Parameters/Options:**
* `id`: `The ID of the specific Taskmaster task you want to break down into subtasks.` (CLI: `-i, --id <id>`)
* `num`: `Suggests how many subtasks Taskmaster should aim to create (uses complexity analysis by default).` (CLI: `-n, --num <number>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed subtask generation (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `prompt`: `Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Use this to make Taskmaster replace existing subtasks with newly generated ones.` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding.
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create. Uses complexity analysis/defaults otherwise.` (CLI: `-n, --num <number>`)
* `research`: `Enable Taskmaster to use the research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding. Automatically uses complexity report recommendations if available and `num` is not specified.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 14. Expand All Tasks (`expand_all`)
* **MCP Tool:** `expand_all`
* **CLI Command:** `task-master expand --all [options]` (Note: CLI uses the `expand` command with the `--all` flag)
* **Description:** `Tell Taskmaster to automatically expand all 'pending' tasks based on complexity analysis.`
* **Description:** `Tell Taskmaster to automatically expand all eligible pending/in-progress tasks based on complexity analysis or defaults. Appends subtasks by default.`
* **Key Parameters/Options:**
* `num`: `Suggests how many subtasks Taskmaster should aim to create per task.` (CLI: `-n, --num <number>`)
* `research`: `Enable Perplexity AI for more informed subtask generation (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `prompt`: `Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Make Taskmaster replace existing subtasks.` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create per task.` (CLI: `-n, --num <number>`)
* `research`: `Enable research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones for each eligible task. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context to expand. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -222,9 +272,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master clear-subtasks [options]`
* **Description:** `Remove all subtasks from one or more specified Taskmaster parent tasks.`
* **Key Parameters/Options:**
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove (e.g., '15', '16,18').` (Required unless using `all`) (CLI: `-i, --id <ids>`)
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove, e.g., '15' or '16,18'. Required unless using 'all'.` (CLI: `-i, --id <ids>`)
* `all`: `Tell Taskmaster to remove subtasks from all parent tasks.` (CLI: `--all`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before regenerating subtasks with `expand_task` if the previous breakdown needs replacement.
### 16. Remove Subtask (`remove_subtask`)
@@ -233,28 +284,56 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master remove-subtask [options]`
* **Description:** `Remove a subtask from its Taskmaster parent, optionally converting it into a standalone task.`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove (e.g., '15.2', '16.1,16.3').` (CLI: `-i, --id <id>`)
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove, e.g., '15.2' or '16.1,16.3'.` (CLI: `-i, --id <id>`)
* `convert`: `If used, Taskmaster will turn the subtask into a regular top-level task instead of deleting it.` (CLI: `-c, --convert`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after removing the subtask.` (CLI: `--skip-generate`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `generate`: `Enable Taskmaster to regenerate markdown task files after removing the subtask.` (CLI: `--generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
### 17. Move Task (`move_task`)
* **MCP Tool:** `move_task`
* **CLI Command:** `task-master move [options]`
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
* **Key Parameters/Options:**
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
* Moving a task to become a subtask
* Moving a subtask to become a standalone task
* Moving a subtask to a different parent
* Reordering subtasks within the same parent
* Moving a task to a new, non-existent ID (automatically creates placeholders)
* Moving multiple tasks at once with comma-separated IDs
* **Validation Features:**
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
* Validates that source tasks exist before attempting to move them
* Maintains proper parent-child relationships
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
---
## Dependency Management
### 17. Add Dependency (`add_dependency`)
### 18. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]`
* **Description:** `Define a dependency in Taskmaster, making one task a prerequisite for another.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task that will depend on another.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first (the prerequisite).` (CLI: `-d, --depends-on <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first, the prerequisite.` (CLI: `-d, --depends-on <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* **Usage:** Establish the correct order of execution between tasks.
### 18. Remove Dependency (`remove_dependency`)
### 19. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]`
@@ -262,92 +341,219 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task you want to remove a prerequisite from.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that should no longer be a prerequisite.` (CLI: `-d, --depends-on <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Update task relationships when the order of execution changes.
### 19. Validate Dependencies (`validate_dependencies`)
### 20. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]`
* **Description:** `Check your Taskmaster tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to validate. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Audit the integrity of your task dependencies.
### 20. Fix Dependencies (`fix_dependencies`)
### 21. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]`
* **Description:** `Automatically fix dependency issues (like circular references or links to non-existent tasks) in your Taskmaster tasks.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to fix dependencies in. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Clean up dependency errors automatically.
---
## Analysis & Reporting
### 21. Analyze Project Complexity (`analyze_project_complexity`)
### 22. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]`
* **Description:** `Have Taskmaster analyze your tasks to determine their complexity and suggest which ones need to be broken down further.`
* **Key Parameters/Options:**
* `output`: `Where to save the complexity analysis report (default: 'scripts/task-complexity-report.json').` (CLI: `-o, --output <file>`)
* `output`: `Where to save the complexity analysis report. Default is '.taskmaster/reports/task-complexity-report.json' (or '..._tagname.json' if a tag is used).` (CLI: `-o, --output <file>`)
* `threshold`: `The minimum complexity score (1-10) that should trigger a recommendation to expand a task.` (CLI: `-t, --threshold <number>`)
* `research`: `Enable Perplexity AI for more accurate complexity analysis (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* `research`: `Enable research role for more accurate complexity analysis. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to analyze. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 22. View Complexity Report (`complexity_report`)
### 23. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]`
* **Description:** `Display the task complexity analysis report in a readable format.`
* **Key Parameters/Options:**
* `file`: `Path to the complexity report (default: 'scripts/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to show the report for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to the complexity report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* **Usage:** Review and understand the complexity analysis results after running analyze-complexity.
---
## File Management
### 23. Generate Task Files (`generate`)
### 24. Generate Task Files (`generate`)
* **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]`
* **Description:** `Create or update individual Markdown files for each task based on your tasks.json.`
* **Key Parameters/Options:**
* `output`: `The directory where Taskmaster should save the task files (default: in a 'tasks' directory).` (CLI: `-o, --output <directory>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date.
* `tag`: `Specify which tag context to generate files for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date. This command is now manual and no longer runs automatically.
---
## Environment Variables Configuration
## AI-Powered Research
Taskmaster's behavior can be customized via environment variables. These affect both CLI and MCP server operation:
### 25. Research (`research`)
* **ANTHROPIC_API_KEY** (Required): Your Anthropic API key for Claude.
* **MODEL**: Claude model to use (default: `claude-3-opus-20240229`).
* **MAX_TOKENS**: Maximum tokens for AI responses (default: 8192).
* **TEMPERATURE**: Temperature for AI model responses (default: 0.7).
* **DEBUG**: Enable debug logging (`true`/`false`, default: `false`).
* **LOG_LEVEL**: Console output level (`debug`, `info`, `warn`, `error`, default: `info`).
* **DEFAULT_SUBTASKS**: Default number of subtasks for `expand` (default: 5).
* **DEFAULT_PRIORITY**: Default priority for new tasks (default: `medium`).
* **PROJECT_NAME**: Project name used in metadata.
* **PROJECT_VERSION**: Project version used in metadata.
* **PERPLEXITY_API_KEY**: API key for Perplexity AI (for `--research` flags).
* **PERPLEXITY_MODEL**: Perplexity model to use (default: `sonar-medium-online`).
Set these in your `.env` file in the project root or in your environment before running Taskmaster.
* **MCP Tool:** `research`
* **CLI Command:** `task-master research [options]`
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
* **Key Parameters/Options:**
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
* `taskIds`: `Comma-separated list of task/subtask IDs from the current tag context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
* `saveTo`: `Task or subtask ID (e.g., "15", "15.2") to automatically save the research conversation to.` (CLI: `--save-to <id>`)
* `saveFile`: `If true, saves the research conversation to a markdown file in '.taskmaster/docs/research/'.` (CLI: `--save-file`)
* `noFollowup`: `Disables the interactive follow-up question menu in the CLI.` (CLI: `--no-followup`)
* `tag`: `Specify which tag context to use for task-based context gathering. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
* Get fresh information beyond knowledge cutoff dates
* Research latest best practices, library updates, security patches
* Find implementation examples for specific technologies
* Validate approaches against current industry standards
* Get contextual advice based on project files and tasks
* **When to Consider Using Research:**
* **Before implementing any task** - Research current best practices
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
* **For security-related tasks** - Find latest security recommendations
* **When updating dependencies** - Research breaking changes and migration guides
* **For performance optimization** - Get current performance best practices
* **When debugging complex issues** - Research known solutions and workarounds
* **Research + Action Pattern:**
* Use `research` to gather fresh information
* Use `update_subtask` to commit findings with timestamps
* Use `update_task` to incorporate research into task details
* Use `add_task` with research flag for informed task creation
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
---
For implementation details:
* CLI commands: See [`commands.mdc`](mdc:.cursor/rules/commands.mdc)
* MCP server: See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)
* Task structure: See [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)
* Workflow: See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)
## Tag Management
This new suite of commands allows you to manage different task contexts (tags).
### 26. List Tags (`tags`)
* **MCP Tool:** `list_tags`
* **CLI Command:** `task-master tags [options]`
* **Description:** `List all available tags with task counts, completion status, and other metadata.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `--show-metadata`: `Include detailed metadata in the output (e.g., creation date, description).` (CLI: `--show-metadata`)
### 27. Add Tag (`add_tag`)
* **MCP Tool:** `add_tag`
* **CLI Command:** `task-master add-tag <tagName> [options]`
* **Description:** `Create a new, empty tag context, or copy tasks from another tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the new tag to create (alphanumeric, hyphens, underscores).` (CLI: `<tagName>` positional)
* `--from-branch`: `Creates a tag with a name derived from the current git branch, ignoring the <tagName> argument.` (CLI: `--from-branch`)
* `--copy-from-current`: `Copy tasks from the currently active tag to the new tag.` (CLI: `--copy-from-current`)
* `--copy-from <tag>`: `Copy tasks from a specific source tag to the new tag.` (CLI: `--copy-from <tag>`)
* `--description <text>`: `Provide an optional description for the new tag.` (CLI: `-d, --description <text>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 28. Delete Tag (`delete_tag`)
* **MCP Tool:** `delete_tag`
* **CLI Command:** `task-master delete-tag <tagName> [options]`
* **Description:** `Permanently delete a tag and all of its associated tasks.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to delete.` (CLI: `<tagName>` positional)
* `--yes`: `Skip the confirmation prompt.` (CLI: `-y, --yes`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 29. Use Tag (`use_tag`)
* **MCP Tool:** `use_tag`
* **CLI Command:** `task-master use-tag <tagName>`
* **Description:** `Switch your active task context to a different tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to switch to.` (CLI: `<tagName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 30. Rename Tag (`rename_tag`)
* **MCP Tool:** `rename_tag`
* **CLI Command:** `task-master rename-tag <oldName> <newName>`
* **Description:** `Rename an existing tag.`
* **Key Parameters/Options:**
* `oldName`: `The current name of the tag.` (CLI: `<oldName>` positional)
* `newName`: `The new name for the tag.` (CLI: `<newName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 31. Copy Tag (`copy_tag`)
* **MCP Tool:** `copy_tag`
* **CLI Command:** `task-master copy-tag <sourceName> <targetName> [options]`
* **Description:** `Copy an entire tag context, including all its tasks and metadata, to a new tag.`
* **Key Parameters/Options:**
* `sourceName`: `Name of the tag to copy from.` (CLI: `<sourceName>` positional)
* `targetName`: `Name of the new tag to create.` (CLI: `<targetName>` positional)
* `--description <text>`: `Optional description for the new tag.` (CLI: `-d, --description <text>`)
---
## Miscellaneous
### 32. Sync Readme (`sync-readme`) -- experimental
* **MCP Tool:** N/A
* **CLI Command:** `task-master sync-readme [options]`
* **Description:** `Exports your task list to your project's README.md file, useful for showcasing progress.`
* **Key Parameters/Options:**
* `status`: `Filter tasks by status (e.g., 'pending', 'done').` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks in the export.` (CLI: `--with-subtasks`)
* `tag`: `Specify which tag context to export from. Defaults to the current active tag.` (CLI: `--tag <name>`)
---
## Environment Variables Configuration (Updated)
Taskmaster primarily uses the **`.taskmaster/config.json`** file (in project root) for configuration (models, parameters, logging level, etc.), managed via `task-master models --setup`.
Environment variables are used **only** for sensitive API keys related to AI providers and specific overrides like the Ollama base URL:
* **API Keys (Required for corresponding provider):**
* `ANTHROPIC_API_KEY`
* `PERPLEXITY_API_KEY`
* `OPENAI_API_KEY`
* `GOOGLE_API_KEY`
* `MISTRAL_API_KEY`
* `AZURE_OPENAI_API_KEY` (Requires `AZURE_OPENAI_ENDPOINT` too)
* `OPENROUTER_API_KEY`
* `XAI_API_KEY`
* `OLLAMA_API_KEY` (Requires `OLLAMA_BASE_URL` too)
* **Endpoints (Optional/Provider Specific inside .taskmaster/config.json):**
* `AZURE_OPENAI_ENDPOINT`
* `OLLAMA_BASE_URL` (Default: `http://localhost:11434/api`)
**Set API keys** in your **`.env`** file in the project root (for CLI use) or within the `env` section of your **`.cursor/mcp.json`** file (for MCP/Cursor integration). All other settings (model choice, max tokens, temperature, log level, custom endpoints) are managed in `.taskmaster/config.json` via `task-master models` command or `models` MCP tool.
---
For details on how these commands fit into the development process, see the [Development Workflow Guide](mdc:.cursor/rules/dev_workflow.mdc).

View File

@@ -3,9 +3,19 @@ description: Guidelines for implementing task management operations
globs: scripts/modules/task-manager.js
alwaysApply: false
---
# Task Management Guidelines
## Tagged Task Lists System
Task Master now uses a **tagged task lists system** for multi-context task management:
- **Data Structure**: Tasks are organized into separate contexts (tags) within `tasks.json`
- **Legacy Format**: `{"tasks": [...]}`
- **Tagged Format**: `{"master": {"tasks": [...]}, "feature-branch": {"tasks": [...]}}`
- **Silent Migration**: Legacy format automatically converts to tagged format on first use
- **Tag Resolution**: Core functions receive legacy format for 100% backward compatibility
- **Default Tag**: "master" is used for all existing and new tasks unless otherwise specified
## Task Structure Standards
- **Core Task Properties**:
@@ -28,6 +38,25 @@ alwaysApply: false
};
```
- **Tagged Data Structure**:
- ✅ DO: Access tasks through tag resolution layer
- ✅ DO: Use `getTasksForTag(data, tagName)` to retrieve tasks for a specific tag
- ✅ DO: Use `setTasksForTag(data, tagName, tasks)` to update tasks for a specific tag
- ❌ DON'T: Directly manipulate the tagged structure in core functions
```javascript
// ✅ DO: Use tag resolution functions
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Manipulate tasks as normal...
// Save back to the tagged structure
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
```
- **Subtask Structure**:
- ✅ DO: Use consistent properties across subtasks
- ✅ DO: Maintain simple numeric IDs within parent tasks
@@ -48,53 +77,56 @@ alwaysApply: false
## Task Creation and Parsing
- **ID Management**:
- ✅ DO: Assign unique sequential IDs to tasks
- ✅ DO: Calculate the next ID based on existing tasks
- ❌ DON'T: Hardcode or reuse IDs
- ✅ DO: Assign unique sequential IDs to tasks within each tag context
- ✅ DO: Calculate the next ID based on existing tasks in the current tag
- ❌ DON'T: Hardcode or reuse IDs within the same tag
```javascript
// ✅ DO: Calculate the next available ID
const highestId = Math.max(...data.tasks.map(t => t.id));
// ✅ DO: Calculate the next available ID within the current tag
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
const highestId = Math.max(...tasks.map(t => t.id));
const nextTaskId = highestId + 1;
```
- **PRD Parsing**:
- ✅ DO: Extract tasks from PRD documents using AI
- ✅ DO: Create tasks in the current tag context (defaults to "master")
- ✅ DO: Provide clear prompts to guide AI task generation
- ✅ DO: Validate and clean up AI-generated tasks
```javascript
// ✅ DO: Validate AI responses
try {
// Parse the JSON response
taskData = JSON.parse(jsonContent);
// Check that we have the required fields
if (!taskData.title || !taskData.description) {
throw new Error("Missing required fields in the generated task");
}
} catch (error) {
log('error', "Failed to parse AI's response as valid task JSON:", error);
process.exit(1);
}
// ✅ DO: Parse into current tag context
const tasksData = readJSON(tasksPath) || {};
const currentTag = getCurrentTag() || 'master';
// Parse tasks and add to current tag
const newTasks = await parseTasksFromPRD(prdContent);
setTasksForTag(tasksData, currentTag, newTasks);
writeJSON(tasksPath, tasksData);
```
## Task Updates and Modifications
- **Status Management**:
- ✅ DO: Provide functions for updating task status
- ✅ DO: Provide functions for updating task status within current tag context
- ✅ DO: Handle both individual tasks and subtasks
- ✅ DO: Consider subtask status when updating parent tasks
```javascript
// ✅ DO: Handle status updates for both tasks and subtasks
// ✅ DO: Handle status updates within tagged context
async function setTaskStatus(tasksPath, taskIdInput, newStatus) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Check if it's a subtask (e.g., "1.2")
if (taskIdInput.includes('.')) {
const [parentId, subtaskId] = taskIdInput.split('.').map(id => parseInt(id, 10));
// Find the parent task and subtask
const parentTask = data.tasks.find(t => t.id === parentId);
const parentTask = tasks.find(t => t.id === parentId);
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
// Update subtask status
@@ -109,7 +141,7 @@ alwaysApply: false
}
} else {
// Handle regular task
const task = data.tasks.find(t => t.id === parseInt(taskIdInput, 10));
const task = tasks.find(t => t.id === parseInt(taskIdInput, 10));
task.status = newStatus;
// If marking as done, also mark subtasks
@@ -119,16 +151,24 @@ alwaysApply: false
});
}
}
// Save updated tasks back to tagged structure
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
}
```
- **Task Expansion**:
- ✅ DO: Use AI to generate detailed subtasks
- ✅ DO: Use AI to generate detailed subtasks within current tag context
- ✅ DO: Consider complexity analysis for subtask counts
- ✅ DO: Ensure proper IDs for newly created subtasks
```javascript
// ✅ DO: Generate appropriate subtasks based on complexity
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
if (taskAnalysis) {
log('info', `Found complexity analysis for task ${taskId}: Score ${taskAnalysis.complexityScore}/10`);
@@ -138,6 +178,11 @@ alwaysApply: false
log('info', `Using recommended number of subtasks: ${numSubtasks}`);
}
}
// Generate subtasks and save back
// ... subtask generation logic ...
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
```
## Task File Generation
@@ -155,67 +200,65 @@ alwaysApply: false
// Format dependencies with their status
if (task.dependencies && task.dependencies.length > 0) {
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, data.tasks)}\n`;
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, tasks)}\n`;
} else {
content += '# Dependencies: None\n';
}
```
- **Subtask Inclusion**:
- ✅ DO: Include subtasks in parent task files
- ✅ DO: Use consistent indentation for subtask sections
- DO: Display subtask dependencies with proper formatting
- **Tagged Context Awareness**:
- ✅ DO: Generate task files from current tag context
- ✅ DO: Include tag information in generated files
- DON'T: Mix tasks from different tags in file generation
```javascript
// ✅ DO: Format subtasks correctly in task files
if (task.subtasks && task.subtasks.length > 0) {
content += '\n# Subtasks:\n';
// ✅ DO: Generate files for current tag context
async function generateTaskFiles(tasksPath, outputDir) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
task.subtasks.forEach(subtask => {
content += `## ${subtask.id}. ${subtask.title} [${subtask.status || 'pending'}]\n`;
// Format subtask dependencies
if (subtask.dependencies && subtask.dependencies.length > 0) {
// Format the dependencies
content += `### Dependencies: ${formattedDeps}\n`;
} else {
content += '### Dependencies: None\n';
}
content += `### Description: ${subtask.description || ''}\n`;
content += '### Details:\n';
content += (subtask.details || '').split('\n').map(line => line).join('\n');
content += '\n\n';
});
// Add tag context to file header
let content = `# Tag Context: ${currentTag}\n`;
content += `# Task ID: ${task.id}\n`;
// ... rest of file generation
}
```
## Task Listing and Display
- **Filtering and Organization**:
- ✅ DO: Allow filtering tasks by status
- ✅ DO: Allow filtering tasks by status within current tag context
- ✅ DO: Handle subtask display in lists
- ✅ DO: Use consistent table formats
```javascript
// ✅ DO: Implement clear filtering and organization
// ✅ DO: Implement clear filtering within tag context
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Filter tasks by status if specified
const filteredTasks = statusFilter
? data.tasks.filter(task =>
? tasks.filter(task =>
task.status && task.status.toLowerCase() === statusFilter.toLowerCase())
: data.tasks;
: tasks;
```
- **Progress Tracking**:
- ✅ DO: Calculate and display completion statistics
- ✅ DO: Calculate and display completion statistics for current tag
- ✅ DO: Track both task and subtask completion
- ✅ DO: Use visual progress indicators
```javascript
// ✅ DO: Track and display progress
// ✅ DO: Track and display progress within tag context
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Calculate completion statistics
const totalTasks = data.tasks.length;
const completedTasks = data.tasks.filter(task =>
const totalTasks = tasks.length;
const completedTasks = tasks.filter(task =>
task.status === 'done' || task.status === 'completed').length;
const completionPercentage = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
@@ -223,7 +266,7 @@ alwaysApply: false
let totalSubtasks = 0;
let completedSubtasks = 0;
data.tasks.forEach(task => {
tasks.forEach(task => {
if (task.subtasks && task.subtasks.length > 0) {
totalSubtasks += task.subtasks.length;
completedSubtasks += task.subtasks.filter(st =>
@@ -232,99 +275,52 @@ alwaysApply: false
});
```
## Complexity Analysis
## Migration and Compatibility
- **Scoring System**:
- ✅ DO: Use AI to analyze task complexity
- ✅ DO: Include complexity scores (1-10)
- ✅ DO: Generate specific expansion recommendations
- **Silent Migration Handling**:
- ✅ DO: Implement silent migration in `readJSON()` function
- ✅ DO: Detect legacy format and convert automatically
- ✅ DO: Preserve all existing task data during migration
```javascript
// ✅ DO: Handle complexity analysis properly
const report = {
meta: {
generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length,
thresholdScore: thresholdScore,
projectName: tasksData.meta?.projectName || 'Your Project Name',
usedResearch: useResearch
},
complexityAnalysis: complexityAnalysis
};
```
- **Analysis-Based Workflow**:
- ✅ DO: Use complexity reports to guide task expansion
- ✅ DO: Prioritize complex tasks for more detailed breakdown
- ✅ DO: Use expansion prompts from complexity analysis
```javascript
// ✅ DO: Apply complexity analysis to workflow
// Sort tasks by complexity if report exists, otherwise by ID
if (complexityReport && complexityReport.complexityAnalysis) {
log('info', 'Sorting tasks by complexity...');
// ✅ DO: Handle silent migration (implemented in utils.js)
function readJSON(filepath) {
let data = JSON.parse(fs.readFileSync(filepath, 'utf8'));
// Create a map of task IDs to complexity scores
const complexityMap = new Map();
complexityReport.complexityAnalysis.forEach(analysis => {
complexityMap.set(analysis.taskId, analysis.complexityScore);
});
// Silent migration for tasks.json files
if (data.tasks && Array.isArray(data.tasks) && !data.master && isTasksFile) {
const migratedData = {
master: {
tasks: data.tasks
}
};
writeJSON(filepath, migratedData);
data = migratedData;
}
// Sort tasks by complexity score (high to low)
tasksToExpand.sort((a, b) => {
const scoreA = complexityMap.get(a.id) || 0;
const scoreB = complexityMap.get(b.id) || 0;
return scoreB - scoreA;
});
return data;
}
```
## Next Task Selection
- **Eligibility Criteria**:
- DO: Consider dependencies when finding next tasks
- ✅ DO: Prioritize by task priority and dependency count
- ✅ DO: Skip completed tasks
- **Tag Resolution**:
- ✅ DO: Use tag resolution functions to maintain backward compatibility
- ✅ DO: Return legacy format to core functions
- DON'T: Expose tagged structure to existing core logic
```javascript
// ✅ DO: Use proper task prioritization logic
function findNextTask(tasks) {
// Get all completed task IDs
const completedTaskIds = new Set(
tasks
.filter(t => t.status === 'done' || t.status === 'completed')
.map(t => t.id)
);
// ✅ DO: Use tag resolution layer
function getTasksForTag(data, tagName) {
if (data.tasks && Array.isArray(data.tasks)) {
// Legacy format - return as-is
return data.tasks;
}
// Filter for pending tasks whose dependencies are all satisfied
const eligibleTasks = tasks.filter(task =>
(task.status === 'pending' || task.status === 'in-progress') &&
task.dependencies &&
task.dependencies.every(depId => completedTaskIds.has(depId))
);
if (data[tagName] && data[tagName].tasks) {
// Tagged format - return tasks for specified tag
return data[tagName].tasks;
}
// Sort by priority, dependency count, and ID
const priorityValues = { 'high': 3, 'medium': 2, 'low': 1 };
const nextTask = eligibleTasks.sort((a, b) => {
// Priority first
const priorityA = priorityValues[a.priority || 'medium'] || 2;
const priorityB = priorityValues[b.priority || 'medium'] || 2;
if (priorityB !== priorityA) {
return priorityB - priorityA; // Higher priority first
}
// Dependency count next
if (a.dependencies.length !== b.dependencies.length) {
return a.dependencies.length - b.dependencies.length; // Fewer dependencies first
}
// ID last
return a.id - b.id; // Lower ID first
})[0];
return nextTask;
return [];
}
```

228
.cursor/rules/telemetry.mdc Normal file
View File

@@ -0,0 +1,228 @@
---
description: Guidelines for integrating AI usage telemetry across Task Master.
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
alwaysApply: true
---
# AI Usage Telemetry Integration
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
## Overview
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
- **`telemetryData` Object Structure**:
```json
{
"timestamp": "ISO_STRING_DATE",
"userId": "USER_ID_FROM_CONFIG",
"commandName": "invoking_command_or_tool_name",
"modelUsed": "ai_model_id",
"providerName": "ai_provider_name",
"inputTokens": NUMBER,
"outputTokens": NUMBER,
"totalTokens": NUMBER,
"totalCost": NUMBER, // e.g., 0.012414
"currency": "USD" // e.g., "USD"
}
```
## Integration Pattern by Layer
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- **Actions**:
1. Call the appropriate AI service function (e.g., `generateObjectService`).
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
3. Extract `aiServiceResponse.mainResult` for the core processing.
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
- **CLI Output Handling (If Applicable)**:
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
1. Check if `outputFormat === 'text'` (or `'cli'`).
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
- This ensures telemetry is displayed directly to CLI users after the main command output.
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
```javascript
import { generateObjectService } from '../ai-services-unified.js';
import { displayAiUsageSummary } from '../ui.js';
async function performAiRelatedAction(params, context, outputFormat = 'text') {
const { commandNameFromContext, /* other context vars */ } = context;
let aiServiceResponse = null;
try {
aiServiceResponse = await generateObjectService({
// ... other parameters for AI service ...
commandName: commandNameFromContext || 'default-action-name',
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
});
const usefulAiOutput = aiServiceResponse.mainResult.object;
// ... do work with usefulAiOutput ...
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
return {
actionData: /* results of processing */,
telemetryData: aiServiceResponse.telemetryData
};
} catch (error) {
// ... handle error ...
throw error;
}
}
```
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
These functions adapt core logic for the MCP server, ensuring structured responses.
- **Actions**:
1. Call the corresponding core logic function.
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
```javascript
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
export async function someAiActionDirect(args, log, context = {}) {
const { session } = context;
// ... prepare arguments for core function from args, including args.projectRoot ...
try {
const coreResult = await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
session,
mcpLog: createLogWrapper(log),
projectRoot: args.projectRoot,
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
outputType: 'mcp'
},
'json' // Request 'json' output format from core function
);
return {
success: true,
data: {
operationSpecificData: coreResult.actionData,
telemetryData: coreResult.telemetryData // Pass telemetry through
}
};
} catch (error) {
// ... error handling, return { success: false, error: ... } ...
}
}
```
### 3. MCP Tools (in `mcp-server/src/tools/`)
These are the exposed endpoints for MCP clients.
- **Actions**:
1. Call the corresponding direct function wrapper.
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
```javascript
import { someAiActionDirect } from '../core/task-master-core.js';
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
// ... zod for parameters ...
export function registerSomeAiActionTool(server) {
server.addTool({
name: "some_ai_action",
// ... description, parameters ...
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const resultFromDirectFunction = await someAiActionDirect(
{ /* args including projectRoot */ },
log,
{ session }
);
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
} catch (error) {
// ... error handling ...
}
})
});
}
```
### 4. CLI Commands (`scripts/modules/commands.js`)
These define the command-line interface.
- **Actions**:
1. Call the appropriate core logic function.
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
- **Example Snippet (CLI Command in `commands.js`)**:
```javascript
// In scripts/modules/commands.js
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
programInstance
.command('some-cli-ai-action')
// ... .option() ...
.action(async (options) => {
try {
const projectRoot = findProjectRoot() || '.'; // Example root finding
// ... prepare parameters for core function from command options ...
await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
projectRoot,
commandNameFromContext: 'some-cli-ai-action',
outputType: 'cli'
},
'text' // Explicitly request text output format for CLI
);
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
} catch (error) {
// ... error handling ...
}
});
```
## Summary Flow
The telemetry data flows as follows:
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
2. **Core Logic Function**:
* Receives `{ mainResult, telemetryData }`.
* Uses `mainResult`.
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
* Returns `{ operationSpecificData, telemetryData }`.
3. **Direct Function Wrapper**:
* Receives `{ operationSpecificData, telemetryData }` from core logic.
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
4. **MCP Tool**:
* Receives direct function response.
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
5. **CLI Command**:
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.

View File

@@ -0,0 +1,803 @@
---
description:
globs:
alwaysApply: true
---
# Test Workflow & Development Process
## **Initial Testing Framework Setup**
Before implementing the TDD workflow, ensure your project has a proper testing framework configured. This section covers setup for different technology stacks.
### **Detecting Project Type & Framework Needs**
**AI Agent Assessment Checklist:**
1. **Language Detection**: Check for `package.json` (Node.js/JavaScript), `requirements.txt` (Python), `Cargo.toml` (Rust), etc.
2. **Existing Tests**: Look for test files (`.test.`, `.spec.`, `_test.`) or test directories
3. **Framework Detection**: Check for existing test runners in dependencies
4. **Project Structure**: Analyze directory structure for testing patterns
### **JavaScript/Node.js Projects (Jest Setup)**
#### **Prerequisites Check**
```bash
# Verify Node.js project
ls package.json # Should exist
# Check for existing testing setup
ls jest.config.js jest.config.ts # Check for Jest config
grep -E "(jest|vitest|mocha)" package.json # Check for test runners
```
#### **Jest Installation & Configuration**
**Step 1: Install Dependencies**
```bash
# Core Jest dependencies
npm install --save-dev jest
# TypeScript support (if using TypeScript)
npm install --save-dev ts-jest @types/jest
# Additional useful packages
npm install --save-dev supertest @types/supertest # For API testing
npm install --save-dev jest-watch-typeahead # Enhanced watch mode
```
**Step 2: Create Jest Configuration**
Create `jest.config.js` with the following production-ready configuration:
```javascript
/** @type {import('jest').Config} */
module.exports = {
// Use ts-jest preset for TypeScript support
preset: 'ts-jest',
// Test environment
testEnvironment: 'node',
// Roots for test discovery
roots: ['<rootDir>/src', '<rootDir>/tests'],
// Test file patterns
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
// Transform files
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: {
target: 'es2020',
module: 'commonjs',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
strict: false,
noImplicitAny: false,
},
},
],
'^.+\\.js$': [
'ts-jest',
{
useESM: false,
tsconfig: {
target: 'es2020',
module: 'commonjs',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
allowJs: true,
},
},
],
},
// Module file extensions
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
// Transform ignore patterns - adjust for ES modules
transformIgnorePatterns: ['node_modules/(?!(your-es-module-deps|.*\\.mjs$))'],
// Coverage configuration
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: [
'text', // Console output
'text-summary', // Brief summary
'lcov', // For IDE integration
'html', // Detailed HTML report
],
// Files to collect coverage from
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
'!src/**/*.test.ts',
'!src/**/index.ts', // Often just exports
'!src/generated/**', // Generated code
'!src/config/database.ts', // Database config (tested via integration)
],
// Coverage thresholds - TaskMaster standards
coverageThreshold: {
global: {
branches: 70,
functions: 80,
lines: 80,
statements: 80,
},
// Higher standards for critical business logic
'./src/utils/': {
branches: 85,
functions: 90,
lines: 90,
statements: 90,
},
'./src/middleware/': {
branches: 80,
functions: 85,
lines: 85,
statements: 85,
},
},
// Setup files
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
// Global teardown to prevent worker process leaks
globalTeardown: '<rootDir>/tests/teardown.ts',
// Module path mapping (if needed)
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
// Clear mocks between tests
clearMocks: true,
// Restore mocks after each test
restoreMocks: true,
// Global test timeout
testTimeout: 10000,
// Projects for different test types
projects: [
// Unit tests - for pure functions only
{
displayName: 'unit',
testMatch: ['<rootDir>/src/**/*.test.ts'],
testPathIgnorePatterns: ['.*\\.integration\\.test\\.ts$', '/tests/'],
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
'!src/**/*.test.ts',
'!src/**/*.integration.test.ts',
],
coverageThreshold: {
global: {
branches: 70,
functions: 80,
lines: 80,
statements: 80,
},
},
},
// Integration tests - real database/services
{
displayName: 'integration',
testMatch: [
'<rootDir>/src/**/*.integration.test.ts',
'<rootDir>/tests/integration/**/*.test.ts',
],
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/tests/setup/integration.ts'],
testTimeout: 10000,
},
// E2E tests - full workflows
{
displayName: 'e2e',
testMatch: ['<rootDir>/tests/e2e/**/*.test.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/tests/setup/e2e.ts'],
testTimeout: 30000,
},
],
// Verbose output for better debugging
verbose: true,
// Run projects sequentially to avoid conflicts
maxWorkers: 1,
// Enable watch mode plugins
watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'],
};
```
**Step 3: Update package.json Scripts**
Add these scripts to your `package.json`:
```json
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:unit": "jest --selectProjects unit",
"test:integration": "jest --selectProjects integration",
"test:e2e": "jest --selectProjects e2e",
"test:ci": "jest --ci --coverage --watchAll=false"
}
}
```
**Step 4: Create Test Setup Files**
Create essential test setup files:
```typescript
// tests/setup.ts - Global setup
import { jest } from '@jest/globals';
// Global test configuration
beforeAll(() => {
// Set test timeout
jest.setTimeout(10000);
});
afterEach(() => {
// Clean up mocks after each test
jest.clearAllMocks();
});
```
```typescript
// tests/setup/integration.ts - Integration test setup
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
beforeAll(async () => {
// Connect to test database
await prisma.$connect();
});
afterAll(async () => {
// Cleanup and disconnect
await prisma.$disconnect();
});
beforeEach(async () => {
// Clean test data before each test
// Add your cleanup logic here
});
```
```typescript
// tests/teardown.ts - Global teardown
export default async () => {
// Global cleanup after all tests
console.log('Global test teardown complete');
};
```
**Step 5: Create Initial Test Structure**
```bash
# Create test directories
mkdir -p tests/{setup,fixtures,unit,integration,e2e}
mkdir -p tests/unit/src/{utils,services,middleware}
# Create sample test fixtures
mkdir tests/fixtures
```
### **Generic Testing Framework Setup (Any Language)**
#### **Framework Selection Guide**
**Python Projects:**
- **pytest**: Recommended for most Python projects
- **unittest**: Built-in, suitable for simple projects
- **Coverage**: Use `coverage.py` for code coverage
```bash
# Python setup example
pip install pytest pytest-cov
echo "[tool:pytest]" > pytest.ini
echo "testpaths = tests" >> pytest.ini
echo "addopts = --cov=src --cov-report=html --cov-report=term" >> pytest.ini
```
**Go Projects:**
- **Built-in testing**: Use Go's built-in `testing` package
- **Coverage**: Built-in with `go test -cover`
```bash
# Go setup example
go mod init your-project
mkdir -p tests
# Tests are typically *_test.go files alongside source
```
**Rust Projects:**
- **Built-in testing**: Use Rust's built-in test framework
- **cargo-tarpaulin**: For coverage analysis
```bash
# Rust setup example
cargo new your-project
cd your-project
cargo install cargo-tarpaulin # For coverage
```
**Java Projects:**
- **JUnit 5**: Modern testing framework
- **Maven/Gradle**: Build tools with testing integration
```xml
<!-- Maven pom.xml example -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
```
#### **Universal Testing Principles**
**Coverage Standards (Adapt to Your Language):**
- **Global Minimum**: 70-80% line coverage
- **Critical Code**: 85-90% coverage
- **New Features**: Must meet or exceed standards
- **Legacy Code**: Gradual improvement strategy
**Test Organization:**
- **Unit Tests**: Fast, isolated, no external dependencies
- **Integration Tests**: Test component interactions
- **E2E Tests**: Test complete user workflows
- **Performance Tests**: Load and stress testing (if applicable)
**Naming Conventions:**
- **Test Files**: `*.test.*`, `*_test.*`, or language-specific patterns
- **Test Functions**: Descriptive names (e.g., `should_return_error_for_invalid_input`)
- **Test Directories**: Organized by test type and mirroring source structure
#### **TaskMaster Integration for Any Framework**
**Document Testing Setup in Subtasks:**
```bash
# Update subtask with testing framework setup
task-master update-subtask --id=X.Y --prompt="Testing framework setup:
- Installed [Framework Name] with coverage support
- Configured [Coverage Tool] with thresholds: 80% lines, 70% branches
- Created test directory structure: unit/, integration/, e2e/
- Added test scripts to build configuration
- All setup tests passing"
```
**Testing Framework Verification:**
```bash
# Verify setup works
[test-command] # e.g., npm test, pytest, go test, cargo test
# Check coverage reporting
[coverage-command] # e.g., npm run test:coverage
# Update task with verification
task-master update-subtask --id=X.Y --prompt="Testing framework verified:
- Sample tests running successfully
- Coverage reporting functional
- CI/CD integration ready
- Ready to begin TDD workflow"
```
## **Test-Driven Development (TDD) Integration**
### **Core TDD Cycle with Jest**
```bash
# 1. Start development with watch mode
npm run test:watch
# 2. Write failing test first
# Create test file: src/utils/newFeature.test.ts
# Write test that describes expected behavior
# 3. Implement minimum code to make test pass
# 4. Refactor while keeping tests green
# 5. Add edge cases and error scenarios
```
### **TDD Workflow Per Subtask**
```bash
# When starting a new subtask:
task-master set-status --id=4.1 --status=in-progress
# Begin TDD cycle:
npm run test:watch # Keep running during development
# Document TDD progress in subtask:
task-master update-subtask --id=4.1 --prompt="TDD Progress:
- Written 3 failing tests for core functionality
- Implemented basic feature, tests now passing
- Adding edge case tests for error handling"
# Complete subtask with test summary:
task-master update-subtask --id=4.1 --prompt="Implementation complete:
- Feature implemented with 8 unit tests
- Coverage: 95% statements, 88% branches
- All tests passing, TDD cycle complete"
```
## **Testing Commands & Usage**
### **Development Commands**
```bash
# Primary development command - use during coding
npm run test:watch # Watch mode with Jest
npm run test:watch -- --testNamePattern="auth" # Watch specific tests
# Targeted testing during development
npm run test:unit # Run only unit tests
npm run test:unit -- --coverage # Unit tests with coverage
# Integration testing when APIs are ready
npm run test:integration # Run integration tests
npm run test:integration -- --detectOpenHandles # Debug hanging tests
# End-to-end testing for workflows
npm run test:e2e # Run E2E tests
npm run test:e2e -- --timeout=30000 # Extended timeout for E2E
```
### **Quality Assurance Commands**
```bash
# Full test suite with coverage (before commits)
npm run test:coverage # Complete coverage analysis
# All tests (CI/CD pipeline)
npm test # Run all test projects
# Specific test file execution
npm test -- auth.test.ts # Run specific test file
npm test -- --testNamePattern="should handle errors" # Run specific tests
```
## **Test Implementation Patterns**
### **Unit Test Development**
```typescript
// ✅ DO: Follow established patterns from auth.test.ts
describe('FeatureName', () => {
beforeEach(() => {
jest.clearAllMocks();
// Setup mocks with proper typing
});
describe('functionName', () => {
it('should handle normal case', () => {
// Test implementation with specific assertions
});
it('should throw error for invalid input', async () => {
// Error scenario testing
await expect(functionName(invalidInput))
.rejects.toThrow('Specific error message');
});
});
});
```
### **Integration Test Development**
```typescript
// ✅ DO: Use supertest for API endpoint testing
import request from 'supertest';
import { app } from '../../src/app';
describe('POST /api/auth/register', () => {
beforeEach(async () => {
await integrationTestUtils.cleanupTestData();
});
it('should register user successfully', async () => {
const userData = createTestUser();
const response = await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: userData.email
});
// Verify database state
const user = await prisma.user.findUnique({
where: { email: userData.email }
});
expect(user).toBeTruthy();
});
});
```
### **E2E Test Development**
```typescript
// ✅ DO: Test complete user workflows
describe('User Authentication Flow', () => {
it('should complete registration → login → protected access', async () => {
// Step 1: Register
const userData = createTestUser();
await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
// Step 2: Login
const loginResponse = await request(app)
.post('/api/auth/login')
.send({ email: userData.email, password: userData.password })
.expect(200);
const { token } = loginResponse.body;
// Step 3: Access protected resource
await request(app)
.get('/api/profile')
.set('Authorization', `Bearer ${token}`)
.expect(200);
}, 30000); // Extended timeout for E2E
});
```
## **Mocking & Test Utilities**
### **Established Mocking Patterns**
```typescript
// ✅ DO: Use established bcrypt mocking pattern
jest.mock('bcrypt');
import bcrypt from 'bcrypt';
const mockHash = bcrypt.hash as jest.MockedFunction<typeof bcrypt.hash>;
const mockCompare = bcrypt.compare as jest.MockedFunction<typeof bcrypt.compare>;
// ✅ DO: Use Prisma mocking for unit tests
jest.mock('@prisma/client', () => ({
PrismaClient: jest.fn().mockImplementation(() => ({
user: {
create: jest.fn(),
findUnique: jest.fn(),
},
$connect: jest.fn(),
$disconnect: jest.fn(),
})),
}));
```
### **Test Fixtures Usage**
```typescript
// ✅ DO: Use centralized test fixtures
import { createTestUser, adminUser, invalidUser } from '../fixtures/users';
describe('User Service', () => {
it('should handle admin user creation', async () => {
const userData = createTestUser(adminUser);
// Test implementation
});
it('should reject invalid user data', async () => {
const userData = createTestUser(invalidUser);
// Error testing
});
});
```
## **Coverage Standards & Monitoring**
### **Coverage Thresholds**
- **Global Standards**: 80% lines/functions, 70% branches
- **Critical Code**: 90% utils, 85% middleware
- **New Features**: Must meet or exceed global thresholds
- **Legacy Code**: Gradual improvement with each change
### **Coverage Reporting & Analysis**
```bash
# Generate coverage reports
npm run test:coverage
# View detailed HTML report
open coverage/lcov-report/index.html
# Coverage files generated:
# - coverage/lcov-report/index.html # Detailed HTML report
# - coverage/lcov.info # LCOV format for IDE integration
# - coverage/coverage-final.json # JSON format for tooling
```
### **Coverage Quality Checks**
```typescript
// ✅ DO: Test all code paths
describe('validateInput', () => {
it('should return true for valid input', () => {
expect(validateInput('valid')).toBe(true);
});
it('should return false for various invalid inputs', () => {
expect(validateInput('')).toBe(false); // Empty string
expect(validateInput(null)).toBe(false); // Null value
expect(validateInput(undefined)).toBe(false); // Undefined
});
it('should throw for unexpected input types', () => {
expect(() => validateInput(123)).toThrow('Invalid input type');
});
});
```
## **Testing During Development Phases**
### **Feature Development Phase**
```bash
# 1. Start feature development
task-master set-status --id=X.Y --status=in-progress
# 2. Begin TDD cycle
npm run test:watch
# 3. Document test progress in subtask
task-master update-subtask --id=X.Y --prompt="Test development:
- Created test file with 5 failing tests
- Implemented core functionality
- Tests passing, adding error scenarios"
# 4. Verify coverage before completion
npm run test:coverage
# 5. Update subtask with final test status
task-master update-subtask --id=X.Y --prompt="Testing complete:
- 12 unit tests with full coverage
- All edge cases and error scenarios covered
- Ready for integration testing"
```
### **Integration Testing Phase**
```bash
# After API endpoints are implemented
npm run test:integration
# Update integration test templates
# Replace placeholder tests with real endpoint calls
# Document integration test results
task-master update-subtask --id=X.Y --prompt="Integration tests:
- Updated auth endpoint tests
- Database integration verified
- All HTTP status codes and responses tested"
```
### **Pre-Commit Testing Phase**
```bash
# Before committing code
npm run test:coverage # Verify all tests pass with coverage
npm run test:unit # Quick unit test verification
npm run test:integration # Integration test verification (if applicable)
# Commit pattern for test updates
git add tests/ src/**/*.test.ts
git commit -m "test(task-X): Add comprehensive tests for Feature Y
- Unit tests with 95% coverage (exceeds 90% threshold)
- Integration tests for API endpoints
- Test fixtures for data generation
- Proper mocking patterns established
Task X: Feature Y - Testing complete"
```
## **Error Handling & Debugging**
### **Test Debugging Techniques**
```typescript
// ✅ DO: Use test utilities for debugging
import { testUtils } from '../setup';
it('should debug complex operation', () => {
testUtils.withConsole(() => {
// Console output visible only for this test
console.log('Debug info:', complexData);
service.complexOperation();
});
});
// ✅ DO: Use proper async debugging
it('should handle async operations', async () => {
const promise = service.asyncOperation();
// Test intermediate state
expect(service.isProcessing()).toBe(true);
const result = await promise;
expect(result).toBe('expected');
expect(service.isProcessing()).toBe(false);
});
```
### **Common Test Issues & Solutions**
```bash
# Hanging tests (common with database connections)
npm run test:integration -- --detectOpenHandles
# Memory leaks in tests
npm run test:unit -- --logHeapUsage
# Slow tests identification
npm run test:coverage -- --verbose
# Mock not working properly
# Check: mock is declared before imports
# Check: jest.clearAllMocks() in beforeEach
# Check: TypeScript typing is correct
```
## **Continuous Integration Integration**
### **CI/CD Pipeline Testing**
```yaml
# Example GitHub Actions integration
- name: Run tests
run: |
npm ci
npm run test:coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
file: ./coverage/lcov.info
```
### **Pre-commit Hooks**
```bash
# Setup pre-commit testing (recommended)
# In package.json scripts:
"pre-commit": "npm run test:unit && npm run test:integration"
# Husky integration example:
npx husky add .husky/pre-commit "npm run test:unit"
```
## **Test Maintenance & Evolution**
### **Adding Tests for New Features**
1. **Create test file** alongside source code or in `tests/unit/`
2. **Follow established patterns** from `src/utils/auth.test.ts`
3. **Use existing fixtures** from `tests/fixtures/`
4. **Apply proper mocking** patterns for dependencies
5. **Meet coverage thresholds** for the module
### **Updating Integration/E2E Tests**
1. **Update templates** in `tests/integration/` when APIs change
2. **Modify E2E workflows** in `tests/e2e/` for new user journeys
3. **Update test fixtures** for new data requirements
4. **Maintain database cleanup** utilities
### **Test Performance Optimization**
- **Parallel execution**: Jest runs tests in parallel by default
- **Test isolation**: Use proper setup/teardown for independence
- **Mock optimization**: Mock heavy dependencies appropriately
- **Database efficiency**: Use transaction rollbacks where possible
---
**Key References:**
- [Testing Standards](mdc:.cursor/rules/tests.mdc)
- [Git Workflow](mdc:.cursor/rules/git_workflow.mdc)
- [Development Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Jest Configuration](mdc:jest.config.js)

View File

@@ -283,107 +283,97 @@ When testing ES modules (`"type": "module"` in package.json), traditional mockin
- Imported functions may not use your mocked dependencies even with proper jest.mock() setup
- ES module exports are read-only properties (cannot be reassigned during tests)
- **Mocking Entire Modules**
- **Mocking Modules Statically Imported**
- For modules imported with standard `import` statements at the top level:
- Use `jest.mock('path/to/module', factory)` **before** any imports.
- Jest hoists these mocks.
- Ensure the factory function returns the mocked structure correctly.
- **Mocking Dependencies for Dynamically Imported Modules**
- **Problem**: Standard `jest.mock()` often fails for dependencies of modules loaded later using dynamic `import('path/to/module')`. The mocks aren't applied correctly when the dynamic import resolves.
- **Solution**: Use `jest.unstable_mockModule(modulePath, factory)` **before** the dynamic `import()` call.
```javascript
// Mock the entire module with custom implementation
jest.mock('../../scripts/modules/task-manager.js', () => {
// Get original implementation for functions you want to preserve
const originalModule = jest.requireActual('../../scripts/modules/task-manager.js');
// Return mix of original and mocked functionality
return {
...originalModule,
generateTaskFiles: jest.fn() // Replace specific functions
};
// 1. Define mock function instances
const mockExistsSync = jest.fn();
const mockReadFileSync = jest.fn();
// ... other mocks
// 2. Mock the dependency module *before* the dynamic import
jest.unstable_mockModule('fs', () => ({
__esModule: true, // Important for ES module mocks
// Mock named exports
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
// Mock default export if necessary
// default: { ... }
}));
// 3. Dynamically import the module under test (e.g., in beforeAll or test case)
let moduleUnderTest;
beforeAll(async () => {
// Ensure mocks are reset if needed before import
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
// ... reset other mocks ...
// Import *after* unstable_mockModule is called
moduleUnderTest = await import('../../scripts/modules/module-using-fs.js');
});
// Import after mocks
import * as taskManager from '../../scripts/modules/task-manager.js';
// Now you can use the mock directly
const { generateTaskFiles } = taskManager;
// 4. Now tests can use moduleUnderTest, and its 'fs' calls will hit the mocks
test('should use mocked fs.readFileSync', () => {
mockReadFileSync.mockReturnValue('mock data');
moduleUnderTest.readFileAndProcess();
expect(mockReadFileSync).toHaveBeenCalled();
// ... other assertions
});
```
- ✅ **DO**: Call `jest.unstable_mockModule()` before `await import()`.
- ✅ **DO**: Include `__esModule: true` in the mock factory for ES modules.
- ✅ **DO**: Mock named and default exports as needed within the factory.
- ✅ **DO**: Reset mock functions (`mockFn.mockReset()`) before the dynamic import if they might have been called previously.
- **Mocking Entire Modules (Static Import)**
```javascript
// Mock the entire module with custom implementation for static imports
// ... (existing example remains valid) ...
```
- **Direct Implementation Testing**
- Instead of calling the actual function which may have module-scope reference issues:
```javascript
test('should perform expected actions', () => {
// Setup mocks for this specific test
mockReadJSON.mockImplementationOnce(() => sampleData);
// Manually simulate the function's behavior
const data = mockReadJSON('path/file.json');
mockValidateAndFixDependencies(data, 'path/file.json');
// Skip calling the actual function and verify mocks directly
expect(mockReadJSON).toHaveBeenCalledWith('path/file.json');
expect(mockValidateAndFixDependencies).toHaveBeenCalledWith(data, 'path/file.json');
});
// ... (existing example remains valid) ...
```
- **Avoiding Module Property Assignment**
```javascript
// ❌ DON'T: This causes "Cannot assign to read only property" errors
const utils = await import('../../scripts/modules/utils.js');
utils.readJSON = mockReadJSON; // Error: read-only property
// ✅ DO: Use the module factory pattern in jest.mock()
jest.mock('../../scripts/modules/utils.js', () => ({
readJSON: mockReadJSONFunc,
writeJSON: mockWriteJSONFunc
}));
// ... (existing example remains valid) ...
```
- **Handling Mock Verification Failures**
- If verification like `expect(mockFn).toHaveBeenCalled()` fails:
1. Check that your mock setup is before imports
2. Ensure you're using the right mock instance
3. Verify your test invokes behavior that would call the mock
4. Use `jest.clearAllMocks()` in beforeEach to reset mock state
5. Consider implementing a simpler test that directly verifies mock behavior
- **Full Example Pattern**
```javascript
// 1. Define mock implementations
const mockReadJSON = jest.fn();
const mockValidateAndFixDependencies = jest.fn();
// 2. Mock modules
jest.mock('../../scripts/modules/utils.js', () => ({
readJSON: mockReadJSON,
// Include other functions as needed
}));
jest.mock('../../scripts/modules/dependency-manager.js', () => ({
validateAndFixDependencies: mockValidateAndFixDependencies
}));
// 3. Import after mocks
import * as taskManager from '../../scripts/modules/task-manager.js';
describe('generateTaskFiles function', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('should generate task files', () => {
// 4. Setup test-specific mock behavior
const sampleData = { tasks: [{ id: 1, title: 'Test' }] };
mockReadJSON.mockReturnValueOnce(sampleData);
// 5. Create direct implementation test
// Instead of calling: taskManager.generateTaskFiles('path', 'dir')
// Simulate reading data
const data = mockReadJSON('path');
expect(mockReadJSON).toHaveBeenCalledWith('path');
// Simulate other operations the function would perform
mockValidateAndFixDependencies(data, 'path');
expect(mockValidateAndFixDependencies).toHaveBeenCalledWith(data, 'path');
});
});
```
1. Check that your mock setup (`jest.mock` or `jest.unstable_mockModule`) is correctly placed **before** imports (static or dynamic).
2. Ensure you're using the right mock instance and it's properly passed to the module.
3. Verify your test invokes behavior that *should* call the mock.
4. Use `jest.clearAllMocks()` or specific `mockFn.mockReset()` in `beforeEach` to prevent state leakage between tests.
5. **Check Console Assertions**: If verifying `console.log`, `console.warn`, or `console.error` calls, ensure your assertion matches the *actual* arguments passed. If the code logs a single formatted string, assert against that single string (using `expect.stringContaining` or exact match), not multiple `expect.stringContaining` arguments.
```javascript
// Example: Code logs console.error(`Error: ${message}. Details: ${details}`)
// ❌ DON'T: Assert multiple arguments if only one is logged
// expect(console.error).toHaveBeenCalledWith(
// expect.stringContaining('Error:'),
// expect.stringContaining('Details:')
// );
// ✅ DO: Assert the single string argument
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Error: Specific message. Details: More details')
);
// or for exact match:
expect(console.error).toHaveBeenCalledWith(
'Error: Specific message. Details: More details'
);
```
6. Consider implementing a simpler test that *only* verifies the mock behavior in isolation.
## Mocking Guidelines

View File

@@ -150,4 +150,91 @@ alwaysApply: false
));
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
## Enhanced Display Patterns
### **Token Breakdown Display**
- Use detailed, granular token breakdowns for AI-powered commands
- Display context sources with individual token counts
- Show both token count and character count for transparency
```javascript
// ✅ DO: Display detailed token breakdown
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **Code Block Syntax Highlighting**
- Use `cli-highlight` library for syntax highlighting in terminal output
- Process code blocks in AI responses for better readability
```javascript
// ✅ DO: Enhance code blocks with syntax highlighting
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
### **Multi-Section Result Display**
- Use separate boxes for headers, content, and metadata
- Maintain consistent styling across different result types
```javascript
// ✅ DO: Use structured result display
function displayResults(result, query, detailLevel) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and display main content
const processedResult = processCodeBlocks(result);
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Operation complete'));
}
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples, [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for context display patterns, and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -1,9 +1,8 @@
---
description: Guidelines for implementing utility functions
globs: scripts/modules/utils.js, mcp-server/src/**/*
description:
globs:
alwaysApply: false
---
# Utility Function Guidelines
## General Principles
@@ -47,7 +46,7 @@ alwaysApply: false
- **Location**:
- **Core CLI Utilities**: Place utilities used primarily by the core `task-master` CLI logic and command modules (`scripts/modules/*`) into [`scripts/modules/utils.js`](mdc:scripts/modules/utils.js).
- **MCP Server Utilities**: Place utilities specifically designed to support the MCP server implementation into the appropriate subdirectories within `mcp-server/src/`.
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils/) (e.g., `path-utils.js`).
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils) (e.g., `path-utils.js`).
- Tool Execution/Response Helpers: [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
## Documentation Standards
@@ -79,28 +78,30 @@ alwaysApply: false
}
```
## Configuration Management (in `scripts/modules/utils.js`)
## Configuration Management (via `config-manager.js`)
- **Environment Variables**:
- ✅ DO: Provide default values for all configuration
- ✅ DO: Use environment variables for customization
- ✅ DO: Document available configuration options
- ❌ DON'T: Hardcode values that should be configurable
Taskmaster configuration (excluding API keys) is primarily managed through the `.taskmasterconfig` file located in the project root and accessed via getters in [`scripts/modules/config-manager.js`](mdc:scripts/modules/config-manager.js).
```javascript
// ✅ DO: Set up configuration with defaults and environment overrides
const CONFIG = {
model: process.env.MODEL || 'claude-3-opus-20240229', // Updated default model
maxTokens: parseInt(process.env.MAX_TOKENS || '4000'),
temperature: parseFloat(process.env.TEMPERATURE || '0.7'),
debug: process.env.DEBUG === "true",
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
projectName: process.env.PROJECT_NAME || "Task Master Project", // Generic project name
projectVersion: "1.5.0" // Version should be updated via release process
};
```
- **`.taskmasterconfig` File**:
- ✅ DO: Use this JSON file to store settings like AI model selections (main, research, fallback), parameters (temperature, maxTokens), logging level, default priority/subtasks, etc.
- ✅ DO: Manage this file using the `task-master models --setup` CLI command or the `models` MCP tool.
- ✅ DO: Rely on [`config-manager.js`](mdc:scripts/modules/config-manager.js) to load this file (using the correct project root passed from MCP or found via CLI utils), merge with defaults, and provide validated settings.
- ❌ DON'T: Store API keys in this file.
- ❌ DON'T: Manually edit this file unless necessary.
- **Configuration Getters (`config-manager.js`)**:
- ✅ DO: Import and use specific getters from `config-manager.js` (e.g., `getMainProvider()`, `getLogLevel()`, `getMainMaxTokens()`) to access configuration values *needed for application logic* (like `getDefaultSubtasks`).
- ✅ DO: Pass the `explicitRoot` parameter to getters if calling from MCP direct functions to ensure the correct project's config is loaded.
- ❌ DON'T: Call AI-specific getters (like `getMainModelId`, `getMainMaxTokens`) from core logic functions (`scripts/modules/task-manager/*`). Instead, pass the `role` to the unified AI service.
- ❌ DON'T: Access configuration values directly from environment variables (except API keys).
- **API Key Handling (`utils.js` & `ai-services-unified.js`)**:
- ✅ DO: Store API keys **only** in `.env` (for CLI, loaded by `dotenv` in `scripts/dev.js`) or `.cursor/mcp.json` (for MCP, accessed via `session.env`).
- ✅ DO: Use `isApiKeySet(providerName, session)` from `config-manager.js` to check if a provider's key is available *before* potentially attempting an AI call if needed, but note the unified service performs its own internal check.
- ✅ DO: Understand that the unified service layer (`ai-services-unified.js`) internally resolves API keys using `resolveEnvVariable(key, session)` from `utils.js`.
- **Error Handling**:
- ✅ DO: Handle potential `ConfigurationError` if the `.taskmasterconfig` file is missing or invalid when accessed via `getConfig` (e.g., in `commands.js` or direct functions).
## Logging Utilities (in `scripts/modules/utils.js`)
@@ -109,7 +110,7 @@ alwaysApply: false
- ✅ DO: Use appropriate icons for different log levels
- ✅ DO: Respect the configured log level
- ❌ DON'T: Add direct console.log calls outside the logging utility
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](mdc:...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
- **Logger Wrapper Pattern**:
- ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors:
@@ -427,36 +428,69 @@ alwaysApply: false
## MCP Server Tool Utilities (`mcp-server/src/tools/utils.js`)
- **Purpose**: These utilities specifically support the MCP server tools ([`mcp-server/src/tools/*.js`](mdc:mcp-server/src/tools/*.js)), handling MCP communication patterns, response formatting, caching integration, and the CLI fallback mechanism.
- **Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)** for detailed usage patterns within the MCP tool `execute` methods and direct function wrappers.
These utilities specifically support the implementation and execution of MCP tools.
- **`getProjectRootFromSession(session, log)`**:
- ✅ **DO**: Call this utility **within the MCP tool's `execute` method** to extract the project root path from the `session` object.
- Decodes the `file://` URI and handles potential errors.
- Returns the project path string or `null`.
- The returned path should then be passed in the `args` object when calling the corresponding `*Direct` function (e.g., `yourDirectFunction({ ...args, projectRoot: rootFolder }, log)`).
- **`normalizeProjectRoot(rawPath, log)`**:
- **Purpose**: Takes a raw project root path (potentially URI encoded, with `file://` prefix, Windows slashes) and returns a normalized, absolute path suitable for the server's OS.
- **Logic**: Decodes URI, strips `file://`, handles Windows drive prefix (`/C:/`), replaces `\` with `/`, uses `path.resolve()`.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF.
- **`getRawProjectRootFromSession(session, log)`**:
- **Purpose**: Extracts the *raw* project root URI string from the session object (`session.roots[0].uri` or `session.roots.roots[0].uri`) without performing normalization.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF as a fallback if `args.projectRoot` isn't provided.
- **`withNormalizedProjectRoot(executeFn)`**:
- **Purpose**: A Higher-Order Function (HOF) designed to wrap a tool's `execute` method.
- **Logic**:
1. Determines the raw project root (from `args.projectRoot` or `getRawProjectRootFromSession`).
2. Normalizes the raw path using `normalizeProjectRoot`.
3. Injects the normalized, absolute path back into the `args` object as `args.projectRoot`.
4. Calls the original `executeFn` with the updated `args`.
- **Usage**: Should wrap the `execute` function of *every* MCP tool that needs a reliable, normalized project root path.
- **Example**:
```javascript
// In mcp-server/src/tools/your-tool.js
import { withNormalizedProjectRoot } from './utils.js';
export function registerYourTool(server) {
server.addTool({
// ... name, description, parameters ...
execute: withNormalizedProjectRoot(async (args, context) => {
// args.projectRoot is now normalized here
const { projectRoot /*, other args */ } = args;
// ... rest of tool logic using normalized projectRoot ...
})
});
}
```
- **`handleApiResult(result, log, errorPrefix, processFunction)`**:
- ✅ **DO**: Call this from the MCP tool's `execute` method after receiving the result from the `*Direct` function wrapper.
- Takes the standard `{ success, data/error, fromCache }` object.
- Formats the standard MCP success or error response, including the `fromCache` flag.
- Uses `processMCPResponseData` by default to filter response data.
- **`executeTaskMasterCommand(command, log, args, projectRootRaw)`**:
- Executes a Task Master CLI command as a child process.
- Handles fallback between global `task-master` and local `node scripts/dev.js`.
- ❌ **DON'T**: Use this as the primary method for MCP tools. Prefer direct function calls via `*Direct` wrappers.
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
- Filters task data (e.g., removing `details`, `testStrategy`) before sending to the MCP client. Called by `handleApiResult`.
- **Purpose**: Standardizes the formatting of responses returned by direct functions (`{ success, data/error, fromCache }`) into the MCP response format.
- **Usage**: Call this at the end of the tool's `execute` method, passing the result from the direct function call.
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
- Formatters for standard MCP success/error responses.
- **Purpose**: Helper functions to create the basic MCP response structure for success or error messages.
- **Usage**: Used internally by `handleApiResult` and potentially directly for simple responses.
- **`createLogWrapper(log)`**:
- **Purpose**: Creates a logger object wrapper with standard methods (`info`, `warn`, `error`, `debug`, `success`) mapping to the passed MCP `log` object's methods. Ensures compatibility when passing loggers to core functions.
- **Usage**: Used within direct functions before passing the `log` object down to core logic that expects the standard method names.
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
- ✅ **DO**: Use this utility *inside direct function wrappers* to implement caching.
- Checks cache, executes `actionFn` on miss, stores result.
- Returns standard `{ success, data/error, fromCache: boolean }`.
- **Purpose**: Utility for implementing caching within direct functions. Checks cache for `cacheKey`; if miss, executes `actionFn`, caches successful result, and returns.
- **Usage**: Wrap the core logic execution within a direct function call.
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
- **Purpose**: Utility to filter potentially sensitive or large fields (like `details`, `testStrategy`) from task objects before sending the response back via MCP.
- **Usage**: Passed as the default `processFunction` to `handleApiResult`.
- **`getProjectRootFromSession(session, log)`**:
- **Purpose**: Legacy function to extract *and normalize* the project root from the session. Replaced by the HOF pattern but potentially still used.
- **Recommendation**: Prefer using the `withNormalizedProjectRoot` HOF in tools instead of calling this directly.
- **`executeTaskMasterCommand(...)`**:
- **Purpose**: Executes `task-master` CLI command as a fallback.
- **Recommendation**: Deprecated for most uses; prefer direct function calls.
## Export Organization
@@ -514,4 +548,628 @@ export {
};
```
Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
## Context Gathering Utilities
### **ContextGatherer** (`scripts/modules/utils/contextGatherer.js`)
- **Multi-Source Context Extraction**:
- ✅ DO: Use for AI-powered commands that need project context
- ✅ DO: Support tasks, files, custom text, and project tree context
- ✅ DO: Implement detailed token counting with `gpt-tokens` library
- ✅ DO: Provide multiple output formats (research, chat, system-prompt)
```javascript
// ✅ DO: Use ContextGatherer for consistent context extraction
import { ContextGatherer } from '../utils/contextGatherer.js';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
const result = await gatherer.gather({
tasks: ['15', '16.2'],
files: ['src/api.js'],
customContext: 'Additional context',
includeProjectTree: true,
format: 'research',
includeTokenCounts: true
});
```
### **FuzzyTaskSearch** (`scripts/modules/utils/fuzzyTaskSearch.js`)
- **Intelligent Task Discovery**:
- ✅ DO: Use for automatic task relevance detection
- ✅ DO: Configure search parameters based on use case context
- ✅ DO: Implement purpose-based categorization for better matching
- ✅ DO: Sort results by relevance score and task ID
```javascript
// ✅ DO: Use FuzzyTaskSearch for intelligent task discovery
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
- **Integration Guidelines**:
- ✅ DO: Use fuzzy search to supplement user-provided task IDs
- ✅ DO: Display discovered task IDs to users for transparency
- ✅ DO: Sort discovered task IDs numerically for better readability
- ❌ DON'T: Replace explicit user task selections with fuzzy results
Refer to [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for detailed implementation patterns, [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
## File System Operations
- **JSON File Handling**:
- ✅ DO: Use `readJSON` and `writeJSON` for all JSON operations
- ✅ DO: Include error handling for file operations
- ✅ DO: Validate JSON structure after reading
- ❌ DON'T: Use raw `fs.readFileSync` or `fs.writeFileSync` for JSON
```javascript
// ✅ DO: Use utility functions with error handling
function readJSON(filepath) {
try {
if (!fs.existsSync(filepath)) {
return null; // or appropriate default
}
let data = JSON.parse(fs.readFileSync(filepath, 'utf8'));
// Silent migration for tasks.json files: Transform old format to tagged format
const isTasksFile = filepath.includes('tasks.json') || path.basename(filepath) === 'tasks.json';
if (data && data.tasks && Array.isArray(data.tasks) && !data.master && isTasksFile) {
// Migrate from old format { "tasks": [...] } to new format { "master": { "tasks": [...] } }
const migratedData = {
master: {
tasks: data.tasks
}
};
writeJSON(filepath, migratedData);
// Set global flag for CLI notice and perform complete migration
global.taskMasterMigrationOccurred = true;
performCompleteTagMigration(filepath);
data = migratedData;
}
return data;
} catch (error) {
log('error', `Failed to read JSON from ${filepath}: ${error.message}`);
return null;
}
}
function writeJSON(filepath, data) {
try {
const dirPath = path.dirname(filepath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
} catch (error) {
log('error', `Failed to write JSON to ${filepath}: ${error.message}`);
throw error;
}
}
```
- **Path Resolution**:
- ✅ DO: Use `path.join()` for cross-platform path construction
- ✅ DO: Use `path.resolve()` for absolute paths
- ✅ DO: Validate paths before file operations
```javascript
// ✅ DO: Handle paths correctly
function findProjectRoot(startPath = process.cwd()) {
let currentPath = path.resolve(startPath);
const rootPath = path.parse(currentPath).root;
while (currentPath !== rootPath) {
const taskMasterPath = path.join(currentPath, '.taskmaster');
if (fs.existsSync(taskMasterPath)) {
return currentPath;
}
currentPath = path.dirname(currentPath);
}
return null; // Not found
}
```
## Tagged Task Lists System Utilities
- **Tag Resolution Functions**:
- ✅ DO: Use tag resolution layer for all task data access
- ✅ DO: Provide backward compatibility with legacy format
- ✅ DO: Default to "master" tag when no tag is specified
```javascript
// ✅ DO: Implement tag resolution functions
function getTasksForTag(data, tagName = 'master') {
if (!data) {
return [];
}
// Handle legacy format - direct tasks array
if (data.tasks && Array.isArray(data.tasks)) {
return data.tasks;
}
// Handle tagged format - tasks under specific tag
if (data[tagName] && data[tagName].tasks && Array.isArray(data[tagName].tasks)) {
return data[tagName].tasks;
}
return [];
}
function setTasksForTag(data, tagName = 'master', tasks) {
// Ensure data object exists
if (!data) {
data = {};
}
// Create tag structure if it doesn't exist
if (!data[tagName]) {
data[tagName] = {};
}
// Set tasks for the tag
data[tagName].tasks = tasks;
return data;
}
function getCurrentTag() {
// Get current tag from state.json or default to 'master'
try {
const projectRoot = findProjectRoot();
if (!projectRoot) return 'master';
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
if (fs.existsSync(statePath)) {
const state = readJSON(statePath);
return state.currentTag || 'master';
}
} catch (error) {
log('debug', `Error reading current tag: ${error.message}`);
}
return 'master';
}
```
- **Migration Functions**:
- ✅ DO: Implement complete migration for all related files
- ✅ DO: Handle configuration and state file creation
- ✅ DO: Provide migration status tracking
```javascript
// ✅ DO: Implement complete migration system
function performCompleteTagMigration(tasksJsonPath) {
try {
// Derive project root from tasks.json path
const projectRoot = findProjectRoot(path.dirname(tasksJsonPath)) || path.dirname(tasksJsonPath);
// 1. Migrate config.json - add defaultTag and tags section
const configPath = path.join(projectRoot, '.taskmaster', 'config.json');
if (fs.existsSync(configPath)) {
migrateConfigJson(configPath);
}
// 2. Create state.json if it doesn't exist
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
if (!fs.existsSync(statePath)) {
createStateJson(statePath);
}
if (getDebugFlag()) {
log('debug', 'Completed tagged task lists migration for project');
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error during complete tag migration: ${error.message}`);
}
}
}
function migrateConfigJson(configPath) {
try {
const config = readJSON(configPath);
if (!config) return;
let modified = false;
// Add global.defaultTag if missing
if (!config.global) {
config.global = {};
}
if (!config.global.defaultTag) {
config.global.defaultTag = 'master';
modified = true;
}
// Add tags section if missing
if (!config.tags) {
config.tags = {
// Git integration settings removed - now manual only
};
modified = true;
}
if (modified) {
writeJSON(configPath, config);
if (getDebugFlag()) {
log('debug', 'Updated config.json with tagged task system settings');
}
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error migrating config.json: ${error.message}`);
}
}
}
function createStateJson(statePath) {
try {
const initialState = {
currentTag: 'master',
lastSwitched: new Date().toISOString(),
migrationNoticeShown: false
};
writeJSON(statePath, initialState);
if (getDebugFlag()) {
log('debug', 'Created initial state.json for tagged task system');
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error creating state.json: ${error.message}`);
}
}
}
function markMigrationForNotice() {
try {
const projectRoot = findProjectRoot();
if (!projectRoot) return;
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
const state = readJSON(statePath) || {};
state.migrationNoticeShown = false; // Reset to show notice
writeJSON(statePath, state);
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error marking migration for notice: ${error.message}`);
}
}
}
```
## Logging Functions
- **Consistent Logging**:
- ✅ DO: Use the central `log` function for all output
- ✅ DO: Use appropriate log levels (info, warn, error, debug)
- ✅ DO: Support silent mode for programmatic usage
```javascript
// ✅ DO: Implement consistent logging with silent mode
let silentMode = false;
function log(level, ...messages) {
if (silentMode && level !== 'error') {
return; // Suppress non-error logs in silent mode
}
const timestamp = new Date().toISOString();
const formattedMessage = messages.join(' ');
switch (level) {
case 'error':
console.error(`[ERROR] ${formattedMessage}`);
break;
case 'warn':
console.warn(`[WARN] ${formattedMessage}`);
break;
case 'info':
console.log(`[INFO] ${formattedMessage}`);
break;
case 'debug':
if (getDebugFlag()) {
console.log(`[DEBUG] ${formattedMessage}`);
}
break;
default:
console.log(formattedMessage);
}
}
function enableSilentMode() {
silentMode = true;
}
function disableSilentMode() {
silentMode = false;
}
function isSilentMode() {
return silentMode;
}
```
## Task Utilities
- **Task Finding and Manipulation**:
- ✅ DO: Use tagged task system aware functions
- ✅ DO: Handle both task and subtask operations
- ✅ DO: Validate task IDs before operations
```javascript
// ✅ DO: Implement tag-aware task utilities
function findTaskById(tasks, taskId) {
if (!Array.isArray(tasks)) {
return null;
}
return tasks.find(task => task.id === taskId) || null;
}
function findSubtaskById(tasks, parentId, subtaskId) {
const parentTask = findTaskById(tasks, parentId);
if (!parentTask || !parentTask.subtasks) {
return null;
}
return parentTask.subtasks.find(subtask => subtask.id === subtaskId) || null;
}
function getNextTaskId(tasks) {
if (!Array.isArray(tasks) || tasks.length === 0) {
return 1;
}
const maxId = Math.max(...tasks.map(task => task.id));
return maxId + 1;
}
function getNextSubtaskId(parentTask) {
if (!parentTask.subtasks || parentTask.subtasks.length === 0) {
return 1;
}
const maxId = Math.max(...parentTask.subtasks.map(subtask => subtask.id));
return maxId + 1;
}
```
## String Utilities
- **Text Processing**:
- ✅ DO: Handle text truncation appropriately
- ✅ DO: Provide consistent formatting functions
- ✅ DO: Support different output formats
```javascript
// ✅ DO: Implement useful string utilities
function truncate(str, maxLength = 50) {
if (!str || typeof str !== 'string') {
return '';
}
if (str.length <= maxLength) {
return str;
}
return str.substring(0, maxLength - 3) + '...';
}
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
}
function capitalizeFirst(str) {
if (!str || typeof str !== 'string') {
return '';
}
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
```
## Dependency Management Utilities
- **Dependency Analysis**:
- ✅ DO: Detect circular dependencies
- ✅ DO: Validate dependency references
- ✅ DO: Support cross-tag dependency checking (future enhancement)
```javascript
// ✅ DO: Implement dependency utilities
function findCycles(tasks) {
const cycles = [];
const visited = new Set();
const recStack = new Set();
function dfs(taskId, path = []) {
if (recStack.has(taskId)) {
// Found a cycle
const cycleStart = path.indexOf(taskId);
const cycle = path.slice(cycleStart).concat([taskId]);
cycles.push(cycle);
return;
}
if (visited.has(taskId)) {
return;
}
visited.add(taskId);
recStack.add(taskId);
const task = findTaskById(tasks, taskId);
if (task && task.dependencies) {
task.dependencies.forEach(depId => {
dfs(depId, path.concat([taskId]));
});
}
recStack.delete(taskId);
}
tasks.forEach(task => {
if (!visited.has(task.id)) {
dfs(task.id);
}
});
return cycles;
}
function validateDependencies(tasks) {
const validationErrors = [];
const taskIds = new Set(tasks.map(task => task.id));
tasks.forEach(task => {
if (task.dependencies) {
task.dependencies.forEach(depId => {
if (!taskIds.has(depId)) {
validationErrors.push({
taskId: task.id,
invalidDependency: depId,
message: `Task ${task.id} depends on non-existent task ${depId}`
});
}
});
}
});
return validationErrors;
}
```
## Environment and Configuration Utilities
- **Environment Variable Resolution**:
- ✅ DO: Support both `.env` files and MCP session environment
- ✅ DO: Provide fallbacks for missing values
- ✅ DO: Handle API key resolution correctly
```javascript
// ✅ DO: Implement flexible environment resolution
function resolveEnvVariable(key, sessionEnv = null) {
// First check session environment (for MCP)
if (sessionEnv && sessionEnv[key]) {
return sessionEnv[key];
}
// Then check process environment
if (process.env[key]) {
return process.env[key];
}
// Finally try .env file if in project root
try {
const projectRoot = findProjectRoot();
if (projectRoot) {
const envPath = path.join(projectRoot, '.env');
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf8');
const lines = envContent.split('\n');
for (const line of lines) {
const [envKey, envValue] = line.split('=');
if (envKey && envKey.trim() === key) {
return envValue ? envValue.trim().replace(/^["']|["']$/g, '') : undefined;
}
}
}
}
} catch (error) {
log('debug', `Error reading .env file: ${error.message}`);
}
return undefined;
}
function getDebugFlag() {
const debugFlag = resolveEnvVariable('TASKMASTER_DEBUG') ||
resolveEnvVariable('DEBUG') ||
'false';
return debugFlag.toLowerCase() === 'true';
}
```
## Export Pattern
- **Module Exports**:
- ✅ DO: Export all utility functions explicitly
- ✅ DO: Group related functions logically
- ✅ DO: Include new tagged system utilities
```javascript
// ✅ DO: Export utilities in logical groups
module.exports = {
// File system utilities
readJSON,
writeJSON,
findProjectRoot,
// Tagged task system utilities
getTasksForTag,
setTasksForTag,
getCurrentTag,
performCompleteTagMigration,
migrateConfigJson,
createStateJson,
markMigrationForNotice,
// Logging utilities
log,
enableSilentMode,
disableSilentMode,
isSilentMode,
// Task utilities
findTaskById,
findSubtaskById,
getNextTaskId,
getNextSubtaskId,
// String utilities
truncate,
formatDuration,
capitalizeFirst,
// Dependency utilities
findCycles,
validateDependencies,
// Environment utilities
resolveEnvVariable,
getDebugFlag,
// Legacy utilities (maintained for compatibility)
aggregateTelemetry
};
```
Refer to [`utils.js`](mdc:scripts/modules/utils.js) for implementation examples and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for integration patterns.

View File

@@ -1,20 +1,17 @@
# API Keys (Required)
ANTHROPIC_API_KEY=your_anthropic_api_key_here # Format: sk-ant-api03-...
PERPLEXITY_API_KEY=your_perplexity_api_key_here # Format: pplx-...
# API Keys (Required for using in any role i.e. main/research/fallback -- see `task-master models`)
ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY_HERE
PERPLEXITY_API_KEY=YOUR_PERPLEXITY_KEY_HERE
OPENAI_API_KEY=YOUR_OPENAI_KEY_HERE
GOOGLE_API_KEY=YOUR_GOOGLE_KEY_HERE
MISTRAL_API_KEY=YOUR_MISTRAL_KEY_HERE
GROQ_API_KEY=YOUR_GROQ_KEY_HERE
OPENROUTER_API_KEY=YOUR_OPENROUTER_KEY_HERE
XAI_API_KEY=YOUR_XAI_KEY_HERE
AZURE_OPENAI_API_KEY=YOUR_AZURE_KEY_HERE
OLLAMA_API_KEY=YOUR_OLLAMA_API_KEY_HERE
# Model Configuration
MODEL=claude-3-7-sonnet-20250219 # Recommended models: claude-3-7-sonnet-20250219, claude-3-opus-20240229
PERPLEXITY_MODEL=sonar-pro # Perplexity model for research-backed subtasks
MAX_TOKENS=64000 # Maximum tokens for model responses
TEMPERATURE=0.2 # Temperature for model responses (0.0-1.0)
# Logging Configuration
DEBUG=false # Enable debug logging (true/false)
LOG_LEVEL=info # Log level (debug, info, warn, error)
# Task Generation Settings
DEFAULT_SUBTASKS=5 # Default number of subtasks when expanding
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
# Project Metadata (Optional)
PROJECT_NAME=Your Project Name # Override default project name in tasks.json
# Google Vertex AI Configuration
VERTEX_PROJECT_ID=your-gcp-project-id
VERTEX_LOCATION=us-central1
# Optional: Path to service account credentials JSON file (alternative to API key)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json

45
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,45 @@
# What type of PR is this?
<!-- Check one -->
- [ ] 🐛 Bug fix
- [ ] ✨ Feature
- [ ] 🔌 Integration
- [ ] 📝 Docs
- [ ] 🧹 Refactor
- [ ] Other:
## Description
<!-- What does this PR do? -->
## Related Issues
<!-- Link issues: Fixes #123 -->
## How to Test This
<!-- Quick steps to verify the changes work -->
```bash
# Example commands or steps
```
**Expected result:**
<!-- What should happen? -->
## Contributor Checklist
- [ ] Created changeset: `npm run changeset`
- [ ] Tests pass: `npm test`
- [ ] Format check passes: `npm run format-check` (or `npm run format` to fix)
- [ ] Addressed CodeRabbit comments (if any)
- [ ] Linked related issues (if any)
- [ ] Manually tested the changes
## Changelog Entry
<!-- One line describing the change for users -->
<!-- Example: "Added Kiro IDE integration with automatic task status updates" -->
---
### For Maintainers
- [ ] PR title follows conventional commits
- [ ] Target branch correct
- [ ] Labels added
- [ ] Milestone assigned (if applicable)

39
.github/PULL_REQUEST_TEMPLATE/bugfix.md vendored Normal file
View File

@@ -0,0 +1,39 @@
## 🐛 Bug Fix
### 🔍 Bug Description
<!-- Describe the bug -->
### 🔗 Related Issues
<!-- Fixes #123 -->
### ✨ Solution
<!-- How does this PR fix the bug? -->
## How to Test
### Steps that caused the bug:
1.
2.
**Before fix:**
**After fix:**
### Quick verification:
```bash
# Commands to verify the fix
```
## Contributor Checklist
- [ ] Created changeset: `npm run changeset`
- [ ] Tests pass: `npm test`
- [ ] Format check passes: `npm run format-check`
- [ ] Addressed CodeRabbit comments
- [ ] Added unit tests (if applicable)
- [ ] Manually verified the fix works
---
### For Maintainers
- [ ] Root cause identified
- [ ] Fix doesn't introduce new issues
- [ ] CI passes

View File

@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: 🐛 Bug Fix
url: https://github.com/eyaltoledano/claude-task-master/compare/next...HEAD?template=bugfix.md
about: Fix a bug in Task Master
- name: ✨ New Feature
url: https://github.com/eyaltoledano/claude-task-master/compare/next...HEAD?template=feature.md
about: Add a new feature to Task Master
- name: 🔌 New Integration
url: https://github.com/eyaltoledano/claude-task-master/compare/next...HEAD?template=integration.md
about: Add support for a new tool, IDE, or platform

View File

@@ -0,0 +1,49 @@
## ✨ New Feature
### 📋 Feature Description
<!-- Brief description -->
### 🎯 Problem Statement
<!-- What problem does this feature solve? Why is it needed? -->
### 💡 Solution
<!-- How does this feature solve the problem? What's the approach? -->
### 🔗 Related Issues
<!-- Link related issues: Fixes #123, Part of #456 -->
## How to Use It
### Quick Start
```bash
# Basic usage example
```
### Example
<!-- Show a real use case -->
```bash
# Practical example
```
**What you should see:**
<!-- Expected behavior -->
## Contributor Checklist
- [ ] Created changeset: `npm run changeset`
- [ ] Tests pass: `npm test`
- [ ] Format check passes: `npm run format-check`
- [ ] Addressed CodeRabbit comments
- [ ] Added tests for new functionality
- [ ] Manually tested in CLI mode
- [ ] Manually tested in MCP mode (if applicable)
## Changelog Entry
<!-- One-liner for release notes -->
---
### For Maintainers
- [ ] Feature aligns with project vision
- [ ] CIs pass
- [ ] Changeset file exists

View File

@@ -0,0 +1,53 @@
# 🔌 New Integration
## What tool/IDE is being integrated?
<!-- Name and brief description -->
## What can users do with it?
<!-- Key benefits -->
## How to Enable
### Setup
```bash
task-master rules add [name]
# Any other setup steps
```
### Example Usage
<!-- Show it in action -->
```bash
# Real example
```
### Natural Language Hooks (if applicable)
```
"When tests pass, mark task as done"
# Other examples
```
## Contributor Checklist
- [ ] Created changeset: `npm run changeset`
- [ ] Tests pass: `npm test`
- [ ] Format check passes: `npm run format-check`
- [ ] Addressed CodeRabbit comments
- [ ] Integration fully tested with target tool/IDE
- [ ] Error scenarios tested
- [ ] Added integration tests
- [ ] Documentation includes setup guide
- [ ] Examples are working and clear
---
## For Maintainers
- [ ] Integration stability verified
- [ ] Documentation comprehensive
- [ ] Examples working

View File

@@ -0,0 +1,259 @@
#!/usr/bin/env node
async function githubRequest(endpoint, token, method = 'GET', body) {
const response = await fetch(`https://api.github.com${endpoint}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'auto-close-duplicates-script',
...(body && { 'Content-Type': 'application/json' })
},
...(body && { body: JSON.stringify(body) })
});
if (!response.ok) {
throw new Error(
`GitHub API request failed: ${response.status} ${response.statusText}`
);
}
return response.json();
}
function extractDuplicateIssueNumber(commentBody) {
const match = commentBody.match(/#(\d+)/);
return match ? parseInt(match[1], 10) : null;
}
async function closeIssueAsDuplicate(
owner,
repo,
issueNumber,
duplicateOfNumber,
token
) {
await githubRequest(
`/repos/${owner}/${repo}/issues/${issueNumber}`,
token,
'PATCH',
{
state: 'closed',
state_reason: 'not_planned',
labels: ['duplicate']
}
);
await githubRequest(
`/repos/${owner}/${repo}/issues/${issueNumber}/comments`,
token,
'POST',
{
body: `This issue has been automatically closed as a duplicate of #${duplicateOfNumber}.
If this is incorrect, please re-open this issue or create a new one.
🤖 Generated with [Task Master Bot]`
}
);
}
async function autoCloseDuplicates() {
console.log('[DEBUG] Starting auto-close duplicates script');
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error('GITHUB_TOKEN environment variable is required');
}
console.log('[DEBUG] GitHub token found');
const owner = process.env.GITHUB_REPOSITORY_OWNER || 'eyaltoledano';
const repo = process.env.GITHUB_REPOSITORY_NAME || 'claude-task-master';
console.log(`[DEBUG] Repository: ${owner}/${repo}`);
const threeDaysAgo = new Date();
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
console.log(
`[DEBUG] Checking for duplicate comments older than: ${threeDaysAgo.toISOString()}`
);
console.log('[DEBUG] Fetching open issues created more than 3 days ago...');
const allIssues = [];
let page = 1;
const perPage = 100;
const MAX_PAGES = 50; // Increase limit for larger repos
let foundRecentIssue = false;
while (true) {
const pageIssues = await githubRequest(
`/repos/${owner}/${repo}/issues?state=open&per_page=${perPage}&page=${page}&sort=created&direction=desc`,
token
);
if (pageIssues.length === 0) break;
// Filter for issues created more than 3 days ago
const oldEnoughIssues = pageIssues.filter(
(issue) => new Date(issue.created_at) <= threeDaysAgo
);
allIssues.push(...oldEnoughIssues);
// If all issues on this page are newer than 3 days, we can stop
if (oldEnoughIssues.length === 0 && page === 1) {
foundRecentIssue = true;
break;
}
// If we found some old issues but not all, continue to next page
// as there might be more old issues
page++;
// Safety limit to avoid infinite loops
if (page > MAX_PAGES) {
console.log(`[WARNING] Reached maximum page limit of ${MAX_PAGES}`);
break;
}
}
const issues = allIssues;
console.log(`[DEBUG] Found ${issues.length} open issues`);
let processedCount = 0;
let candidateCount = 0;
for (const issue of issues) {
processedCount++;
console.log(
`[DEBUG] Processing issue #${issue.number} (${processedCount}/${issues.length}): ${issue.title}`
);
console.log(`[DEBUG] Fetching comments for issue #${issue.number}...`);
const comments = await githubRequest(
`/repos/${owner}/${repo}/issues/${issue.number}/comments`,
token
);
console.log(
`[DEBUG] Issue #${issue.number} has ${comments.length} comments`
);
const dupeComments = comments.filter(
(comment) =>
comment.body.includes('Found') &&
comment.body.includes('possible duplicate') &&
comment.user.type === 'Bot'
);
console.log(
`[DEBUG] Issue #${issue.number} has ${dupeComments.length} duplicate detection comments`
);
if (dupeComments.length === 0) {
console.log(
`[DEBUG] Issue #${issue.number} - no duplicate comments found, skipping`
);
continue;
}
const lastDupeComment = dupeComments[dupeComments.length - 1];
const dupeCommentDate = new Date(lastDupeComment.created_at);
console.log(
`[DEBUG] Issue #${
issue.number
} - most recent duplicate comment from: ${dupeCommentDate.toISOString()}`
);
if (dupeCommentDate > threeDaysAgo) {
console.log(
`[DEBUG] Issue #${issue.number} - duplicate comment is too recent, skipping`
);
continue;
}
console.log(
`[DEBUG] Issue #${
issue.number
} - duplicate comment is old enough (${Math.floor(
(Date.now() - dupeCommentDate.getTime()) / (1000 * 60 * 60 * 24)
)} days)`
);
const commentsAfterDupe = comments.filter(
(comment) => new Date(comment.created_at) > dupeCommentDate
);
console.log(
`[DEBUG] Issue #${issue.number} - ${commentsAfterDupe.length} comments after duplicate detection`
);
if (commentsAfterDupe.length > 0) {
console.log(
`[DEBUG] Issue #${issue.number} - has activity after duplicate comment, skipping`
);
continue;
}
console.log(
`[DEBUG] Issue #${issue.number} - checking reactions on duplicate comment...`
);
const reactions = await githubRequest(
`/repos/${owner}/${repo}/issues/comments/${lastDupeComment.id}/reactions`,
token
);
console.log(
`[DEBUG] Issue #${issue.number} - duplicate comment has ${reactions.length} reactions`
);
const authorThumbsDown = reactions.some(
(reaction) =>
reaction.user.id === issue.user.id && reaction.content === '-1'
);
console.log(
`[DEBUG] Issue #${issue.number} - author thumbs down reaction: ${authorThumbsDown}`
);
if (authorThumbsDown) {
console.log(
`[DEBUG] Issue #${issue.number} - author disagreed with duplicate detection, skipping`
);
continue;
}
const duplicateIssueNumber = extractDuplicateIssueNumber(
lastDupeComment.body
);
if (!duplicateIssueNumber) {
console.log(
`[DEBUG] Issue #${issue.number} - could not extract duplicate issue number from comment, skipping`
);
continue;
}
candidateCount++;
const issueUrl = `https://github.com/${owner}/${repo}/issues/${issue.number}`;
try {
console.log(
`[INFO] Auto-closing issue #${issue.number} as duplicate of #${duplicateIssueNumber}: ${issueUrl}`
);
await closeIssueAsDuplicate(
owner,
repo,
issue.number,
duplicateIssueNumber,
token
);
console.log(
`[SUCCESS] Successfully closed issue #${issue.number} as duplicate of #${duplicateIssueNumber}`
);
} catch (error) {
console.error(
`[ERROR] Failed to close issue #${issue.number} as duplicate: ${error}`
);
}
}
console.log(
`[DEBUG] Script completed. Processed ${processedCount} issues, found ${candidateCount} candidates for auto-close`
);
}
autoCloseDuplicates().catch(console.error);

View File

@@ -0,0 +1,178 @@
#!/usr/bin/env node
async function githubRequest(endpoint, token, method = 'GET', body) {
const response = await fetch(`https://api.github.com${endpoint}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'backfill-duplicate-comments-script',
...(body && { 'Content-Type': 'application/json' })
},
...(body && { body: JSON.stringify(body) })
});
if (!response.ok) {
throw new Error(
`GitHub API request failed: ${response.status} ${response.statusText}`
);
}
return response.json();
}
async function triggerDedupeWorkflow(
owner,
repo,
issueNumber,
token,
dryRun = true
) {
if (dryRun) {
console.log(
`[DRY RUN] Would trigger dedupe workflow for issue #${issueNumber}`
);
return;
}
await githubRequest(
`/repos/${owner}/${repo}/actions/workflows/claude-dedupe-issues.yml/dispatches`,
token,
'POST',
{
ref: 'main',
inputs: {
issue_number: issueNumber.toString()
}
}
);
}
async function backfillDuplicateComments() {
console.log('[DEBUG] Starting backfill duplicate comments script');
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error(`GITHUB_TOKEN environment variable is required
Usage:
node .github/scripts/backfill-duplicate-comments.mjs
Environment Variables:
GITHUB_TOKEN - GitHub personal access token with repo and actions permissions (required)
DRY_RUN - Set to "false" to actually trigger workflows (default: true for safety)
DAYS_BACK - How many days back to look for old issues (default: 90)`);
}
console.log('[DEBUG] GitHub token found');
const owner = process.env.GITHUB_REPOSITORY_OWNER || 'eyaltoledano';
const repo = process.env.GITHUB_REPOSITORY_NAME || 'claude-task-master';
const dryRun = process.env.DRY_RUN !== 'false';
const daysBack = parseInt(process.env.DAYS_BACK || '90', 10);
console.log(`[DEBUG] Repository: ${owner}/${repo}`);
console.log(`[DEBUG] Dry run mode: ${dryRun}`);
console.log(`[DEBUG] Looking back ${daysBack} days`);
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysBack);
console.log(
`[DEBUG] Fetching issues created since ${cutoffDate.toISOString()}...`
);
const allIssues = [];
let page = 1;
const perPage = 100;
while (true) {
const pageIssues = await githubRequest(
`/repos/${owner}/${repo}/issues?state=all&per_page=${perPage}&page=${page}&since=${cutoffDate.toISOString()}`,
token
);
if (pageIssues.length === 0) break;
allIssues.push(...pageIssues);
page++;
// Safety limit to avoid infinite loops
if (page > 100) {
console.log('[DEBUG] Reached page limit, stopping pagination');
break;
}
}
console.log(
`[DEBUG] Found ${allIssues.length} issues from the last ${daysBack} days`
);
let processedCount = 0;
let candidateCount = 0;
let triggeredCount = 0;
for (const issue of allIssues) {
processedCount++;
console.log(
`[DEBUG] Processing issue #${issue.number} (${processedCount}/${allIssues.length}): ${issue.title}`
);
console.log(`[DEBUG] Fetching comments for issue #${issue.number}...`);
const comments = await githubRequest(
`/repos/${owner}/${repo}/issues/${issue.number}/comments`,
token
);
console.log(
`[DEBUG] Issue #${issue.number} has ${comments.length} comments`
);
// Look for existing duplicate detection comments (from the dedupe bot)
const dupeDetectionComments = comments.filter(
(comment) =>
comment.body.includes('Found') &&
comment.body.includes('possible duplicate') &&
comment.user.type === 'Bot'
);
console.log(
`[DEBUG] Issue #${issue.number} has ${dupeDetectionComments.length} duplicate detection comments`
);
// Skip if there's already a duplicate detection comment
if (dupeDetectionComments.length > 0) {
console.log(
`[DEBUG] Issue #${issue.number} already has duplicate detection comment, skipping`
);
continue;
}
candidateCount++;
const issueUrl = `https://github.com/${owner}/${repo}/issues/${issue.number}`;
try {
console.log(
`[INFO] ${dryRun ? '[DRY RUN] ' : ''}Triggering dedupe workflow for issue #${issue.number}: ${issueUrl}`
);
await triggerDedupeWorkflow(owner, repo, issue.number, token, dryRun);
if (!dryRun) {
console.log(
`[SUCCESS] Successfully triggered dedupe workflow for issue #${issue.number}`
);
}
triggeredCount++;
} catch (error) {
console.error(
`[ERROR] Failed to trigger workflow for issue #${issue.number}: ${error}`
);
}
// Add a delay between workflow triggers to avoid overwhelming the system
await new Promise((resolve) => setTimeout(resolve, 1000));
}
console.log(
`[DEBUG] Script completed. Processed ${processedCount} issues, found ${candidateCount} candidates without duplicate comments, ${dryRun ? 'would trigger' : 'triggered'} ${triggeredCount} workflows`
);
}
backfillDuplicateComments().catch(console.error);

102
.github/scripts/check-pre-release-mode.mjs vendored Executable file
View File

@@ -0,0 +1,102 @@
#!/usr/bin/env node
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Get context from command line argument or environment
const context = process.argv[2] || process.env.GITHUB_WORKFLOW || 'manual';
function findRootDir(startDir) {
let currentDir = resolve(startDir);
while (currentDir !== '/') {
if (existsSync(join(currentDir, 'package.json'))) {
try {
const pkg = JSON.parse(
readFileSync(join(currentDir, 'package.json'), 'utf8')
);
if (pkg.name === 'task-master-ai' || pkg.repository) {
return currentDir;
}
} catch {}
}
currentDir = dirname(currentDir);
}
throw new Error('Could not find root directory');
}
function checkPreReleaseMode() {
console.log('🔍 Checking if branch is in pre-release mode...');
const rootDir = findRootDir(__dirname);
const preJsonPath = join(rootDir, '.changeset', 'pre.json');
// Check if pre.json exists
if (!existsSync(preJsonPath)) {
console.log('✅ Not in active pre-release mode - safe to proceed');
process.exit(0);
}
try {
// Read and parse pre.json
const preJsonContent = readFileSync(preJsonPath, 'utf8');
const preJson = JSON.parse(preJsonContent);
// Check if we're in active pre-release mode
if (preJson.mode === 'pre') {
console.error('❌ ERROR: This branch is in active pre-release mode!');
console.error('');
// Provide context-specific error messages
if (context === 'Release Check' || context === 'pull_request') {
console.error(
'Pre-release mode must be exited before merging to main.'
);
console.error('');
console.error(
'To fix this, run the following commands in your branch:'
);
console.error(' npx changeset pre exit');
console.error(' git add -u');
console.error(' git commit -m "chore: exit pre-release mode"');
console.error(' git push');
console.error('');
console.error('Then update this pull request.');
} else if (context === 'Release' || context === 'main') {
console.error(
'Pre-release mode should only be used on feature branches, not main.'
);
console.error('');
console.error('To fix this, run the following commands locally:');
console.error(' npx changeset pre exit');
console.error(' git add -u');
console.error(' git commit -m "chore: exit pre-release mode"');
console.error(' git push origin main');
console.error('');
console.error('Then re-run this workflow.');
} else {
console.error('Pre-release mode must be exited before proceeding.');
console.error('');
console.error('To fix this, run the following commands:');
console.error(' npx changeset pre exit');
console.error(' git add -u');
console.error(' git commit -m "chore: exit pre-release mode"');
console.error(' git push');
}
process.exit(1);
}
console.log('✅ Not in active pre-release mode - safe to proceed');
process.exit(0);
} catch (error) {
console.error(`❌ ERROR: Unable to parse .changeset/pre.json aborting.`);
console.error(`Error details: ${error.message}`);
process.exit(1);
}
}
// Run the check
checkPreReleaseMode();

157
.github/scripts/parse-metrics.mjs vendored Normal file
View File

@@ -0,0 +1,157 @@
#!/usr/bin/env node
import { readFileSync, existsSync, writeFileSync } from 'fs';
function parseMetricsTable(content, metricName) {
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Match a markdown table row like: | Metric Name | value | ...
const safeName = metricName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`^\\|\\s*${safeName}\\s*\\|\\s*([^|]+)\\|?`);
const match = line.match(re);
if (match) {
return match[1].trim() || 'N/A';
}
}
return 'N/A';
}
function parseCountMetric(content, metricName) {
const result = parseMetricsTable(content, metricName);
// Extract number from string, handling commas and spaces
const numberMatch = result.toString().match(/[\d,]+/);
if (numberMatch) {
const number = parseInt(numberMatch[0].replace(/,/g, ''));
return isNaN(number) ? 0 : number;
}
return 0;
}
function main() {
const metrics = {
issues_created: 0,
issues_closed: 0,
prs_created: 0,
prs_merged: 0,
issue_avg_first_response: 'N/A',
issue_avg_time_to_close: 'N/A',
pr_avg_first_response: 'N/A',
pr_avg_merge_time: 'N/A'
};
// Parse issue metrics
if (existsSync('issue_metrics.md')) {
console.log('📄 Found issue_metrics.md, parsing...');
const issueContent = readFileSync('issue_metrics.md', 'utf8');
metrics.issues_created = parseCountMetric(
issueContent,
'Total number of items created'
);
metrics.issues_closed = parseCountMetric(
issueContent,
'Number of items closed'
);
metrics.issue_avg_first_response = parseMetricsTable(
issueContent,
'Time to first response'
);
metrics.issue_avg_time_to_close = parseMetricsTable(
issueContent,
'Time to close'
);
} else {
console.warn('[parse-metrics] issue_metrics.md not found; using defaults.');
}
// Parse PR created metrics
if (existsSync('pr_created_metrics.md')) {
console.log('📄 Found pr_created_metrics.md, parsing...');
const prCreatedContent = readFileSync('pr_created_metrics.md', 'utf8');
metrics.prs_created = parseCountMetric(
prCreatedContent,
'Total number of items created'
);
metrics.pr_avg_first_response = parseMetricsTable(
prCreatedContent,
'Time to first response'
);
} else {
console.warn(
'[parse-metrics] pr_created_metrics.md not found; using defaults.'
);
}
// Parse PR merged metrics (for more accurate merge data)
if (existsSync('pr_merged_metrics.md')) {
console.log('📄 Found pr_merged_metrics.md, parsing...');
const prMergedContent = readFileSync('pr_merged_metrics.md', 'utf8');
metrics.prs_merged = parseCountMetric(
prMergedContent,
'Total number of items created'
);
// For merged PRs, "Time to close" is actually time to merge
metrics.pr_avg_merge_time = parseMetricsTable(
prMergedContent,
'Time to close'
);
} else {
console.warn(
'[parse-metrics] pr_merged_metrics.md not found; falling back to pr_metrics.md.'
);
// Fallback: try old pr_metrics.md if it exists
if (existsSync('pr_metrics.md')) {
console.log('📄 Falling back to pr_metrics.md...');
const prContent = readFileSync('pr_metrics.md', 'utf8');
const mergedCount = parseCountMetric(prContent, 'Number of items merged');
metrics.prs_merged =
mergedCount || parseCountMetric(prContent, 'Number of items closed');
const maybeMergeTime = parseMetricsTable(
prContent,
'Average time to merge'
);
metrics.pr_avg_merge_time =
maybeMergeTime !== 'N/A'
? maybeMergeTime
: parseMetricsTable(prContent, 'Time to close');
} else {
console.warn('[parse-metrics] pr_metrics.md not found; using defaults.');
}
}
// Output for GitHub Actions
const output = Object.entries(metrics)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
// Always output to stdout for debugging
console.log('\n=== FINAL METRICS ===');
Object.entries(metrics).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Write to GITHUB_OUTPUT if in GitHub Actions
if (process.env.GITHUB_OUTPUT) {
try {
writeFileSync(process.env.GITHUB_OUTPUT, output + '\n', { flag: 'a' });
console.log(
`\nSuccessfully wrote metrics to ${process.env.GITHUB_OUTPUT}`
);
} catch (error) {
console.error(`Failed to write to GITHUB_OUTPUT: ${error.message}`);
process.exit(1);
}
} else {
console.log(
'\nNo GITHUB_OUTPUT environment variable found, skipping file write'
);
}
}
main();

30
.github/scripts/release.mjs vendored Executable file
View File

@@ -0,0 +1,30 @@
#!/usr/bin/env node
import { existsSync, unlinkSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { findRootDir, runCommand } from './utils.mjs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = findRootDir(__dirname);
console.log('🚀 Starting release process...');
// Double-check we're not in pre-release mode (safety net)
const preJsonPath = join(rootDir, '.changeset', 'pre.json');
if (existsSync(preJsonPath)) {
console.log('⚠️ Warning: pre.json still exists. Removing it...');
unlinkSync(preJsonPath);
}
// Check if the extension version has changed and tag it
// This prevents changeset from trying to publish the private package
runCommand('node', [join(__dirname, 'tag-extension.mjs')]);
// Run changeset publish for npm packages
runCommand('npx', ['changeset', 'publish']);
console.log('✅ Release process completed!');
// The extension tag (if created) will trigger the extension-release workflow

33
.github/scripts/tag-extension.mjs vendored Executable file
View File

@@ -0,0 +1,33 @@
#!/usr/bin/env node
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { findRootDir, createAndPushTag } from './utils.mjs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = findRootDir(__dirname);
// Read the extension's package.json
const extensionDir = join(rootDir, 'apps', 'extension');
const pkgPath = join(extensionDir, 'package.json');
let pkg;
try {
const pkgContent = readFileSync(pkgPath, 'utf8');
pkg = JSON.parse(pkgContent);
} catch (error) {
console.error('Failed to read package.json:', error.message);
process.exit(1);
}
// Ensure we have required fields
assert(pkg.name, 'package.json must have a name field');
assert(pkg.version, 'package.json must have a version field');
const tag = `${pkg.name}@${pkg.version}`;
// Create and push the tag if it doesn't exist
createAndPushTag(tag);

88
.github/scripts/utils.mjs vendored Executable file
View File

@@ -0,0 +1,88 @@
#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
// Find the root directory by looking for package.json with task-master-ai
export function findRootDir(startDir) {
let currentDir = resolve(startDir);
while (currentDir !== '/') {
const pkgPath = join(currentDir, 'package.json');
try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
if (pkg.name === 'task-master-ai' || pkg.repository) {
return currentDir;
}
} catch {}
currentDir = dirname(currentDir);
}
throw new Error('Could not find root directory');
}
// Run a command with proper error handling
export function runCommand(command, args = [], options = {}) {
console.log(`Running: ${command} ${args.join(' ')}`);
const result = spawnSync(command, args, {
encoding: 'utf8',
stdio: 'inherit',
...options
});
if (result.status !== 0) {
console.error(`Command failed with exit code ${result.status}`);
process.exit(result.status);
}
return result;
}
// Get package version from a package.json file
export function getPackageVersion(packagePath) {
try {
const pkg = JSON.parse(readFileSync(packagePath, 'utf8'));
return pkg.version;
} catch (error) {
console.error(
`Failed to read package version from ${packagePath}:`,
error.message
);
process.exit(1);
}
}
// Check if a git tag exists on remote
export function tagExistsOnRemote(tag, remote = 'origin') {
const result = spawnSync('git', ['ls-remote', remote, tag], {
encoding: 'utf8'
});
return result.status === 0 && result.stdout.trim() !== '';
}
// Create and push a git tag if it doesn't exist
export function createAndPushTag(tag, remote = 'origin') {
// Check if tag already exists
if (tagExistsOnRemote(tag, remote)) {
console.log(`Tag ${tag} already exists on remote, skipping`);
return false;
}
console.log(`Creating new tag: ${tag}`);
// Create the tag locally
const tagResult = spawnSync('git', ['tag', tag]);
if (tagResult.status !== 0) {
console.error('Failed to create tag:', tagResult.error || tagResult.stderr);
process.exit(1);
}
// Push the tag to remote
const pushResult = spawnSync('git', ['push', remote, tag]);
if (pushResult.status !== 0) {
console.error('Failed to push tag:', pushResult.error || pushResult.stderr);
process.exit(1);
}
console.log(`✅ Successfully created and pushed tag: ${tag}`);
return true;
}

View File

@@ -0,0 +1,31 @@
name: Auto-close duplicate issues
# description: Auto-closes issues that are duplicates of existing issues
on:
schedule:
- cron: "0 9 * * *" # Runs daily at 9 AM UTC
workflow_dispatch:
jobs:
auto-close-duplicates:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write # Need write permission to close issues and add comments
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Auto-close duplicate issues
run: node .github/scripts/auto-close-duplicates.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_REPOSITORY_OWNER: ${{ github.repository_owner }}
GITHUB_REPOSITORY_NAME: ${{ github.event.repository.name }}

View File

@@ -0,0 +1,46 @@
name: Backfill Duplicate Comments
# description: Triggers duplicate detection for old issues that don't have duplicate comments
on:
workflow_dispatch:
inputs:
days_back:
description: "How many days back to look for old issues"
required: false
default: "90"
type: string
dry_run:
description: "Dry run mode (true to only log what would be done)"
required: false
default: "true"
type: choice
options:
- "true"
- "false"
jobs:
backfill-duplicate-comments:
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
issues: read
actions: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Backfill duplicate comments
run: node .github/scripts/backfill-duplicate-comments.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_REPOSITORY_OWNER: ${{ github.repository_owner }}
GITHUB_REPOSITORY_NAME: ${{ github.event.repository.name }}
DAYS_BACK: ${{ inputs.days_back }}
DRY_RUN: ${{ inputs.dry_run }}

View File

@@ -6,73 +6,124 @@ on:
- main
- next
pull_request:
branches:
- main
- next
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
DO_NOT_TRACK: 1
NODE_ENV: development
jobs:
setup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install Dependencies
id: install
run: npm ci
timeout-minutes: 2
- name: Cache node_modules
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
# Fast checks that can run in parallel
format-check:
needs: setup
name: Format Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Restore node_modules
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
- name: Install dependencies
run: npm install --frozen-lockfile --prefer-offline
timeout-minutes: 5
- name: Format Check
run: npm run format-check
env:
FORCE_COLOR: 1
test:
needs: setup
typecheck:
name: Typecheck
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Restore node_modules
uses: actions/cache@v4
- name: Install dependencies
run: npm install --frozen-lockfile --prefer-offline
timeout-minutes: 5
- name: Typecheck
run: npm run turbo:typecheck
env:
FORCE_COLOR: 1
# Build job to ensure everything compiles
build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
path: node_modules
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
fetch-depth: 2
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Install dependencies
run: npm install --frozen-lockfile --prefer-offline
timeout-minutes: 5
- name: Build
run: npm run turbo:build
env:
NODE_ENV: production
FORCE_COLOR: 1
TM_PUBLIC_BASE_DOMAIN: ${{ secrets.TM_PUBLIC_BASE_DOMAIN }}
TM_PUBLIC_SUPABASE_URL: ${{ secrets.TM_PUBLIC_SUPABASE_URL }}
TM_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.TM_PUBLIC_SUPABASE_ANON_KEY }}
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: build-artifacts
path: dist/
retention-days: 1
test:
name: Test
timeout-minutes: 15
runs-on: ubuntu-latest
needs: [format-check, typecheck, build]
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Install dependencies
run: npm install --frozen-lockfile --prefer-offline
timeout-minutes: 5
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: build-artifacts
path: dist/
- name: Run Tests
run: |
@@ -81,7 +132,6 @@ jobs:
NODE_ENV: test
CI: true
FORCE_COLOR: 1
timeout-minutes: 10
- name: Upload Test Results
if: always()

View File

@@ -0,0 +1,81 @@
name: Claude Issue Dedupe
# description: Automatically dedupe GitHub issues using Claude Code
on:
issues:
types: [opened]
workflow_dispatch:
inputs:
issue_number:
description: "Issue number to process for duplicate detection"
required: true
type: string
jobs:
claude-dedupe-issues:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run Claude Code slash command
uses: anthropics/claude-code-base-action@beta
with:
prompt: "/dedupe ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_env: |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Log duplicate comment event to Statsig
if: always()
env:
STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
run: |
ISSUE_NUMBER=${{ github.event.issue.number || inputs.issue_number }}
REPO=${{ github.repository }}
if [ -z "$STATSIG_API_KEY" ]; then
echo "STATSIG_API_KEY not found, skipping Statsig logging"
exit 0
fi
# Prepare the event payload
EVENT_PAYLOAD=$(jq -n \
--arg issue_number "$ISSUE_NUMBER" \
--arg repo "$REPO" \
--arg triggered_by "${{ github.event_name }}" \
'{
events: [{
eventName: "github_duplicate_comment_added",
value: 1,
metadata: {
repository: $repo,
issue_number: ($issue_number | tonumber),
triggered_by: $triggered_by,
workflow_run_id: "${{ github.run_id }}"
},
time: (now | floor | tostring)
}]
}')
# Send to Statsig API
echo "Logging duplicate comment event to Statsig for issue #${ISSUE_NUMBER}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
-H "Content-Type: application/json" \
-H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
-d "$EVENT_PAYLOAD")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)
if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
echo "Successfully logged duplicate comment event for issue #${ISSUE_NUMBER}"
else
echo "Failed to log duplicate comment event for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
fi

View File

@@ -0,0 +1,57 @@
name: Trigger Claude Documentation Update
on:
push:
branches:
- next
paths-ignore:
- "apps/docs/**"
- "*.md"
- ".github/workflows/**"
jobs:
trigger-docs-update:
# Only run if changes were merged (not direct pushes from bots)
if: github.actor != 'github-actions[bot]' && github.actor != 'dependabot[bot]'
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 2 # Need previous commit for comparison
- name: Get changed files
id: changed-files
run: |
echo "Changed files in this push:"
git diff --name-only HEAD^ HEAD | tee changed_files.txt
# Store changed files for Claude to analyze (escaped for JSON)
CHANGED_FILES=$(git diff --name-only HEAD^ HEAD | jq -Rs .)
echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT
# Get the commit message (escaped for JSON)
COMMIT_MSG=$(git log -1 --pretty=%B | jq -Rs .)
echo "commit_message=$COMMIT_MSG" >> $GITHUB_OUTPUT
# Get diff for documentation context (escaped for JSON)
COMMIT_DIFF=$(git diff HEAD^ HEAD --stat | jq -Rs .)
echo "commit_diff=$COMMIT_DIFF" >> $GITHUB_OUTPUT
# Get commit SHA
echo "commit_sha=${{ github.sha }}" >> $GITHUB_OUTPUT
- name: Trigger Claude workflow
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Trigger the Claude docs updater workflow with the change information
gh workflow run claude-docs-updater.yml \
--ref next \
-f commit_sha="${{ steps.changed-files.outputs.commit_sha }}" \
-f commit_message=${{ steps.changed-files.outputs.commit_message }} \
-f changed_files=${{ steps.changed-files.outputs.changed_files }} \
-f commit_diff=${{ steps.changed-files.outputs.commit_diff }}

View File

@@ -0,0 +1,145 @@
name: Claude Documentation Updater
on:
workflow_dispatch:
inputs:
commit_sha:
description: 'The commit SHA that triggered this update'
required: true
type: string
commit_message:
description: 'The commit message'
required: true
type: string
changed_files:
description: 'List of changed files'
required: true
type: string
commit_diff:
description: 'Diff summary of changes'
required: true
type: string
jobs:
update-docs:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: next
fetch-depth: 0 # Need full history to checkout specific commit
- name: Create docs update branch
id: create-branch
run: |
BRANCH_NAME="docs/auto-update-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
- name: Run Claude Code to Update Documentation
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
timeout_minutes: "30"
mode: "agent"
github_token: ${{ secrets.GITHUB_TOKEN }}
experimental_allowed_domains: |
.anthropic.com
.github.com
api.github.com
.githubusercontent.com
registry.npmjs.org
.task-master.dev
base_branch: "next"
direct_prompt: |
You are a documentation specialist. Analyze the recent changes pushed to the 'next' branch and update the documentation accordingly.
Recent changes:
- Commit: ${{ inputs.commit_message }}
- Changed files:
${{ inputs.changed_files }}
- Changes summary:
${{ inputs.commit_diff }}
Your task:
1. Analyze the changes to understand what functionality was added, modified, or removed
2. Check if these changes require documentation updates in apps/docs/
3. If documentation updates are needed:
- Update relevant documentation files in apps/docs/
- Ensure examples are updated if APIs changed
- Update any configuration documentation if config options changed
- Add new documentation pages if new features were added
- Update the changelog or release notes if applicable
4. If no documentation updates are needed, skip creating changes
Guidelines:
- Focus only on user-facing changes that need documentation
- Keep documentation clear, concise, and helpful
- Include code examples where appropriate
- Maintain consistent documentation style with existing docs
- Don't document internal implementation details unless they affect users
- Update navigation/menu files if new pages are added
Only make changes if the documentation truly needs updating based on the code changes.
- name: Check if changes were made
id: check-changes
run: |
if git diff --quiet; then
echo "has_changes=false" >> $GITHUB_OUTPUT
else
echo "has_changes=true" >> $GITHUB_OUTPUT
git add -A
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "docs: auto-update documentation based on changes in next branch
This PR was automatically generated to update documentation based on recent changes.
Original commit: ${{ inputs.commit_message }}
Co-authored-by: Claude <claude-assistant@anthropic.com>"
fi
- name: Push changes and create PR
if: steps.check-changes.outputs.has_changes == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git push origin ${{ steps.create-branch.outputs.branch_name }}
# Create PR using GitHub CLI
gh pr create \
--title "docs: update documentation for recent changes" \
--body "## 📚 Documentation Update
This PR automatically updates documentation based on recent changes merged to the \`next\` branch.
### Original Changes
**Commit:** ${{ inputs.commit_sha }}
**Message:** ${{ inputs.commit_message }}
### Changed Files in Original Commit
\`\`\`
${{ inputs.changed_files }}
\`\`\`
### Documentation Updates
This PR includes documentation updates to reflect the changes above. Please review to ensure:
- [ ] Documentation accurately reflects the changes
- [ ] Examples are correct and working
- [ ] No important details are missing
- [ ] Style is consistent with existing documentation
---
*This PR was automatically generated by Claude Code GitHub Action*" \
--base next \
--head ${{ steps.create-branch.outputs.branch_name }} \
--label "documentation" \
--label "automated"

View File

@@ -0,0 +1,107 @@
name: Claude Issue Triage
# description: Automatically triage GitHub issues using Claude Code
on:
issues:
types: [opened]
jobs:
triage-issue:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Create triage prompt
run: |
mkdir -p /tmp/claude-prompts
cat > /tmp/claude-prompts/triage-prompt.txt << 'EOF'
You're an issue triage assistant for GitHub issues. Your task is to analyze the issue and select appropriate labels from the provided list.
IMPORTANT: Don't post any comments or messages to the issue. Your only action should be to apply labels.
Issue Information:
- REPO: ${{ github.repository }}
- ISSUE_NUMBER: ${{ github.event.issue.number }}
TASK OVERVIEW:
1. First, fetch the list of labels available in this repository by running: `gh label list`. Run exactly this command with nothing else.
2. Next, use the GitHub tools to get context about the issue:
- You have access to these tools:
- mcp__github__get_issue: Use this to retrieve the current issue's details including title, description, and existing labels
- mcp__github__get_issue_comments: Use this to read any discussion or additional context provided in the comments
- mcp__github__update_issue: Use this to apply labels to the issue (do not use this for commenting)
- mcp__github__search_issues: Use this to find similar issues that might provide context for proper categorization and to identify potential duplicate issues
- mcp__github__list_issues: Use this to understand patterns in how other issues are labeled
- Start by using mcp__github__get_issue to get the issue details
3. Analyze the issue content, considering:
- The issue title and description
- The type of issue (bug report, feature request, question, etc.)
- Technical areas mentioned
- Severity or priority indicators
- User impact
- Components affected
4. Select appropriate labels from the available labels list provided above:
- Choose labels that accurately reflect the issue's nature
- Be specific but comprehensive
- Select priority labels if you can determine urgency (high-priority, med-priority, or low-priority)
- Consider platform labels (android, ios) if applicable
- If you find similar issues using mcp__github__search_issues, consider using a "duplicate" label if appropriate. Only do so if the issue is a duplicate of another OPEN issue.
5. Apply the selected labels:
- Use mcp__github__update_issue to apply your selected labels
- DO NOT post any comments explaining your decision
- DO NOT communicate directly with users
- If no labels are clearly applicable, do not apply any labels
IMPORTANT GUIDELINES:
- Be thorough in your analysis
- Only select labels from the provided list above
- DO NOT post any comments to the issue
- Your ONLY action should be to apply labels using mcp__github__update_issue
- It's okay to not add any labels if none are clearly applicable
EOF
- name: Setup GitHub MCP Server
run: |
mkdir -p /tmp/mcp-config
cat > /tmp/mcp-config/mcp-servers.json << 'EOF'
{
"mcpServers": {
"github": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-7aced2b"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
}
}
}
}
EOF
- name: Run Claude Code for Issue Triage
uses: anthropics/claude-code-base-action@beta
with:
prompt_file: /tmp/claude-prompts/triage-prompt.txt
allowed_tools: "Bash(gh label list),mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__update_issue,mcp__github__search_issues,mcp__github__list_issues"
timeout_minutes: "5"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
mcp_config: /tmp/mcp-config/mcp-servers.json
claude_env: |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

36
.github/workflows/claude.yml vendored Normal file
View File

@@ -0,0 +1,36 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

140
.github/workflows/extension-ci.yml vendored Normal file
View File

@@ -0,0 +1,140 @@
name: Extension CI
on:
push:
branches:
- main
- next
paths:
- 'apps/extension/**'
- '.github/workflows/extension-ci.yml'
pull_request:
branches:
- main
- next
paths:
- 'apps/extension/**'
- '.github/workflows/extension-ci.yml'
permissions:
contents: read
jobs:
setup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install Monorepo Dependencies
run: npm ci
timeout-minutes: 5
typecheck:
needs: setup
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Restore node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install if cache miss
run: npm ci
timeout-minutes: 3
- name: Type Check Extension
working-directory: apps/extension
run: npm run check-types
env:
FORCE_COLOR: 1
build:
needs: setup
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Restore node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install if cache miss
run: npm ci
timeout-minutes: 3
- name: Build Extension
working-directory: apps/extension
run: npm run build
env:
FORCE_COLOR: 1
- name: Package Extension
working-directory: apps/extension
run: npm run package
env:
FORCE_COLOR: 1
- name: Verify Package Contents
working-directory: apps/extension
run: |
echo "Checking vsix-build contents..."
ls -la vsix-build/
echo "Checking dist contents..."
ls -la vsix-build/dist/
echo "Checking package.json exists..."
test -f vsix-build/package.json
- name: Create VSIX Package (Test)
working-directory: apps/extension/vsix-build
run: npx vsce package --no-dependencies
env:
FORCE_COLOR: 1
- name: Upload Extension Artifact
uses: actions/upload-artifact@v4
with:
name: extension-package
path: |
apps/extension/vsix-build/*.vsix
apps/extension/dist/
retention-days: 30

110
.github/workflows/extension-release.yml vendored Normal file
View File

@@ -0,0 +1,110 @@
name: Extension Release
on:
push:
tags:
- "extension@*"
permissions:
contents: write
concurrency: extension-release-${{ github.ref }}
jobs:
publish-extension:
runs-on: ubuntu-latest
environment: extension-release
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install Monorepo Dependencies
run: npm ci
timeout-minutes: 5
- name: Type Check Extension
working-directory: apps/extension
run: npm run check-types
env:
FORCE_COLOR: 1
- name: Build Extension
working-directory: apps/extension
run: npm run build
env:
FORCE_COLOR: 1
- name: Package Extension
working-directory: apps/extension
run: npm run package
env:
FORCE_COLOR: 1
- name: Create VSIX Package
working-directory: apps/extension/vsix-build
run: npx vsce package --no-dependencies
env:
FORCE_COLOR: 1
- name: Get VSIX filename
id: vsix-info
working-directory: apps/extension/vsix-build
run: |
VSIX_FILE=$(find . -maxdepth 1 -name "*.vsix" -type f | head -n1 | xargs basename)
if [ -z "$VSIX_FILE" ]; then
echo "Error: No VSIX file found"
exit 1
fi
echo "vsix-filename=$VSIX_FILE" >> "$GITHUB_OUTPUT"
echo "Found VSIX: $VSIX_FILE"
- name: Publish to VS Code Marketplace
working-directory: apps/extension/vsix-build
run: npx vsce publish --packagePath "${{ steps.vsix-info.outputs.vsix-filename }}"
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
FORCE_COLOR: 1
- name: Install Open VSX CLI
run: npm install -g ovsx
- name: Publish to Open VSX Registry
working-directory: apps/extension/vsix-build
run: ovsx publish "${{ steps.vsix-info.outputs.vsix-filename }}"
env:
OVSX_PAT: ${{ secrets.OVSX_PAT }}
FORCE_COLOR: 1
- name: Upload Build Artifacts
uses: actions/upload-artifact@v4
with:
name: extension-release-${{ github.ref_name }}
path: |
apps/extension/vsix-build/*.vsix
apps/extension/dist/
retention-days: 90
notify-success:
needs: publish-extension
if: success()
runs-on: ubuntu-latest
steps:
- name: Success Notification
run: |
echo "🎉 Extension ${{ github.ref_name }} successfully published!"
echo "📦 Available on VS Code Marketplace"
echo "🌍 Available on Open VSX Registry"
echo "🏷️ GitHub release created: ${{ github.ref_name }}"

176
.github/workflows/log-issue-events.yml vendored Normal file
View File

@@ -0,0 +1,176 @@
name: Log GitHub Issue Events
on:
issues:
types: [opened, closed]
jobs:
log-issue-created:
if: github.event.action == 'opened'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: read
steps:
- name: Log issue creation to Statsig
env:
STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
run: |
ISSUE_NUMBER=${{ github.event.issue.number }}
REPO=${{ github.repository }}
ISSUE_TITLE=$(echo '${{ github.event.issue.title }}' | sed "s/'/'\\\\''/g")
AUTHOR="${{ github.event.issue.user.login }}"
CREATED_AT="${{ github.event.issue.created_at }}"
if [ -z "$STATSIG_API_KEY" ]; then
echo "STATSIG_API_KEY not found, skipping Statsig logging"
exit 0
fi
# Prepare the event payload
EVENT_PAYLOAD=$(jq -n \
--arg issue_number "$ISSUE_NUMBER" \
--arg repo "$REPO" \
--arg title "$ISSUE_TITLE" \
--arg author "$AUTHOR" \
--arg created_at "$CREATED_AT" \
'{
events: [{
eventName: "github_issue_created",
value: 1,
metadata: {
repository: $repo,
issue_number: ($issue_number | tonumber),
issue_title: $title,
issue_author: $author,
created_at: $created_at
},
time: (now | floor | tostring)
}]
}')
# Send to Statsig API
echo "Logging issue creation to Statsig for issue #${ISSUE_NUMBER}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
-H "Content-Type: application/json" \
-H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
-d "$EVENT_PAYLOAD")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)
if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
echo "Successfully logged issue creation for issue #${ISSUE_NUMBER}"
else
echo "Failed to log issue creation for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
fi
log-issue-closed:
if: github.event.action == 'closed'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: read
steps:
- name: Log issue closure to Statsig
env:
STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ISSUE_NUMBER=${{ github.event.issue.number }}
REPO=${{ github.repository }}
ISSUE_TITLE=$(echo '${{ github.event.issue.title }}' | sed "s/'/'\\\\''/g")
CLOSED_BY="${{ github.event.issue.closed_by.login }}"
CLOSED_AT="${{ github.event.issue.closed_at }}"
STATE_REASON="${{ github.event.issue.state_reason }}"
if [ -z "$STATSIG_API_KEY" ]; then
echo "STATSIG_API_KEY not found, skipping Statsig logging"
exit 0
fi
# Get additional issue data via GitHub API
echo "Fetching additional issue data for #${ISSUE_NUMBER}"
ISSUE_DATA=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${REPO}/issues/${ISSUE_NUMBER}")
COMMENTS_COUNT=$(echo "$ISSUE_DATA" | jq -r '.comments')
# Get reactions data
REACTIONS_DATA=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${REPO}/issues/${ISSUE_NUMBER}/reactions")
REACTIONS_COUNT=$(echo "$REACTIONS_DATA" | jq '. | length')
# Check if issue was closed automatically (by checking if closed_by is a bot)
CLOSED_AUTOMATICALLY="false"
if [[ "$CLOSED_BY" == *"[bot]"* ]]; then
CLOSED_AUTOMATICALLY="true"
fi
# Check if closed as duplicate by state_reason
CLOSED_AS_DUPLICATE="false"
if [ "$STATE_REASON" = "duplicate" ]; then
CLOSED_AS_DUPLICATE="true"
fi
# Prepare the event payload
EVENT_PAYLOAD=$(jq -n \
--arg issue_number "$ISSUE_NUMBER" \
--arg repo "$REPO" \
--arg title "$ISSUE_TITLE" \
--arg closed_by "$CLOSED_BY" \
--arg closed_at "$CLOSED_AT" \
--arg state_reason "$STATE_REASON" \
--arg comments_count "$COMMENTS_COUNT" \
--arg reactions_count "$REACTIONS_COUNT" \
--arg closed_automatically "$CLOSED_AUTOMATICALLY" \
--arg closed_as_duplicate "$CLOSED_AS_DUPLICATE" \
'{
events: [{
eventName: "github_issue_closed",
value: 1,
metadata: {
repository: $repo,
issue_number: ($issue_number | tonumber),
issue_title: $title,
closed_by: $closed_by,
closed_at: $closed_at,
state_reason: $state_reason,
comments_count: ($comments_count | tonumber),
reactions_count: ($reactions_count | tonumber),
closed_automatically: ($closed_automatically | test("true")),
closed_as_duplicate: ($closed_as_duplicate | test("true"))
},
time: (now | floor | tostring)
}]
}')
# Send to Statsig API
echo "Logging issue closure to Statsig for issue #${ISSUE_NUMBER}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
-H "Content-Type: application/json" \
-H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
-d "$EVENT_PAYLOAD")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)
if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
echo "Successfully logged issue closure for issue #${ISSUE_NUMBER}"
echo "Closed by: $CLOSED_BY"
echo "Comments: $COMMENTS_COUNT"
echo "Reactions: $REACTIONS_COUNT"
echo "Closed automatically: $CLOSED_AUTOMATICALLY"
echo "Closed as duplicate: $CLOSED_AS_DUPLICATE"
else
echo "Failed to log issue closure for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
fi

95
.github/workflows/pre-release.yml vendored Normal file
View File

@@ -0,0 +1,95 @@
name: Pre-Release (RC)
on:
workflow_dispatch: # Allows manual triggering from GitHub UI/API
concurrency: pre-release-${{ github.ref_name }}
jobs:
rc:
runs-on: ubuntu-latest
# Only allow pre-releases on non-main branches
if: github.ref != 'refs/heads/main'
environment: extension-release
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
timeout-minutes: 2
- name: Enter RC mode (if not already in RC mode)
run: |
# Check if we're in pre-release mode with the "rc" tag
if [ -f .changeset/pre.json ]; then
MODE=$(jq -r '.mode' .changeset/pre.json 2>/dev/null || echo '')
TAG=$(jq -r '.tag' .changeset/pre.json 2>/dev/null || echo '')
if [ "$MODE" = "exit" ]; then
echo "Pre-release mode is in 'exit' state, re-entering RC mode..."
npx changeset pre enter rc
elif [ "$MODE" = "pre" ] && [ "$TAG" != "rc" ]; then
echo "In pre-release mode but with wrong tag ($TAG), switching to RC..."
npx changeset pre exit
npx changeset pre enter rc
elif [ "$MODE" = "pre" ] && [ "$TAG" = "rc" ]; then
echo "Already in RC pre-release mode"
else
echo "Unknown mode state: $MODE, entering RC mode..."
npx changeset pre enter rc
fi
else
echo "No pre.json found, entering RC mode..."
npx changeset pre enter rc
fi
- name: Version RC packages
run: npx changeset version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Run format
run: npm run format
env:
FORCE_COLOR: 1
- name: Build packages
run: npm run turbo:build
env:
NODE_ENV: production
FORCE_COLOR: 1
TM_PUBLIC_BASE_DOMAIN: ${{ secrets.TM_PUBLIC_BASE_DOMAIN }}
TM_PUBLIC_SUPABASE_URL: ${{ secrets.TM_PUBLIC_SUPABASE_URL }}
TM_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.TM_PUBLIC_SUPABASE_ANON_KEY }}
- name: Create Release Candidate Pull Request or Publish Release Candidate to npm
uses: changesets/action@v1
with:
publish: npx changeset publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Commit & Push changes
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
message: "chore: rc version bump"

21
.github/workflows/release-check.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Release Check
on:
pull_request:
branches:
- main
concurrency:
group: release-check-${{ github.head_ref }}
cancel-in-progress: true
jobs:
check-release-mode:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check release mode
run: node ./.github/scripts/check-pre-release-mode.mjs "pull_request"

View File

@@ -3,6 +3,14 @@ on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
permissions:
contents: write
pull-requests: write
id-token: write
jobs:
release:
runs-on: ubuntu-latest
@@ -14,7 +22,7 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
cache: "npm"
- name: Cache node_modules
uses: actions/cache@v4
@@ -30,10 +38,22 @@ jobs:
run: npm ci
timeout-minutes: 2
- name: Check pre-release mode
run: node ./.github/scripts/check-pre-release-mode.mjs "main"
- name: Build packages
run: npm run turbo:build
env:
NODE_ENV: production
FORCE_COLOR: 1
TM_PUBLIC_BASE_DOMAIN: ${{ secrets.TM_PUBLIC_BASE_DOMAIN }}
TM_PUBLIC_SUPABASE_URL: ${{ secrets.TM_PUBLIC_SUPABASE_URL }}
TM_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.TM_PUBLIC_SUPABASE_ANON_KEY }}
- name: Create Release Pull Request or Publish to npm
uses: changesets/action@v1
with:
publish: npm run release
publish: node ./.github/scripts/release.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

40
.github/workflows/update-models-md.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Update models.md from supported-models.json
on:
push:
branches:
- main
- next
paths:
- 'scripts/modules/supported-models.json'
- 'docs/scripts/models-json-to-markdown.js'
jobs:
update_markdown:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run transformation script
run: node docs/scripts/models-json-to-markdown.js
- name: Format Markdown with Prettier
run: npx prettier --write docs/models.md
- name: Stage docs/models.md
run: git add docs/models.md
- name: Commit & Push docs/models.md
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref_name }}
message: 'docs: Auto-update and format models.md'
author_name: 'github-actions[bot]'
author_email: 'github-actions[bot]@users.noreply.github.com'

View File

@@ -0,0 +1,108 @@
name: Weekly Metrics to Discord
# description: Sends weekly metrics summary to Discord channel
on:
schedule:
- cron: "0 9 * * 1" # Every Monday at 9 AM
workflow_dispatch:
permissions:
contents: read
issues: read
pull-requests: read
jobs:
weekly-metrics:
runs-on: ubuntu-latest
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_METRICS_WEBHOOK }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Get dates for last 14 days
run: |
set -Eeuo pipefail
# Last 14 days
first_day=$(date -d "14 days ago" +%Y-%m-%d)
last_day=$(date +%Y-%m-%d)
echo "first_day=$first_day" >> $GITHUB_ENV
echo "last_day=$last_day" >> $GITHUB_ENV
echo "week_of=$(date -d '7 days ago' +'Week of %B %d, %Y')" >> $GITHUB_ENV
echo "date_range=Past 14 days ($first_day to $last_day)" >> $GITHUB_ENV
- name: Generate issue metrics
uses: github/issue-metrics@v3
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SEARCH_QUERY: "repo:${{ github.repository }} is:issue created:${{ env.first_day }}..${{ env.last_day }}"
HIDE_TIME_TO_ANSWER: true
HIDE_LABEL_METRICS: false
OUTPUT_FILE: issue_metrics.md
- name: Generate PR created metrics
uses: github/issue-metrics@v3
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SEARCH_QUERY: "repo:${{ github.repository }} is:pr created:${{ env.first_day }}..${{ env.last_day }}"
OUTPUT_FILE: pr_created_metrics.md
- name: Generate PR merged metrics
uses: github/issue-metrics@v3
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SEARCH_QUERY: "repo:${{ github.repository }} is:pr is:merged merged:${{ env.first_day }}..${{ env.last_day }}"
OUTPUT_FILE: pr_merged_metrics.md
- name: Debug generated metrics
run: |
set -Eeuo pipefail
echo "Listing markdown files in workspace:"
ls -la *.md || true
for f in issue_metrics.md pr_created_metrics.md pr_merged_metrics.md; do
if [ -f "$f" ]; then
echo "== $f (first 10 lines) =="
head -n 10 "$f"
else
echo "Missing $f"
fi
done
- name: Parse metrics
id: metrics
run: node .github/scripts/parse-metrics.mjs
- name: Send to Discord
uses: sarisia/actions-status-discord@v1
if: env.DISCORD_WEBHOOK != ''
with:
webhook: ${{ env.DISCORD_WEBHOOK }}
status: Success
title: "📊 Weekly Metrics Report"
description: |
**${{ env.week_of }}**
*${{ env.date_range }}*
**🎯 Issues**
• Created: ${{ steps.metrics.outputs.issues_created }}
• Closed: ${{ steps.metrics.outputs.issues_closed }}
• Avg Response Time: ${{ steps.metrics.outputs.issue_avg_first_response }}
• Avg Time to Close: ${{ steps.metrics.outputs.issue_avg_time_to_close }}
**🔀 Pull Requests**
• Created: ${{ steps.metrics.outputs.prs_created }}
• Merged: ${{ steps.metrics.outputs.prs_merged }}
• Avg Response Time: ${{ steps.metrics.outputs.pr_avg_first_response }}
• Avg Time to Merge: ${{ steps.metrics.outputs.pr_avg_merge_time }}
**📈 Visual Analytics**
https://repobeats.axiom.co/api/embed/b439f28f0ab5bd7a2da19505355693cd2c55bfd4.svg
color: 0x58AFFF
username: Task Master Metrics Bot
avatar_url: https://raw.githubusercontent.com/eyaltoledano/claude-task-master/main/images/logo.png

42
.gitignore vendored
View File

@@ -21,9 +21,24 @@ yarn-error.log*
lerna-debug.log*
# Coverage directory used by tools like istanbul
coverage
coverage/
*.lcov
# Jest cache
.jest/
# Test temporary files and directories
tests/temp/
tests/e2e/_runs/
tests/e2e/log/
tests/**/*.log
tests/**/coverage/
# Test database files (if any)
tests/**/*.db
tests/**/*.sqlite
tests/**/*.sqlite3
# Optional npm cache directory
.npm
@@ -58,4 +73,27 @@ dist
# Debug files
*.debug
init-debug.log
dev-debug.log
dev-debug.log
# NPMRC
.npmrc
# Added by Task Master AI
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# VS Code extension test files
.vscode-test/
apps/extension/.vscode-test/
# apps/extension
apps/extension/vsix-build/
# turbo
.turbo

View File

@@ -0,0 +1,23 @@
{
"enabled": true,
"name": "[TM] Code Change Task Tracker",
"description": "Track implementation progress by monitoring code changes",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
"**/*.{js,ts,jsx,tsx,py,go,rs,java,cpp,c,h,hpp,cs,rb,php,swift,kt,scala,clj}",
"!**/node_modules/**",
"!**/vendor/**",
"!**/.git/**",
"!**/build/**",
"!**/dist/**",
"!**/target/**",
"!**/__pycache__/**"
]
},
"then": {
"type": "askAgent",
"prompt": "I just saved a source code file. Please:\n\n1. Check what task is currently 'in-progress' using 'tm list --status=in-progress'\n2. Look at the file I saved and summarize what was changed (considering the programming language and context)\n3. Update the task's notes with: 'tm update-subtask --id=<task_id> --prompt=\"Implemented: <summary_of_changes> in <file_path>\"'\n4. If the changes seem to complete the task based on its description, ask if I want to mark it as done"
}
}

View File

@@ -0,0 +1,16 @@
{
"enabled": false,
"name": "[TM] Complexity Analyzer",
"description": "Analyze task complexity when new tasks are added",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
".taskmaster/tasks/tasks.json"
]
},
"then": {
"type": "askAgent",
"prompt": "New tasks were added to tasks.json. For each new task:\n\n1. Run 'tm analyze-complexity --id=<task_id>'\n2. If complexity score is > 7, automatically expand it: 'tm expand --id=<task_id> --num=5'\n3. Show the complexity analysis results\n4. Suggest task dependencies based on the expanded subtasks"
}
}

View File

@@ -0,0 +1,13 @@
{
"enabled": true,
"name": "[TM] Daily Standup Assistant",
"description": "Morning workflow summary and task selection",
"version": "1",
"when": {
"type": "userTriggered"
},
"then": {
"type": "askAgent",
"prompt": "Good morning! Please provide my daily standup summary:\n\n1. Run 'tm list --status=done' and show tasks completed in the last 24 hours\n2. Run 'tm list --status=in-progress' to show current work\n3. Run 'tm next' to suggest the highest priority task to start\n4. Show the dependency graph for upcoming work\n5. Ask which task I'd like to focus on today"
}
}

View File

@@ -0,0 +1,13 @@
{
"enabled": true,
"name": "[TM] Git Commit Task Linker",
"description": "Link commits to tasks for traceability",
"version": "1",
"when": {
"type": "manual"
},
"then": {
"type": "askAgent",
"prompt": "I'm about to commit code. Please:\n\n1. Run 'git diff --staged' to see what's being committed\n2. Analyze the changes and suggest which tasks they relate to\n3. Generate a commit message in format: 'feat(task-<id>): <description>'\n4. Update the relevant tasks with a note about this commit\n5. Show the proposed commit message for approval"
}
}

View File

@@ -0,0 +1,13 @@
{
"enabled": true,
"name": "[TM] PR Readiness Checker",
"description": "Validate tasks before creating a pull request",
"version": "1",
"when": {
"type": "manual"
},
"then": {
"type": "askAgent",
"prompt": "I'm about to create a PR. Please:\n\n1. List all tasks marked as 'done' in this branch\n2. For each done task, verify:\n - All subtasks are also done\n - Test files exist for new functionality\n - No TODO comments remain related to the task\n3. Generate a PR description listing completed tasks\n4. Suggest a PR title based on the main tasks completed"
}
}

View File

@@ -0,0 +1,17 @@
{
"enabled": true,
"name": "[TM] Task Dependency Auto-Progression",
"description": "Automatically progress tasks when dependencies are completed",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
".taskmaster/tasks/tasks.json",
".taskmaster/tasks/*.json"
]
},
"then": {
"type": "askAgent",
"prompt": "Check the tasks.json file for any tasks that just changed status to 'done'. For each completed task:\n\n1. Find all tasks that depend on it\n2. Check if those dependent tasks now have all their dependencies satisfied\n3. If a task has all dependencies met and is still 'pending', use the command 'tm set-status --id=<task_id> --status=in-progress' to start it\n4. Show me which tasks were auto-started and why"
}
}

View File

@@ -0,0 +1,23 @@
{
"enabled": true,
"name": "[TM] Test Success Task Completer",
"description": "Mark tasks as done when their tests pass",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
"**/*test*.{js,ts,jsx,tsx,py,go,java,rb,php,rs,cpp,cs}",
"**/*spec*.{js,ts,jsx,tsx,rb}",
"**/test_*.py",
"**/*_test.go",
"**/*Test.java",
"**/*Tests.cs",
"!**/node_modules/**",
"!**/vendor/**"
]
},
"then": {
"type": "askAgent",
"prompt": "A test file was just saved. Please:\n\n1. Identify the test framework/language and run the appropriate test command for this file (npm test, pytest, go test, cargo test, dotnet test, mvn test, etc.)\n2. If all tests pass, check which tasks mention this functionality\n3. For any matching tasks that are 'in-progress', ask if the passing tests mean the task is complete\n4. If confirmed, mark the task as done with 'tm set-status --id=<task_id> --status=done'"
}
}

19
.kiro/settings/mcp.json Normal file
View File

@@ -0,0 +1,19 @@
{
"mcpServers": {
"task-master-ai": {
"command": "npx",
"args": ["-y", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE",
"GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE",
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
}
}
}
}

View File

@@ -0,0 +1,422 @@
---
inclusion: always
---
# Taskmaster Development Workflow
This guide outlines the standard process for using Taskmaster to manage software development projects. It is written as a set of instructions for you, the AI agent.
- **Your Default Stance**: For most projects, the user can work directly within the `master` task context. Your initial actions should operate on this default context unless a clear pattern for multi-context work emerges.
- **Your Goal**: Your role is to elevate the user's workflow by intelligently introducing advanced features like **Tagged Task Lists** when you detect the appropriate context. Do not force tags on the user; suggest them as a helpful solution to a specific need.
## The Basic Loop
The fundamental development cycle you will facilitate is:
1. **`list`**: Show the user what needs to be done.
2. **`next`**: Help the user decide what to work on.
3. **`show <id>`**: Provide details for a specific task.
4. **`expand <id>`**: Break down a complex task into smaller, manageable subtasks.
5. **Implement**: The user writes the code and tests.
6. **`update-subtask`**: Log progress and findings on behalf of the user.
7. **`set-status`**: Mark tasks and subtasks as `done` as work is completed.
8. **Repeat**.
All your standard command executions should operate on the user's current task context, which defaults to `master`.
---
## Standard Development Workflow Process
### Simple Workflow (Default Starting Point)
For new projects or when users are getting started, operate within the `master` tag context:
- Start new projects by running `initialize_project` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see @`taskmaster.md`) to generate initial tasks.json with tagged structure
- Configure rule sets during initialization with `--rules` flag (e.g., `task-master init --rules kiro,windsurf`) or manage them later with `task-master rules add/remove` commands
- Begin coding sessions with `get_tasks` / `task-master list` (see @`taskmaster.md`) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see @`taskmaster.md`)
- Analyze task complexity with `analyze_project_complexity` / `task-master analyze-complexity --research` (see @`taskmaster.md`) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see @`taskmaster.md`)
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- View specific task details using `get_task` / `task-master show <id>` (see @`taskmaster.md`) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id> --force --research` (see @`taskmaster.md`) with appropriate flags like `--force` (to replace existing subtasks) and `--research`
- Implement code following task details, dependencies, and project standards
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see @`taskmaster.md`)
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see @`taskmaster.md`)
---
## Leveling Up: Agent-Led Multi-Context Workflows
While the basic workflow is powerful, your primary opportunity to add value is by identifying when to introduce **Tagged Task Lists**. These patterns are your tools for creating a more organized and efficient development environment for the user, especially if you detect agentic or parallel development happening across the same session.
**Critical Principle**: Most users should never see a difference in their experience. Only introduce advanced workflows when you detect clear indicators that the project has evolved beyond simple task management.
### When to Introduce Tags: Your Decision Patterns
Here are the patterns to look for. When you detect one, you should propose the corresponding workflow to the user.
#### Pattern 1: Simple Git Feature Branching
This is the most common and direct use case for tags.
- **Trigger**: The user creates a new git branch (e.g., `git checkout -b feature/user-auth`).
- **Your Action**: Propose creating a new tag that mirrors the branch name to isolate the feature's tasks from `master`.
- **Your Suggested Prompt**: *"I see you've created a new branch named 'feature/user-auth'. To keep all related tasks neatly organized and separate from your main list, I can create a corresponding task tag for you. This helps prevent merge conflicts in your `tasks.json` file later. Shall I create the 'feature-user-auth' tag?"*
- **Tool to Use**: `task-master add-tag --from-branch`
#### Pattern 2: Team Collaboration
- **Trigger**: The user mentions working with teammates (e.g., "My teammate Alice is handling the database schema," or "I need to review Bob's work on the API.").
- **Your Action**: Suggest creating a separate tag for the user's work to prevent conflicts with shared master context.
- **Your Suggested Prompt**: *"Since you're working with Alice, I can create a separate task context for your work to avoid conflicts. This way, Alice can continue working with the master list while you have your own isolated context. When you're ready to merge your work, we can coordinate the tasks back to master. Shall I create a tag for your current work?"*
- **Tool to Use**: `task-master add-tag my-work --copy-from-current --description="My tasks while collaborating with Alice"`
#### Pattern 3: Experiments or Risky Refactors
- **Trigger**: The user wants to try something that might not be kept (e.g., "I want to experiment with switching our state management library," or "Let's refactor the old API module, but I want to keep the current tasks as a reference.").
- **Your Action**: Propose creating a sandboxed tag for the experimental work.
- **Your Suggested Prompt**: *"This sounds like a great experiment. To keep these new tasks separate from our main plan, I can create a temporary 'experiment-zustand' tag for this work. If we decide not to proceed, we can simply delete the tag without affecting the main task list. Sound good?"*
- **Tool to Use**: `task-master add-tag experiment-zustand --description="Exploring Zustand migration"`
#### Pattern 4: Large Feature Initiatives (PRD-Driven)
This is a more structured approach for significant new features or epics.
- **Trigger**: The user describes a large, multi-step feature that would benefit from a formal plan.
- **Your Action**: Propose a comprehensive, PRD-driven workflow.
- **Your Suggested Prompt**: *"This sounds like a significant new feature. To manage this effectively, I suggest we create a dedicated task context for it. Here's the plan: I'll create a new tag called 'feature-xyz', then we can draft a Product Requirements Document (PRD) together to scope the work. Once the PRD is ready, I'll automatically generate all the necessary tasks within that new tag. How does that sound?"*
- **Your Implementation Flow**:
1. **Create an empty tag**: `task-master add-tag feature-xyz --description "Tasks for the new XYZ feature"`. You can also start by creating a git branch if applicable, and then create the tag from that branch.
2. **Collaborate & Create PRD**: Work with the user to create a detailed PRD file (e.g., `.taskmaster/docs/feature-xyz-prd.txt`).
3. **Parse PRD into the new tag**: `task-master parse-prd .taskmaster/docs/feature-xyz-prd.txt --tag feature-xyz`
4. **Prepare the new task list**: Follow up by suggesting `analyze-complexity` and `expand-all` for the newly created tasks within the `feature-xyz` tag.
#### Pattern 5: Version-Based Development
Tailor your approach based on the project maturity indicated by tag names.
- **Prototype/MVP Tags** (`prototype`, `mvp`, `poc`, `v0.x`):
- **Your Approach**: Focus on speed and functionality over perfection
- **Task Generation**: Create tasks that emphasize "get it working" over "get it perfect"
- **Complexity Level**: Lower complexity, fewer subtasks, more direct implementation paths
- **Research Prompts**: Include context like "This is a prototype - prioritize speed and basic functionality over optimization"
- **Example Prompt Addition**: *"Since this is for the MVP, I'll focus on tasks that get core functionality working quickly rather than over-engineering."*
- **Production/Mature Tags** (`v1.0+`, `production`, `stable`):
- **Your Approach**: Emphasize robustness, testing, and maintainability
- **Task Generation**: Include comprehensive error handling, testing, documentation, and optimization
- **Complexity Level**: Higher complexity, more detailed subtasks, thorough implementation paths
- **Research Prompts**: Include context like "This is for production - prioritize reliability, performance, and maintainability"
- **Example Prompt Addition**: *"Since this is for production, I'll ensure tasks include proper error handling, testing, and documentation."*
### Advanced Workflow (Tag-Based & PRD-Driven)
**When to Transition**: Recognize when the project has evolved (or has initiated a project which existing code) beyond simple task management. Look for these indicators:
- User mentions teammates or collaboration needs
- Project has grown to 15+ tasks with mixed priorities
- User creates feature branches or mentions major initiatives
- User initializes Taskmaster on an existing, complex codebase
- User describes large features that would benefit from dedicated planning
**Your Role in Transition**: Guide the user to a more sophisticated workflow that leverages tags for organization and PRDs for comprehensive planning.
#### Master List Strategy (High-Value Focus)
Once you transition to tag-based workflows, the `master` tag should ideally contain only:
- **High-level deliverables** that provide significant business value
- **Major milestones** and epic-level features
- **Critical infrastructure** work that affects the entire project
- **Release-blocking** items
**What NOT to put in master**:
- Detailed implementation subtasks (these go in feature-specific tags' parent tasks)
- Refactoring work (create dedicated tags like `refactor-auth`)
- Experimental features (use `experiment-*` tags)
- Team member-specific tasks (use person-specific tags)
#### PRD-Driven Feature Development
**For New Major Features**:
1. **Identify the Initiative**: When user describes a significant feature
2. **Create Dedicated Tag**: `add_tag feature-[name] --description="[Feature description]"`
3. **Collaborative PRD Creation**: Work with user to create comprehensive PRD in `.taskmaster/docs/feature-[name]-prd.txt`
4. **Parse & Prepare**:
- `parse_prd .taskmaster/docs/feature-[name]-prd.txt --tag=feature-[name]`
- `analyze_project_complexity --tag=feature-[name] --research`
- `expand_all --tag=feature-[name] --research`
5. **Add Master Reference**: Create a high-level task in `master` that references the feature tag
**For Existing Codebase Analysis**:
When users initialize Taskmaster on existing projects:
1. **Codebase Discovery**: Use your native tools for producing deep context about the code base. You may use `research` tool with `--tree` and `--files` to collect up to date information using the existing architecture as context.
2. **Collaborative Assessment**: Work with user to identify improvement areas, technical debt, or new features
3. **Strategic PRD Creation**: Co-author PRDs that include:
- Current state analysis (based on your codebase research)
- Proposed improvements or new features
- Implementation strategy considering existing code
4. **Tag-Based Organization**: Parse PRDs into appropriate tags (`refactor-api`, `feature-dashboard`, `tech-debt`, etc.)
5. **Master List Curation**: Keep only the most valuable initiatives in master
The parse-prd's `--append` flag enables the user to parse multiple PRDs within tags or across tags. PRDs should be focused and the number of tasks they are parsed into should be strategically chosen relative to the PRD's complexity and level of detail.
### Workflow Transition Examples
**Example 1: Simple → Team-Based**
```
User: "Alice is going to help with the API work"
Your Response: "Great! To avoid conflicts, I'll create a separate task context for your work. Alice can continue with the master list while you work in your own context. When you're ready to merge, we can coordinate the tasks back together."
Action: add_tag my-api-work --copy-from-current --description="My API tasks while collaborating with Alice"
```
**Example 2: Simple → PRD-Driven**
```
User: "I want to add a complete user dashboard with analytics, user management, and reporting"
Your Response: "This sounds like a major feature that would benefit from detailed planning. Let me create a dedicated context for this work and we can draft a PRD together to ensure we capture all requirements."
Actions:
1. add_tag feature-dashboard --description="User dashboard with analytics and management"
2. Collaborate on PRD creation
3. parse_prd dashboard-prd.txt --tag=feature-dashboard
4. Add high-level "User Dashboard" task to master
```
**Example 3: Existing Project → Strategic Planning**
```
User: "I just initialized Taskmaster on my existing React app. It's getting messy and I want to improve it."
Your Response: "Let me research your codebase to understand the current architecture, then we can create a strategic plan for improvements."
Actions:
1. research "Current React app architecture and improvement opportunities" --tree --files=src/
2. Collaborate on improvement PRD based on findings
3. Create tags for different improvement areas (refactor-components, improve-state-management, etc.)
4. Keep only major improvement initiatives in master
```
---
## Primary Interaction: MCP Server vs. CLI
Taskmaster offers two primary ways to interact:
1. **MCP Server (Recommended for Integrated Tools)**:
- For AI agents and integrated development environments (like Kiro), interacting via the **MCP server is the preferred method**.
- The MCP server exposes Taskmaster functionality through a set of tools (e.g., `get_tasks`, `add_subtask`).
- This method offers better performance, structured data exchange, and richer error handling compared to CLI parsing.
- Refer to @`mcp.md` for details on the MCP architecture and available tools.
- A comprehensive list and description of MCP tools and their corresponding CLI commands can be found in @`taskmaster.md`.
- **Restart the MCP server** if core logic in `scripts/modules` or MCP tool/direct function definitions change.
- **Note**: MCP tools fully support tagged task lists with complete tag management capabilities.
2. **`task-master` CLI (For Users & Fallback)**:
- The global `task-master` command provides a user-friendly interface for direct terminal interaction.
- It can also serve as a fallback if the MCP server is inaccessible or a specific function isn't exposed via MCP.
- Install globally with `npm install -g task-master-ai` or use locally via `npx task-master-ai ...`.
- The CLI commands often mirror the MCP tools (e.g., `task-master list` corresponds to `get_tasks`).
- Refer to @`taskmaster.md` for a detailed command reference.
- **Tagged Task Lists**: CLI fully supports the new tagged system with seamless migration.
## How the Tag System Works (For Your Reference)
- **Data Structure**: Tasks are organized into separate contexts (tags) like "master", "feature-branch", or "v2.0".
- **Silent Migration**: Existing projects automatically migrate to use a "master" tag with zero disruption.
- **Context Isolation**: Tasks in different tags are completely separate. Changes in one tag do not affect any other tag.
- **Manual Control**: The user is always in control. There is no automatic switching. You facilitate switching by using `use-tag <name>`.
- **Full CLI & MCP Support**: All tag management commands are available through both the CLI and MCP tools for you to use. Refer to @`taskmaster.md` for a full command list.
---
## Task Complexity Analysis
- Run `analyze_project_complexity` / `task-master analyze-complexity --research` (see @`taskmaster.md`) for comprehensive analysis
- Review complexity report via `complexity_report` / `task-master complexity-report` (see @`taskmaster.md`) for a formatted, readable version.
- Focus on tasks with highest complexity scores (8-10) for detailed breakdown
- Use analysis results to determine appropriate subtask allocation
- Note that reports are automatically used by the `expand_task` tool/command
## Task Breakdown Process
- Use `expand_task` / `task-master expand --id=<id>`. It automatically uses the complexity report if found, otherwise generates default number of subtasks.
- Use `--num=<number>` to specify an explicit number of subtasks, overriding defaults or complexity report recommendations.
- Add `--research` flag to leverage Perplexity AI for research-backed expansion.
- Add `--force` flag to clear existing subtasks before generating new ones (default is to append).
- Use `--prompt="<context>"` to provide additional context when needed.
- Review and adjust generated subtasks as necessary.
- Use `expand_all` tool or `task-master expand --all` to expand multiple pending tasks at once, respecting flags like `--force` and `--research`.
- If subtasks need complete replacement (regardless of the `--force` flag on `expand`), clear them first with `clear_subtasks` / `task-master clear-subtasks --id=<id>`.
## Implementation Drift Handling
- When implementation differs significantly from planned approach
- When future tasks need modification due to current implementation choices
- When new dependencies or requirements emerge
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...' --research` to update multiple future tasks.
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...' --research` to update a single specific task.
## Task Status Management
- Use 'pending' for tasks ready to be worked on
- Use 'done' for completed and verified tasks
- Use 'deferred' for postponed tasks
- Add custom status values as needed for project-specific workflows
## Task Structure Fields
- **id**: Unique identifier for the task (Example: `1`, `1.1`)
- **title**: Brief, descriptive title (Example: `"Initialize Repo"`)
- **description**: Concise summary of what the task involves (Example: `"Create a new repository, set up initial structure."`)
- **status**: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
- **dependencies**: IDs of prerequisite tasks (Example: `[1, 2.1]`)
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
- This helps quickly identify which prerequisite tasks are blocking work
- **priority**: Importance level (Example: `"high"`, `"medium"`, `"low"`)
- **details**: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
- **testStrategy**: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
- **subtasks**: List of smaller, more specific tasks (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
- Refer to task structure details (previously linked to `tasks.md`).
## Configuration Management (Updated)
Taskmaster configuration is managed through two main mechanisms:
1. **`.taskmaster/config.json` File (Primary):**
* Located in the project root directory.
* Stores most configuration settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default subtasks/priority, project name, etc.
* **Tagged System Settings**: Includes `global.defaultTag` (defaults to "master") and `tags` section for tag management configuration.
* **Managed via `task-master models --setup` command.** Do not edit manually unless you know what you are doing.
* **View/Set specific models via `task-master models` command or `models` MCP tool.**
* Created automatically when you run `task-master models --setup` for the first time or during tagged system migration.
2. **Environment Variables (`.env` / `mcp.json`):**
* Used **only** for sensitive API keys and specific endpoint URLs.
* Place API keys (one per provider) in a `.env` file in the project root for CLI usage.
* For MCP/Kiro integration, configure these keys in the `env` section of `.kiro/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.md`).
3. **`.taskmaster/state.json` File (Tagged System State):**
* Tracks current tag context and migration status.
* Automatically created during tagged system migration.
* Contains: `currentTag`, `lastSwitched`, `migrationNoticeShown`.
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.kiro/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.
## Rules Management
Taskmaster supports multiple AI coding assistant rule sets that can be configured during project initialization or managed afterward:
- **Available Profiles**: Claude Code, Cline, Codex, Kiro, Roo Code, Trae, Windsurf (claude, cline, codex, kiro, roo, trae, windsurf)
- **During Initialization**: Use `task-master init --rules kiro,windsurf` to specify which rule sets to include
- **After Initialization**: Use `task-master rules add <profiles>` or `task-master rules remove <profiles>` to manage rule sets
- **Interactive Setup**: Use `task-master rules setup` to launch an interactive prompt for selecting rule profiles
- **Default Behavior**: If no `--rules` flag is specified during initialization, all available rule profiles are included
- **Rule Structure**: Each profile creates its own directory (e.g., `.kiro/steering`, `.roo/rules`) with appropriate configuration files
## Determining the Next Task
- Run `next_task` / `task-master next` to show the next task to work on.
- The command identifies tasks with all dependencies satisfied
- Tasks are prioritized by priority level, dependency count, and ID
- The command shows comprehensive task information including:
- Basic task details and description
- Implementation details
- Subtasks (if they exist)
- Contextual suggested actions
- Recommended before starting any new development work
- Respects your project's dependency structure
- Ensures tasks are completed in the appropriate sequence
- Provides ready-to-use commands for common task actions
## Viewing Specific Task Details
- Run `get_task` / `task-master show <id>` to view a specific task.
- Use dot notation for subtasks: `task-master show 1.2` (shows subtask 2 of task 1)
- Displays comprehensive information similar to the next command, but for a specific task
- For parent tasks, shows all subtasks and their current status
- For subtasks, shows parent task information and relationship
- Provides contextual suggested actions appropriate for the specific task
- Useful for examining task details before implementation or checking status
## Managing Task Dependencies
- Use `add_dependency` / `task-master add-dependency --id=<id> --depends-on=<id>` to add a dependency.
- Use `remove_dependency` / `task-master remove-dependency --id=<id> --depends-on=<id>` to remove a dependency.
- The system prevents circular dependencies and duplicate dependency entries
- Dependencies are checked for existence before being added or removed
- Task files are automatically regenerated after dependency changes
- Dependencies are visualized with status indicators in task listings and files
## Task Reorganization
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
- This command supports several use cases:
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
- The system includes validation to prevent data loss:
- Allows moving to non-existent IDs by creating placeholder tasks
- Prevents moving to existing task IDs that have content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- The system maintains proper parent-child relationships and dependency integrity
- Task files are automatically regenerated after the move operation
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
## Iterative Subtask Implementation
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
1. **Understand the Goal (Preparation):**
* Use `get_task` / `task-master show <subtaskId>` (see @`taskmaster.md`) to thoroughly understand the specific goals and requirements of the subtask.
2. **Initial Exploration & Planning (Iteration 1):**
* This is the first attempt at creating a concrete implementation plan.
* Explore the codebase to identify the precise files, functions, and even specific lines of code that will need modification.
* Determine the intended code changes (diffs) and their locations.
* Gather *all* relevant details from this exploration phase.
3. **Log the Plan:**
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'`.
* Provide the *complete and detailed* findings from the exploration phase in the prompt. Include file paths, line numbers, proposed diffs, reasoning, and any potential challenges identified. Do not omit details. The goal is to create a rich, timestamped log within the subtask's `details`.
4. **Verify the Plan:**
* Run `get_task` / `task-master show <subtaskId>` again to confirm that the detailed implementation plan has been successfully appended to the subtask's details.
5. **Begin Implementation:**
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress`.
* Start coding based on the logged plan.
6. **Refine and Log Progress (Iteration 2+):**
* As implementation progresses, you will encounter challenges, discover nuances, or confirm successful approaches.
* **Before appending new information**: Briefly review the *existing* details logged in the subtask (using `get_task` or recalling from context) to ensure the update adds fresh insights and avoids redundancy.
* **Regularly** use `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<update details>\n- What worked...\n- What didn't work...'` to append new findings.
* **Crucially, log:**
* What worked ("fundamental truths" discovered).
* What didn't work and why (to avoid repeating mistakes).
* Specific code snippets or configurations that were successful.
* Decisions made, especially if confirmed with user input.
* Any deviations from the initial plan and the reasoning.
* The objective is to continuously enrich the subtask's details, creating a log of the implementation journey that helps the AI (and human developers) learn, adapt, and avoid repeating errors.
7. **Review & Update Rules (Post-Implementation):**
* Once the implementation for the subtask is functionally complete, review all code changes and the relevant chat history.
* Identify any new or modified code patterns, conventions, or best practices established during the implementation.
* Create new or update existing rules following internal guidelines (previously linked to `cursor_rules.md` and `self_improve.md`).
8. **Mark Task Complete:**
* After verifying the implementation and updating any necessary rules, mark the subtask as completed: `set_task_status` / `task-master set-status --id=<subtaskId> --status=done`.
9. **Commit Changes (If using Git):**
* Stage the relevant code changes and any updated/new rule files (`git add .`).
* Craft a comprehensive Git commit message summarizing the work done for the subtask, including both code implementation and any rule adjustments.
* Execute the commit command directly in the terminal (e.g., `git commit -m 'feat(module): Implement feature X for subtask <subtaskId>\n\n- Details about changes...\n- Updated rule Y for pattern Z'`).
* Consider if a Changeset is needed according to internal versioning guidelines (previously linked to `changeset.md`). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
10. **Proceed to Next Subtask:**
* Identify the next subtask (e.g., using `next_task` / `task-master next`).
## Code Analysis & Refactoring Techniques
- **Top-Level Function Search**:
- Useful for understanding module structure or planning refactors.
- Use grep/ripgrep to find exported functions/constants:
`rg "export (async function|function|const) \w+"` or similar patterns.
- Can help compare functions between files during migrations or identify potential naming conflicts.
---
*This workflow provides a general guideline. Adapt it based on your specific project needs and team practices.*

View File

@@ -0,0 +1,51 @@
---
inclusion: always
---
- **Required Rule Structure:**
```markdown
---
description: Clear, one-line description of what the rule enforces
globs: path/to/files/*.ext, other/path/**/*
alwaysApply: boolean
---
- **Main Points in Bold**
- Sub-points with details
- Examples and explanations
```
- **File References:**
- Use `[filename](mdc:path/to/file)` ([filename](mdc:filename)) to reference files
- Example: [prisma.md](.kiro/steering/prisma.md) for rule references
- Example: [schema.prisma](mdc:prisma/schema.prisma) for code references
- **Code Examples:**
- Use language-specific code blocks
```typescript
// ✅ DO: Show good examples
const goodExample = true;
// ❌ DON'T: Show anti-patterns
const badExample = false;
```
- **Rule Content Guidelines:**
- Start with high-level overview
- Include specific, actionable requirements
- Show examples of correct implementation
- Reference existing code when possible
- Keep rules DRY by referencing other rules
- **Rule Maintenance:**
- Update rules when new patterns emerge
- Add examples from actual codebase
- Remove outdated patterns
- Cross-reference related rules
- **Best Practices:**
- Use bullet points for clarity
- Keep descriptions concise
- Include both DO and DON'T examples
- Reference actual code over theoretical examples
- Use consistent formatting across rules

View File

@@ -0,0 +1,70 @@
---
inclusion: always
---
- **Rule Improvement Triggers:**
- New code patterns not covered by existing rules
- Repeated similar implementations across files
- Common error patterns that could be prevented
- New libraries or tools being used consistently
- Emerging best practices in the codebase
- **Analysis Process:**
- Compare new code with existing rules
- Identify patterns that should be standardized
- Look for references to external documentation
- Check for consistent error handling patterns
- Monitor test patterns and coverage
- **Rule Updates:**
- **Add New Rules When:**
- A new technology/pattern is used in 3+ files
- Common bugs could be prevented by a rule
- Code reviews repeatedly mention the same feedback
- New security or performance patterns emerge
- **Modify Existing Rules When:**
- Better examples exist in the codebase
- Additional edge cases are discovered
- Related rules have been updated
- Implementation details have changed
- **Example Pattern Recognition:**
```typescript
// If you see repeated patterns like:
const data = await prisma.user.findMany({
select: { id: true, email: true },
where: { status: 'ACTIVE' }
});
// Consider adding to [prisma.md](.kiro/steering/prisma.md):
// - Standard select fields
// - Common where conditions
// - Performance optimization patterns
```
- **Rule Quality Checks:**
- Rules should be actionable and specific
- Examples should come from actual code
- References should be up to date
- Patterns should be consistently enforced
- **Continuous Improvement:**
- Monitor code review comments
- Track common development questions
- Update rules after major refactors
- Add links to relevant documentation
- Cross-reference related rules
- **Rule Deprecation:**
- Mark outdated patterns as deprecated
- Remove rules that no longer apply
- Update references to deprecated rules
- Document migration paths for old patterns
- **Documentation Updates:**
- Keep examples synchronized with code
- Update references to external docs
- Maintain links between related rules
- Document breaking changes
Follow [kiro_rules.md](.kiro/steering/kiro_rules.md) for proper rule formatting and structure.

View File

@@ -0,0 +1,556 @@
---
inclusion: always
---
# Taskmaster Tool & Command Reference
This document provides a detailed reference for interacting with Taskmaster, covering both the recommended MCP tools, suitable for integrations like Kiro, and the corresponding `task-master` CLI commands, designed for direct user interaction or fallback.
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback.
**Important:** Several MCP tools involve AI processing... The AI-powered tools include `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
**🏷️ Tagged Task Lists System:** Task Master now supports **tagged task lists** for multi-context task management. This allows you to maintain separate, isolated lists of tasks for different features, branches, or experiments. Existing projects are seamlessly migrated to use a default "master" tag. Most commands now support a `--tag <name>` flag to specify which context to operate on. If omitted, commands use the currently active tag.
---
## Initialization & Setup
### 1. Initialize Project (`init`)
* **MCP Tool:** `initialize_project`
* **CLI Command:** `task-master init [options]`
* **Description:** `Set up the basic Taskmaster file structure and configuration in the current directory for a new project.`
* **Key CLI Options:**
* `--name <name>`: `Set the name for your project in Taskmaster's configuration.`
* `--description <text>`: `Provide a brief description for your project.`
* `--version <version>`: `Set the initial version for your project, e.g., '0.1.0'.`
* `-y, --yes`: `Initialize Taskmaster quickly using default settings without interactive prompts.`
* **Usage:** Run this once at the beginning of a new project.
* **MCP Variant Description:** `Set up the basic Taskmaster file structure and configuration in the current directory for a new project by running the 'task-master init' command.`
* **Key MCP Parameters/Options:**
* `projectName`: `Set the name for your project.` (CLI: `--name <name>`)
* `projectDescription`: `Provide a brief description for your project.` (CLI: `--description <text>`)
* `projectVersion`: `Set the initial version for your project, e.g., '0.1.0'.` (CLI: `--version <version>`)
* `authorName`: `Author name.` (CLI: `--author <author>`)
* `skipInstall`: `Skip installing dependencies. Default is false.` (CLI: `--skip-install`)
* `addAliases`: `Add shell aliases tm and taskmaster. Default is false.` (CLI: `--aliases`)
* `yes`: `Skip prompts and use defaults/provided arguments. Default is false.` (CLI: `-y, --yes`)
* **Usage:** Run this once at the beginning of a new project, typically via an integrated tool like Kiro. Operates on the current working directory of the MCP server.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in .taskmaster/templates/example_prd.txt.
* **Tagging:** Use the `--tag` option to parse the PRD into a specific, non-default tag context. If the tag doesn't exist, it will be created automatically. Example: `task-master parse-prd spec.txt --tag=new-feature`.
### 2. Parse PRD (`parse_prd`)
* **MCP Tool:** `parse_prd`
* **CLI Command:** `task-master parse-prd [file] [options]`
* **Description:** `Parse a Product Requirements Document, PRD, or text file with Taskmaster to automatically generate an initial set of tasks in tasks.json.`
* **Key Parameters/Options:**
* `input`: `Path to your PRD or requirements text file that Taskmaster should parse for tasks.` (CLI: `[file]` positional or `-i, --input <file>`)
* `output`: `Specify where Taskmaster should save the generated 'tasks.json' file. Defaults to '.taskmaster/tasks/tasks.json'.` (CLI: `-o, --output <file>`)
* `numTasks`: `Approximate number of top-level tasks Taskmaster should aim to generate from the document.` (CLI: `-n, --num-tasks <number>`)
* `force`: `Use this to allow Taskmaster to overwrite an existing 'tasks.json' without asking for confirmation.` (CLI: `-f, --force`)
* **Usage:** Useful for bootstrapping a project from an existing requirements document.
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD, such as libraries, database schemas, frameworks, tech stacks, etc., while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress. If the user does not have a PRD, suggest discussing their idea and then use the example PRD in `.taskmaster/templates/example_prd.txt` as a template for creating the PRD based on their idea, for use with `parse-prd`.
---
## AI Model Configuration
### 2. Manage Models (`models`)
* **MCP Tool:** `models`
* **CLI Command:** `task-master models [options]`
* **Description:** `View the current AI model configuration or set specific models for different roles (main, research, fallback). Allows setting custom model IDs for Ollama and OpenRouter.`
* **Key MCP Parameters/Options:**
* `setMain <model_id>`: `Set the primary model ID for task generation/updates.` (CLI: `--set-main <model_id>`)
* `setResearch <model_id>`: `Set the model ID for research-backed operations.` (CLI: `--set-research <model_id>`)
* `setFallback <model_id>`: `Set the model ID to use if the primary fails.` (CLI: `--set-fallback <model_id>`)
* `ollama <boolean>`: `Indicates the set model ID is a custom Ollama model.` (CLI: `--ollama`)
* `openrouter <boolean>`: `Indicates the set model ID is a custom OpenRouter model.` (CLI: `--openrouter`)
* `listAvailableModels <boolean>`: `If true, lists available models not currently assigned to a role.` (CLI: No direct equivalent; CLI lists available automatically)
* `projectRoot <string>`: `Optional. Absolute path to the project root directory.` (CLI: Determined automatically)
* **Key CLI Options:**
* `--set-main <model_id>`: `Set the primary model.`
* `--set-research <model_id>`: `Set the research model.`
* `--set-fallback <model_id>`: `Set the fallback model.`
* `--ollama`: `Specify that the provided model ID is for Ollama (use with --set-*).`
* `--openrouter`: `Specify that the provided model ID is for OpenRouter (use with --set-*). Validates against OpenRouter API.`
* `--bedrock`: `Specify that the provided model ID is for AWS Bedrock (use with --set-*).`
* `--setup`: `Run interactive setup to configure models, including custom Ollama/OpenRouter IDs.`
* **Usage (MCP):** Call without set flags to get current config. Use `setMain`, `setResearch`, or `setFallback` with a valid model ID to update the configuration. Use `listAvailableModels: true` to get a list of unassigned models. To set a custom model, provide the model ID and set `ollama: true` or `openrouter: true`.
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
* **Notes:** Configuration is stored in `.taskmaster/config.json` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live.
* **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them.
* **Model costs:** The costs in supported models are expressed in dollars. An input/output value of 3 is $3.00. A value of 0.8 is $0.80.
* **Warning:** DO NOT MANUALLY EDIT THE .taskmaster/config.json FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback.
---
## Task Listing & Viewing
### 3. Get Tasks (`get_tasks`)
* **MCP Tool:** `get_tasks`
* **CLI Command:** `task-master list [options]`
* **Description:** `List your Taskmaster tasks, optionally filtering by status and showing subtasks.`
* **Key Parameters/Options:**
* `status`: `Show only Taskmaster tasks matching this status (or multiple statuses, comma-separated), e.g., 'pending' or 'done,in-progress'.` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks indented under their parent tasks in the list.` (CLI: `--with-subtasks`)
* `tag`: `Specify which tag context to list tasks from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Get an overview of the project status, often used at the start of a work session.
### 4. Get Next Task (`next_task`)
* **MCP Tool:** `next_task`
* **CLI Command:** `task-master next [options]`
* **Description:** `Ask Taskmaster to show the next available task you can work on, based on status and completed dependencies.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to use. Defaults to the current active tag.` (CLI: `--tag <name>`)
* **Usage:** Identify what to work on next according to the plan.
### 5. Get Task Details (`get_task`)
* **MCP Tool:** `get_task`
* **CLI Command:** `task-master show [id] [options]`
* **Description:** `Display detailed information for one or more specific Taskmaster tasks or subtasks by ID.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task (e.g., '15'), subtask (e.g., '15.2'), or a comma-separated list of IDs ('1,5,10.2') you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
* `tag`: `Specify which tag context to get the task(s) from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Understand the full details for a specific task. When multiple IDs are provided, a summary table is shown.
* **CRITICAL INFORMATION** If you need to collect information from multiple tasks, use comma-separated IDs (i.e. 1,2,3) to receive an array of tasks. Do not needlessly get tasks one at a time if you need to get many as that is wasteful.
---
## Task Creation & Modification
### 6. Add Task (`add_task`)
* **MCP Tool:** `add_task`
* **CLI Command:** `task-master add-task [options]`
* **Description:** `Add a new task to Taskmaster by describing it; AI will structure it.`
* **Key Parameters/Options:**
* `prompt`: `Required. Describe the new task you want Taskmaster to create, e.g., "Implement user authentication using JWT".` (CLI: `-p, --prompt <text>`)
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start, e.g., '12,14'.` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task: 'high', 'medium', or 'low'. Default is 'medium'.` (CLI: `--priority <priority>`)
* `research`: `Enable Taskmaster to use the research role for potentially more informed task creation.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to add the task to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Quickly add newly identified tasks during development.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 7. Add Subtask (`add_subtask`)
* **MCP Tool:** `add_subtask`
* **CLI Command:** `task-master add-subtask [options]`
* **Description:** `Add a new subtask to a Taskmaster parent task, or convert an existing task into a subtask.`
* **Key Parameters/Options:**
* `id` / `parent`: `Required. The ID of the Taskmaster task that will be the parent.` (MCP: `id`, CLI: `-p, --parent <id>`)
* `taskId`: `Use this if you want to convert an existing top-level Taskmaster task into a subtask of the specified parent.` (CLI: `-i, --task-id <id>`)
* `title`: `Required if not using taskId. The title for the new subtask Taskmaster should create.` (CLI: `-t, --title <title>`)
* `description`: `A brief description for the new subtask.` (CLI: `-d, --description <text>`)
* `details`: `Provide implementation notes or details for the new subtask.` (CLI: `--details <text>`)
* `dependencies`: `Specify IDs of other tasks or subtasks, e.g., '15' or '16.1', that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask. Default is 'pending'.` (CLI: `-s, --status <status>`)
* `generate`: `Enable Taskmaster to regenerate markdown task files after adding the subtask.` (CLI: `--generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Break down tasks manually or reorganize existing tasks.
### 8. Update Tasks (`update`)
* **MCP Tool:** `update`
* **CLI Command:** `task-master update [options]`
* **Description:** `Update multiple upcoming tasks in Taskmaster based on new context or changes, starting from a specific task ID.`
* **Key Parameters/Options:**
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher that are not 'done' will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks, e.g., "We are now using React Query instead of Redux Toolkit for data fetching".` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks. Example CLI: `task-master update --from='18' --prompt='Switching to React Query.\nNeed to refactor data fetching...'`
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 9. Update Task (`update_task`)
* **MCP Tool:** `update_task`
* **CLI Command:** `task-master update-task [options]`
* **Description:** `Modify a specific Taskmaster task by ID, incorporating new information or changes. By default, this replaces the existing task details.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster task, e.g., '15', you want to update.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
* `append`: `If true, appends the prompt content to the task's details with a timestamp, rather than replacing them. Behaves like update-subtask.` (CLI: `--append`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Refine a specific task based on new understanding. Use `--append` to log progress without creating subtasks.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 10. Update Subtask (`update_subtask`)
* **MCP Tool:** `update_subtask`
* **CLI Command:** `task-master update-subtask [options]`
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content. Intended for iterative implementation logging.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster subtask, e.g., '5.2', to update with new information.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. The information, findings, or progress notes to append to the subtask's details with a timestamp.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the subtask belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Log implementation progress, findings, and discoveries during subtask development. Each update is timestamped and appended to preserve the implementation journey.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 11. Set Task Status (`set_task_status`)
* **MCP Tool:** `set_task_status`
* **CLI Command:** `task-master set-status [options]`
* **Description:** `Update the status of one or more Taskmaster tasks or subtasks, e.g., 'pending', 'in-progress', 'done'.`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s), e.g., '15', '15.2', or '16,17.1', to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set, e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled'.` (CLI: `-s, --status <status>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Mark progress as tasks move through the development cycle.
### 12. Remove Task (`remove_task`)
* **MCP Tool:** `remove_task`
* **CLI Command:** `task-master remove-task [options]`
* **Description:** `Permanently remove a task or subtask from the Taskmaster tasks list.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task, e.g., '5', or subtask, e.g., '5.2', to permanently remove.` (CLI: `-i, --id <id>`)
* `yes`: `Skip the confirmation prompt and immediately delete the task.` (CLI: `-y, --yes`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Permanently delete tasks or subtasks that are no longer needed in the project.
* **Notes:** Use with caution as this operation cannot be undone. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you just want to exclude a task from active planning but keep it for reference. The command automatically cleans up dependency references in other tasks.
---
## Task Structure & Breakdown
### 13. Expand Task (`expand_task`)
* **MCP Tool:** `expand_task`
* **CLI Command:** `task-master expand [options]`
* **Description:** `Use Taskmaster's AI to break down a complex task into smaller, manageable subtasks. Appends subtasks by default.`
* **Key Parameters/Options:**
* `id`: `The ID of the specific Taskmaster task you want to break down into subtasks.` (CLI: `-i, --id <id>`)
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create. Uses complexity analysis/defaults otherwise.` (CLI: `-n, --num <number>`)
* `research`: `Enable Taskmaster to use the research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding. Automatically uses complexity report recommendations if available and `num` is not specified.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 14. Expand All Tasks (`expand_all`)
* **MCP Tool:** `expand_all`
* **CLI Command:** `task-master expand --all [options]` (Note: CLI uses the `expand` command with the `--all` flag)
* **Description:** `Tell Taskmaster to automatically expand all eligible pending/in-progress tasks based on complexity analysis or defaults. Appends subtasks by default.`
* **Key Parameters/Options:**
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create per task.` (CLI: `-n, --num <number>`)
* `research`: `Enable research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones for each eligible task. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context to expand. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 15. Clear Subtasks (`clear_subtasks`)
* **MCP Tool:** `clear_subtasks`
* **CLI Command:** `task-master clear-subtasks [options]`
* **Description:** `Remove all subtasks from one or more specified Taskmaster parent tasks.`
* **Key Parameters/Options:**
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove, e.g., '15' or '16,18'. Required unless using 'all'.` (CLI: `-i, --id <ids>`)
* `all`: `Tell Taskmaster to remove subtasks from all parent tasks.` (CLI: `--all`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before regenerating subtasks with `expand_task` if the previous breakdown needs replacement.
### 16. Remove Subtask (`remove_subtask`)
* **MCP Tool:** `remove_subtask`
* **CLI Command:** `task-master remove-subtask [options]`
* **Description:** `Remove a subtask from its Taskmaster parent, optionally converting it into a standalone task.`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove, e.g., '15.2' or '16.1,16.3'.` (CLI: `-i, --id <id>`)
* `convert`: `If used, Taskmaster will turn the subtask into a regular top-level task instead of deleting it.` (CLI: `-c, --convert`)
* `generate`: `Enable Taskmaster to regenerate markdown task files after removing the subtask.` (CLI: `--generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
### 17. Move Task (`move_task`)
* **MCP Tool:** `move_task`
* **CLI Command:** `task-master move [options]`
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
* **Key Parameters/Options:**
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
* Moving a task to become a subtask
* Moving a subtask to become a standalone task
* Moving a subtask to a different parent
* Reordering subtasks within the same parent
* Moving a task to a new, non-existent ID (automatically creates placeholders)
* Moving multiple tasks at once with comma-separated IDs
* **Validation Features:**
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
* Validates that source tasks exist before attempting to move them
* Maintains proper parent-child relationships
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
---
## Dependency Management
### 18. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]`
* **Description:** `Define a dependency in Taskmaster, making one task a prerequisite for another.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task that will depend on another.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first, the prerequisite.` (CLI: `-d, --depends-on <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* **Usage:** Establish the correct order of execution between tasks.
### 19. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]`
* **Description:** `Remove a dependency relationship between two Taskmaster tasks.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task you want to remove a prerequisite from.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that should no longer be a prerequisite.` (CLI: `-d, --depends-on <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Update task relationships when the order of execution changes.
### 20. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]`
* **Description:** `Check your Taskmaster tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to validate. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Audit the integrity of your task dependencies.
### 21. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]`
* **Description:** `Automatically fix dependency issues (like circular references or links to non-existent tasks) in your Taskmaster tasks.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to fix dependencies in. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Clean up dependency errors automatically.
---
## Analysis & Reporting
### 22. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]`
* **Description:** `Have Taskmaster analyze your tasks to determine their complexity and suggest which ones need to be broken down further.`
* **Key Parameters/Options:**
* `output`: `Where to save the complexity analysis report. Default is '.taskmaster/reports/task-complexity-report.json' (or '..._tagname.json' if a tag is used).` (CLI: `-o, --output <file>`)
* `threshold`: `The minimum complexity score (1-10) that should trigger a recommendation to expand a task.` (CLI: `-t, --threshold <number>`)
* `research`: `Enable research role for more accurate complexity analysis. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to analyze. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 23. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]`
* **Description:** `Display the task complexity analysis report in a readable format.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to show the report for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to the complexity report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* **Usage:** Review and understand the complexity analysis results after running analyze-complexity.
---
## File Management
### 24. Generate Task Files (`generate`)
* **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]`
* **Description:** `Create or update individual Markdown files for each task based on your tasks.json.`
* **Key Parameters/Options:**
* `output`: `The directory where Taskmaster should save the task files (default: in a 'tasks' directory).` (CLI: `-o, --output <directory>`)
* `tag`: `Specify which tag context to generate files for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date. This command is now manual and no longer runs automatically.
---
## AI-Powered Research
### 25. Research (`research`)
* **MCP Tool:** `research`
* **CLI Command:** `task-master research [options]`
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
* **Key Parameters/Options:**
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
* `taskIds`: `Comma-separated list of task/subtask IDs from the current tag context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
* `saveTo`: `Task or subtask ID (e.g., "15", "15.2") to automatically save the research conversation to.` (CLI: `--save-to <id>`)
* `saveFile`: `If true, saves the research conversation to a markdown file in '.taskmaster/docs/research/'.` (CLI: `--save-file`)
* `noFollowup`: `Disables the interactive follow-up question menu in the CLI.` (CLI: `--no-followup`)
* `tag`: `Specify which tag context to use for task-based context gathering. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
* Get fresh information beyond knowledge cutoff dates
* Research latest best practices, library updates, security patches
* Find implementation examples for specific technologies
* Validate approaches against current industry standards
* Get contextual advice based on project files and tasks
* **When to Consider Using Research:**
* **Before implementing any task** - Research current best practices
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
* **For security-related tasks** - Find latest security recommendations
* **When updating dependencies** - Research breaking changes and migration guides
* **For performance optimization** - Get current performance best practices
* **When debugging complex issues** - Research known solutions and workarounds
* **Research + Action Pattern:**
* Use `research` to gather fresh information
* Use `update_subtask` to commit findings with timestamps
* Use `update_task` to incorporate research into task details
* Use `add_task` with research flag for informed task creation
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
---
## Tag Management
This new suite of commands allows you to manage different task contexts (tags).
### 26. List Tags (`tags`)
* **MCP Tool:** `list_tags`
* **CLI Command:** `task-master tags [options]`
* **Description:** `List all available tags with task counts, completion status, and other metadata.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `--show-metadata`: `Include detailed metadata in the output (e.g., creation date, description).` (CLI: `--show-metadata`)
### 27. Add Tag (`add_tag`)
* **MCP Tool:** `add_tag`
* **CLI Command:** `task-master add-tag <tagName> [options]`
* **Description:** `Create a new, empty tag context, or copy tasks from another tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the new tag to create (alphanumeric, hyphens, underscores).` (CLI: `<tagName>` positional)
* `--from-branch`: `Creates a tag with a name derived from the current git branch, ignoring the <tagName> argument.` (CLI: `--from-branch`)
* `--copy-from-current`: `Copy tasks from the currently active tag to the new tag.` (CLI: `--copy-from-current`)
* `--copy-from <tag>`: `Copy tasks from a specific source tag to the new tag.` (CLI: `--copy-from <tag>`)
* `--description <text>`: `Provide an optional description for the new tag.` (CLI: `-d, --description <text>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 28. Delete Tag (`delete_tag`)
* **MCP Tool:** `delete_tag`
* **CLI Command:** `task-master delete-tag <tagName> [options]`
* **Description:** `Permanently delete a tag and all of its associated tasks.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to delete.` (CLI: `<tagName>` positional)
* `--yes`: `Skip the confirmation prompt.` (CLI: `-y, --yes`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 29. Use Tag (`use_tag`)
* **MCP Tool:** `use_tag`
* **CLI Command:** `task-master use-tag <tagName>`
* **Description:** `Switch your active task context to a different tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to switch to.` (CLI: `<tagName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 30. Rename Tag (`rename_tag`)
* **MCP Tool:** `rename_tag`
* **CLI Command:** `task-master rename-tag <oldName> <newName>`
* **Description:** `Rename an existing tag.`
* **Key Parameters/Options:**
* `oldName`: `The current name of the tag.` (CLI: `<oldName>` positional)
* `newName`: `The new name for the tag.` (CLI: `<newName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 31. Copy Tag (`copy_tag`)
* **MCP Tool:** `copy_tag`
* **CLI Command:** `task-master copy-tag <sourceName> <targetName> [options]`
* **Description:** `Copy an entire tag context, including all its tasks and metadata, to a new tag.`
* **Key Parameters/Options:**
* `sourceName`: `Name of the tag to copy from.` (CLI: `<sourceName>` positional)
* `targetName`: `Name of the new tag to create.` (CLI: `<targetName>` positional)
* `--description <text>`: `Optional description for the new tag.` (CLI: `-d, --description <text>`)
---
## Miscellaneous
### 32. Sync Readme (`sync-readme`) -- experimental
* **MCP Tool:** N/A
* **CLI Command:** `task-master sync-readme [options]`
* **Description:** `Exports your task list to your project's README.md file, useful for showcasing progress.`
* **Key Parameters/Options:**
* `status`: `Filter tasks by status (e.g., 'pending', 'done').` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks in the export.` (CLI: `--with-subtasks`)
* `tag`: `Specify which tag context to export from. Defaults to the current active tag.` (CLI: `--tag <name>`)
---
## Environment Variables Configuration (Updated)
Taskmaster primarily uses the **`.taskmaster/config.json`** file (in project root) for configuration (models, parameters, logging level, etc.), managed via `task-master models --setup`.
Environment variables are used **only** for sensitive API keys related to AI providers and specific overrides like the Ollama base URL:
* **API Keys (Required for corresponding provider):**
* `ANTHROPIC_API_KEY`
* `PERPLEXITY_API_KEY`
* `OPENAI_API_KEY`
* `GOOGLE_API_KEY`
* `MISTRAL_API_KEY`
* `AZURE_OPENAI_API_KEY` (Requires `AZURE_OPENAI_ENDPOINT` too)
* `OPENROUTER_API_KEY`
* `XAI_API_KEY`
* `OLLAMA_API_KEY` (Requires `OLLAMA_BASE_URL` too)
* **Endpoints (Optional/Provider Specific inside .taskmaster/config.json):**
* `AZURE_OPENAI_ENDPOINT`
* `OLLAMA_BASE_URL` (Default: `http://localhost:11434/api`)
**Set API keys** in your **`.env`** file in the project root (for CLI use) or within the `env` section of your **`.kiro/mcp.json`** file (for MCP/Kiro integration). All other settings (model choice, max tokens, temperature, log level, custom endpoints) are managed in `.taskmaster/config.json` via `task-master models` command or `models` MCP tool.
---
For details on how these commands fit into the development process, see the [dev_workflow.md](.kiro/steering/dev_workflow.md).

View File

@@ -0,0 +1,59 @@
---
inclusion: always
---
# Taskmaster Hook-Driven Workflow
## Core Principle: Hooks Automate Task Management
When working with Taskmaster in Kiro, **avoid manually marking tasks as done**. The hook system automatically handles task completion based on:
- **Test Success**: `[TM] Test Success Task Completer` detects passing tests and prompts for task completion
- **Code Changes**: `[TM] Code Change Task Tracker` monitors implementation progress
- **Dependency Chains**: `[TM] Task Dependency Auto-Progression` auto-starts dependent tasks
## AI Assistant Workflow
Follow this pattern when implementing features:
1. **Implement First**: Write code, create tests, make changes
2. **Save Frequently**: Hooks trigger on file saves to track progress automatically
3. **Let Hooks Decide**: Allow hooks to detect completion rather than manually setting status
4. **Respond to Prompts**: Confirm when hooks suggest task completion
## Key Rules for AI Assistants
- **Never use `tm set-status --status=done`** unless hooks fail to detect completion
- **Always write tests** - they provide the most reliable completion signal
- **Save files after implementation** - this triggers progress tracking
- **Trust hook suggestions** - if no completion prompt appears, more work may be needed
## Automatic Behaviors
The hook system provides:
- **Progress Logging**: Implementation details automatically added to task notes
- **Evidence-Based Completion**: Tasks marked done only when criteria are met
- **Dependency Management**: Next tasks auto-started when dependencies complete
- **Natural Flow**: Focus on coding, not task management overhead
## Manual Override Cases
Only manually set task status for:
- Documentation-only tasks
- Tasks without testable outcomes
- Emergency fixes without proper test coverage
Use `tm set-status` sparingly - prefer hook-driven completion.
## Implementation Pattern
```
1. Implement feature → Save file
2. Write tests → Save test file
3. Tests pass → Hook prompts completion
4. Confirm completion → Next task auto-starts
```
This workflow ensures proper task tracking while maintaining development flow.

6
.manypkg.json Normal file
View File

@@ -0,0 +1,6 @@
{
"$schema": "https://unpkg.com/@manypkg/get-packages@1.1.3/schema.json",
"defaultBranch": "main",
"ignoredRules": ["ROOT_HAS_DEPENDENCIES", "INTERNAL_MISMATCH"],
"ignoredPackages": ["@tm/core", "@tm/cli", "@tm/build-config"]
}

9
.mcp.json Normal file
View File

@@ -0,0 +1,9 @@
{
"mcpServers": {
"task-master-ai": {
"type": "stdio",
"command": "npx",
"args": ["-y", "task-master-ai"]
}
}
}

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
22

View File

@@ -1,7 +0,0 @@
# Ignore artifacts:
build
coverage
.changeset
tasks
package-lock.json
tests/fixture/*.json

View File

@@ -1,11 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": true,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}

417
.taskmaster/CLAUDE.md Normal file
View File

@@ -0,0 +1,417 @@
# Task Master AI - Agent Integration Guide
## Essential Commands
### Core Workflow Commands
```bash
# Project Setup
task-master init # Initialize Task Master in current project
task-master parse-prd .taskmaster/docs/prd.txt # Generate tasks from PRD document
task-master models --setup # Configure AI models interactively
# Daily Development Workflow
task-master list # Show all tasks with status
task-master next # Get next available task to work on
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
task-master set-status --id=<id> --status=done # Mark task complete
# Task Management
task-master add-task --prompt="description" --research # Add new task with AI assistance
task-master expand --id=<id> --research --force # Break task into subtasks
task-master update-task --id=<id> --prompt="changes" # Update specific task
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
# Analysis & Planning
task-master analyze-complexity --research # Analyze task complexity
task-master complexity-report # View complexity analysis
task-master expand --all --research # Expand all eligible tasks
# Dependencies & Organization
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
task-master validate-dependencies # Check for dependency issues
task-master generate # Update task markdown files (usually auto-called)
```
## Key Files & Project Structure
### Core Files
- `.taskmaster/tasks/tasks.json` - Main task data file (auto-managed)
- `.taskmaster/config.json` - AI model configuration (use `task-master models` to modify)
- `.taskmaster/docs/prd.txt` - Product Requirements Document for parsing
- `.taskmaster/tasks/*.txt` - Individual task files (auto-generated from tasks.json)
- `.env` - API keys for CLI usage
### Claude Code Integration Files
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
- `.claude/settings.json` - Claude Code tool allowlist and preferences
- `.claude/commands/` - Custom slash commands for repeated workflows
- `.mcp.json` - MCP server configuration (project-specific)
### Directory Structure
```
project/
├── .taskmaster/
│ ├── tasks/ # Task files directory
│ │ ├── tasks.json # Main task database
│ │ ├── task-1.md # Individual task files
│ │ └── task-2.md
│ ├── docs/ # Documentation directory
│ │ ├── prd.txt # Product requirements
│ ├── reports/ # Analysis reports directory
│ │ └── task-complexity-report.json
│ ├── templates/ # Template files
│ │ └── example_prd.txt # Example PRD template
│ └── config.json # AI models & settings
├── .claude/
│ ├── settings.json # Claude Code configuration
│ └── commands/ # Custom slash commands
├── .env # API keys
├── .mcp.json # MCP configuration
└── CLAUDE.md # This file - auto-loaded by Claude Code
```
## MCP Integration
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
```json
{
"mcpServers": {
"task-master-ai": {
"command": "npx",
"args": ["-y", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "your_key_here",
"PERPLEXITY_API_KEY": "your_key_here",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
}
}
}
}
```
### Essential MCP Tools
```javascript
help; // = shows available taskmaster commands
// Project setup
initialize_project; // = task-master init
parse_prd; // = task-master parse-prd
// Daily workflow
get_tasks; // = task-master list
next_task; // = task-master next
get_task; // = task-master show <id>
set_task_status; // = task-master set-status
// Task management
add_task; // = task-master add-task
expand_task; // = task-master expand
update_task; // = task-master update-task
update_subtask; // = task-master update-subtask
update; // = task-master update
// Analysis
analyze_project_complexity; // = task-master analyze-complexity
complexity_report; // = task-master complexity-report
```
## Claude Code Workflow Integration
### Standard Development Workflow
#### 1. Project Initialization
```bash
# Initialize Task Master
task-master init
# Create or obtain PRD, then parse it
task-master parse-prd .taskmaster/docs/prd.txt
# Analyze complexity and expand tasks
task-master analyze-complexity --research
task-master expand --all --research
```
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
#### 2. Daily Development Loop
```bash
# Start each session
task-master next # Find next available task
task-master show <id> # Review task details
# During implementation, check in code context into the tasks and subtasks
task-master update-subtask --id=<id> --prompt="implementation notes..."
# Complete tasks
task-master set-status --id=<id> --status=done
```
#### 3. Multi-Claude Workflows
For complex projects, use multiple Claude Code sessions:
```bash
# Terminal 1: Main implementation
cd project && claude
# Terminal 2: Testing and validation
cd project-test-worktree && claude
# Terminal 3: Documentation updates
cd project-docs-worktree && claude
```
### Custom Slash Commands
Create `.claude/commands/taskmaster-next.md`:
```markdown
Find the next available Task Master task and show its details.
Steps:
1. Run `task-master next` to get the next task
2. If a task is available, run `task-master show <id>` for full details
3. Provide a summary of what needs to be implemented
4. Suggest the first implementation step
```
Create `.claude/commands/taskmaster-complete.md`:
```markdown
Complete a Task Master task: $ARGUMENTS
Steps:
1. Review the current task with `task-master show $ARGUMENTS`
2. Verify all implementation is complete
3. Run any tests related to this task
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
5. Show the next available task with `task-master next`
```
## Tool Allowlist Recommendations
Add to `.claude/settings.json`:
```json
{
"allowedTools": [
"Edit",
"Bash(task-master *)",
"Bash(git commit:*)",
"Bash(git add:*)",
"Bash(npm run *)",
"mcp__task_master_ai__*"
]
}
```
## Configuration & Setup
### API Keys Required
At least **one** of these API keys must be configured:
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
- `OPENAI_API_KEY` (GPT models)
- `GOOGLE_API_KEY` (Gemini models)
- `MISTRAL_API_KEY` (Mistral models)
- `OPENROUTER_API_KEY` (Multiple models)
- `XAI_API_KEY` (Grok models)
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
### Model Configuration
```bash
# Interactive setup (recommended)
task-master models --setup
# Set specific models
task-master models --set-main claude-3-5-sonnet-20241022
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
task-master models --set-fallback gpt-4o-mini
```
## Task Structure & IDs
### Task ID Format
- Main tasks: `1`, `2`, `3`, etc.
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
### Task Status Values
- `pending` - Ready to work on
- `in-progress` - Currently being worked on
- `done` - Completed and verified
- `deferred` - Postponed
- `cancelled` - No longer needed
- `blocked` - Waiting on external factors
### Task Fields
```json
{
"id": "1.2",
"title": "Implement user authentication",
"description": "Set up JWT-based auth system",
"status": "pending",
"priority": "high",
"dependencies": ["1.1"],
"details": "Use bcrypt for hashing, JWT for tokens...",
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
"subtasks": []
}
```
## Claude Code Best Practices with Task Master
### Context Management
- Use `/clear` between different tasks to maintain focus
- This CLAUDE.md file is automatically loaded for context
- Use `task-master show <id>` to pull specific task context when needed
### Iterative Implementation
1. `task-master show <subtask-id>` - Understand requirements
2. Explore codebase and plan implementation
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
4. `task-master set-status --id=<id> --status=in-progress` - Start work
5. Implement code following logged plan
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
7. `task-master set-status --id=<id> --status=done` - Complete task
### Complex Workflows with Checklists
For large migrations or multi-step processes:
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
4. Work through items systematically, checking them off as completed
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
### Git Integration
Task Master works well with `gh` CLI:
```bash
# Create PR for completed task
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
# Reference task in commits
git commit -m "feat: implement JWT auth (task 1.2)"
```
### Parallel Development with Git Worktrees
```bash
# Create worktrees for parallel task development
git worktree add ../project-auth feature/auth-system
git worktree add ../project-api feature/api-refactor
# Run Claude Code in each worktree
cd ../project-auth && claude # Terminal 1: Auth work
cd ../project-api && claude # Terminal 2: API work
```
## Troubleshooting
### AI Commands Failing
```bash
# Check API keys are configured
cat .env # For CLI usage
# Verify model configuration
task-master models
# Test with different model
task-master models --set-fallback gpt-4o-mini
```
### MCP Connection Issues
- Check `.mcp.json` configuration
- Verify Node.js installation
- Use `--mcp-debug` flag when starting Claude Code
- Use CLI as fallback if MCP unavailable
### Task File Sync Issues
```bash
# Regenerate task files from tasks.json
task-master generate
# Fix dependency issues
task-master fix-dependencies
```
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
## Important Notes
### AI-Powered Operations
These commands make AI calls and may take up to a minute:
- `parse_prd` / `task-master parse-prd`
- `analyze_project_complexity` / `task-master analyze-complexity`
- `expand_task` / `task-master expand`
- `expand_all` / `task-master expand --all`
- `add_task` / `task-master add-task`
- `update` / `task-master update`
- `update_task` / `task-master update-task`
- `update_subtask` / `task-master update-subtask`
### File Management
- Never manually edit `tasks.json` - use commands instead
- Never manually edit `.taskmaster/config.json` - use `task-master models`
- Task markdown files in `tasks/` are auto-generated
- Run `task-master generate` after manual changes to tasks.json
### Claude Code Session Management
- Use `/clear` frequently to maintain focused context
- Create custom slash commands for repeated Task Master workflows
- Configure tool allowlist to streamline permissions
- Use headless mode for automation: `claude -p "task-master next"`
### Multi-Task Updates
- Use `update --from=<id>` to update multiple future tasks
- Use `update-task --id=<id>` for single task updates
- Use `update-subtask --id=<id>` for implementation logging
### Research Mode
- Add `--research` flag for research-based AI enhancement
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
- Provides more informed task creation and updates
- Recommended for complex technical tasks
---
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._

43
.taskmaster/config.json Normal file
View File

@@ -0,0 +1,43 @@
{
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-sonnet-4-20250514",
"maxTokens": 64000,
"temperature": 0.2
},
"research": {
"provider": "perplexity",
"modelId": "sonar",
"maxTokens": 8700,
"temperature": 0.1
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 120000,
"temperature": 0.2
}
},
"global": {
"logLevel": "info",
"debug": false,
"defaultNumTasks": 10,
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseURL": "http://localhost:11434/api",
"bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com",
"responseLanguage": "English",
"enableCodebaseAnalysis": true,
"userId": "1234567890",
"azureBaseURL": "https://your-endpoint.azure.com/",
"defaultTag": "master"
},
"claudeCode": {},
"grokCli": {
"timeout": 120000,
"workingDirectory": null,
"defaultModel": "grok-4-latest"
}
}

View File

@@ -0,0 +1,188 @@
# Task Master Migration Roadmap
## Overview
Gradual migration from scripts-based architecture to a clean monorepo with separated concerns.
## Architecture Vision
```
┌─────────────────────────────────────────────────┐
│ User Interfaces │
├──────────┬──────────┬──────────┬────────────────┤
│ @tm/cli │ @tm/mcp │ @tm/ext │ @tm/web │
│ (CLI) │ (MCP) │ (VSCode)│ (Future) │
└──────────┴──────────┴──────────┴────────────────┘
┌──────────────────────┐
│ @tm/core │
│ (Business Logic) │
└──────────────────────┘
```
## Migration Phases
### Phase 1: Core Extraction ✅ (In Progress)
**Goal**: Move all business logic to @tm/core
- [x] Create @tm/core package structure
- [x] Move types and interfaces
- [x] Implement TaskMasterCore facade
- [x] Move storage adapters
- [x] Move task services
- [ ] Move AI providers
- [ ] Move parser logic
- [ ] Complete test coverage
### Phase 2: CLI Package Creation 🚧 (Started)
**Goal**: Create @tm/cli as a thin presentation layer
- [x] Create @tm/cli package structure
- [x] Implement Command interface pattern
- [x] Create CommandRegistry
- [x] Build legacy bridge/adapter
- [x] Migrate list-tasks command
- [ ] Migrate remaining commands one by one
- [ ] Remove UI logic from core
### Phase 3: Transitional Integration
**Goal**: Use new packages in existing scripts without breaking changes
```javascript
// scripts/modules/commands.js gradually adopts new commands
import { ListTasksCommand } from '@tm/cli';
const listCommand = new ListTasksCommand();
// Old interface remains the same
programInstance
.command('list')
.action(async (options) => {
// Use new command internally
const result = await listCommand.execute(convertOptions(options));
});
```
### Phase 4: MCP Package
**Goal**: Separate MCP server as its own package
- [ ] Create @tm/mcp package
- [ ] Move MCP server code
- [ ] Use @tm/core for all logic
- [ ] MCP becomes a thin RPC layer
### Phase 5: Complete Migration
**Goal**: Remove old scripts, pure monorepo
- [ ] All commands migrated to @tm/cli
- [ ] Remove scripts/modules/task-manager/*
- [ ] Remove scripts/modules/commands.js
- [ ] Update bin/task-master.js to use @tm/cli
- [ ] Clean up dependencies
## Current Transitional Strategy
### 1. Adapter Pattern (commands-adapter.js)
```javascript
// Checks if new CLI is available and uses it
// Falls back to legacy implementation if not
export async function listTasksAdapter(...args) {
if (cliAvailable) {
return useNewImplementation(...args);
}
return useLegacyImplementation(...args);
}
```
### 2. Command Bridge Pattern
```javascript
// Allows new commands to work in old code
const bridge = new CommandBridge(new ListTasksCommand());
const data = await bridge.run(legacyOptions); // Legacy style
const result = await bridge.execute(newOptions); // New style
```
### 3. Gradual File Migration
Instead of big-bang refactoring:
1. Create new implementation in @tm/cli
2. Add adapter in commands-adapter.js
3. Update commands.js to use adapter
4. Test both paths work
5. Eventually remove adapter when all migrated
## Benefits of This Approach
1. **No Breaking Changes**: Existing CLI continues to work
2. **Incremental PRs**: Each command can be migrated separately
3. **Parallel Development**: New features can use new architecture
4. **Easy Rollback**: Can disable new implementation if issues
5. **Clear Separation**: Business logic (core) vs presentation (cli/mcp/etc)
## Example PR Sequence
### PR 1: Core Package Setup ✅
- Create @tm/core
- Move types and interfaces
- Basic TaskMasterCore implementation
### PR 2: CLI Package Foundation ✅
- Create @tm/cli
- Command interface and registry
- Legacy bridge utilities
### PR 3: First Command Migration
- Migrate list-tasks to new system
- Add adapter in scripts
- Test both implementations
### PR 4-N: Migrate Commands One by One
- Each PR migrates 1-2 related commands
- Small, reviewable changes
- Continuous delivery
### Final PR: Cleanup
- Remove legacy implementations
- Remove adapters
- Update documentation
## Testing Strategy
### Dual Testing During Migration
```javascript
describe('List Tasks', () => {
it('works with legacy implementation', async () => {
// Force legacy
const result = await legacyListTasks(...);
expect(result).toBeDefined();
});
it('works with new implementation', async () => {
// Force new
const command = new ListTasksCommand();
const result = await command.execute(...);
expect(result.success).toBe(true);
});
it('adapter chooses correctly', async () => {
// Let adapter decide
const result = await listTasksAdapter(...);
expect(result).toBeDefined();
});
});
```
## Success Metrics
- [ ] All commands migrated without breaking changes
- [ ] Test coverage maintained or improved
- [ ] Performance maintained or improved
- [ ] Cleaner, more maintainable codebase
- [ ] Easy to add new interfaces (web, desktop, etc.)
## Notes for Contributors
1. **Keep PRs Small**: Migrate one command at a time
2. **Test Both Paths**: Ensure legacy and new both work
3. **Document Changes**: Update this roadmap as you go
4. **Communicate**: Discuss in PRs if architecture needs adjustment
This is a living document - update as the migration progresses!

View File

@@ -32,7 +32,7 @@ The script can be configured through environment variables in a `.env` file at t
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false)
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `TASKMASTER_LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
- `PROJECT_NAME`: Override default project name in tasks.json
@@ -47,7 +47,7 @@ The script can be configured through environment variables in a `.env` file at t
- Tasks can have `subtasks` for more detailed implementation steps.
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **Script Commands**
2. **Script Commands**
You can run the script via:
```bash
@@ -225,7 +225,7 @@ To use the Perplexity integration:
## Logging
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default)
@@ -382,25 +382,25 @@ The output report structure is:
```json
{
"meta": {
"generatedAt": "2023-06-15T12:34:56.789Z",
"tasksAnalyzed": 20,
"thresholdScore": 5,
"projectName": "Your Project Name",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 8,
"taskTitle": "Develop Implementation Drift Handling",
"complexityScore": 9.5,
"recommendedSubtasks": 6,
"expansionPrompt": "Create subtasks that handle detecting...",
"reasoning": "This task requires sophisticated logic...",
"expansionCommand": "node scripts/dev.js expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
}
// More tasks sorted by complexity score (highest first)
]
"meta": {
"generatedAt": "2023-06-15T12:34:56.789Z",
"tasksAnalyzed": 20,
"thresholdScore": 5,
"projectName": "Your Project Name",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 8,
"taskTitle": "Develop Implementation Drift Handling",
"complexityScore": 9.5,
"recommendedSubtasks": 6,
"expansionPrompt": "Create subtasks that handle detecting...",
"reasoning": "This task requires sophisticated logic...",
"expansionCommand": "node scripts/dev.js expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
}
// More tasks sorted by complexity score (highest first)
]
}
```

View File

@@ -0,0 +1,91 @@
<context>
# Overview
Add a new CLI command: `task-master start <task_id>` (alias: `tm start <task_id>`). This command hard-codes `claude-code` as the executor, fetches task details, builds a standardized prompt, runs claude-code, shows the result, checks for git changes, and auto-marks the task as done if successful.
We follow the Commander class pattern, reuse task retrieval from `show` command flow. Extremely minimal for 1-hour hackathon timeline.
# Core Features
- `start` command (Commander class style)
- Hard-coded executor: `claude-code`
- Standardized prompt designed for minimal changes following existing patterns
- Shows claude-code output (no streaming)
- Git status check for success detection
- Auto-mark task done if successful
# User Experience
```
task-master start 12
```
1) Fetches Task #12 details
2) Builds standardized prompt with task context
3) Runs claude-code with the prompt
4) Shows output
5) Checks git status for changes
6) Auto-marks task done if changes detected
</context>
<PRD>
# Technical Architecture
- Command pattern:
- Create `apps/cli/src/commands/start.command.ts` modeled on [list.command.ts](mdc:apps/cli/src/commands/list.command.ts) and task lookup from [show.command.ts](mdc:apps/cli/src/commands/show.command.ts)
- Task retrieval:
- Use `@tm/core` via `createTaskMasterCore` to get task by ID
- Extract: id, title, description, details
- Executor (ultra-simple approach):
- Execute `claude "full prompt here"` command directly
- The prompt tells Claude to first run `tm show <task_id>` to get task details
- Then tells Claude to implement the code changes
- This opens Claude CLI interface naturally in the current terminal
- No subprocess management needed - just execute the command
- Execution flow:
1) Validate `<task_id>` exists; exit with error if not
2) Build standardized prompt that includes instructions to run `tm show <task_id>`
3) Execute `claude "prompt"` command directly in terminal
4) Claude CLI opens, runs `tm show`, then implements changes
5) After Claude session ends, run `git status --porcelain` to detect changes
6) If changes detected, auto-run `task-master set-status --id=<task_id> --status=done`
- Success criteria:
- Success = exit code 0 AND git shows modified/created files
- Print changed file paths; warn if no changes detected
# Development Roadmap
MVP (ship in ~1 hour):
1) Implement `start.command.ts` (Commander class), parse `<task_id>`
2) Validate task exists via tm-core
3) Build prompt that tells Claude to run `tm show <task_id>` then implement
4) Execute `claude "prompt"` command, then check git status and auto-mark done
# Risks and Mitigations
- Executor availability: Error clearly if `claude-code` provider fails
- False success: Git-change heuristic acceptable for hackathon MVP
# Appendix
**Standardized Prompt Template:**
```
You are an AI coding assistant with access to this repository's codebase.
First, run this command to get the task details:
tm show <task_id>
Then implement the task with these requirements:
- Make the SMALLEST number of code changes possible
- Follow ALL existing patterns in the codebase (you have access to analyze the code)
- Do NOT over-engineer the solution
- Use existing files/functions/patterns wherever possible
- When complete, print: COMPLETED: <brief summary of changes>
Begin by running tm show <task_id> to understand what needs to be implemented.
```
**Key References:**
- [list.command.ts](mdc:apps/cli/src/commands/list.command.ts) - Command structure
- [show.command.ts](mdc:apps/cli/src/commands/show.command.ts) - Task validation
- Node.js `child_process.exec()` - For executing `claude "prompt"` command
</PRD>

View File

@@ -0,0 +1,128 @@
---
title: Research Session
query: "how can i improve the scope-up and scope-down command"
date: 6/14/2025
time: 4:35:03 PM
timestamp: 2025-06-14T20:35:03.231Z
exchanges: 2
---
# Research Session
## Initial Query
**Question:** how can i improve the scope-up and scope-down command
**Response:**
## Improving the `scope-up` and `scope-down` Commands
**Clarify Command Purpose and User Experience**
- Ensure the commands have clear, intuitive behavior. For example, `scope-up` should consistently broaden the context or task view, while `scope-down` should reliably narrow it.
- Provide immediate, user-friendly feedback after each command, indicating what changed (e.g., "Now viewing parent task and all subtasks" or "Focused on subtask: X").
- Document the commands with examples in your `docs/command-reference.md` and `docs/examples.md` to help users understand their effects and use cases.
**Enhance Context Awareness**
- Make the commands context-sensitive: if the user is already at the top or bottom of the scope hierarchy, return a helpful message instead of failing silently.
- Allow optional arguments to specify the exact level or target (e.g., `scope-up 2` to move up two levels, or `scope-down <subtask-id>` to jump directly to a subtask).
**Robust Error Handling and Validation**
- Implement checks to prevent invalid operations, such as attempting to scope up from the root or scope down when no subtasks exist.
- Provide clear error messages and suggestions for next steps, improving user trust and reducing confusion[1][5].
**Integrate with Task and Tag Systems**
- Ensure `scope-up` and `scope-down` interact smoothly with your tagging and task hierarchy features. For example, scoping up from a subtask should show the parent task and its context, while scoping down should allow selection from available subtasks or related tags.
- Consider supporting batch operations, such as scoping down into all subtasks and displaying them in a summarized view.
**Improve Performance and Synchronization**
- Optimize the underlying logic to minimize delays, especially in large task trees. Use asynchronous operations where possible to keep the UI responsive.
- If the commands trigger data loading or context switching, ensure synchronization so that subsequent commands operate on the correct, updated context[2][4].
**Testing and Stakeholder Feedback**
- Add or expand unit and integration tests for these commands (see `tests/unit/commands.test.js` and `integration/cli/commands.test.js`) to cover edge cases and ensure reliability.
- Gather feedback from users and stakeholders to identify pain points and desired enhancements, then iterate on the command design and implementation[1][5].
**Example Improvements Table**
| Area | Current Issue | Suggested Improvement |
|---------------------|-----------------------------|----------------------------------------------|
| User Feedback | Minimal or unclear output | Add explicit, contextual messages |
| Error Handling | Silent failures | Informative errors and recovery suggestions |
| Flexibility | Only single-level movement | Support multi-level and targeted navigation |
| Integration | Limited context awareness | Sync with tags, parent/child relationships |
| Performance | Slow on large hierarchies | Optimize data access and UI updates |
By focusing on these areas, you can make `scope-up` and `scope-down` more robust, user-friendly, and aligned with best practices in scope management and command design[1][5].
---
## Follow-up 1
**Question:** how might i do this relative to the tag system?
**Response:**
## Integrating Scope-Up and Scope-Down with the Tag System
**Conceptual Mapping**
- In your project, *scope-up* and *scope-down* commands currently operate on the task hierarchy, broadening or narrowing the context by moving between parent and child tasks.
- The tag system provides a parallel, orthogonal way to group and filter tasks—tags can represent categories, priorities, or any custom grouping, independent of strict parent/child relationships.
**How to Make Scope Commands Tag-Aware**
- **Scoping by Tag**: Allow users to "scope-down" into a tag, viewing only tasks associated with that tag. Conversely, "scope-up" could move from a specific tag context back to the broader task list or to a parent tag grouping if you support tag hierarchies.
- **Tag-Scoped Views**: When a tag is active as the current scope, all navigation and operations (listing, editing, etc.) are limited to tasks with that tag. This is similar to how some systems let you set the "Tag Scope" to filter navigation and search to only tagged items[1][5].
- **Combining Hierarchy and Tags**: Enable compound scoping, such as "all subtasks of Task X that also have Tag Y." This can be implemented by intersecting the results of hierarchical and tag-based queries.
**Implementation Strategies**
- **Scope Stack or Context Object**: Maintain a stack or context object that tracks both the current task scope and any active tag filters. Each scope change (up/down or tag in/out) updates this context.
- **Commands**:
- `scope-down --tag <tag>`: Narrows the view to tasks with the specified tag.
- `scope-up --tag`: Removes the tag filter, broadening the view.
- `scope-down <subtask-id> --tag <tag>`: Narrows to a specific subtask *and* applies a tag filter.
- **Tag Hierarchies (Optional)**: If your tag system supports parent/child tags or tag groups, allow "scope-up" to move from a specific tag to its parent tag or group, and "scope-down" to move into a child tag[4][5].
**Example User Flows**
- *Scoping Down by Tag*:
User runs `scope-down --tag urgent` → Only tasks tagged "urgent" are shown.
- *Combining Task and Tag*:
User runs `scope-down <task-id> --tag frontend` → Only subtasks of `<task-id>` that are tagged "frontend" are shown.
- *Scoping Up from Tag*:
User runs `scope-up --tag` → Removes the tag filter, returning to the previous broader context.
**Technical Considerations**
- **Efficient Filtering**: Use indexed queries or in-memory filtering to efficiently combine tag and hierarchy filters, especially for large task sets.
- **Feedback and UI**: Always display the current scope context (e.g., "Viewing tasks tagged 'urgent' under 'Feature X'") so users understand what they're seeing.
- **Extensibility**: Design the scope system so new types of scopes (e.g., by status, assignee) can be added in the future, not just tags and hierarchy.
**Relevant Precedents**
- Tag-based file systems and management tools often implement "scopes" as dynamic groups defined by tag criteria, allowing users to build up complex views by combining tags and other filters[5].
- Some systems allow scoping into tag management itself, where you can create, edit, or view tags and their associated objects, which could be mirrored in your CLI or UI[4].
**Summary Table**
| Command Example | Resulting Scope |
|----------------------------------|--------------------------------------------------|
| `scope-down --tag bug` | All tasks tagged "bug" |
| `scope-down <task-id> --tag api` | Subtasks of `<task-id>` tagged "api" |
| `scope-up --tag` | Removes tag filter, returns to previous scope |
| `scope-down --tag frontend` | All tasks tagged "frontend" |
By integrating tag-based scoping, you make your scope commands more flexible and powerful, supporting both hierarchical and ad-hoc organizational strategies[1][5].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T20:35:03.231Z*

View File

@@ -0,0 +1,158 @@
---
title: Research Session
query: "should i be using any specific libraries for this?"
date: 6/14/2025
time: 5:20:00 PM
timestamp: 2025-06-14T21:20:00.561Z
exchanges: 2
---
# Research Session
## Initial Query
**Question:** should i be using any specific libraries for this?
**Response:**
HELL YEAH PARTNER
For implementing a GitHub Issue export feature with bidirectional linking in your project, you absolutely should use a dedicated library for interacting with the GitHub API. This will save you a ton of time, reduce boilerplate, and help you avoid common pitfalls with authentication, pagination, and error handling.
## Recommended Library: PyGithub
- **PyGithub** is the most widely used and well-documented Python library for accessing the GitHub REST API v3. It allows you to manage repositories, issues, user profiles, and more, all with a clean, object-oriented interface[1][2][3][5].
- It supports all the operations youll need for your export feature, including creating issues, updating them, and managing references for bidirectional linking.
### Key Features
- **Authentication**: Easily authenticate with a personal access token.
- **Issue Management**: Create, update, and link issues programmatically.
- **Repository Access**: Fetch and manipulate repository data.
- **User/Org Support**: Works for both user and organization repos.
- **Pagination & Rate Limiting**: Handles these for you.
### Example Usage
```python
from github import Github, Auth
# Authenticate with a personal access token
auth = Auth.Token("your_github_token")
g = Github(auth=auth)
# Get the repo
repo = g.get_repo("owner/repo_name")
# Create a new issue
issue = repo.create_issue(
title="Exported from Task Master",
body="This issue was created by Task Master. [Task ID: 123]"
)
# Add a comment or update the issue to include a backlink
issue.create_comment("Linked to Task Master task #123")
```
[3][5]
## Why Not Use Raw Requests?
- While you *can* use the `requests` library to call the GitHub API directly[4], PyGithub abstracts away authentication, error handling, and pagination, making your code much cleaner and less error-prone[2][5].
## Integration Tips
- Store your GitHub token securely (e.g., in environment variables).
- Use PyGithubs objects to fetch, create, and update issues.
- For bidirectional linking, store the GitHub issue URL in your task data and the Task Master task ID in the GitHub issue body or as a label/comment.
- PyGithub is actively maintained and widely used, so youll find plenty of support and documentation.
## Installation
```bash
pip install PyGithub
```
[3]
## Summary Table
| Library | Language | API Coverage | Ease of Use | Maintained | Docs/Support |
|-----------|----------|--------------|-------------|------------|--------------|
| PyGithub | Python | Full | High | Yes | Excellent |
| requests | Python | Full (manual)| Medium | Yes | Good |
**Use PyGithub for all GitHub API interactions in your export/import features.** Its the standard for Python projects and will make your implementation faster, safer, and more maintainable[1][2][3][5].
---
## Follow-up 1
**Question:** we don't want to use py github because we have a node project
**Response:**
HELL YEAH PARTNER
For a Node.js project, you should use a Node-native library to interact with the GitHub API instead of PyGithub, which is Python-only. The industry standard for Node.js is **Octokit**, the official GitHub SDK for JavaScript/TypeScript[1][2].
## Why Use Octokit?
- **Official & Complete**: Octokit is maintained by GitHub and covers all REST and GraphQL API endpoints, including issues, repositories, users, and more[1][2].
- **Universal**: Works in Node.js, browsers, and Deno environments[2].
- **Typed & Tested**: Comes with TypeScript declarations and 100% test coverage[2].
- **Authentication**: Supports personal access tokens, GitHub Apps, OAuth, and more.
- **Pagination & Error Handling**: Handles pagination and common error scenarios out of the box.
- **Extendable**: Supports plugins and custom hooks for advanced use cases[2].
## How to Use Octokit for GitHub Issue Export
Install Octokit in your Node.js project:
```bash
npm install @octokit/rest
```
Basic usage for creating and linking issues:
```js
const { Octokit } = require("@octokit/rest");
// Authenticate with a personal access token
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
// Create a new issue
const { data: issue } = await octokit.issues.create({
owner: "owner",
repo: "repo_name",
title: "Exported from Task Master",
body: "This issue was created by Task Master. [Task ID: 123]"
});
// Add a comment for bidirectional linking
await octokit.issues.createComment({
owner: "owner",
repo: "repo_name",
issue_number: issue.number,
body: "Linked to Task Master task #123"
});
```
## Alternatives
- **node-github**: An older library, less maintained than Octokit, but still functional for basic API access[5].
- **Raw HTTP Requests**: You can use `node-fetch` or `axios` to call the GitHub API directly, but youll need to handle authentication, pagination, and error handling yourself[3]. Octokit abstracts all of this for you.
## Summary Table
| Library | Language | API Coverage | Maintained | TypeScript | Docs/Support |
|-----------------|----------|--------------|------------|------------|--------------|
| Octokit | Node.js | Full | Yes | Yes | Excellent |
| node-github | Node.js | Full | No | No | Limited |
| Raw HTTP | Node.js | Full (manual)| N/A | N/A | N/A |
**Recommendation:** Use Octokit for all GitHub API interactions in your Node.js project. Its the official, most robust, and best-supported option for your use case[1][2].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T21:20:00.561Z*

View File

@@ -0,0 +1,76 @@
---
title: Research Session
query: "test save functionality"
date: 6/14/2025
time: 5:50:23 PM
timestamp: 2025-06-14T21:50:23.797Z
exchanges: 1
---
# Research Session
## Initial Query
**Question:** test save functionality
**Response:**
## Testing Save Functionality in a Task Management System
**Core Steps for Testing Save Functionality**
- Create or update a task in the system using the CLI or UI.
- Trigger the save operation (e.g., by issuing a command or clicking a save button).
- Verify that the data is correctly written to the persistent storage (e.g., `tasks.json`).
- Reload or re-query the data to ensure the saved changes persist and are accurately reflected.
- Validate that all required fields and relationships (such as dependencies and subtasks) are preserved and correctly structured.
**Key Test Scenarios**
- **Basic Save:** Add a new task and confirm it appears in `tasks.json` with all fields populated.
- **Update Save:** Modify an existing task (e.g., change status, description, or priority) and verify the changes are saved.
- **Subtask and Dependency Preservation:** Update a parent task and ensure that completed subtasks and dependency links remain intact, especially after using commands like `updateTask`.
- **Batch Operations:** Perform bulk updates or additions and confirm all affected tasks are saved correctly, with no data loss or corruption.
- **Validation:** Attempt to save invalid data and ensure the system rejects it or provides meaningful error messages, confirming validation logic is enforced.
**Recommended Practices**
- Use automated tests to simulate save operations for various scenarios, including edge cases (e.g., circular dependencies, missing required fields).
- After each save, reload the data and compare it to the expected state to ensure integrity.
- Log all save operations and errors for traceability and debugging.
- Regularly back up the `tasks.json` file to prevent data loss during testing and development.
**Relevant Features from Industry Standards**
- Task management systems typically provide robust save and update mechanisms, ensuring that all task attributes (including dependencies, subtasks, and comments) are consistently maintained[1][2][5].
- Validation and error handling are critical to prevent corrupt or incomplete saves, especially when handling complex relationships or batch operations[1][5].
- User feedback (such as success messages or error alerts) is important for confirming save actions and guiding users in case of issues[1][2].
**Example Test Case**
1. Create a task with subtasks and dependencies.
2. Mark some subtasks as complete.
3. Use the `updateTask` command to modify the parent task.
4. Save and reload the data.
5. Assert that:
- The parent task reflects the updates.
- Completed subtasks remain marked as complete.
- Dependencies are unchanged and valid.
**Summary Table: Save Functionality Test Aspects**
| Aspect | What to Test | Expected Outcome |
|-----------------------|---------------------------------------------------|-----------------------------------------|
| Basic Save | Add/update task, save, reload | Data persists and matches expectations |
| Subtask Preservation | Update parent, check subtask status | Completed subtasks remain complete |
| Dependency Handling | Save with dependencies, reload | Dependencies are intact and valid |
| Batch Operations | Bulk save/update, reload | All changes persist, no data loss |
| Validation | Save invalid data | Error is raised, data not corrupted |
These steps and scenarios ensure that the save functionality is robust, reliable, and meets the requirements of a modern task management system[1][2][5].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T21:50:23.797Z*

View File

@@ -0,0 +1,81 @@
---
title: Research Session
query: "test the fix for duplicate saves - final test"
date: 6/14/2025
time: 6:10:00 PM
timestamp: 2025-06-14T22:10:00.394Z
exchanges: 1
---
# Research Session
## Initial Query
**Question:** test the fix for duplicate saves - final test
**Response:**
## Steps to Test the Fix for Duplicate Saves
**1. Prepare a Clean Test Environment**
- Ensure the tasks.json file and any related data stores are in a known, clean state with no pre-existing duplicate entries.
- Back up the current tasks.json in case rollback is needed.
**2. Define Test Scenarios**
- Attempt to save a new task with unique data.
- Attempt to save a task with the same ID or unique identifier as an existing task (simulate a duplicate).
- Attempt to save a task with the same title or content but a different ID (to test if the fix is based on ID or content).
- Simultaneously trigger multiple save operations (if the system supports concurrency) to test race conditions.
**3. Execute Manual and Automated Tests**
- Use the application's UI or API to create and save tasks as per the scenarios above.
- For each save operation, check the tasks.json file or the data store to verify:
- No duplicate entries are created.
- Existing tasks are not overwritten unless intended (e.g., for updates).
- The system returns appropriate error messages or warnings when a duplicate save is attempted.
**4. Validate System Behavior**
- Confirm that after all test operations, each task in tasks.json is unique according to the defined criteria (ID, title, or other unique fields).
- If the system is designed to merge duplicates, verify that merging occurs as expected.
- If the system is designed to reject duplicates, ensure that the rejection is clear and no duplicate is present.
**5. Test Edge Cases**
- Attempt to save tasks with minor variations (e.g., whitespace differences, case sensitivity) to ensure the duplicate detection logic is robust.
- Test with large numbers of tasks to ensure performance and correctness at scale.
**6. Review Logs and Error Handling**
- Check application logs for any errors or warnings related to duplicate saves.
- Ensure that error handling is user-friendly and provides actionable feedback.
**7. Regression Testing**
- Run the full suite of task operations (create, update, delete) to ensure the fix for duplicate saves does not introduce new issues elsewhere in the system.
## Additional Best Practices
- Communicate test results with the team to confirm the fix is effective and to prevent future regressions[1][2][5].
- Consider implementing automated duplicate detection as part of the save operation to prevent future issues[2][3].
- Document the test cases and results for future reference and audits.
## Example Test Case Table
| Test Scenario | Expected Result | Actual Result | Pass/Fail |
|--------------------------------------|-------------------------------|---------------|-----------|
| Save unique task | Task saved | | |
| Save duplicate task (same ID) | Duplicate rejected/merged | | |
| Save duplicate task (same title) | Duplicate rejected/merged | | |
| Simultaneous saves (race condition) | Only one unique task present | | |
| Save with minor variations | No false positives/negatives | | |
Fill in the "Actual Result" and "Pass/Fail" columns during testing.
## Action Items
- Complete all test scenarios above.
- Document any issues found and retest after fixes.
- Confirm with stakeholders before closing the issue.
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T22:10:00.394Z*

View File

@@ -0,0 +1,153 @@
---
title: Research Session
query: "do we need to add new commands or can we just weaponize the gh cli tool"
date: 2025-08-01
time: 2:27:52 p.m.
timestamp: 2025-08-01T11:27:52.249Z
exchanges: 3
---
# Research Session
## Initial Query
**Question:** do we need to add new commands or can we just weaponize the gh cli tool
**Response:**
For the implementation of the `task-master git` command suite to automate git workflows (Task 97), it is possible to leverage the existing **GitHub CLI (`gh`) tool** rather than creating entirely new git commands from scratch. The GitHub CLI provides a rich set of commands that cover many GitHub-related operations such as branch management, pull request handling, workflow triggering, and release management, which can be scripted and integrated into your CLI tool[1][2][3][4].
### Key Points Supporting Weaponizing GitHub CLI:
- **Comprehensive GitHub Operations**: The `gh` CLI supports creating branches, managing pull requests, releases, tags, and even triggering and monitoring GitHub Actions workflows. This aligns well with the requirements of automated branch management, commit generation, and PR description generation in Task 97[1][3].
- **Scripting and Automation Friendly**: GitHub CLI commands can be scripted and integrated into custom workflows or CLI tools. You can create aliases or wrap `gh` commands inside your own CLI commands to provide a seamless user experience while relying on the battle-tested GitHub CLI for underlying operations[1][3].
- **Authentication and Permissions**: `gh` uses environment variables like `GH_TOKEN` or `GITHUB_TOKEN` for authentication, which can be securely managed in CI/CD pipelines or local environments. This simplifies integration without needing to implement custom authentication logic[3][4].
- **Extensibility**: If some specific git workflow features are not directly supported by `gh`, you can extend it with custom scripts or combine it with native git commands. This hybrid approach reduces the need to reinvent core git operations while allowing customization[1].
### Considerations for Your Project:
- Since Task 97 requires **automated branch management** (branch creation, validation, switching, cleanup), **intelligent commit generation**, and **PR description generation**, you can implement these by invoking `gh` commands programmatically within your `task-master git` commands.
- For example, branch creation and switching can be done with native git commands wrapped in your CLI, while PR creation and management can be handled via `gh pr create`, `gh pr merge`, etc.
- You may still need to implement some **custom logic** for commit type detection, branch name validation, and PR description generation based on your task metadata, but the underlying git and GitHub operations can be delegated to `gh`.
- This approach aligns with your existing CLI foundation (Task 2) and leverages a well-supported tool, reducing development effort and increasing reliability.
### Summary
You **do not necessarily need to add entirely new git commands** for Task 97. Instead, you can **weaponize the GitHub CLI (`gh`) tool** by wrapping and scripting its commands within your `task-master git` command suite. This will allow you to automate git workflows efficiently, maintain consistency, and leverage GitHubs API capabilities without reinventing the wheel[1][2][3][4].
If there are gaps in `gh` functionality for your specific workflow needs, you can supplement with native git commands or custom scripts, but the core git and GitHub operations should be handled by `gh` for best results.
---
## Follow-up 1
**Question:** how does this relate to git worktrees? i hear that they get super complicated when trying to implement them.
**Response:**
Git worktrees allow you to have multiple working directories attached to the same Git repository, each checked out to different branches simultaneously. This enables parallel development workflows without the overhead of cloning the repository multiple times or constantly switching branches in a single working directory[2][3].
However, **implementing or managing git worktrees can get complicated** for several reasons:
- **Complexity for users and tooling:** Managing multiple active worktrees requires careful tracking of which directory corresponds to which branch. This can be confusing and error-prone, especially for novices or when many worktrees are in use simultaneously. Mistakes like committing to the wrong branch or working in the wrong directory are common risks[1].
- **Maintenance overhead:** Worktrees accumulate over time and need to be pruned or cleaned up regularly (`git worktree prune`) to avoid clutter and potential confusion. This adds an extra maintenance step to the workflow[1].
- **Syncing and update challenges:** Each worktree is a separate checkout and can become outdated if not regularly updated from the main repository. This can lead to merge conflicts or redundant work if branches diverge significantly[1].
- **Tooling and integration limitations:** Not all Git tools, scripts, or GUIs fully support worktrees or are optimized for them. This can cause inconsistencies or require additional custom tooling to manage worktrees effectively[1].
- **Performance considerations:** Managing multiple worktrees simultaneously can have performance implications, especially in very large repositories, due to the overhead of maintaining multiple checkouts and metadata[1].
In the context of your project, which involves automating git workflows and possibly wrapping or extending git/GitHub CLI commands, these complexities imply:
- If you consider supporting git worktrees in your `task-master git` command suite, you will need to handle the complexity of managing multiple directories and branches carefully.
- You might need to implement additional logic or tooling to track and manage worktrees, avoid user confusion, and ensure synchronization between them.
- Since your project already plans to leverage the GitHub CLI (`gh`) and native git commands, you could integrate worktree commands (`git worktree add`, `git worktree remove`, `git worktree list`) but should be prepared for the added complexity in workflow management and user documentation.
- Custom wrappers or managers (like the one described in [3]) can help reduce friction by automating worktree creation, switching, and cleanup, which might be a useful approach to consider.
Overall, **git worktrees provide powerful parallel branch management but introduce complexity in implementation and user experience** that must be carefully managed through tooling, automation, and clear documentation[1][3][4].
---
**Summary Table of Git Worktree Challenges and Considerations**
| Aspect | Description | Implication for Project |
|-------------------------|-----------------------------------------------------------------------------------------------|----------------------------------------------------------|
| User Complexity | Confusing multiple directories and branches | Need clear UI/UX and safeguards |
| Maintenance Overhead | Requires pruning and cleanup of stale worktrees | Automate cleanup or provide commands |
| Syncing Issues | Worktrees can become outdated or diverge | Implement update checks and sync workflows |
| Tooling Support | Limited support in some Git tools and GUIs | May require custom tooling or wrappers |
| Performance | Overhead in large repos with many worktrees | Monitor and optimize performance |
| Workflow Automation | Manual worktree management is tedious | Build custom managers or wrappers to simplify usage |
---
Given your projects focus on automating git workflows and leveraging existing CLI tools, **implementing git worktree support is feasible but will require careful design to handle these complexities effectively**. You may want to start with basic worktree commands and incrementally add automation and safeguards as needed.
---
## Follow-up 2
**Question:** since we already have a way to have separated task lists per branch, couldn't we do the same thing for worktrees? each taskmaster list (tag) would have its own worktree based on the name of the tag?
**Response:**
Yes, you can apply a similar approach used for separated task lists per branch to git worktrees by associating each taskmaster list (tag) with its own git worktree named after the tag. This means each tag would correspond to a dedicated worktree directory checked out to a branch or commit related to that tag, enabling isolated parallel work environments for each task list.
### How This Maps to Git Worktrees
- **Git worktrees** allow multiple working directories linked to the same repository, each checked out to a different branch or commit[1][2]. This lets you work on multiple branches simultaneously without switching contexts in a single directory.
- When you create a worktree with `git worktree add <path> [<branch>]`, Git creates a new linked working tree at `<path>`, optionally checking out a specified branch or creating a new one[1][2]. Naming the worktree directory after the tag (taskmaster list) is straightforward and semantically clear.
- This setup mirrors your existing branch-based task list separation but extends it to physical directories, which can improve workflow isolation and reduce context switching.
### Benefits for Your Project
- **Isolated environments per task list/tag:** Each tags worktree can have its own checked-out branch, allowing independent development, testing, or review without interference.
- **Parallel workflows:** Developers can switch between worktrees (directories) instead of switching branches in one directory, reducing errors and improving productivity.
- **Automation potential:** Your `task-master git` commands can automate creating, switching, and cleaning up these worktrees based on tags, similar to how you manage branches and task lists.
### Challenges and Considerations
- **Complexity in management:** Git worktrees add complexity in tracking multiple directories and ensuring users operate in the correct one[1]. Your CLI should provide clear commands and feedback to avoid confusion.
- **Maintenance overhead:** Worktrees need pruning and cleanup (`git worktree prune` or `git worktree remove`) to avoid clutter[1]. Automating cleanup in your tool would be beneficial.
- **Syncing and updates:** Each worktree is a separate checkout and can become outdated. Your automation should include commands to update or rebase worktrees as needed.
- **Tooling support:** Not all Git tools or scripts fully support worktrees, so your CLI wrappers should handle edge cases and provide a consistent experience[1][3].
### Practical Implementation Ideas
- When a new tag (taskmaster list) is created, run `git worktree add` to create a new worktree directory named after the tag.
- Store metadata linking tags to worktree paths in your taskmaster configuration to track and manage them.
- Provide commands like `task-master worktree list`, `task-master worktree add <tag>`, and `task-master worktree remove <tag>` to manage these worktrees.
- Integrate with GitHub CLI (`gh`) and native git commands to automate branch creation, PR handling, and syncing within each worktree.
- Consider inspiration from existing tools like [wt](https://github.com/taecontrol/wt) that automate worktree environment setup and teardown[3].
### Summary
Using git worktrees per taskmaster tag is a feasible and potentially powerful extension of your current branch-based task list separation. It offers isolated, parallel working directories aligned with your tags, improving workflow clarity and reducing branch-switching overhead. However, it requires careful tooling and automation to manage complexity, maintenance, and synchronization effectively. Given your projects focus on automating git workflows and leveraging CLI tools, implementing this feature incrementally with robust user feedback and cleanup commands would be a practical approach.
---
*Generated by Task Master Research Command*
*Timestamp: 2025-08-01T11:27:52.249Z*

View File

@@ -0,0 +1,471 @@
# Task Template Importing System - Product Requirements Document
<context>
# Overview
The Task Template Importing system enables seamless integration of external task templates into the Task Master CLI through automatic file discovery. This system allows users to drop task template files into the tasks directory and immediately access them as new tag contexts without manual import commands or configuration. The solution addresses the need for multi-project task management, team collaboration through shared templates, and clean separation between permanent tasks and temporary project contexts.
# Core Features
## Silent Task Template Discovery
- **What it does**: Automatically scans for `tasks_*.json` files in the tasks directory during tag operations
- **Why it's important**: Eliminates friction in adding new task contexts and enables zero-configuration workflow
- **How it works**: File pattern matching extracts tag names from filenames and validates against internal tag keys
## External Tag Resolution System
- **What it does**: Provides fallback mechanism to external files when tags are not found in main tasks.json
- **Why it's important**: Maintains clean separation between core tasks and project-specific templates
- **How it works**: Tag resolution logic checks external files as secondary source while preserving main file precedence
## Read-Only External Tag Access
- **What it does**: Allows viewing and switching to external tags while preventing modifications
- **Why it's important**: Protects template integrity and prevents accidental changes to shared templates
- **How it works**: All task modifications route to main tasks.json regardless of current tag context
## Tag Precedence Management
- **What it does**: Ensures main tasks.json tags override external files with same tag names
- **Why it's important**: Prevents conflicts and maintains data integrity
- **How it works**: Priority system where main file tags take precedence over external file tags
# User Experience
## User Personas
- **Solo Developer**: Manages multiple projects with different task contexts
- **Team Lead**: Shares standardized task templates across team members
- **Project Manager**: Organizes tasks by project phases or feature branches
## Key User Flows
### Template Addition Flow
1. User receives or creates a `tasks_projectname.json` file
2. User drops file into `.taskmaster/tasks/` directory
3. Tag becomes immediately available via `task-master use-tag projectname`
4. User can list, view, and switch to external tag without configuration
### Template Usage Flow
1. User runs `task-master tags` to see available tags including external ones
2. External tags display with `(imported)` indicator
3. User switches to external tag with `task-master use-tag projectname`
4. User can view tasks but modifications are routed to main tasks.json
## UI/UX Considerations
- External tags clearly marked with `(imported)` suffix in listings
- Visual indicators distinguish between main and external tags
- Error messages guide users when external files are malformed
- Read-only warnings when attempting to modify external tag contexts
</context>
<PRD>
# Technical Architecture
## System Components
1. **External File Discovery Engine**
- File pattern scanner for `tasks_*.json` files
- Tag name extraction from filenames using regex
- Dynamic tag registry combining main and external sources
- Error handling for malformed external files
2. **Enhanced Tag Resolution System**
- Fallback mechanism to external files when tags not found in main tasks.json
- Precedence management ensuring main file tags override external files
- Read-only access enforcement for external tags
- Tag metadata preservation during discovery operations
3. **Silent Discovery Integration**
- Automatic scanning during tag-related operations
- Seamless integration with existing tag management functions
- Zero-configuration workflow requiring no manual import commands
- Dynamic tag availability without restart requirements
## Data Models
### External Task File Structure
```json
{
"meta": {
"projectName": "External Project Name",
"version": "1.0.0",
"templateSource": "external",
"createdAt": "ISO-8601 timestamp"
},
"tags": {
"projectname": {
"meta": {
"name": "Project Name",
"description": "Project description",
"createdAt": "ISO-8601 timestamp"
},
"tasks": [
// Array of task objects
]
},
"master": {
// This section is ignored to prevent conflicts
}
}
}
```
### Enhanced Tag Registry Model
```json
{
"mainTags": [
{
"name": "master",
"source": "main",
"taskCount": 150,
"isActive": true
}
],
"externalTags": [
{
"name": "projectname",
"source": "external",
"filename": "tasks_projectname.json",
"taskCount": 25,
"isReadOnly": true
}
]
}
```
## APIs and Integrations
1. **File System Discovery API**
- Directory scanning with pattern matching
- JSON file validation and parsing
- Error handling for corrupted or malformed files
- File modification time tracking for cache invalidation
2. **Enhanced Tag Management API**
- `scanForExternalTaskFiles(projectRoot)` - Discover external template files
- `getExternalTagsFromFiles(projectRoot)` - Extract tag names from external files
- `readExternalTagData(projectRoot, tagName)` - Read specific external tag data
- `getAvailableTags(projectRoot)` - Combined main and external tag listing
3. **Tag Resolution Enhancement**
- Modified `readJSON()` with external file fallback
- Enhanced `tags()` function with external tag display
- Updated `useTag()` function supporting external tag switching
- Read-only enforcement for external tag operations
## Infrastructure Requirements
1. **File System Access**
- Read permissions for tasks directory
- JSON parsing capabilities
- Pattern matching and regex support
- Error handling for file system operations
2. **Backward Compatibility**
- Existing tag operations continue unchanged
- Main tasks.json structure preserved
- No breaking changes to current workflows
- Graceful degradation when external files unavailable
# Development Roadmap
## Phase 1: Core External File Discovery (Foundation)
1. **External File Scanner Implementation**
- Create `scanForExternalTaskFiles()` function in utils.js
- Implement file pattern matching for `tasks_*.json` files
- Add error handling for file system access issues
- Test with various filename patterns and edge cases
2. **Tag Name Extraction System**
- Implement `getExternalTagsFromFiles()` function
- Create regex pattern for extracting tag names from filenames
- Add validation to ensure tag names match internal tag key format
- Handle special characters and invalid filename patterns
3. **External Tag Data Reader**
- Create `readExternalTagData()` function
- Implement JSON parsing with error handling
- Add validation for required tag structure
- Ignore 'master' key in external files to prevent conflicts
## Phase 2: Tag Resolution Enhancement (Core Integration)
1. **Enhanced Tag Registry**
- Implement `getAvailableTags()` function combining main and external sources
- Create tag metadata structure including source information
- Add deduplication logic prioritizing main tags over external
- Implement caching mechanism for performance optimization
2. **Modified readJSON Function**
- Add external file fallback when tag not found in main tasks.json
- Maintain precedence rule: main tasks.json overrides external files
- Preserve existing error handling and validation patterns
- Ensure read-only access for external tags
3. **Tag Listing Enhancement**
- Update `tags()` function to display external tags with `(imported)` indicator
- Show external tag metadata and task counts
- Maintain current tag highlighting and sorting functionality
- Add visual distinction between main and external tags
## Phase 3: User Interface Integration (User Experience)
1. **Tag Switching Enhancement**
- Update `useTag()` function to support external tag switching
- Add read-only warnings when switching to external tags
- Update state.json with external tag context information
- Maintain current tag switching behavior for main tags
2. **Error Handling and User Feedback**
- Implement comprehensive error messages for malformed external files
- Add user guidance for proper external file structure
- Create warnings for read-only operations on external tags
- Ensure graceful degradation when external files are corrupted
3. **Documentation and Help Integration**
- Update command help text to include external tag information
- Add examples of external file structure and usage
- Create troubleshooting guide for common external file issues
- Document file naming conventions and best practices
## Phase 4: Advanced Features and Optimization (Enhancement)
1. **Performance Optimization**
- Implement file modification time caching
- Add lazy loading for external tag data
- Optimize file scanning for directories with many files
- Create efficient tag resolution caching mechanism
2. **Advanced External File Features**
- Support for nested external file directories
- Batch external file validation and reporting
- External file metadata display and management
- Integration with version control ignore patterns
3. **Team Collaboration Features**
- Shared external file validation
- External file conflict detection and resolution
- Team template sharing guidelines and documentation
- Integration with git workflows for template management
# Logical Dependency Chain
## Foundation Layer (Must Be Built First)
1. **External File Scanner**
- Core requirement for all other functionality
- Provides the discovery mechanism for external template files
- Must handle file system access and pattern matching reliably
2. **Tag Name Extraction**
- Depends on file scanner functionality
- Required for identifying available external tags
- Must validate tag names against internal format requirements
3. **External Tag Data Reader**
- Depends on tag name extraction
- Provides access to external tag content
- Must handle JSON parsing and validation safely
## Integration Layer (Builds on Foundation)
4. **Enhanced Tag Registry**
- Depends on all foundation components
- Combines main and external tag sources
- Required for unified tag management across the system
5. **Modified readJSON Function**
- Depends on enhanced tag registry
- Provides fallback mechanism for tag resolution
- Critical for maintaining backward compatibility
6. **Tag Listing Enhancement**
- Depends on enhanced tag registry
- Provides user visibility into external tags
- Required for user discovery of available templates
## User Experience Layer (Completes the Feature)
7. **Tag Switching Enhancement**
- Depends on modified readJSON and tag listing
- Enables user interaction with external tags
- Must enforce read-only access properly
8. **Error Handling and User Feedback**
- Can be developed in parallel with other UX components
- Enhances reliability and user experience
- Should be integrated throughout development process
9. **Documentation and Help Integration**
- Should be developed alongside implementation
- Required for user adoption and proper usage
- Can be completed in parallel with advanced features
## Optimization Layer (Performance and Advanced Features)
10. **Performance Optimization**
- Can be developed after core functionality is stable
- Improves user experience with large numbers of external files
- Not blocking for initial release
11. **Advanced External File Features**
- Can be developed independently after core features
- Enhances power user workflows
- Optional for initial release
12. **Team Collaboration Features**
- Depends on stable core functionality
- Enhances team workflows and template sharing
- Can be prioritized based on user feedback
# Risks and Mitigations
## Technical Challenges
### File System Performance
**Risk**: Scanning for external files on every tag operation could impact performance with large directories.
**Mitigation**:
- Implement file modification time caching to avoid unnecessary rescans
- Use lazy loading for external tag data - only read when accessed
- Add configurable limits on number of external files to scan
- Optimize file pattern matching with efficient regex patterns
### External File Corruption
**Risk**: Malformed or corrupted external JSON files could break tag operations.
**Mitigation**:
- Implement robust JSON parsing with comprehensive error handling
- Add file validation before attempting to parse external files
- Gracefully skip corrupted files and continue with valid ones
- Provide clear error messages guiding users to fix malformed files
### Tag Name Conflicts
**Risk**: External files might contain tag names that conflict with main tasks.json tags.
**Mitigation**:
- Implement strict precedence rule: main tasks.json always overrides external files
- Add warnings when external tags are ignored due to conflicts
- Document naming conventions to avoid common conflicts
- Provide validation tools to check for potential conflicts
## MVP Definition
### Core Feature Scope
**Risk**: Including too many advanced features could delay the core functionality.
**Mitigation**:
- Define MVP as basic external file discovery + tag switching
- Focus on the silent discovery mechanism as the primary value proposition
- Defer advanced features like nested directories and batch operations
- Ensure each phase delivers complete, usable functionality
### User Experience Complexity
**Risk**: The read-only nature of external tags might confuse users.
**Mitigation**:
- Provide clear visual indicators for external tags in all interfaces
- Add explicit warnings when users attempt to modify external tag contexts
- Document the read-only behavior and its rationale clearly
- Consider future enhancement for external tag modification workflows
### Backward Compatibility
**Risk**: Changes to tag resolution logic might break existing workflows.
**Mitigation**:
- Maintain existing tag operations unchanged for main tasks.json
- Add external file support as enhancement, not replacement
- Test thoroughly with existing task structures and workflows
- Provide migration path if any breaking changes are necessary
## Resource Constraints
### Development Complexity
**Risk**: Integration with existing tag management system could be complex.
**Mitigation**:
- Phase implementation to minimize risk of breaking existing functionality
- Create comprehensive test suite covering both main and external tag scenarios
- Use feature flags to enable/disable external file support during development
- Implement thorough error handling to prevent system failures
### File System Dependencies
**Risk**: Different operating systems might handle file operations differently.
**Mitigation**:
- Use Node.js built-in file system APIs for cross-platform compatibility
- Test on multiple operating systems (Windows, macOS, Linux)
- Handle file path separators and naming conventions properly
- Add fallback mechanisms for file system access issues
### User Adoption
**Risk**: Users might not understand or adopt the external file template system.
**Mitigation**:
- Create clear documentation with practical examples
- Provide sample external template files for common use cases
- Integrate help and guidance directly into the CLI interface
- Gather user feedback early and iterate on the user experience
# Appendix
## External File Naming Convention
### Filename Pattern
- **Format**: `tasks_[tagname].json`
- **Examples**: `tasks_feature-auth.json`, `tasks_v2-migration.json`, `tasks_project-alpha.json`
- **Validation**: Tag name must match internal tag key format (alphanumeric, hyphens, underscores)
### File Structure Requirements
```json
{
"meta": {
"projectName": "Required: Human-readable project name",
"version": "Optional: Template version",
"templateSource": "Optional: Source identifier",
"createdAt": "Optional: ISO-8601 timestamp"
},
"tags": {
"[tagname]": {
"meta": {
"name": "Required: Tag display name",
"description": "Optional: Tag description",
"createdAt": "Optional: ISO-8601 timestamp"
},
"tasks": [
// Required: Array of task objects following standard task structure
]
}
}
}
```
## Implementation Functions Specification
### Core Discovery Functions
```javascript
// Scan tasks directory for external template files
function scanForExternalTaskFiles(projectRoot) {
// Returns: Array of external file paths
}
// Extract tag names from external filenames
function getExternalTagsFromFiles(projectRoot) {
// Returns: Array of external tag names
}
// Read specific external tag data
function readExternalTagData(projectRoot, tagName) {
// Returns: Tag data object or null if not found
}
// Get combined main and external tags
function getAvailableTags(projectRoot) {
// Returns: Combined tag registry with metadata
}
```
### Integration Points
```javascript
// Enhanced readJSON with external fallback
function readJSON(projectRoot, tag = null) {
// Modified to check external files when tag not found in main
}
// Enhanced tags listing with external indicators
function tags(projectRoot, options = {}) {
// Modified to display external tags with (imported) suffix
}
// Enhanced tag switching with external support
function useTag(projectRoot, tagName) {
// Modified to support switching to external tags (read-only)
}
```
## Error Handling Specifications
### File System Errors
- **ENOENT**: External file not found - gracefully skip and continue
- **EACCES**: Permission denied - warn user and continue with available files
- **EISDIR**: Directory instead of file - skip and continue scanning
### JSON Parsing Errors
- **SyntaxError**: Malformed JSON - skip file and log warning with filename
- **Missing required fields**: Skip file and provide specific error message
- **Invalid tag structure**: Skip file and guide user to correct format
### Tag Conflict Resolution
- **Duplicate tag names**: Main tasks.json takes precedence, log warning
- **Invalid tag names**: Skip external file and provide naming guidance
- **Master key in external**: Ignore master key, process other tags normally
</PRD>

View File

@@ -0,0 +1,8 @@
Simple Todo App PRD
Create a basic todo list application with the following features:
1. Add new todos
2. Mark todos as complete
3. Delete todos
That's it. Keep it simple.

View File

@@ -0,0 +1,343 @@
# Product Requirements Document: tm-core Package - Parse PRD Feature
## Project Overview
Create a TypeScript package named `tm-core` at `packages/tm-core` that implements parse-prd functionality using class-based architecture similar to the existing AI providers pattern.
## Design Patterns & Architecture
### Patterns to Apply
1. **Factory Pattern**: Use for `ProviderFactory` to create AI provider instances
2. **Strategy Pattern**: Use for `IAIProvider` implementations and `IStorage` implementations
3. **Facade Pattern**: Use for `TaskMasterCore` as the main API entry point
4. **Template Method Pattern**: Use for `BaseProvider` abstract class
5. **Dependency Injection**: Use throughout for testability (pass dependencies via constructor)
6. **Repository Pattern**: Use for `FileStorage` to abstract data persistence
### Naming Conventions
- **Files**: kebab-case (e.g., `task-parser.ts`, `file-storage.ts`)
- **Classes**: PascalCase (e.g., `TaskParser`, `FileStorage`)
- **Interfaces**: PascalCase with 'I' prefix (e.g., `IStorage`, `IAIProvider`)
- **Methods**: camelCase (e.g., `parsePRD`, `loadTasks`)
- **Constants**: UPPER_SNAKE_CASE (e.g., `DEFAULT_MODEL`)
- **Type aliases**: PascalCase (e.g., `TaskStatus`, `ParseOptions`)
## Exact Folder Structure Required
```
packages/tm-core/
├── src/
│ ├── index.ts
│ ├── types/
│ │ └── index.ts
│ ├── interfaces/
│ │ ├── index.ts # Barrel export
│ │ ├── storage.interface.ts
│ │ ├── ai-provider.interface.ts
│ │ └── configuration.interface.ts
│ ├── tasks/
│ │ ├── index.ts # Barrel export
│ │ └── task-parser.ts
│ ├── ai/
│ │ ├── index.ts # Barrel export
│ │ ├── base-provider.ts
│ │ ├── provider-factory.ts
│ │ ├── prompt-builder.ts
│ │ └── providers/
│ │ ├── index.ts # Barrel export
│ │ ├── anthropic-provider.ts
│ │ ├── openai-provider.ts
│ │ └── google-provider.ts
│ ├── storage/
│ │ ├── index.ts # Barrel export
│ │ └── file-storage.ts
│ ├── config/
│ │ ├── index.ts # Barrel export
│ │ └── config-manager.ts
│ ├── utils/
│ │ ├── index.ts # Barrel export
│ │ └── id-generator.ts
│ └── errors/
│ ├── index.ts # Barrel export
│ └── task-master-error.ts
├── tests/
│ ├── task-parser.test.ts
│ ├── integration/
│ │ └── parse-prd.test.ts
│ └── mocks/
│ └── mock-provider.ts
├── package.json
├── tsconfig.json
├── tsup.config.js
└── jest.config.js
```
## Specific Implementation Requirements
### 1. Create types/index.ts
Define these exact TypeScript interfaces:
- `Task` interface with fields: id, title, description, status, priority, complexity, dependencies, subtasks, metadata, createdAt, updatedAt, source
- `Subtask` interface with fields: id, title, description, completed
- `TaskMetadata` interface with fields: parsedFrom, aiProvider, version, tags (optional)
- Type literals: `TaskStatus` = 'pending' | 'in-progress' | 'completed' | 'blocked'
- Type literals: `TaskPriority` = 'low' | 'medium' | 'high' | 'critical'
- Type literals: `TaskComplexity` = 'simple' | 'moderate' | 'complex'
- `ParseOptions` interface with fields: dryRun (optional), additionalContext (optional), tag (optional), maxTasks (optional)
### 2. Create interfaces/storage.interface.ts
Define `IStorage` interface with these exact methods:
- `loadTasks(tag?: string): Promise<Task[]>`
- `saveTasks(tasks: Task[], tag?: string): Promise<void>`
- `appendTasks(tasks: Task[], tag?: string): Promise<void>`
- `updateTask(id: string, task: Partial<Task>, tag?: string): Promise<void>`
- `deleteTask(id: string, tag?: string): Promise<void>`
- `exists(tag?: string): Promise<boolean>`
### 3. Create interfaces/ai-provider.interface.ts
Define `IAIProvider` interface with these exact methods:
- `generateCompletion(prompt: string, options?: AIOptions): Promise<string>`
- `calculateTokens(text: string): number`
- `getName(): string`
- `getModel(): string`
Define `AIOptions` interface with fields: temperature (optional), maxTokens (optional), systemPrompt (optional)
### 4. Create interfaces/configuration.interface.ts
Define `IConfiguration` interface with fields:
- `projectPath: string`
- `aiProvider: string`
- `apiKey?: string`
- `aiOptions?: AIOptions`
- `mainModel?: string`
- `researchModel?: string`
- `fallbackModel?: string`
- `tasksPath?: string`
- `enableTags?: boolean`
### 5. Create tasks/task-parser.ts
Create class `TaskParser` with:
- Constructor accepting `aiProvider: IAIProvider` and `config: IConfiguration`
- Private property `promptBuilder: PromptBuilder`
- Public method `parsePRD(prdPath: string, options: ParseOptions = {}): Promise<Task[]>`
- Private method `readPRD(prdPath: string): Promise<string>`
- Private method `extractTasks(aiResponse: string): Partial<Task>[]`
- Private method `enrichTasks(rawTasks: Partial<Task>[], prdPath: string): Task[]`
- Apply **Dependency Injection** pattern via constructor
### 6. Create ai/base-provider.ts
Copy existing base-provider.js and convert to TypeScript abstract class:
- Abstract class `BaseProvider` implementing `IAIProvider`
- Protected properties: `apiKey: string`, `model: string`
- Constructor accepting `apiKey: string` and `options: { model?: string }`
- Abstract methods matching IAIProvider interface
- Abstract method `getDefaultModel(): string`
- Apply **Template Method** pattern for common provider logic
### 7. Create ai/provider-factory.ts
Create class `ProviderFactory` with:
- Static method `create(config: { provider: string; apiKey?: string; model?: string }): Promise<IAIProvider>`
- Switch statement for providers: 'anthropic', 'openai', 'google'
- Dynamic imports for each provider
- Throw error for unknown providers
- Apply **Factory** pattern for creating provider instances
Example implementation structure:
```typescript
switch (provider.toLowerCase()) {
case 'anthropic':
const { AnthropicProvider } = await import('./providers/anthropic-provider.js');
return new AnthropicProvider(apiKey, { model });
}
```
### 8. Create ai/providers/anthropic-provider.ts
Create class `AnthropicProvider` extending `BaseProvider`:
- Import Anthropic SDK: `import { Anthropic } from '@anthropic-ai/sdk'`
- Private property `client: Anthropic`
- Implement all abstract methods from BaseProvider
- Default model: 'claude-3-sonnet-20240229'
- Handle API errors and wrap with meaningful messages
### 9. Create ai/providers/openai-provider.ts (placeholder)
Create class `OpenAIProvider` extending `BaseProvider`:
- Import OpenAI SDK when implemented
- For now, throw error: "OpenAI provider not yet implemented"
### 10. Create ai/providers/google-provider.ts (placeholder)
Create class `GoogleProvider` extending `BaseProvider`:
- Import Google Generative AI SDK when implemented
- For now, throw error: "Google provider not yet implemented"
### 11. Create ai/prompt-builder.ts
Create class `PromptBuilder` with:
- Method `buildParsePrompt(prdContent: string, options: ParseOptions = {}): string`
- Method `buildExpandPrompt(task: string, context?: string): string`
- Use template literals for prompt construction
- Include specific JSON format instructions in prompts
### 9. Create storage/file-storage.ts
Create class `FileStorage` implementing `IStorage`:
- Private property `basePath: string` set to `{projectPath}/.taskmaster`
- Constructor accepting `projectPath: string`
- Private method `getTasksPath(tag?: string): string` returning correct path based on tag
- Private method `ensureDirectory(dir: string): Promise<void>`
- Implement all IStorage methods
- Handle ENOENT errors by returning empty arrays
- Use JSON format with structure: `{ tasks: Task[], metadata: { version: string, lastModified: string } }`
- Apply **Repository** pattern for data access abstraction
### 10. Create config/config-manager.ts
Create class `ConfigManager`:
- Private property `config: IConfiguration`
- Constructor accepting `options: Partial<IConfiguration>`
- Use Zod for validation with schema matching IConfiguration
- Method `get<K extends keyof IConfiguration>(key: K): IConfiguration[K]`
- Method `getAll(): IConfiguration`
- Method `validate(): boolean`
- Default values: projectPath = process.cwd(), aiProvider = 'anthropic', enableTags = true
### 11. Create utils/id-generator.ts
Export functions:
- `generateTaskId(index: number = 0): string` returning format `task_{timestamp}_{index}_{random}`
- `generateSubtaskId(parentId: string, index: number = 0): string` returning format `{parentId}_sub_{index}_{random}`
### 16. Create src/index.ts
Create main class `TaskMasterCore`:
- Private properties: `config: ConfigManager`, `storage: IStorage`, `aiProvider?: IAIProvider`, `parser?: TaskParser`
- Constructor accepting `options: Partial<IConfiguration>`
- Method `initialize(): Promise<void>` for lazy loading
- Method `parsePRD(prdPath: string, options: ParseOptions = {}): Promise<Task[]>`
- Method `getTasks(tag?: string): Promise<Task[]>`
- Apply **Facade** pattern to provide simple API over complex subsystems
Export:
- Class `TaskMasterCore`
- Function `createTaskMaster(options: Partial<IConfiguration>): TaskMasterCore`
- All types from './types'
- All interfaces from './interfaces/*'
Import statements should use kebab-case:
```typescript
import { TaskParser } from './tasks/task-parser';
import { FileStorage } from './storage/file-storage';
import { ConfigManager } from './config/config-manager';
import { ProviderFactory } from './ai/provider-factory';
```
### 17. Configure package.json
Create package.json with:
- name: "@task-master/core"
- version: "0.1.0"
- type: "module"
- main: "./dist/index.js"
- module: "./dist/index.mjs"
- types: "./dist/index.d.ts"
- exports map for proper ESM/CJS support
- scripts: build (tsup), dev (tsup --watch), test (jest), typecheck (tsc --noEmit)
- dependencies: zod@^3.23.8
- peerDependencies: @anthropic-ai/sdk, openai, @google/generative-ai
- devDependencies: typescript, tsup, jest, ts-jest, @types/node, @types/jest
### 18. Configure TypeScript
Create tsconfig.json with:
- target: "ES2022"
- module: "ESNext"
- strict: true (with all strict flags enabled)
- declaration: true
- outDir: "./dist"
- rootDir: "./src"
### 19. Configure tsup
Create tsup.config.js with:
- entry: ['src/index.ts']
- format: ['cjs', 'esm']
- dts: true
- sourcemap: true
- clean: true
- external: AI provider SDKs
### 20. Configure Jest
Create jest.config.js with:
- preset: 'ts-jest'
- testEnvironment: 'node'
- Coverage threshold: 80% for all metrics
## Build Process
1. Use tsup to compile TypeScript to both CommonJS and ESM
2. Generate .d.ts files for TypeScript consumers
3. Output to dist/ directory
4. Ensure tree-shaking works properly
## Testing Requirements
- Create unit tests for TaskParser in tests/task-parser.test.ts
- Create MockProvider class in tests/mocks/mock-provider.ts for testing without API calls
- Test error scenarios (file not found, invalid JSON, etc.)
- Create integration test in tests/integration/parse-prd.test.ts
- Follow kebab-case naming for all test files
## Success Criteria
- TypeScript compilation with zero errors
- No use of 'any' type
- All interfaces properly exported
- Compatible with existing tasks.json format
- Feature flag support via USE_TM_CORE environment variable
## Import/Export Conventions
- Use named exports for all classes and interfaces
- Use barrel exports (index.ts) in each directory
- Import types/interfaces with type-only imports: `import type { Task } from '../types'`
- Group imports in order: Node built-ins, external packages, internal packages, relative imports
- Use .js extension in import paths for ESM compatibility
## Error Handling Patterns
- Create custom error classes in `src/errors/` directory
- All public methods should catch and wrap errors with context
- Use error codes for different error types (e.g., 'FILE_NOT_FOUND', 'PARSE_ERROR')
- Never expose internal implementation details in error messages
- Log errors to console.error only in development mode
## Barrel Exports Content
### interfaces/index.ts
```typescript
export type { IStorage } from './storage.interface';
export type { IAIProvider, AIOptions } from './ai-provider.interface';
export type { IConfiguration } from './configuration.interface';
```
### tasks/index.ts
```typescript
export { TaskParser } from './task-parser';
```
### ai/index.ts
```typescript
export { BaseProvider } from './base-provider';
export { ProviderFactory } from './provider-factory';
export { PromptBuilder } from './prompt-builder';
```
### ai/providers/index.ts
```typescript
export { AnthropicProvider } from './anthropic-provider';
export { OpenAIProvider } from './openai-provider';
export { GoogleProvider } from './google-provider';
```
### storage/index.ts
```typescript
export { FileStorage } from './file-storage';
```
### config/index.ts
```typescript
export { ConfigManager } from './config-manager';
```
### utils/index.ts
```typescript
export { generateTaskId, generateSubtaskId } from './id-generator';
```
### errors/index.ts
```typescript
export { TaskMasterError } from './task-master-error';
```

View File

@@ -0,0 +1,21 @@
{
"meta": {
"generatedAt": "2025-08-02T14:28:59.851Z",
"tasksAnalyzed": 1,
"totalTasks": 93,
"analysisCount": 1,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": false
},
"complexityAnalysis": [
{
"taskId": 24,
"taskTitle": "Implement AI-Powered Test Generation Command",
"complexityScore": 8,
"recommendedSubtasks": 6,
"expansionPrompt": "Expand task 24 'Implement AI-Powered Test Generation Command' into 6 subtasks, focusing on: 1) Command structure implementation, 2) AI prompt engineering for test generation, 3) Test file generation and output, 4) Framework-specific template implementation, 5) MCP tool integration, and 6) Documentation and help system integration. Include detailed implementation steps, dependencies, and testing approaches for each subtask.",
"reasoning": "This task has high complexity due to several challenging aspects: 1) AI integration requiring sophisticated prompt engineering, 2) Test generation across multiple frameworks, 3) File system operations with proper error handling, 4) MCP tool integration, 5) Complex configuration requirements, and 6) Framework-specific template generation. The task already has 5 subtasks but could benefit from reorganization based on the updated implementation details in the info blocks, particularly around framework support and configuration."
}
]
}

View File

@@ -0,0 +1,93 @@
{
"meta": {
"generatedAt": "2025-07-22T09:41:10.517Z",
"tasksAnalyzed": 10,
"totalTasks": 10,
"analysisCount": 10,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": false
},
"complexityAnalysis": [
{
"taskId": 1,
"taskTitle": "Implement Task Integration Layer (TIL) Core",
"complexityScore": 8,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the TIL Core implementation into distinct components: hook registration system, task lifecycle management, event coordination, state persistence layer, and configuration validation. Each subtask should focus on a specific architectural component with clear interfaces and testable boundaries.",
"reasoning": "This is a foundational component with multiple complex subsystems including event-driven architecture, API integration, state management, and configuration validation. The existing 5 subtasks are well-structured and appropriately sized."
},
{
"taskId": 2,
"taskTitle": "Develop Dependency Monitor with Taskmaster MCP Integration",
"complexityScore": 7,
"recommendedSubtasks": 4,
"expansionPrompt": "Divide the dependency monitor into: dependency graph data structure implementation, circular dependency detection algorithm, Taskmaster MCP integration layer, and real-time notification system. Focus on performance optimization for large graphs and efficient caching strategies.",
"reasoning": "Complex graph algorithms and real-time monitoring require careful implementation. The task involves sophisticated data structures, algorithm design, and API integration with performance constraints."
},
{
"taskId": 3,
"taskTitle": "Build Execution Manager with Priority Queue and Parallel Execution",
"complexityScore": 8,
"recommendedSubtasks": 5,
"expansionPrompt": "Structure the execution manager into: priority queue implementation, resource conflict detection system, parallel execution coordinator, timeout and cancellation handler, and execution history persistence layer. Each component should handle specific aspects of concurrent task management.",
"reasoning": "Managing concurrent execution with resource conflicts, priority scheduling, and persistence is highly complex. Requires careful synchronization, error handling, and performance optimization."
},
{
"taskId": 4,
"taskTitle": "Implement Safety Manager with Configurable Constraints and Emergency Controls",
"complexityScore": 7,
"recommendedSubtasks": 4,
"expansionPrompt": "Break down into: constraint validation engine, emergency control system (stop/pause), user approval workflow implementation, and safety monitoring/audit logging. Each subtask should address specific safety aspects with fail-safe mechanisms.",
"reasoning": "Safety systems require careful design with multiple fail-safes. The task involves validation logic, real-time controls, workflow management, and comprehensive logging."
},
{
"taskId": 5,
"taskTitle": "Develop Event-Based Hook Processor",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "Organize into: file system event integration, Git/VCS event listeners, build system event connectors, and event filtering/debouncing mechanism. Focus on modular event source integration with configurable processing pipelines.",
"reasoning": "While conceptually straightforward, integrating multiple event sources with proper filtering and performance optimization requires careful implementation. Each event source has unique characteristics."
},
{
"taskId": 6,
"taskTitle": "Implement Prompt-Based Hook Processor with AI Integration",
"complexityScore": 7,
"recommendedSubtasks": 4,
"expansionPrompt": "Divide into: prompt interception mechanism, NLP-based task suggestion engine, context injection system, and conversation-based status updater. Each component should handle specific aspects of AI conversation integration.",
"reasoning": "AI integration with prompt analysis and dynamic context injection is complex. Requires understanding of conversation flow, relevance scoring, and seamless integration with existing systems."
},
{
"taskId": 7,
"taskTitle": "Create Update-Based Hook Processor for Automatic Progress Tracking",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "Structure as: code change monitor, acceptance criteria validator, dependency update propagator, and conflict detection/resolution system. Focus on accurate progress tracking and automated validation logic.",
"reasoning": "Automatic progress tracking requires integration with version control and intelligent analysis of code changes. Conflict detection and dependency propagation add complexity."
},
{
"taskId": 8,
"taskTitle": "Develop Real-Time Automation Dashboard and User Controls",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down into: WebSocket real-time communication layer, interactive dependency graph visualization, task queue and status displays, user control interfaces, and analytics/charting components. Each UI component should be modular and reusable.",
"reasoning": "Building a responsive real-time dashboard with complex visualizations and interactive controls is challenging. Requires careful state management, performance optimization, and user experience design."
},
{
"taskId": 9,
"taskTitle": "Integrate Kiro IDE and Taskmaster MCP with Core Services",
"complexityScore": 8,
"recommendedSubtasks": 4,
"expansionPrompt": "Organize into: KiroHookAdapter implementation, TaskmasterMCPAdapter development, error handling and retry logic layer, and IDE UI component integration. Focus on robust adapter patterns and comprehensive error recovery.",
"reasoning": "End-to-end integration of multiple systems with different architectures is highly complex. Requires careful adapter design, extensive error handling, and thorough testing across all integration points."
},
{
"taskId": 10,
"taskTitle": "Implement Configuration Management and Safety Profiles",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "Divide into: visual configuration editor UI, JSON Schema validation engine, import/export functionality, and version control integration. Each component should provide intuitive configuration management with robust validation.",
"reasoning": "While technically less complex than core systems, building an intuitive configuration editor with validation, versioning, and import/export requires careful UI/UX design and robust data handling."
}
]
}

View File

@@ -0,0 +1,53 @@
{
"meta": {
"generatedAt": "2025-06-13T06:52:00.611Z",
"tasksAnalyzed": 5,
"totalTasks": 5,
"analysisCount": 5,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 1,
"taskTitle": "Setup Project Repository and Node.js Environment",
"complexityScore": 4,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the setup process into subtasks such as initializing npm, creating directory structure, installing dependencies, configuring package.json, adding configuration files, and setting up the main entry point.",
"reasoning": "This task involves several standard setup steps that are well-defined and sequential, with low algorithmic complexity but moderate procedural detail. Each step is independent and can be assigned as a subtask, making the overall complexity moderate."
},
{
"taskId": 2,
"taskTitle": "Implement Core Functionality and CLI Interface",
"complexityScore": 7,
"recommendedSubtasks": 7,
"expansionPrompt": "Expand into subtasks for implementing main logic, designing CLI commands, creating the CLI entry point, integrating business logic, adding error handling, formatting output, and ensuring CLI executability.",
"reasoning": "This task requires both application logic and user interface (CLI) development, including error handling and integration. The need to coordinate between core logic and CLI, plus ensuring usability, increases complexity and warrants detailed subtasking."
},
{
"taskId": 3,
"taskTitle": "Implement Testing Suite and Validation",
"complexityScore": 6,
"recommendedSubtasks": 6,
"expansionPrompt": "Divide into subtasks for configuring Jest, writing unit tests, writing integration tests, testing CLI commands, setting up coverage reporting, and preparing test fixtures/mocks.",
"reasoning": "Comprehensive testing involves multiple types of tests and configuration steps. While each is straightforward, the breadth of coverage and need for automation and validation increases the overall complexity."
},
{
"taskId": 4,
"taskTitle": "Setup Node.js Project with CLI Interface",
"complexityScore": 5,
"recommendedSubtasks": 7,
"expansionPrompt": "Break down into subtasks for npm initialization, package.json setup, directory structure creation, dependency installation, CLI entry point creation, package.json bin configuration, and CLI executability.",
"reasoning": "This task combines project setup with initial CLI implementation. While each step is standard, the integration of CLI elements adds a layer of complexity beyond a basic setup."
},
{
"taskId": 5,
"taskTitle": "Implement Core Functionality with Testing",
"complexityScore": 8,
"recommendedSubtasks": 8,
"expansionPrompt": "Expand into subtasks for implementing each feature (A, B, C), setting up the testing framework, writing tests for each feature, integrating CLI with core logic, and adding coverage reporting.",
"reasoning": "This task requires simultaneous development of multiple features, integration with CLI, and comprehensive testing. The coordination and depth required for both implementation and validation make it the most complex among the listed tasks."
}
]
}

View File

@@ -0,0 +1,77 @@
{
"meta": {
"generatedAt": "2025-08-06T12:39:03.250Z",
"tasksAnalyzed": 8,
"totalTasks": 11,
"analysisCount": 8,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": false
},
"complexityAnalysis": [
{
"taskId": 118,
"taskTitle": "Create AI Provider Base Architecture",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the implementation of BaseProvider abstract TypeScript class into subtasks focusing on: 1) Converting existing JavaScript base-provider.js to TypeScript with proper interface definitions, 2) Implementing the Template Method pattern with abstract methods, 3) Adding comprehensive error handling and retry logic with exponential backoff, 4) Creating proper TypeScript types for all method signatures and options, 5) Setting up comprehensive unit tests with MockProvider. Consider that the existing codebase uses JavaScript ES modules and Vercel AI SDK, so the TypeScript implementation needs to maintain compatibility while adding type safety.",
"reasoning": "This task requires significant architectural work including converting existing JavaScript code to TypeScript, creating new interfaces, implementing design patterns, and ensuring backward compatibility. The existing base-provider.js already implements a sophisticated provider pattern using Vercel AI SDK, so the TypeScript conversion needs careful consideration of type definitions and maintaining existing functionality."
},
{
"taskId": 119,
"taskTitle": "Implement Provider Factory with Dynamic Imports",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the Provider Factory implementation into: 1) Creating the ProviderFactory class structure with proper TypeScript typing, 2) Implementing the switch statement for provider selection logic, 3) Adding dynamic imports for each provider to enable tree-shaking, 4) Handling provider instantiation with configuration passing, 5) Implementing comprehensive error handling for module loading failures. Note that the existing codebase already has a provider selection mechanism in the JavaScript files, so ensure the factory pattern integrates smoothly with existing infrastructure.",
"reasoning": "This is a moderate complexity task that involves creating a factory pattern with dynamic imports. The existing codebase already has provider management logic, so the main complexity is in creating a clean TypeScript implementation with proper dynamic imports while maintaining compatibility with the existing JavaScript module system."
},
{
"taskId": 120,
"taskTitle": "Implement Anthropic Provider",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement the AnthropicProvider class in stages: 1) Set up the class structure extending BaseProvider with proper TypeScript imports and type definitions, 2) Implement constructor with Anthropic SDK client initialization and configuration handling, 3) Implement generateCompletion method with proper message format transformation and error handling, 4) Add token calculation methods and utility functions (getName, getModel, getDefaultModel), 5) Implement comprehensive error handling with custom error wrapping and type exports. The existing anthropic.js provider can serve as a reference but needs to be reimplemented to extend the new TypeScript BaseProvider.",
"reasoning": "This task involves integrating with an external SDK (@anthropic-ai/sdk) and implementing all abstract methods from BaseProvider. The existing JavaScript implementation provides a good reference, but the TypeScript version needs proper type definitions, error handling, and must work with the new abstract base class architecture."
},
{
"taskId": 121,
"taskTitle": "Create Prompt Builder and Task Parser",
"complexityScore": 8,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement PromptBuilder and TaskParser with focus on: 1) Creating PromptBuilder class with template methods for building structured prompts with JSON format instructions, 2) Implementing TaskParser class structure with dependency injection of IAIProvider and IConfiguration, 3) Implementing parsePRD method with file reading, prompt generation, and AI provider integration, 4) Adding task enrichment logic with metadata, validation, and structure verification, 5) Implementing comprehensive error handling for all failure scenarios including file I/O, AI provider errors, and JSON parsing. The existing parse-prd.js provides complex logic that needs to be reimplemented with proper TypeScript types and cleaner architecture.",
"reasoning": "This is a complex task that involves multiple components working together: file I/O, AI provider integration, JSON parsing, and data validation. The existing parse-prd.js implementation is quite sophisticated with Zod schemas and complex task processing logic that needs to be reimplemented in TypeScript with proper separation of concerns."
},
{
"taskId": 122,
"taskTitle": "Implement Configuration Management",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Create ConfigManager implementation focusing on: 1) Setting up Zod validation schema that matches the IConfiguration interface structure, 2) Implementing ConfigManager constructor with default values merging and storage initialization, 3) Creating validate method with Zod schema parsing and user-friendly error transformation, 4) Implementing type-safe get method using TypeScript generics and keyof operator, 5) Adding getAll method and ensuring proper immutability and module exports. The existing config-manager.js has complex configuration loading logic that can inform the TypeScript implementation but needs cleaner architecture.",
"reasoning": "This task involves creating a configuration management system with validation using Zod. The existing JavaScript config-manager.js is quite complex with multiple configuration sources, defaults, and validation logic. The TypeScript version needs to provide a cleaner API while maintaining the flexibility of the current system."
},
{
"taskId": 123,
"taskTitle": "Create Utility Functions and Error Handling",
"complexityScore": 4,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement utilities and error handling in stages: 1) Create ID generation module with generateTaskId and generateSubtaskId functions using proper random generation, 2) Implement base TaskMasterError class extending Error with proper TypeScript typing, 3) Add error sanitization methods to prevent sensitive data exposure in production, 4) Implement development-only logging with environment detection, 5) Create specialized error subclasses (FileNotFoundError, ParseError, ValidationError, APIError) with appropriate error codes and formatting.",
"reasoning": "This is a relatively straightforward task involving utility functions and error class hierarchies. The main complexity is in ensuring proper error sanitization for production use and creating a well-structured error hierarchy that can be used throughout the application."
},
{
"taskId": 124,
"taskTitle": "Implement TaskMasterCore Facade",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Build TaskMasterCore facade implementation: 1) Create class structure with proper TypeScript imports and type definitions for all subsystem interfaces, 2) Implement initialize method for lazy loading AI provider and parser instances based on configuration, 3) Create parsePRD method that coordinates parser, AI provider, and storage subsystems, 4) Implement getTasks and other facade methods for task retrieval and management, 5) Create createTaskMaster factory function and set up all module exports including type re-exports. Ensure proper ESM compatibility with .js extensions in imports.",
"reasoning": "This is a complex integration task that brings together all the other components into a cohesive facade. It requires understanding of the facade pattern, proper dependency management, lazy initialization, and careful module export structure for the public API."
},
{
"taskId": 125,
"taskTitle": "Create Placeholder Providers and Complete Testing",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "Complete the implementation with placeholders and testing: 1) Create OpenAIProvider placeholder class extending BaseProvider with 'not yet implemented' errors, 2) Create GoogleProvider placeholder class with similar structure, 3) Implement MockProvider in tests/mocks directory with configurable responses and behavior simulation, 4) Write comprehensive unit tests for TaskParser covering all methods and edge cases, 5) Create integration tests for the complete parse-prd workflow ensuring 80% code coverage. Follow kebab-case naming convention for test files.",
"reasoning": "This task involves creating placeholder implementations and a comprehensive test suite. While the placeholder providers are simple, creating a good MockProvider and comprehensive tests requires understanding the entire system architecture and ensuring all edge cases are covered."
}
]
}

View File

@@ -0,0 +1,77 @@
{
"meta": {
"generatedAt": "2025-08-06T12:15:01.327Z",
"tasksAnalyzed": 8,
"totalTasks": 11,
"analysisCount": 8,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": false
},
"complexityAnalysis": [
{
"taskId": 118,
"taskTitle": "Create AI Provider Base Architecture",
"complexityScore": 4,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the conversion of base-provider.js to TypeScript BaseProvider class: 1) Convert to TypeScript and define IAIProvider interface, 2) Implement abstract class with core properties, 3) Define abstract methods and Template Method pattern, 4) Add retry logic with exponential backoff, 5) Implement validation and logging. Focus on maintaining compatibility with existing provider pattern while adding type safety.",
"reasoning": "The codebase already has a well-established BaseAIProvider class in JavaScript. Converting to TypeScript mainly involves adding type definitions and ensuring the existing pattern is preserved. The complexity is moderate because the pattern is already proven in the codebase."
},
{
"taskId": 119,
"taskTitle": "Implement Provider Factory with Dynamic Imports",
"complexityScore": 3,
"recommendedSubtasks": 5,
"expansionPrompt": "Create ProviderFactory implementation: 1) Set up class structure and types, 2) Implement provider selection switch statement, 3) Add dynamic imports for tree-shaking, 4) Handle provider instantiation with config, 5) Add comprehensive error handling. The existing PROVIDERS registry pattern should guide the implementation.",
"reasoning": "The codebase already uses a dual registry pattern (static PROVIDERS and dynamic ProviderRegistry). Creating a factory is straightforward as the provider registration patterns are well-established. Dynamic imports are already used in the codebase."
},
{
"taskId": 120,
"taskTitle": "Implement Anthropic Provider",
"complexityScore": 3,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement AnthropicProvider following existing patterns: 1) Create class structure with imports, 2) Implement constructor and client initialization, 3) Add generateCompletion with Claude API integration, 4) Implement token calculation and utility methods, 5) Add error handling and exports. Use the existing anthropic.js provider as reference.",
"reasoning": "AnthropicProvider already exists in the codebase with full implementation. This task essentially involves adapting the existing implementation to match the new TypeScript architecture, making it relatively straightforward."
},
{
"taskId": 121,
"taskTitle": "Create Prompt Builder and Task Parser",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Build prompt system and parser: 1) Create PromptBuilder with template methods, 2) Implement TaskParser with dependency injection, 3) Add parsePRD core logic with file reading, 4) Implement task enrichment and metadata, 5) Add comprehensive error handling. Leverage the existing prompt management system in src/prompts/.",
"reasoning": "While the codebase has a sophisticated prompt management system, creating a new PromptBuilder and TaskParser requires understanding the existing prompt templates, JSON schema validation, and integration with the AI provider system. The task involves significant new code."
},
{
"taskId": 122,
"taskTitle": "Implement Configuration Management",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "Create ConfigManager with validation: 1) Define Zod schema for IConfiguration, 2) Implement constructor with defaults, 3) Add validate method with error handling, 4) Create type-safe get method with generics, 5) Implement getAll and finalize exports. Reference existing config-manager.js for patterns.",
"reasoning": "The codebase has an existing config-manager.js with sophisticated configuration handling. Adding Zod validation and TypeScript generics adds complexity, but the existing patterns provide a solid foundation."
},
{
"taskId": 123,
"taskTitle": "Create Utility Functions and Error Handling",
"complexityScore": 2,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement utilities and error handling: 1) Create ID generation module with unique formats, 2) Build TaskMasterError base class, 3) Add error sanitization for security, 4) Implement development-only logging, 5) Create specialized error subclasses. Keep implementation simple and focused.",
"reasoning": "This is a straightforward utility implementation task. The codebase already has error handling patterns, and ID generation is a simple algorithmic task. The main work is creating clean, reusable utilities."
},
{
"taskId": 124,
"taskTitle": "Implement TaskMasterCore Facade",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Create main facade class: 1) Set up TaskMasterCore structure with imports, 2) Implement lazy initialization logic, 3) Add parsePRD coordination method, 4) Implement getTasks and other facade methods, 5) Create factory function and exports. This ties together all other components into a cohesive API.",
"reasoning": "This is the most complex task as it requires understanding and integrating all other components. The facade must coordinate between configuration, providers, storage, and parsing while maintaining a clean API. It's the architectural keystone of the system."
},
{
"taskId": 125,
"taskTitle": "Create Placeholder Providers and Complete Testing",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "Implement testing infrastructure: 1) Create OpenAIProvider placeholder, 2) Create GoogleProvider placeholder, 3) Build MockProvider for testing, 4) Write TaskParser unit tests, 5) Create integration tests for parse-prd flow. Follow the existing test patterns in tests/ directory.",
"reasoning": "While creating placeholder providers is simple, the testing infrastructure requires understanding Jest with ES modules, mocking patterns, and comprehensive test coverage. The existing test structure provides good examples to follow."
}
]
}

9
.taskmaster/state.json Normal file
View File

@@ -0,0 +1,9 @@
{
"currentTag": "master",
"lastSwitched": "2025-09-12T22:25:27.535Z",
"branchTagMapping": {
"v017-adds": "v017-adds",
"next": "next"
},
"migrationNoticeShown": true
}

View File

@@ -0,0 +1,34 @@
# Task ID: 1
# Title: Create start command class structure
# Status: pending
# Dependencies: None
# Priority: high
# Description: Create the basic structure for the start command following the Commander class pattern
# Details:
Create a new file `apps/cli/src/commands/start.command.ts` based on the existing list.command.ts pattern. Implement the command class with proper command registration, description, and argument handling for the task_id parameter. The class should extend the base Command class and implement the required methods.
Example structure:
```typescript
import { Command } from 'commander';
import { BaseCommand } from './base.command';
export class StartCommand extends BaseCommand {
public register(program: Command): void {
program
.command('start')
.alias('tm start')
.description('Start implementing a task using claude-code')
.argument('<task_id>', 'ID of the task to start')
.action(async (taskId: string) => {
await this.execute(taskId);
});
}
public async execute(taskId: string): Promise<void> {
// Implementation will be added in subsequent tasks
}
}
```
# Test Strategy:
Verify the command registers correctly by running the CLI with --help and checking that the start command appears with proper description and arguments. Test the basic structure by ensuring the command can be invoked without errors.

View File

@@ -0,0 +1,26 @@
# Task ID: 2
# Title: Register start command in CLI
# Status: pending
# Dependencies: 7
# Priority: high
# Description: Register the start command in the CLI application
# Details:
Update the CLI application to register the new start command. This involves importing the StartCommand class and adding it to the commands array in the CLI initialization.
In `apps/cli/src/index.ts` or the appropriate file where commands are registered:
```typescript
import { StartCommand } from './commands/start.command';
// Add StartCommand to the commands array
const commands = [
// ... existing commands
new StartCommand(),
];
// Register all commands
commands.forEach(command => command.register(program));
```
# Test Strategy:
Verify the command is correctly registered by running the CLI with --help and checking that the start command appears in the list of available commands.

View File

@@ -0,0 +1,32 @@
# Task ID: 3
# Title: Create standardized prompt builder
# Status: pending
# Dependencies: 1
# Priority: medium
# Description: Implement a function to build the standardized prompt for claude-code based on the task details
# Details:
Create a function in the StartCommand class that builds the standardized prompt according to the template provided in the PRD. The prompt should include instructions for Claude to first run `tm show <task_id>` to get task details, and then implement the required changes.
```typescript
private buildPrompt(taskId: string): string {
return `You are an AI coding assistant with access to this repository's codebase.
First, run this command to get the task details:
tm show ${taskId}
Then implement the task with these requirements:
- Make the SMALLEST number of code changes possible
- Follow ALL existing patterns in the codebase (you have access to analyze the code)
- Do NOT over-engineer the solution
- Use existing files/functions/patterns wherever possible
- When complete, print: COMPLETED: <brief summary of changes>
Begin by running tm show ${taskId} to understand what needs to be implemented.`;
}
```
<info added on 2025-09-12T02:40:01.812Z>
The prompt builder function will handle task context retrieval by instructing Claude to use the task-master show command. This approach ensures Claude has access to all necessary task details before implementation begins. The command syntax "tm show ${taskId}" embedded in the prompt will direct Claude to first gather the complete task context, including description, requirements, and any existing implementation details, before proceeding with code changes.
</info added on 2025-09-12T02:40:01.812Z>
# Test Strategy:
Verify the prompt is correctly formatted by calling the function with a sample task ID and checking that the output matches the expected template with the task ID properly inserted.

View File

@@ -0,0 +1,36 @@
# Task ID: 4
# Title: Implement claude-code executor
# Status: pending
# Dependencies: 3
# Priority: high
# Description: Add functionality to execute the claude-code command with the built prompt
# Details:
Implement the functionality to execute the claude command with the built prompt. This should use Node.js child_process.exec() to run the command directly in the terminal.
```typescript
import { exec } from 'child_process';
// Inside execute method, after task validation
private async executeClaude(prompt: string): Promise<void> {
console.log('Starting claude-code to implement the task...');
try {
// Execute claude with the prompt
const claudeCommand = `claude "${prompt.replace(/"/g, '\\"')}"`;
// Use execSync to wait for the command to complete
const { execSync } = require('child_process');
execSync(claudeCommand, { stdio: 'inherit' });
console.log('Claude session completed.');
} catch (error) {
console.error('Error executing claude-code:', error.message);
process.exit(1);
}
}
```
Then call this method from the execute method after building the prompt.
# Test Strategy:
Test by running the command with a valid task ID and verifying that the claude command is executed with the correct prompt. Check that the command handles errors appropriately if claude-code is not available.

View File

@@ -0,0 +1,49 @@
# Task ID: 7
# Title: Integrate execution flow in start command
# Status: pending
# Dependencies: 3, 4
# Priority: high
# Description: Connect all the components to implement the complete execution flow for the start command
# Details:
Update the execute method in the StartCommand class to integrate all the components and implement the complete execution flow as described in the PRD:
1. Validate task exists
2. Build standardized prompt
3. Execute claude-code
4. Check git status for changes
5. Auto-mark task as done if changes detected
```typescript
public async execute(taskId: string): Promise<void> {
// Validate task exists
const core = await createTaskMasterCore();
const task = await core.tasks.getById(parseInt(taskId, 10));
if (!task) {
console.error(`Task with ID ${taskId} not found`);
process.exit(1);
}
// Build prompt
const prompt = this.buildPrompt(taskId);
// Execute claude-code
await this.executeClaude(prompt);
// Check git status
const changedFiles = await this.checkGitChanges();
if (changedFiles.length > 0) {
console.log('\nChanges detected in the following files:');
changedFiles.forEach(file => console.log(`- ${file}`));
// Auto-mark task as done
await this.markTaskAsDone(taskId);
console.log(`\nTask ${taskId} completed successfully and marked as done.`);
} else {
console.warn('\nNo changes detected after claude-code execution. Task not marked as done.');
}
}
```
# Test Strategy:
Test the complete execution flow by running the start command with a valid task ID and verifying that all steps are executed correctly. Test with both scenarios: when changes are detected and when no changes are detected.

7905
.taskmaster/tasks/tasks.json Normal file

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More