@linxiraos/pi-messenger 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +676 -0
  2. package/README.md +424 -0
  3. package/config-overlay.ts +171 -0
  4. package/config.ts +209 -0
  5. package/crew/agents/crew-plan-sync.md +64 -0
  6. package/crew/agents/crew-planner.md +172 -0
  7. package/crew/agents/crew-reviewer.md +58 -0
  8. package/crew/agents/crew-worker.md +129 -0
  9. package/crew/agents.ts +434 -0
  10. package/crew/handlers/coordination.ts +332 -0
  11. package/crew/handlers/plan.ts +906 -0
  12. package/crew/handlers/review.ts +333 -0
  13. package/crew/handlers/revise.ts +376 -0
  14. package/crew/handlers/status.ts +295 -0
  15. package/crew/handlers/sync.ts +233 -0
  16. package/crew/handlers/task.ts +792 -0
  17. package/crew/handlers/team.ts +235 -0
  18. package/crew/handlers/work.ts +425 -0
  19. package/crew/id-allocator.ts +30 -0
  20. package/crew/index.ts +257 -0
  21. package/crew/live-progress.ts +58 -0
  22. package/crew/lobby.ts +473 -0
  23. package/crew/prompt.ts +252 -0
  24. package/crew/registry.ts +114 -0
  25. package/crew/spawn.ts +111 -0
  26. package/crew/state-autonomous.ts +164 -0
  27. package/crew/state-planning.ts +263 -0
  28. package/crew/state.ts +20 -0
  29. package/crew/store.ts +642 -0
  30. package/crew/task-actions.ts +131 -0
  31. package/crew/team/store.ts +479 -0
  32. package/crew/team/subagent-roles.ts +87 -0
  33. package/crew/team/types.ts +50 -0
  34. package/crew/types.ts +194 -0
  35. package/crew/utils/artifacts.ts +62 -0
  36. package/crew/utils/config.ts +156 -0
  37. package/crew/utils/discover.ts +219 -0
  38. package/crew/utils/install.ts +85 -0
  39. package/crew/utils/progress.ts +187 -0
  40. package/crew/utils/result.ts +16 -0
  41. package/crew/utils/risk-labels.ts +7 -0
  42. package/crew/utils/task-format.ts +14 -0
  43. package/crew/utils/team-roles.ts +28 -0
  44. package/crew/utils/truncate.ts +79 -0
  45. package/crew/utils/verdict.ts +55 -0
  46. package/feed.ts +268 -0
  47. package/handlers.ts +1107 -0
  48. package/index.ts +1206 -0
  49. package/install.mjs +189 -0
  50. package/lib.ts +467 -0
  51. package/overlay-actions.ts +511 -0
  52. package/overlay-coordinator.ts +150 -0
  53. package/overlay-render.ts +676 -0
  54. package/overlay.ts +830 -0
  55. package/package.json +62 -0
  56. package/skills/pi-messenger-crew/SKILL.md +347 -0
  57. package/store.ts +1139 -0
  58. package/vitest.config.ts +10 -0
package/crew/store.ts ADDED
@@ -0,0 +1,642 @@
1
+ /**
2
+ * Crew - Store Operations
3
+ *
4
+ * Simplified PRD-based storage: plan.json + tasks/*.json
5
+ */
6
+
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { execSync } from "node:child_process";
10
+ import type { Plan, Task, TaskApproval, TaskApprovalDecisionStatus, TaskEvidence } from "./types.ts";
11
+ import { allocateTaskId } from "./id-allocator.ts";
12
+ import { normalizeRiskLabels } from "./utils/risk-labels.ts";
13
+
14
+ // =============================================================================
15
+ // Directory Helpers
16
+ // =============================================================================
17
+
18
+ function ensureDir(dir: string): void {
19
+ if (!fs.existsSync(dir)) {
20
+ fs.mkdirSync(dir, { recursive: true });
21
+ }
22
+ }
23
+
24
+ export function getCrewDir(cwd: string): string {
25
+ return path.join(cwd, ".pi", "messenger", "crew");
26
+ }
27
+
28
+ function getTasksDir(cwd: string): string {
29
+ return path.join(getCrewDir(cwd), "tasks");
30
+ }
31
+
32
+ function getBlocksDir(cwd: string): string {
33
+ return path.join(getCrewDir(cwd), "blocks");
34
+ }
35
+
36
+ export function cleanupBlockFiles(cwd: string, taskId: string): void {
37
+ try { fs.unlinkSync(path.join(getBlocksDir(cwd), `${taskId}.md`)); } catch {}
38
+ }
39
+
40
+ // =============================================================================
41
+ // JSON Helpers
42
+ // =============================================================================
43
+
44
+ function readJson<T>(filePath: string): T | null {
45
+ if (!fs.existsSync(filePath)) return null;
46
+ try {
47
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function writeJson(filePath: string, data: unknown): void {
54
+ ensureDir(path.dirname(filePath));
55
+ const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
56
+ fs.writeFileSync(temp, JSON.stringify(data, null, 2));
57
+ fs.renameSync(temp, filePath);
58
+ }
59
+
60
+ function readText(filePath: string): string | null {
61
+ if (!fs.existsSync(filePath)) return null;
62
+ try {
63
+ return fs.readFileSync(filePath, "utf-8");
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ function writeText(filePath: string, content: string): void {
70
+ ensureDir(path.dirname(filePath));
71
+ const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
72
+ fs.writeFileSync(temp, content);
73
+ fs.renameSync(temp, filePath);
74
+ }
75
+
76
+ // =============================================================================
77
+ // Plan Operations
78
+ // =============================================================================
79
+
80
+ export function getPlan(cwd: string): Plan | null {
81
+ return readJson<Plan>(path.join(getCrewDir(cwd), "plan.json"));
82
+ }
83
+
84
+ export function createPlan(cwd: string, prdPath: string, prompt?: string): Plan {
85
+ const now = new Date().toISOString();
86
+
87
+ const plan: Plan = {
88
+ prd: prdPath,
89
+ ...(prompt ? { prompt } : {}),
90
+ created_at: now,
91
+ updated_at: now,
92
+ task_count: 0,
93
+ completed_count: 0,
94
+ };
95
+
96
+ writeJson(path.join(getCrewDir(cwd), "plan.json"), plan);
97
+ return plan;
98
+ }
99
+
100
+ export function getPlanLabel(plan: Plan, maxLen = 60): string {
101
+ if (!plan.prompt) return plan.prd;
102
+ return plan.prompt.length > maxLen
103
+ ? plan.prompt.slice(0, maxLen - 3) + "..."
104
+ : plan.prompt;
105
+ }
106
+
107
+ export function updatePlan(cwd: string, updates: Partial<Plan>): Plan | null {
108
+ const plan = getPlan(cwd);
109
+ if (!plan) return null;
110
+
111
+ const updated: Plan = {
112
+ ...plan,
113
+ ...updates,
114
+ updated_at: new Date().toISOString(),
115
+ };
116
+
117
+ writeJson(path.join(getCrewDir(cwd), "plan.json"), updated);
118
+ return updated;
119
+ }
120
+
121
+ export function deletePlan(cwd: string): boolean {
122
+ const planPath = path.join(getCrewDir(cwd), "plan.json");
123
+ const planMdPath = path.join(getCrewDir(cwd), "plan.md");
124
+ const tasksDir = getTasksDir(cwd);
125
+
126
+ let deleted = false;
127
+
128
+ // Delete plan.json
129
+ if (fs.existsSync(planPath)) {
130
+ fs.unlinkSync(planPath);
131
+ deleted = true;
132
+ }
133
+
134
+ // Delete plan.md
135
+ if (fs.existsSync(planMdPath)) {
136
+ fs.unlinkSync(planMdPath);
137
+ }
138
+
139
+ // Delete all task files
140
+ if (fs.existsSync(tasksDir)) {
141
+ for (const file of fs.readdirSync(tasksDir)) {
142
+ fs.unlinkSync(path.join(tasksDir, file));
143
+ }
144
+ }
145
+
146
+ // Delete all block files
147
+ const blocksDir = getBlocksDir(cwd);
148
+ if (fs.existsSync(blocksDir)) {
149
+ for (const file of fs.readdirSync(blocksDir)) {
150
+ fs.unlinkSync(path.join(blocksDir, file));
151
+ }
152
+ }
153
+
154
+ return deleted;
155
+ }
156
+
157
+ // =============================================================================
158
+ // Plan Spec Operations
159
+ // =============================================================================
160
+
161
+ export function getPlanSpec(cwd: string): string | null {
162
+ return readText(path.join(getCrewDir(cwd), "plan.md"));
163
+ }
164
+
165
+ export function setPlanSpec(cwd: string, content: string): void {
166
+ writeText(path.join(getCrewDir(cwd), "plan.md"), content);
167
+ updatePlan(cwd, {}); // Touch updated_at
168
+ }
169
+
170
+ // =============================================================================
171
+ // Task Operations
172
+ // =============================================================================
173
+
174
+ export function createTask(
175
+ cwd: string,
176
+ title: string,
177
+ description?: string,
178
+ dependsOn?: string[],
179
+ options?: Pick<Task, "role" | "risk_labels" | "approval" | "skills" | "model">
180
+ ): Task {
181
+ const id = allocateTaskId(cwd);
182
+ const now = new Date().toISOString();
183
+ const riskLabels = normalizeRiskLabels(options?.risk_labels);
184
+
185
+ const task: Task = {
186
+ id,
187
+ title,
188
+ status: "todo",
189
+ depends_on: dependsOn ?? [],
190
+ ...(options?.model ? { model: options.model } : {}),
191
+ ...(options?.role ? { role: options.role } : {}),
192
+ ...(riskLabels ? { risk_labels: riskLabels } : {}),
193
+ ...(options?.approval ? { approval: options.approval } : {}),
194
+ ...(options?.skills && options.skills.length > 0 ? { skills: options.skills } : {}),
195
+ created_at: now,
196
+ updated_at: now,
197
+ attempt_count: 0,
198
+ };
199
+
200
+ writeJson(path.join(getTasksDir(cwd), `${id}.json`), task);
201
+
202
+ // Create task spec file
203
+ const specContent = description
204
+ ? `# ${title}\n\n${description}\n`
205
+ : `# ${title}\n\n*Spec pending*\n`;
206
+ writeText(path.join(getTasksDir(cwd), `${id}.md`), specContent);
207
+
208
+ // Update plan task count
209
+ const plan = getPlan(cwd);
210
+ if (plan) {
211
+ updatePlan(cwd, { task_count: plan.task_count + 1 });
212
+ }
213
+
214
+ return task;
215
+ }
216
+
217
+ function normalizeApproval(raw: unknown): TaskApproval | undefined {
218
+ if (!raw || typeof raw !== "object") return undefined;
219
+ const value = raw as Record<string, unknown>;
220
+ const metadata = {
221
+ ...(typeof value.plan === "string" ? { plan: value.plan } : {}),
222
+ ...(typeof value.feedback === "string" ? { feedback: value.feedback } : {}),
223
+ ...(typeof value.decided_by === "string" ? { decided_by: value.decided_by } : {}),
224
+ ...(typeof value.decided_at === "string" ? { decided_at: value.decided_at } : {}),
225
+ };
226
+ if (value.required !== true) return { required: false, status: "not_required", ...metadata };
227
+
228
+ const status: TaskApprovalDecisionStatus = value.status === "approved" || value.status === "rejected"
229
+ ? value.status
230
+ : "pending";
231
+ return { required: true, status, ...metadata };
232
+ }
233
+
234
+ function normalizeTask(raw: Task): Task {
235
+ const approval = normalizeApproval(raw.approval);
236
+ return {
237
+ ...raw,
238
+ depends_on: Array.isArray(raw.depends_on) ? raw.depends_on : [],
239
+ skills: Array.isArray(raw.skills) ? raw.skills.filter(s => typeof s === "string") : undefined,
240
+ role: typeof raw.role === "string" && raw.role.trim().length > 0 ? raw.role : undefined,
241
+ risk_labels: normalizeRiskLabels(Array.isArray(raw.risk_labels) ? raw.risk_labels.filter(s => typeof s === "string") : undefined),
242
+ approval,
243
+ attempt_count: typeof raw.attempt_count === "number" ? raw.attempt_count : 0,
244
+ };
245
+ }
246
+
247
+ export function getTask(cwd: string, taskId: string): Task | null {
248
+ const raw = readJson<Task>(path.join(getTasksDir(cwd), `${taskId}.json`));
249
+ return raw ? normalizeTask(raw) : null;
250
+ }
251
+
252
+ export function updateTask(cwd: string, taskId: string, updates: Partial<Task>): Task | null {
253
+ const task = getTask(cwd, taskId);
254
+ if (!task) return null;
255
+
256
+ const updated: Task = {
257
+ ...task,
258
+ ...updates,
259
+ updated_at: new Date().toISOString(),
260
+ };
261
+
262
+ writeJson(path.join(getTasksDir(cwd), `${taskId}.json`), updated);
263
+ return updated;
264
+ }
265
+
266
+ export function getTasks(cwd: string): Task[] {
267
+ const dir = getTasksDir(cwd);
268
+ if (!fs.existsSync(dir)) return [];
269
+
270
+ const tasks: Task[] = [];
271
+ for (const file of fs.readdirSync(dir)) {
272
+ if (!file.endsWith(".json")) continue;
273
+ const raw = readJson<Task>(path.join(dir, file));
274
+ if (raw) tasks.push(normalizeTask(raw));
275
+ }
276
+
277
+ // Sort by ID number (task-1, task-2, ...)
278
+ return tasks.sort((a, b) => {
279
+ const aNum = parseInt(a.id.replace("task-", ""));
280
+ const bNum = parseInt(b.id.replace("task-", ""));
281
+ return aNum - bNum;
282
+ });
283
+ }
284
+
285
+ export function getTaskSpec(cwd: string, taskId: string): string | null {
286
+ return readText(path.join(getTasksDir(cwd), `${taskId}.md`));
287
+ }
288
+
289
+ export function appendTaskProgress(cwd: string, taskId: string, agent: string, message: string): void {
290
+ const progressPath = path.join(getTasksDir(cwd), `${taskId}.progress.md`);
291
+ ensureDir(path.dirname(progressPath));
292
+ const timestamp = new Date().toISOString();
293
+ fs.appendFileSync(progressPath, `[${timestamp}] (${agent}) ${message}\n`);
294
+ }
295
+
296
+ export function getTaskProgress(cwd: string, taskId: string): string | null {
297
+ const content = readText(path.join(getTasksDir(cwd), `${taskId}.progress.md`));
298
+ return content && content.trim().length > 0 ? content : null;
299
+ }
300
+
301
+ export function getBlockContext(cwd: string, taskId: string): string | null {
302
+ return readText(path.join(getBlocksDir(cwd), `${taskId}.md`));
303
+ }
304
+
305
+ export function setTaskSpec(cwd: string, taskId: string, content: string): void {
306
+ writeText(path.join(getTasksDir(cwd), `${taskId}.md`), content);
307
+ updateTask(cwd, taskId, {}); // Touch updated_at
308
+ }
309
+
310
+ export function deleteTask(cwd: string, taskId: string): boolean {
311
+ const task = getTask(cwd, taskId);
312
+ if (!task) return false;
313
+
314
+ const tasksDir = getTasksDir(cwd);
315
+ for (const ext of [".json", ".md", ".progress.md"]) {
316
+ try { fs.unlinkSync(path.join(tasksDir, `${taskId}${ext}`)); } catch {}
317
+ }
318
+
319
+ try { fs.unlinkSync(path.join(getBlocksDir(cwd), `${taskId}.md`)); } catch {}
320
+
321
+ const allTasks = getTasks(cwd);
322
+ for (const t of allTasks) {
323
+ if (t.depends_on.includes(taskId)) {
324
+ updateTask(cwd, t.id, {
325
+ depends_on: t.depends_on.filter(d => d !== taskId),
326
+ });
327
+ }
328
+ }
329
+
330
+ const plan = getPlan(cwd);
331
+ if (plan) {
332
+ const updates: Partial<Plan> = { task_count: plan.task_count - 1 };
333
+ if (task.status === "done") {
334
+ updates.completed_count = plan.completed_count - 1;
335
+ }
336
+ updatePlan(cwd, updates);
337
+ }
338
+
339
+ return true;
340
+ }
341
+
342
+ // =============================================================================
343
+ // Task Lifecycle Operations
344
+ // =============================================================================
345
+
346
+ export function getBaseCommit(cwd: string): string | undefined {
347
+ try {
348
+ return execSync("git rev-parse HEAD", {
349
+ cwd,
350
+ encoding: "utf-8",
351
+ stdio: ["pipe", "pipe", "pipe"],
352
+ timeout: 2000,
353
+ }).trim();
354
+ } catch {
355
+ return undefined;
356
+ }
357
+ }
358
+
359
+ export function startTask(cwd: string, taskId: string, agentName: string): Task | null {
360
+ const task = getTask(cwd, taskId);
361
+ if (!task || task.status !== "todo") return null;
362
+
363
+ return updateTask(cwd, taskId, {
364
+ status: "in_progress",
365
+ started_at: new Date().toISOString(),
366
+ base_commit: getBaseCommit(cwd),
367
+ assigned_to: agentName,
368
+ attempt_count: task.attempt_count + 1,
369
+ });
370
+ }
371
+
372
+ export function completeTask(
373
+ cwd: string,
374
+ taskId: string,
375
+ summary: string,
376
+ evidence?: TaskEvidence
377
+ ): Task | null {
378
+ const task = getTask(cwd, taskId);
379
+ if (!task || task.status !== "in_progress") return null;
380
+
381
+ const updated = updateTask(cwd, taskId, {
382
+ status: "done",
383
+ completed_at: new Date().toISOString(),
384
+ summary,
385
+ evidence,
386
+ assigned_to: undefined,
387
+ });
388
+
389
+ // Update plan completed count
390
+ if (updated) {
391
+ const plan = getPlan(cwd);
392
+ if (plan) {
393
+ updatePlan(cwd, { completed_count: plan.completed_count + 1 });
394
+ }
395
+ }
396
+
397
+ autoCompleteMilestones(cwd);
398
+
399
+ return updated;
400
+ }
401
+
402
+ export function blockTask(cwd: string, taskId: string, reason: string): Task | null {
403
+ const task = getTask(cwd, taskId);
404
+ if (!task) return null;
405
+
406
+ // Write block context to blocks directory
407
+ const blockPath = path.join(getBlocksDir(cwd), `${taskId}.md`);
408
+ writeText(blockPath, `# Blocked: ${task.title}\n\n**Reason:** ${reason}\n\n**Blocked at:** ${new Date().toISOString()}\n`);
409
+
410
+ return updateTask(cwd, taskId, {
411
+ status: "blocked",
412
+ blocked_reason: reason,
413
+ assigned_to: undefined,
414
+ });
415
+ }
416
+
417
+ export function unblockTask(cwd: string, taskId: string): Task | null {
418
+ const task = getTask(cwd, taskId);
419
+ if (!task || task.status !== "blocked") return null;
420
+
421
+ cleanupBlockFiles(cwd, taskId);
422
+
423
+ return updateTask(cwd, taskId, {
424
+ status: "todo",
425
+ blocked_reason: undefined,
426
+ });
427
+ }
428
+
429
+ export function resetTask(cwd: string, taskId: string, cascade: boolean = false): Task[] {
430
+ const task = getTask(cwd, taskId);
431
+ if (!task) return [];
432
+
433
+ const resetTasks: Task[] = [];
434
+ const wasDone = task.status === "done";
435
+
436
+ // Reset this task
437
+ const updated = updateTask(cwd, taskId, {
438
+ status: "todo",
439
+ started_at: undefined,
440
+ completed_at: undefined,
441
+ base_commit: undefined,
442
+ assigned_to: undefined,
443
+ summary: undefined,
444
+ evidence: undefined,
445
+ blocked_reason: undefined,
446
+ // Keep attempt_count for tracking
447
+ });
448
+ if (updated) resetTasks.push(updated);
449
+
450
+ cleanupBlockFiles(cwd, taskId);
451
+
452
+ // If cascade, reset all tasks that depend on this one
453
+ if (cascade) {
454
+ const allTasks = getTasks(cwd);
455
+ for (const t of allTasks) {
456
+ if (t.depends_on.includes(taskId) && t.status !== "todo") {
457
+ const cascaded = resetTask(cwd, t.id, true);
458
+ resetTasks.push(...cascaded);
459
+ }
460
+ }
461
+ }
462
+
463
+ // Update plan completed count if needed
464
+ if (wasDone && resetTasks.length > 0) {
465
+ const plan = getPlan(cwd);
466
+ if (plan) {
467
+ const doneTasks = getTasks(cwd).filter(t => t.status === "done");
468
+ updatePlan(cwd, { completed_count: doneTasks.length });
469
+ }
470
+ }
471
+
472
+ return resetTasks;
473
+ }
474
+
475
+ // =============================================================================
476
+ // Ready Tasks (Dependency Resolution)
477
+ // =============================================================================
478
+
479
+ export function getReadyTasksFrom(tasks: Task[], options?: { advisory?: boolean }): Task[] {
480
+ if (options?.advisory) {
481
+ return tasks.filter(t => t.status === "todo" && !t.milestone);
482
+ }
483
+ const doneIds = new Set(tasks.filter(t => t.status === "done").map(t => t.id));
484
+
485
+ return tasks.filter(task => {
486
+ if (task.status !== "todo" || task.milestone) return false;
487
+ return task.depends_on.every(depId => doneIds.has(depId));
488
+ });
489
+ }
490
+
491
+ export function getReadyTasks(cwd: string, options?: { advisory?: boolean }): Task[] {
492
+ return getReadyTasksFrom(getTasks(cwd), options);
493
+ }
494
+
495
+ export function autoCompleteMilestones(cwd: string): void {
496
+ let changed = true;
497
+ while (changed) {
498
+ changed = false;
499
+ const tasks = getTasks(cwd);
500
+ for (const task of tasks) {
501
+ if (!task.milestone || task.status !== "todo") continue;
502
+ const allDepsDone = task.depends_on.every(depId => {
503
+ const dep = getTask(cwd, depId);
504
+ return dep?.status === "done";
505
+ });
506
+ if (allDepsDone) {
507
+ updateTask(cwd, task.id, {
508
+ status: "done",
509
+ completed_at: new Date().toISOString(),
510
+ summary: "All subtasks completed",
511
+ });
512
+ const doneCount = getTasks(cwd).filter(t => t.status === "done").length;
513
+ const plan = getPlan(cwd);
514
+ if (plan) updatePlan(cwd, { completed_count: doneCount });
515
+ changed = true;
516
+ }
517
+ }
518
+ }
519
+ }
520
+
521
+ // =============================================================================
522
+ // Validation
523
+ // =============================================================================
524
+
525
+ export interface ValidationResult {
526
+ valid: boolean;
527
+ errors: string[];
528
+ warnings: string[];
529
+ }
530
+
531
+ export function validatePlan(cwd: string): ValidationResult {
532
+ const errors: string[] = [];
533
+ const warnings: string[] = [];
534
+
535
+ const plan = getPlan(cwd);
536
+ if (!plan) {
537
+ return { valid: false, errors: ["No plan found"], warnings: [] };
538
+ }
539
+
540
+ const tasks = getTasks(cwd);
541
+
542
+ // Check for orphan dependencies
543
+ const taskIds = new Set(tasks.map(t => t.id));
544
+ for (const task of tasks) {
545
+ for (const depId of task.depends_on) {
546
+ if (!taskIds.has(depId)) {
547
+ errors.push(`Task ${task.id} depends on non-existent task ${depId}`);
548
+ }
549
+ }
550
+ }
551
+
552
+ // Check for circular dependencies
553
+ const visited = new Set<string>();
554
+ const recursionStack = new Set<string>();
555
+
556
+ function hasCycle(taskId: string): boolean {
557
+ if (recursionStack.has(taskId)) return true;
558
+ if (visited.has(taskId)) return false;
559
+
560
+ visited.add(taskId);
561
+ recursionStack.add(taskId);
562
+
563
+ const task = tasks.find(t => t.id === taskId);
564
+ if (task) {
565
+ for (const depId of task.depends_on) {
566
+ if (hasCycle(depId)) return true;
567
+ }
568
+ }
569
+
570
+ recursionStack.delete(taskId);
571
+ return false;
572
+ }
573
+
574
+ for (const task of tasks) {
575
+ visited.clear();
576
+ recursionStack.clear();
577
+ if (hasCycle(task.id)) {
578
+ errors.push(`Circular dependency detected involving task ${task.id}`);
579
+ }
580
+ }
581
+
582
+ // Check for tasks without specs
583
+ for (const task of tasks) {
584
+ const spec = getTaskSpec(cwd, task.id);
585
+ if (!spec || spec.includes("*Spec pending*")) {
586
+ warnings.push(`Task ${task.id} has no detailed spec`);
587
+ }
588
+ }
589
+
590
+ // Check plan spec
591
+ const planSpec = getPlanSpec(cwd);
592
+ if (!planSpec || planSpec.includes("*Spec pending*")) {
593
+ warnings.push("Plan has no detailed spec");
594
+ }
595
+
596
+ // Check task counts
597
+ if (plan.task_count !== tasks.length) {
598
+ warnings.push(`Plan task_count (${plan.task_count}) doesn't match actual tasks (${tasks.length})`);
599
+ }
600
+
601
+ const actualDone = tasks.filter(t => t.status === "done").length;
602
+ if (plan.completed_count !== actualDone) {
603
+ warnings.push(`Plan completed_count (${plan.completed_count}) doesn't match actual (${actualDone})`);
604
+ }
605
+
606
+ return {
607
+ valid: errors.length === 0,
608
+ errors,
609
+ warnings,
610
+ };
611
+ }
612
+
613
+ // =============================================================================
614
+ // Dependency Graph
615
+ // =============================================================================
616
+
617
+ export function getTransitiveDependents(cwd: string, targetId: string): Task[] {
618
+ const tasks = getTasks(cwd);
619
+ const collected = new Set<string>();
620
+ const queue = [targetId];
621
+
622
+ while (queue.length > 0) {
623
+ const current = queue.shift()!;
624
+ for (const task of tasks) {
625
+ if (collected.has(task.id) || task.id === targetId) continue;
626
+ if (task.depends_on.includes(current)) {
627
+ collected.add(task.id);
628
+ queue.push(task.id);
629
+ }
630
+ }
631
+ }
632
+
633
+ return tasks.filter(t => collected.has(t.id));
634
+ }
635
+
636
+ // =============================================================================
637
+ // Plan Existence Check
638
+ // =============================================================================
639
+
640
+ export function hasPlan(cwd: string): boolean {
641
+ return getPlan(cwd) !== null;
642
+ }