File size: 8,333 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
 * Notification Service - Handles reading/writing notifications to JSON files
 *
 * Provides persistent storage for project-level notifications in
 * {projectPath}/.automaker/notifications.json
 *
 * Notifications alert users when:
 * - Features reach specific statuses (waiting_approval, verified)
 * - Long-running operations complete (spec generation)
 */

import { createLogger } from '@automaker/utils';
import * as secureFs from '../lib/secure-fs.js';
import { getNotificationsPath, ensureAutomakerDir } from '@automaker/platform';
import type { Notification, NotificationsFile, NotificationType } from '@automaker/types';
import { DEFAULT_NOTIFICATIONS_FILE } from '@automaker/types';
import type { EventEmitter } from '../lib/events.js';
import { randomUUID } from 'crypto';

const logger = createLogger('NotificationService');

/**
 * Atomic file write - write to temp file then rename
 */
async function atomicWriteJson(filePath: string, data: unknown): Promise<void> {
  const tempPath = `${filePath}.tmp.${Date.now()}`;
  const content = JSON.stringify(data, null, 2);

  try {
    await secureFs.writeFile(tempPath, content, 'utf-8');
    await secureFs.rename(tempPath, filePath);
  } catch (error) {
    // Clean up temp file if it exists
    try {
      await secureFs.unlink(tempPath);
    } catch {
      // Ignore cleanup errors
    }
    throw error;
  }
}

/**
 * Safely read JSON file with fallback to default
 */
async function readJsonFile<T>(filePath: string, defaultValue: T): Promise<T> {
  try {
    const content = (await secureFs.readFile(filePath, 'utf-8')) as string;
    return JSON.parse(content) as T;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
      return defaultValue;
    }
    logger.error(`Error reading ${filePath}:`, error);
    return defaultValue;
  }
}

/**
 * Input for creating a new notification
 */
export interface CreateNotificationInput {
  type: NotificationType;
  title: string;
  message: string;
  featureId?: string;
  projectPath: string;
}

/**
 * NotificationService - Manages persistent storage of notifications
 *
 * Handles reading and writing notifications to JSON files with atomic operations
 * for reliability. Each project has its own notifications.json file.
 */
export class NotificationService {
  private events: EventEmitter | null = null;

  /**
   * Set the event emitter for broadcasting notification events
   */
  setEventEmitter(events: EventEmitter): void {
    this.events = events;
  }

  /**
   * Get all notifications for a project
   *
   * @param projectPath - Absolute path to project directory
   * @returns Promise resolving to array of notifications
   */
  async getNotifications(projectPath: string): Promise<Notification[]> {
    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );
    // Filter out dismissed notifications and sort by date (newest first)
    return file.notifications
      .filter((n) => !n.dismissed)
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
  }

  /**
   * Get unread notification count for a project
   *
   * @param projectPath - Absolute path to project directory
   * @returns Promise resolving to unread count
   */
  async getUnreadCount(projectPath: string): Promise<number> {
    const notifications = await this.getNotifications(projectPath);
    return notifications.filter((n) => !n.read).length;
  }

  /**
   * Create a new notification
   *
   * @param input - Notification creation input
   * @returns Promise resolving to the created notification
   */
  async createNotification(input: CreateNotificationInput): Promise<Notification> {
    const { projectPath, type, title, message, featureId } = input;

    // Ensure automaker directory exists
    await ensureAutomakerDir(projectPath);

    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );

    const notification: Notification = {
      id: randomUUID(),
      type,
      title,
      message,
      createdAt: new Date().toISOString(),
      read: false,
      dismissed: false,
      featureId,
      projectPath,
    };

    file.notifications.push(notification);
    await atomicWriteJson(notificationsPath, file);

    logger.info(`Created notification: ${title} for project ${projectPath}`);

    // Emit event for real-time updates
    if (this.events) {
      this.events.emit('notification:created', notification);
    }

    return notification;
  }

  /**
   * Mark a notification as read
   *
   * @param projectPath - Absolute path to project directory
   * @param notificationId - ID of the notification to mark as read
   * @returns Promise resolving to the updated notification or null if not found
   */
  async markAsRead(projectPath: string, notificationId: string): Promise<Notification | null> {
    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );

    const notification = file.notifications.find((n) => n.id === notificationId);
    if (!notification) {
      return null;
    }

    notification.read = true;
    await atomicWriteJson(notificationsPath, file);

    logger.info(`Marked notification ${notificationId} as read`);
    return notification;
  }

  /**
   * Mark all notifications as read for a project
   *
   * @param projectPath - Absolute path to project directory
   * @returns Promise resolving to number of notifications marked as read
   */
  async markAllAsRead(projectPath: string): Promise<number> {
    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );

    let count = 0;
    for (const notification of file.notifications) {
      if (!notification.read && !notification.dismissed) {
        notification.read = true;
        count++;
      }
    }

    if (count > 0) {
      await atomicWriteJson(notificationsPath, file);
      logger.info(`Marked ${count} notifications as read`);
    }

    return count;
  }

  /**
   * Dismiss a notification
   *
   * @param projectPath - Absolute path to project directory
   * @param notificationId - ID of the notification to dismiss
   * @returns Promise resolving to true if notification was dismissed
   */
  async dismissNotification(projectPath: string, notificationId: string): Promise<boolean> {
    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );

    const notification = file.notifications.find((n) => n.id === notificationId);
    if (!notification) {
      return false;
    }

    notification.dismissed = true;
    await atomicWriteJson(notificationsPath, file);

    logger.info(`Dismissed notification ${notificationId}`);
    return true;
  }

  /**
   * Dismiss all notifications for a project
   *
   * @param projectPath - Absolute path to project directory
   * @returns Promise resolving to number of notifications dismissed
   */
  async dismissAll(projectPath: string): Promise<number> {
    const notificationsPath = getNotificationsPath(projectPath);
    const file = await readJsonFile<NotificationsFile>(
      notificationsPath,
      DEFAULT_NOTIFICATIONS_FILE
    );

    let count = 0;
    for (const notification of file.notifications) {
      if (!notification.dismissed) {
        notification.dismissed = true;
        count++;
      }
    }

    if (count > 0) {
      await atomicWriteJson(notificationsPath, file);
      logger.info(`Dismissed ${count} notifications`);
    }

    return count;
  }
}

// Singleton instance
let notificationServiceInstance: NotificationService | null = null;

/**
 * Get the singleton notification service instance
 */
export function getNotificationService(): NotificationService {
  if (!notificationServiceInstance) {
    notificationServiceInstance = new NotificationService();
  }
  return notificationServiceInstance;
}