task-cli.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. #!/usr/bin/env npx ts-node
  2. /**
  3. * Task Management CLI
  4. *
  5. * Usage: npx ts-node task-cli.ts <command> [feature] [args...]
  6. *
  7. * Commands:
  8. * status [feature] - Show task status summary
  9. * next [feature] - Show next eligible tasks
  10. * parallel [feature] - Show parallelizable tasks ready to run
  11. * deps <feature> <seq> - Show dependency tree for a task
  12. * blocked [feature] - Show blocked tasks and why
  13. * complete <feature> <seq> "summary" - Mark task completed
  14. * validate [feature] - Validate JSON files and dependencies
  15. *
  16. * Task files are stored in .tmp/tasks/ at the project root:
  17. * .tmp/tasks/{feature-slug}/task.json
  18. * .tmp/tasks/{feature-slug}/subtask_01.json
  19. * .tmp/tasks/completed/{feature-slug}/
  20. */
  21. const fs = require('fs');
  22. const path = require('path');
  23. // Find project root (look for .git or package.json)
  24. function findProjectRoot(): string {
  25. let dir = process.cwd();
  26. while (dir !== path.dirname(dir)) {
  27. if (fs.existsSync(path.join(dir, '.git')) || fs.existsSync(path.join(dir, 'package.json'))) {
  28. return dir;
  29. }
  30. dir = path.dirname(dir);
  31. }
  32. return process.cwd();
  33. }
  34. const PROJECT_ROOT = findProjectRoot();
  35. const TASKS_DIR = path.join(PROJECT_ROOT, '.tmp', 'tasks');
  36. const COMPLETED_DIR = path.join(TASKS_DIR, 'completed');
  37. interface Task {
  38. id: string;
  39. name: string;
  40. status: 'active' | 'completed' | 'blocked' | 'archived';
  41. objective: string;
  42. context_files: string[];
  43. reference_files?: string[];
  44. exit_criteria: string[];
  45. subtask_count: number;
  46. completed_count: number;
  47. created_at: string;
  48. completed_at: string | null;
  49. }
  50. interface Subtask {
  51. id: string;
  52. seq: string;
  53. title: string;
  54. status: 'pending' | 'in_progress' | 'completed' | 'blocked';
  55. depends_on: string[];
  56. parallel: boolean;
  57. context_files: string[];
  58. reference_files?: string[];
  59. acceptance_criteria: string[];
  60. deliverables: string[];
  61. agent_id: string | null;
  62. suggested_agent?: string;
  63. started_at: string | null;
  64. completed_at: string | null;
  65. completion_summary: string | null;
  66. }
  67. // Helpers
  68. function getFeatureDirs(): string[] {
  69. if (!fs.existsSync(TASKS_DIR)) return [];
  70. return fs.readdirSync(TASKS_DIR).filter((f: string) => {
  71. const fullPath = path.join(TASKS_DIR, f);
  72. return fs.statSync(fullPath).isDirectory() && f !== 'completed';
  73. });
  74. }
  75. function loadTask(feature: string): Task | null {
  76. const taskPath = path.join(TASKS_DIR, feature, 'task.json');
  77. if (!fs.existsSync(taskPath)) return null;
  78. return JSON.parse(fs.readFileSync(taskPath, 'utf-8'));
  79. }
  80. function loadSubtasks(feature: string): Subtask[] {
  81. const featureDir = path.join(TASKS_DIR, feature);
  82. if (!fs.existsSync(featureDir)) return [];
  83. const files = fs.readdirSync(featureDir)
  84. .filter((f: string) => f.match(/^subtask_\d{2}\.json$/))
  85. .sort();
  86. return files.map((f: string) => JSON.parse(fs.readFileSync(path.join(featureDir, f), 'utf-8')));
  87. }
  88. function saveSubtask(feature: string, subtask: Subtask): void {
  89. const subtaskPath = path.join(TASKS_DIR, feature, `subtask_${subtask.seq}.json`);
  90. fs.writeFileSync(subtaskPath, JSON.stringify(subtask, null, 2));
  91. }
  92. function saveTask(feature: string, task: Task): void {
  93. const taskPath = path.join(TASKS_DIR, feature, 'task.json');
  94. fs.writeFileSync(taskPath, JSON.stringify(task, null, 2));
  95. }
  96. // Commands
  97. function cmdStatus(feature?: string): void {
  98. const features = feature ? [feature] : getFeatureDirs();
  99. if (features.length === 0) {
  100. console.log('No active features found.');
  101. return;
  102. }
  103. for (const f of features) {
  104. const task = loadTask(f);
  105. const subtasks = loadSubtasks(f);
  106. if (!task) {
  107. console.log(`\n[${f}] - No task.json found`);
  108. continue;
  109. }
  110. const counts = {
  111. pending: subtasks.filter(s => s.status === 'pending').length,
  112. in_progress: subtasks.filter(s => s.status === 'in_progress').length,
  113. completed: subtasks.filter(s => s.status === 'completed').length,
  114. blocked: subtasks.filter(s => s.status === 'blocked').length,
  115. };
  116. const progress = subtasks.length > 0
  117. ? Math.round((counts.completed / subtasks.length) * 100)
  118. : 0;
  119. console.log(`\n[${f}] ${task.name}`);
  120. console.log(` Status: ${task.status} | Progress: ${progress}% (${counts.completed}/${subtasks.length})`);
  121. console.log(` Pending: ${counts.pending} | In Progress: ${counts.in_progress} | Completed: ${counts.completed} | Blocked: ${counts.blocked}`);
  122. }
  123. }
  124. function cmdNext(feature?: string): void {
  125. const features = feature ? [feature] : getFeatureDirs();
  126. console.log('\n=== Ready Tasks (deps satisfied) ===\n');
  127. for (const f of features) {
  128. const subtasks = loadSubtasks(f);
  129. const completedSeqs = new Set(subtasks.filter(s => s.status === 'completed').map(s => s.seq));
  130. const ready = subtasks.filter(s => {
  131. if (s.status !== 'pending') return false;
  132. return s.depends_on.every(dep => completedSeqs.has(dep));
  133. });
  134. if (ready.length > 0) {
  135. console.log(`[${f}]`);
  136. for (const s of ready) {
  137. const parallel = s.parallel ? '[parallel]' : '[sequential]';
  138. console.log(` ${s.seq} - ${s.title} ${parallel}`);
  139. }
  140. console.log();
  141. }
  142. }
  143. }
  144. function cmdParallel(feature?: string): void {
  145. const features = feature ? [feature] : getFeatureDirs();
  146. console.log('\n=== Parallelizable Tasks Ready Now ===\n');
  147. for (const f of features) {
  148. const subtasks = loadSubtasks(f);
  149. const completedSeqs = new Set(subtasks.filter(s => s.status === 'completed').map(s => s.seq));
  150. const parallel = subtasks.filter(s => {
  151. if (s.status !== 'pending') return false;
  152. if (!s.parallel) return false;
  153. return s.depends_on.every(dep => completedSeqs.has(dep));
  154. });
  155. if (parallel.length > 0) {
  156. console.log(`[${f}] - ${parallel.length} parallel tasks:`);
  157. for (const s of parallel) {
  158. console.log(` ${s.seq} - ${s.title}`);
  159. }
  160. console.log();
  161. }
  162. }
  163. }
  164. function cmdDeps(feature: string, seq: string): void {
  165. const subtasks = loadSubtasks(feature);
  166. const target = subtasks.find(s => s.seq === seq);
  167. if (!target) {
  168. console.log(`Task ${seq} not found in ${feature}`);
  169. return;
  170. }
  171. console.log(`\n=== Dependency Tree: ${feature}/${seq} ===\n`);
  172. console.log(`${seq} - ${target.title} [${target.status}]`);
  173. if (target.depends_on.length === 0) {
  174. console.log(' └── (no dependencies)');
  175. return;
  176. }
  177. const printDeps = (seqs: string[], indent: string = ' '): void => {
  178. for (let i = 0; i < seqs.length; i++) {
  179. const depSeq = seqs[i];
  180. const dep = subtasks.find(s => s.seq === depSeq);
  181. const isLast = i === seqs.length - 1;
  182. const branch = isLast ? '└──' : '├──';
  183. if (dep) {
  184. const statusIcon = dep.status === 'completed' ? '✓' : dep.status === 'in_progress' ? '~' : '○';
  185. console.log(`${indent}${branch} ${statusIcon} ${depSeq} - ${dep.title} [${dep.status}]`);
  186. if (dep.depends_on.length > 0) {
  187. const newIndent = indent + (isLast ? ' ' : '│ ');
  188. printDeps(dep.depends_on, newIndent);
  189. }
  190. } else {
  191. console.log(`${indent}${branch} ? ${depSeq} - NOT FOUND`);
  192. }
  193. }
  194. };
  195. printDeps(target.depends_on);
  196. }
  197. function cmdBlocked(feature?: string): void {
  198. const features = feature ? [feature] : getFeatureDirs();
  199. console.log('\n=== Blocked Tasks ===\n');
  200. for (const f of features) {
  201. const subtasks = loadSubtasks(f);
  202. const completedSeqs = new Set(subtasks.filter(s => s.status === 'completed').map(s => s.seq));
  203. const blocked = subtasks.filter(s => {
  204. if (s.status === 'blocked') return true;
  205. if (s.status !== 'pending') return false;
  206. return !s.depends_on.every(dep => completedSeqs.has(dep));
  207. });
  208. if (blocked.length > 0) {
  209. console.log(`[${f}]`);
  210. for (const s of blocked) {
  211. const waitingFor = s.depends_on.filter(dep => !completedSeqs.has(dep));
  212. const reason = s.status === 'blocked'
  213. ? 'explicitly blocked'
  214. : `waiting: ${waitingFor.join(', ')}`;
  215. console.log(` ${s.seq} - ${s.title} (${reason})`);
  216. }
  217. console.log();
  218. }
  219. }
  220. }
  221. function cmdComplete(feature: string, seq: string, summary: string): void {
  222. if (summary.length > 200) {
  223. console.log('Error: Summary must be max 200 characters');
  224. process.exit(1);
  225. }
  226. const subtasks = loadSubtasks(feature);
  227. const subtask = subtasks.find(s => s.seq === seq);
  228. if (!subtask) {
  229. console.log(`Task ${seq} not found in ${feature}`);
  230. process.exit(1);
  231. }
  232. subtask.status = 'completed';
  233. subtask.completed_at = new Date().toISOString();
  234. subtask.completion_summary = summary;
  235. saveSubtask(feature, subtask);
  236. // Update task.json counts
  237. const task = loadTask(feature);
  238. if (task) {
  239. const newSubtasks = loadSubtasks(feature);
  240. task.completed_count = newSubtasks.filter(s => s.status === 'completed').length;
  241. saveTask(feature, task);
  242. }
  243. console.log(`\n✓ Marked ${feature}/${seq} as completed`);
  244. console.log(` Summary: ${summary}`);
  245. if (task) {
  246. console.log(` Progress: ${task.completed_count}/${task.subtask_count}`);
  247. }
  248. }
  249. function cmdValidate(feature?: string): void {
  250. const features = feature ? [feature] : getFeatureDirs();
  251. let hasErrors = false;
  252. console.log('\n=== Validation Results ===\n');
  253. for (const f of features) {
  254. const errors: string[] = [];
  255. const warnings: string[] = [];
  256. // Check task.json exists
  257. const task = loadTask(f);
  258. if (!task) {
  259. errors.push('Missing task.json');
  260. }
  261. // Load and validate subtasks
  262. const subtasks = loadSubtasks(f);
  263. const seqs = new Set(subtasks.map(s => s.seq));
  264. for (const s of subtasks) {
  265. // Check ID format
  266. if (!s.id.startsWith(f)) {
  267. errors.push(`${s.seq}: ID should start with feature name`);
  268. }
  269. // Check for missing dependencies
  270. for (const dep of s.depends_on) {
  271. if (!seqs.has(dep)) {
  272. errors.push(`${s.seq}: depends on non-existent task ${dep}`);
  273. }
  274. }
  275. // Check for circular dependencies
  276. const visited = new Set<string>();
  277. const checkCircular = (seq: string, path: string[]): boolean => {
  278. if (path.includes(seq)) {
  279. errors.push(`${s.seq}: circular dependency detected: ${[...path, seq].join(' -> ')}`);
  280. return true;
  281. }
  282. if (visited.has(seq)) return false;
  283. visited.add(seq);
  284. const task = subtasks.find(t => t.seq === seq);
  285. if (task) {
  286. for (const dep of task.depends_on) {
  287. if (checkCircular(dep, [...path, seq])) return true;
  288. }
  289. }
  290. return false;
  291. };
  292. checkCircular(s.seq, []);
  293. // Warnings
  294. if (s.acceptance_criteria.length === 0) {
  295. warnings.push(`${s.seq}: No acceptance criteria defined`);
  296. }
  297. if (s.deliverables.length === 0) {
  298. warnings.push(`${s.seq}: No deliverables defined`);
  299. }
  300. }
  301. // Check counts match
  302. if (task && task.subtask_count !== subtasks.length) {
  303. errors.push(`task.json subtask_count (${task.subtask_count}) doesn't match actual count (${subtasks.length})`);
  304. }
  305. // Print results
  306. console.log(`[${f}]`);
  307. if (errors.length === 0 && warnings.length === 0) {
  308. console.log(' ✓ All checks passed');
  309. } else {
  310. for (const e of errors) {
  311. console.log(` ✗ ERROR: ${e}`);
  312. hasErrors = true;
  313. }
  314. for (const w of warnings) {
  315. console.log(` ⚠ WARNING: ${w}`);
  316. }
  317. }
  318. console.log();
  319. }
  320. process.exit(hasErrors ? 1 : 0);
  321. }
  322. // Main
  323. const [,, command, ...args] = process.argv;
  324. switch (command) {
  325. case 'status':
  326. cmdStatus(args[0]);
  327. break;
  328. case 'next':
  329. cmdNext(args[0]);
  330. break;
  331. case 'parallel':
  332. cmdParallel(args[0]);
  333. break;
  334. case 'deps':
  335. if (args.length < 2) {
  336. console.log('Usage: deps <feature> <seq>');
  337. process.exit(1);
  338. }
  339. cmdDeps(args[0], args[1]);
  340. break;
  341. case 'blocked':
  342. cmdBlocked(args[0]);
  343. break;
  344. case 'complete':
  345. if (args.length < 3) {
  346. console.log('Usage: complete <feature> <seq> "summary"');
  347. process.exit(1);
  348. }
  349. cmdComplete(args[0], args[1], args.slice(2).join(' '));
  350. break;
  351. case 'validate':
  352. cmdValidate(args[0]);
  353. break;
  354. default:
  355. console.log(`
  356. Task Management CLI
  357. Usage: npx ts-node task-cli.ts <command> [feature] [args...]
  358. Task files are stored in: .tmp/tasks/{feature-slug}/
  359. Commands:
  360. status [feature] Show task status summary
  361. next [feature] Show next eligible tasks (deps satisfied)
  362. parallel [feature] Show parallelizable tasks ready to run
  363. deps <feature> <seq> Show dependency tree for a task
  364. blocked [feature] Show blocked tasks and why
  365. complete <feature> <seq> "summary" Mark task completed with summary
  366. validate [feature] Validate JSON files and dependencies
  367. Examples:
  368. npx ts-node task-cli.ts status
  369. npx ts-node task-cli.ts next my-feature
  370. npx ts-node task-cli.ts complete my-feature 02 "Implemented auth module"
  371. `);
  372. }