File size: 6,391 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import fs from 'node:fs/promises';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { debugLogger } from '../utils/debugLogger.js';
import { coreEvents } from '../utils/events.js';
import {
  TrackerTaskSchema,
  TaskStatus,
  type TrackerTask,
} from './trackerTypes.js';
import { type z } from 'zod';

export class TrackerService {
  private readonly tasksDir: string;

  private initialized = false;

  constructor(readonly trackerDir: string) {
    this.tasksDir = trackerDir;
  }

  private async ensureInitialized(): Promise<void> {
    if (!this.initialized) {
      await fs.mkdir(this.tasksDir, { recursive: true });
      this.initialized = true;
    }
  }

  /**
   * Generates a 6-character hex ID.
   */
  private generateId(): string {
    return randomBytes(3).toString('hex');
  }

  /**
   * Creates a new task and saves it to disk.
   */
  async createTask(taskData: Omit<TrackerTask, 'id'>): Promise<TrackerTask> {
    await this.ensureInitialized();
    const id = this.generateId();
    const task: TrackerTask = {
      ...taskData,
      id,
    };

    if (task.parentId) {
      const parent = await this.getTask(task.parentId);
      if (!parent) {
        throw new Error(`Parent task with ID ${task.parentId} not found.`);
      }
    }

    TrackerTaskSchema.parse(task);

    await this.saveTask(task);
    return task;
  }

  /**
   * Helper to read and validate a JSON file.
   */
  private async readJsonFile<T>(
    filePath: string,
    schema: z.ZodSchema<T>,
  ): Promise<T | null> {
    try {
      const content = await fs.readFile(filePath, 'utf8');
      const data: unknown = JSON.parse(content);
      return schema.parse(data);
    } catch (error) {
      if (
        error &&
        typeof error === 'object' &&
        'code' in error &&
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        (error as NodeJS.ErrnoException).code === 'ENOENT'
      ) {
        return null;
      }

      const fileName = path.basename(filePath);
      debugLogger.warn(`Failed to read or parse task file ${fileName}:`, error);
      coreEvents.emitFeedback(
        'warning',
        `Task tracker encountered an issue reading ${fileName}. The data might be corrupted.`,
        error,
      );
      throw error;
    }
  }

  /**
   * Reads a task by ID.
   */
  async getTask(id: string): Promise<TrackerTask | null> {
    await this.ensureInitialized();
    const taskPath = path.join(this.tasksDir, `${id}.json`);
    return this.readJsonFile(taskPath, TrackerTaskSchema);
  }

  /**
   * Lists all tasks in the tracker.
   */
  async listTasks(): Promise<TrackerTask[]> {
    await this.ensureInitialized();
    try {
      const files = await fs.readdir(this.tasksDir);
      const jsonFiles = files.filter((f: string) => f.endsWith('.json'));
      const tasks = await Promise.all(
        jsonFiles.map(async (f: string) => {
          const taskPath = path.join(this.tasksDir, f);
          return this.readJsonFile(taskPath, TrackerTaskSchema);
        }),
      );
      return tasks.filter((t): t is TrackerTask => t !== null);
    } catch (error) {
      if (
        error &&
        typeof error === 'object' &&
        'code' in error &&
        error.code === 'ENOENT'
      ) {
        return [];
      }
      throw error;
    }
  }

  /**
   * Updates an existing task and saves it to disk.
   */
  async updateTask(
    id: string,
    updates: Partial<TrackerTask>,
  ): Promise<TrackerTask> {
    const isClosing = updates.status === TaskStatus.CLOSED;
    const changingDependencies = updates.dependencies !== undefined;

    const task = await this.getTask(id);

    if (!task) {
      throw new Error(`Task with ID ${id} not found.`);
    }

    const updatedTask = { ...task, ...updates, id: task.id };

    if (updatedTask.parentId) {
      const parentExists = !!(await this.getTask(updatedTask.parentId));
      if (!parentExists) {
        throw new Error(
          `Parent task with ID ${updatedTask.parentId} not found.`,
        );
      }
    }

    if (isClosing && task.status !== TaskStatus.CLOSED) {
      await this.validateCanClose(updatedTask);
    }

    if (changingDependencies) {
      await this.validateNoCircularDependencies(updatedTask);
    }

    TrackerTaskSchema.parse(updatedTask);

    await this.saveTask(updatedTask);
    return updatedTask;
  }

  /**
   * Saves a task to disk.
   */
  private async saveTask(task: TrackerTask): Promise<void> {
    const taskPath = path.join(this.tasksDir, `${task.id}.json`);
    await fs.writeFile(taskPath, JSON.stringify(task, null, 2), 'utf8');
  }

  /**
   * Validates that a task can be closed (all dependencies must be closed).
   */
  private async validateCanClose(task: TrackerTask): Promise<void> {
    for (const depId of task.dependencies) {
      const dep = await this.getTask(depId);
      if (!dep) {
        throw new Error(`Dependency ${depId} not found for task ${task.id}.`);
      }
      if (dep.status !== TaskStatus.CLOSED) {
        throw new Error(
          `Cannot close task ${task.id} because dependency ${depId} is still ${dep.status}.`,
        );
      }
    }
  }

  /**
   * Validates that there are no circular dependencies.
   */
  private async validateNoCircularDependencies(
    task: TrackerTask,
  ): Promise<void> {
    const visited = new Set<string>();
    const stack = new Set<string>();
    const cache = new Map<string, TrackerTask>();
    cache.set(task.id, task);

    const check = async (currentId: string) => {
      if (stack.has(currentId)) {
        throw new Error(
          `Circular dependency detected involving task ${currentId}.`,
        );
      }
      if (visited.has(currentId)) {
        return;
      }

      visited.add(currentId);
      stack.add(currentId);

      let currentTask = cache.get(currentId);
      if (!currentTask) {
        const fetched = await this.getTask(currentId);
        if (!fetched) {
          throw new Error(`Dependency ${currentId} not found.`);
        }
        currentTask = fetched;
        cache.set(currentId, currentTask);
      }

      for (const depId of currentTask.dependencies) {
        await check(depId);
      }

      stack.delete(currentId);
    };

    await check(task.id);
  }
}