-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfs.ts
More file actions
405 lines (366 loc) · 10.7 KB
/
fs.ts
File metadata and controls
405 lines (366 loc) · 10.7 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { exec } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { type IpcMainInvokeEvent, ipcMain } from "electron";
const execAsync = promisify(exec);
const fsPromises = fs.promises;
interface FileEntry {
path: string;
name: string;
}
// Cache for repository files to avoid rescanning
const repoFileCache = new Map<
string,
{ files: FileEntry[]; timestamp: number }
>();
const CACHE_TTL = 30000; // 30 seconds
async function getGitIgnoredFiles(repoPath: string): Promise<Set<string>> {
try {
const { stdout } = await execAsync(
"git ls-files --others --ignored --exclude-standard",
{ cwd: repoPath },
);
return new Set(
stdout
.split("\n")
.filter(Boolean)
.map((f) => path.join(repoPath, f)),
);
} catch {
// If git command fails, return empty set
return new Set();
}
}
async function listFilesRecursive(
dirPath: string,
ignoredFiles: Set<string>,
baseDir: string,
): Promise<FileEntry[]> {
const files: FileEntry[] = [];
try {
const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(baseDir, fullPath);
// Skip hidden files/directories, node_modules, and common build dirs
if (
entry.name.startsWith(".") ||
entry.name === "node_modules" ||
entry.name === "dist" ||
entry.name === "build" ||
entry.name === "__pycache__"
) {
continue;
}
// Skip git-ignored files
if (ignoredFiles.has(fullPath)) {
continue;
}
if (entry.isDirectory()) {
const subFiles = await listFilesRecursive(
fullPath,
ignoredFiles,
baseDir,
);
files.push(...subFiles);
} else if (entry.isFile()) {
files.push({
path: relativePath,
name: entry.name,
});
}
}
} catch (error) {
// Skip directories we can't read
console.error(`Error reading directory ${dirPath}:`, error);
}
return files;
}
export function registerFsIpc(): void {
ipcMain.handle(
"list-repo-files",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
query?: string,
): Promise<FileEntry[]> => {
if (!repoPath) return [];
try {
// Check cache
const cached = repoFileCache.get(repoPath);
const now = Date.now();
let allFiles: FileEntry[];
if (cached && now - cached.timestamp < CACHE_TTL) {
allFiles = cached.files;
} else {
// Get git-ignored files
const ignoredFiles = await getGitIgnoredFiles(repoPath);
// List all files
allFiles = await listFilesRecursive(repoPath, ignoredFiles, repoPath);
// Update cache
repoFileCache.set(repoPath, {
files: allFiles,
timestamp: now,
});
}
// Filter by query if provided
if (query?.trim()) {
const lowerQuery = query.toLowerCase();
return allFiles
.filter(
(f) =>
f.path.toLowerCase().includes(lowerQuery) ||
f.name.toLowerCase().includes(lowerQuery),
)
.slice(0, 50); // Limit results
}
return allFiles.slice(0, 100); // Limit initial results
} catch (error) {
console.error("Error listing repo files:", error);
return [];
}
},
);
// Plan file operations
ipcMain.handle(
"ensure-posthog-folder",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
): Promise<string> => {
const posthogDir = path.join(repoPath, ".posthog", taskId);
await fsPromises.mkdir(posthogDir, { recursive: true });
return posthogDir;
},
);
ipcMain.handle(
"read-plan-file",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
): Promise<string | null> => {
try {
const planPath = path.join(repoPath, ".posthog", taskId, "plan.md");
const content = await fsPromises.readFile(planPath, "utf-8");
return content;
} catch (error) {
// File doesn't exist or can't be read
console.log(`Plan file not found for task ${taskId}:`, error);
return null;
}
},
);
ipcMain.handle(
"write-plan-file",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
content: string,
): Promise<void> => {
try {
const posthogDir = path.join(repoPath, ".posthog", taskId);
await fsPromises.mkdir(posthogDir, { recursive: true });
const planPath = path.join(posthogDir, "plan.md");
await fsPromises.writeFile(planPath, content, "utf-8");
console.log(`Plan file written for task ${taskId}`);
} catch (error) {
console.error(`Failed to write plan file for task ${taskId}:`, error);
throw error;
}
},
);
ipcMain.handle(
"list-task-artifacts",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
): Promise<
Array<{ name: string; path: string; size: number; modifiedAt: string }>
> => {
try {
const posthogDir = path.join(repoPath, ".posthog", taskId);
// Check if directory exists
try {
await fsPromises.access(posthogDir);
} catch {
return []; // Directory doesn't exist yet
}
const entries = await fsPromises.readdir(posthogDir, {
withFileTypes: true,
});
const artifacts = [];
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith(".md")) {
const filePath = path.join(posthogDir, entry.name);
const stats = await fsPromises.stat(filePath);
artifacts.push({
name: entry.name,
path: filePath,
size: stats.size,
modifiedAt: stats.mtime.toISOString(),
});
}
}
return artifacts;
} catch (error) {
console.error(`Failed to list artifacts for task ${taskId}:`, error);
return [];
}
},
);
ipcMain.handle(
"read-task-artifact",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
fileName: string,
): Promise<string | null> => {
try {
const filePath = path.join(repoPath, ".posthog", taskId, fileName);
const content = await fsPromises.readFile(filePath, "utf-8");
return content;
} catch (error) {
console.error(
`Failed to read artifact ${fileName} for task ${taskId}:`,
error,
);
return null;
}
},
);
ipcMain.handle(
"append-to-artifact",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
fileName: string,
content: string,
): Promise<void> => {
try {
const filePath = path.join(repoPath, ".posthog", taskId, fileName);
// Ensure the file exists before appending
try {
await fsPromises.access(filePath);
} catch {
throw new Error(`File ${fileName} does not exist for task ${taskId}`);
}
await fsPromises.appendFile(filePath, content, "utf-8");
console.log(`Appended content to ${fileName} for task ${taskId}`);
} catch (error) {
console.error(
`Failed to append to artifact ${fileName} for task ${taskId}:`,
error,
);
throw error;
}
},
);
ipcMain.handle(
"save-question-answers",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
taskId: string,
answers: Array<{
questionId: string;
selectedOption: string;
customInput?: string;
}>,
): Promise<void> => {
try {
const researchPath = path.join(
repoPath,
".posthog",
taskId,
"research.json",
);
// Read existing research.json
let researchData: {
actionabilityScore: number;
context: string;
keyFiles: string[];
blockers?: string[];
questions?: Array<{
id: string;
question: string;
options: string[];
}>;
answered?: boolean;
answers?: Array<{
questionId: string;
selectedOption: string;
customInput?: string;
}>;
};
try {
const content = await fsPromises.readFile(researchPath, "utf-8");
researchData = JSON.parse(content);
} catch {
throw new Error(`research.json not found for task ${taskId}`);
}
// Update with answers
researchData.answered = true;
researchData.answers = answers;
// Write back to file
await fsPromises.writeFile(
researchPath,
JSON.stringify(researchData, null, 2),
"utf-8",
);
console.log(`Saved answers to research.json for task ${taskId}`);
// Commit the answers (local mode - no push)
try {
await execAsync(`cd "${repoPath}" && git add .posthog/`, {
cwd: repoPath,
});
await execAsync(
`cd "${repoPath}" && git commit -m "Answer research questions for task ${taskId}"`,
{ cwd: repoPath },
);
console.log(`Committed answers for task ${taskId}`);
} catch (gitError) {
console.warn(
`Failed to commit answers (may not be a git repo or no changes):`,
gitError,
);
// Don't throw - answers are still saved
}
} catch (error) {
console.error(`Failed to save answers for task ${taskId}:`, error);
throw error;
}
},
);
ipcMain.handle(
"read-repo-file",
async (
_event: IpcMainInvokeEvent,
repoPath: string,
filePath: string,
): Promise<string | null> => {
try {
const fullPath = path.join(repoPath, filePath);
const resolvedPath = path.resolve(fullPath);
const resolvedRepo = path.resolve(repoPath);
if (!resolvedPath.startsWith(resolvedRepo)) {
throw new Error("Access denied: path outside repository");
}
const content = await fsPromises.readFile(fullPath, "utf-8");
return content;
} catch (error) {
console.error(
`Failed to read file ${filePath} from ${repoPath}:`,
error,
);
return null;
}
},
);
}