๐Ÿ“ฆ juspay / workforge

๐Ÿ“„ AuditLogger.ts ยท 387 lines
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387import { existsSync, readFileSync, writeFileSync, appendFileSync, mkdirSync, unlinkSync } from 'fs';
import * as path from 'path';
import { ProjectIdentifier } from './ProjectIdentifier.js';
import { ConfigManager } from './ConfigManager.js';
import { AuditOperation, SyncResult, AuditStatistics } from '../types/index.js';

/**
 * Audit Logger
 *
 * Dual-format audit logging system:
 * 1. Human-readable log: ~/.workforge/projects/<project-id>/audit.log
 * 2. Machine-readable JSON: ~/.workforge/projects/<project-id>/sync-history.json
 *
 * Features:
 * - Configurable variable value inclusion
 * - Auto-cleanup based on retention days
 * - Project metadata tracking
 */
export class AuditLogger {
  private configManager: ConfigManager;
  private auditEnabled!: boolean;
  private includeValues!: boolean;
  private retentionDays!: number;

  constructor(configManager?: ConfigManager) {
    this.configManager = configManager || new ConfigManager();
    this.loadConfig();
  }

  /**
   * Load audit configuration
   */
  private loadConfig(): void {
    try {
      const config = this.configManager.load();
      this.auditEnabled = config.audit.enabled;
      this.includeValues = config.audit.includeVariableValues;
      this.retentionDays = config.audit.retentionDays;
    } catch {
      // Fallback to defaults
      this.auditEnabled = true;
      this.includeValues = true;
      this.retentionDays = 90;
    }
  }

  /**
   * Log an audit operation
   *
   * @param operation - Audit operation details
   * @param repoRoot - Repository root path
   */
  log(operation: AuditOperation, repoRoot: string): void {
    if (!this.auditEnabled) {
      return;
    }

    // Get project directory
    const projectDir = ProjectIdentifier.getProjectDir(repoRoot);

    // Create project directory if it doesn't exist
    if (!existsSync(projectDir)) {
      mkdirSync(projectDir, { recursive: true });
    }

    // Update project metadata
    ProjectIdentifier.updateMetadata(repoRoot);

    // Append to human-readable log
    this.appendToLog(operation, projectDir);

    // Add to JSON history
    this.addToHistory(operation, projectDir);

    // Cleanup old logs if needed
    this.cleanupOldLogs(projectDir);
  }

  /**
   * Append operation to human-readable log file
   */
  private appendToLog(operation: AuditOperation, projectDir: string): void {
    const logPath = path.join(projectDir, 'audit.log');
    const logEntry = this.formatLogEntry(operation);

    try {
      appendFileSync(logPath, logEntry + '\n', 'utf8');
    } catch (error) {
      console.warn(`Warning: Failed to write to audit log: ${error}`);
    }
  }

  /**
   * Format operation as human-readable log entry
   */
  private formatLogEntry(operation: AuditOperation): string {
    const timestamp = new Date(operation.timestamp).toISOString();
    const separator = 'โ”€'.repeat(80);

    let entry = `\n${separator}\n`;
    entry += `[${timestamp}] ${operation.operation.toUpperCase()}\n`;
    entry += `${separator}\n\n`;

    // Source and target
    entry += `Source: ${operation.source}\n`;
    entry += `Target: ${operation.target}\n\n`;

    // Changes
    entry += `Changes:\n`;
    entry += `  Added:    ${operation.changesApplied.added} variable(s)\n`;
    entry += `  Modified: ${operation.changesApplied.modified} variable(s)\n`;
    entry += `  Removed:  ${operation.changesApplied.removed} variable(s)\n\n`;

    // Details (if values included in config)
    if (this.includeValues && operation.variableDetails) {
      entry += `Details:\n`;

      if (operation.variableDetails.added.length > 0) {
        entry += `\n  Added Variables:\n`;
        for (const key of operation.variableDetails.added) {
          entry += `    + ${key}\n`;
        }
      }

      if (operation.variableDetails.modified.length > 0) {
        entry += `\n  Modified Variables:\n`;
        for (const key of operation.variableDetails.modified) {
          entry += `    ~ ${key}\n`;
        }
      }

      if (operation.variableDetails.removed.length > 0) {
        entry += `\n  Removed Variables:\n`;
        for (const key of operation.variableDetails.removed) {
          entry += `    - ${key}\n`;
        }
      }

      entry += '\n';
    }

    // Success/failure
    entry += `Status: ${operation.success ? 'SUCCESS' : 'FAILED'}\n`;

    if (operation.error) {
      entry += `Error: ${operation.error}\n`;
    }

    if (operation.backupCreated) {
      entry += `Backup: Created\n`;
    }

    return entry;
  }

  /**
   * Add operation to JSON history
   */
  private addToHistory(operation: AuditOperation, projectDir: string): void {
    const historyPath = path.join(projectDir, 'sync-history.json');

    // Read existing history
    let history: AuditOperation[] = [];

    if (existsSync(historyPath)) {
      try {
        const content = readFileSync(historyPath, 'utf8');
        history = JSON.parse(content);
      } catch (error) {
        console.warn(`Warning: Failed to parse sync history, creating new file: ${error}`);
        history = [];
      }
    }

    // Add new operation
    history.push(operation);

    // Write updated history
    try {
      writeFileSync(historyPath, JSON.stringify(history, null, 2), 'utf8');
    } catch (error) {
      console.warn(`Warning: Failed to write sync history: ${error}`);
    }
  }

  /**
   * Cleanup old logs based on retention days
   */
  private cleanupOldLogs(projectDir: string): void {
    const historyPath = path.join(projectDir, 'sync-history.json');

    if (!existsSync(historyPath)) {
      return;
    }

    try {
      const content = readFileSync(historyPath, 'utf8');
      const history: AuditOperation[] = JSON.parse(content);

      // Calculate cutoff date
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - this.retentionDays);

      // Filter out old entries
      const filtered = history.filter(operation => {
        const opDate = new Date(operation.timestamp);
        return opDate >= cutoffDate;
      });

      // Write back if entries were removed
      if (filtered.length < history.length) {
        writeFileSync(historyPath, JSON.stringify(filtered, null, 2), 'utf8');

        // Also cleanup human-readable log
        // (We'll rebuild it from filtered history)
        this.rebuildHumanLog(filtered, projectDir);
      }
    } catch (error) {
      console.warn(`Warning: Failed to cleanup old logs: ${error}`);
    }
  }

  /**
   * Rebuild human-readable log from JSON history
   */
  private rebuildHumanLog(history: AuditOperation[], projectDir: string): void {
    const logPath = path.join(projectDir, 'audit.log');

    try {
      // Clear existing log
      if (existsSync(logPath)) {
        unlinkSync(logPath);
      }

      // Rebuild from history
      for (const operation of history) {
        const logEntry = this.formatLogEntry(operation);
        appendFileSync(logPath, logEntry + '\n', 'utf8');
      }
    } catch (error) {
      console.warn(`Warning: Failed to rebuild audit log: ${error}`);
    }
  }

  /**
   * Get audit history for a project
   *
   * @param repoRoot - Repository root
   * @returns Array of audit operations
   */
  getHistory(repoRoot: string): AuditOperation[] {
    const projectDir = ProjectIdentifier.getProjectDir(repoRoot);
    const historyPath = path.join(projectDir, 'sync-history.json');

    if (!existsSync(historyPath)) {
      return [];
    }

    try {
      const content = readFileSync(historyPath, 'utf8');
      return JSON.parse(content);
    } catch (error) {
      console.warn(`Warning: Failed to read sync history: ${error}`);
      return [];
    }
  }

  /**
   * Get recent audit operations
   *
   * @param repoRoot - Repository root
   * @param limit - Maximum number of operations to return
   * @returns Array of recent audit operations
   */
  getRecentHistory(repoRoot: string, limit: number = 10): AuditOperation[] {
    const history = this.getHistory(repoRoot);

    // Sort by timestamp (newest first)
    history.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

    return history.slice(0, limit);
  }

  /**
   * Get audit statistics for a project
   *
   * @param repoRoot - Repository root
   * @returns Statistics object
   */
  getStatistics(repoRoot: string): AuditStatistics {
    const history = this.getHistory(repoRoot);

    const stats = {
      totalOperations: history.length,
      successfulOperations: 0,
      failedOperations: 0,
      totalAdded: 0,
      totalModified: 0,
      totalRemoved: 0,
      lastOperation: null as Date | null
    };

    for (const operation of history) {
      if (operation.success) {
        stats.successfulOperations++;
      } else {
        stats.failedOperations++;
      }

      stats.totalAdded += operation.changesApplied.added;
      stats.totalModified += operation.changesApplied.modified;
      stats.totalRemoved += operation.changesApplied.removed;
    }

    if (history.length > 0) {
      // Find most recent operation
      const sorted = history.sort(
        (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      );
      stats.lastOperation = new Date(sorted[0].timestamp);
    }

    return stats;
  }

  /**
   * Clear all audit logs for a project
   *
   * @param repoRoot - Repository root
   */
  clearHistory(repoRoot: string): void {
    const projectDir = ProjectIdentifier.getProjectDir(repoRoot);
    const logPath = path.join(projectDir, 'audit.log');
    const historyPath = path.join(projectDir, 'sync-history.json');

    try {
      if (existsSync(logPath)) {
        unlinkSync(logPath);
      }

      if (existsSync(historyPath)) {
        unlinkSync(historyPath);
      }
    } catch (error) {
      console.warn(`Warning: Failed to clear audit history: ${error}`);
    }
  }

  /**
   * Create audit operation from sync result
   *
   * @param result - Sync result
   * @param source - Source label
   * @param target - Target label
   * @param backupCreated - Whether backup was created
   * @returns Audit operation
   */
  createAuditOperation(
    result: SyncResult,
    source: string,
    target: string,
    backupCreated: boolean
  ): AuditOperation {
    return {
      timestamp: new Date().toISOString(),
      operation: 'sync',
      source,
      target,
      changesApplied: {
        added: result.addedCount,
        modified: result.modifiedCount,
        removed: result.removedCount
      },
      variableDetails: this.includeValues
        ? {
            added: Array.from(result.addedKeys || []),
            modified: Array.from(result.modifiedKeys || []),
            removed: Array.from(result.removedKeys || [])
          }
        : undefined,
      success: result.success,
      error: result.error,
      backupCreated
    };
  }
}