diffprism 0.31.1 → 0.33.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.
- package/dist/bin.js +122 -7
- package/dist/chunk-ZLIUNVTW.js +6498 -0
- package/dist/mcp-server.js +184 -6
- package/package.json +1 -1
- package/ui-dist/assets/{index-Cwwzm9DK.js → index-D_thqcUo.js} +78 -73
- package/ui-dist/assets/index-w55XbIEb.css +1 -0
- package/ui-dist/index.html +2 -2
- package/dist/chunk-OJ723D6Z.js +0 -2589
- package/ui-dist/assets/index-r-H-ptFw.css +0 -1
package/dist/chunk-OJ723D6Z.js
DELETED
|
@@ -1,2589 +0,0 @@
|
|
|
1
|
-
// packages/git/src/local.ts
|
|
2
|
-
import { execSync } from "child_process";
|
|
3
|
-
import { readFileSync } from "fs";
|
|
4
|
-
import path from "path";
|
|
5
|
-
function getGitDiff(ref, options) {
|
|
6
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
7
|
-
try {
|
|
8
|
-
execSync("git --version", { cwd, stdio: "pipe" });
|
|
9
|
-
} catch {
|
|
10
|
-
throw new Error(
|
|
11
|
-
"git is not available. Please install git and make sure it is on your PATH."
|
|
12
|
-
);
|
|
13
|
-
}
|
|
14
|
-
try {
|
|
15
|
-
execSync("git rev-parse --is-inside-work-tree", { cwd, stdio: "pipe" });
|
|
16
|
-
} catch {
|
|
17
|
-
throw new Error(
|
|
18
|
-
`The directory "${cwd}" is not inside a git repository.`
|
|
19
|
-
);
|
|
20
|
-
}
|
|
21
|
-
let command;
|
|
22
|
-
let includeUntracked = false;
|
|
23
|
-
switch (ref) {
|
|
24
|
-
case "staged":
|
|
25
|
-
command = "git diff --staged --no-color";
|
|
26
|
-
break;
|
|
27
|
-
case "unstaged":
|
|
28
|
-
command = "git diff --no-color";
|
|
29
|
-
includeUntracked = true;
|
|
30
|
-
break;
|
|
31
|
-
case "all":
|
|
32
|
-
command = "git diff HEAD --no-color";
|
|
33
|
-
includeUntracked = true;
|
|
34
|
-
break;
|
|
35
|
-
default:
|
|
36
|
-
command = `git diff --no-color ${ref}`;
|
|
37
|
-
break;
|
|
38
|
-
}
|
|
39
|
-
let output;
|
|
40
|
-
try {
|
|
41
|
-
output = execSync(command, {
|
|
42
|
-
cwd,
|
|
43
|
-
encoding: "utf-8",
|
|
44
|
-
maxBuffer: 50 * 1024 * 1024
|
|
45
|
-
// 50 MB
|
|
46
|
-
});
|
|
47
|
-
} catch (err) {
|
|
48
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
49
|
-
throw new Error(`git diff failed: ${message}`);
|
|
50
|
-
}
|
|
51
|
-
if (includeUntracked) {
|
|
52
|
-
output += getUntrackedDiffs(cwd);
|
|
53
|
-
}
|
|
54
|
-
return output;
|
|
55
|
-
}
|
|
56
|
-
function getCurrentBranch(options) {
|
|
57
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
58
|
-
try {
|
|
59
|
-
return execSync("git rev-parse --abbrev-ref HEAD", {
|
|
60
|
-
cwd,
|
|
61
|
-
encoding: "utf-8",
|
|
62
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
63
|
-
}).trim();
|
|
64
|
-
} catch {
|
|
65
|
-
return "unknown";
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
function listBranches(options) {
|
|
69
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
70
|
-
try {
|
|
71
|
-
const output = execSync(
|
|
72
|
-
"git branch -a --format='%(refname:short)' --sort=-committerdate",
|
|
73
|
-
{ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
|
|
74
|
-
).trim();
|
|
75
|
-
if (!output) return { local: [], remote: [] };
|
|
76
|
-
const local = [];
|
|
77
|
-
const remote = [];
|
|
78
|
-
for (const line of output.split("\n")) {
|
|
79
|
-
const name = line.trim();
|
|
80
|
-
if (!name) continue;
|
|
81
|
-
if (name.endsWith("/HEAD")) continue;
|
|
82
|
-
if (name.includes("/")) {
|
|
83
|
-
remote.push(name);
|
|
84
|
-
} else {
|
|
85
|
-
local.push(name);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return { local, remote };
|
|
89
|
-
} catch {
|
|
90
|
-
return { local: [], remote: [] };
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
function listCommits(options) {
|
|
94
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
95
|
-
const limit = options?.limit ?? 50;
|
|
96
|
-
try {
|
|
97
|
-
const output = execSync(
|
|
98
|
-
`git log --format='%H<<>>%h<<>>%s<<>>%an<<>>%aI' -n ${limit}`,
|
|
99
|
-
{ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
|
|
100
|
-
).trim();
|
|
101
|
-
if (!output) return [];
|
|
102
|
-
const commits = [];
|
|
103
|
-
for (const line of output.split("\n")) {
|
|
104
|
-
const parts = line.split("<<>>");
|
|
105
|
-
if (parts.length < 5) continue;
|
|
106
|
-
commits.push({
|
|
107
|
-
hash: parts[0],
|
|
108
|
-
shortHash: parts[1],
|
|
109
|
-
subject: parts[2],
|
|
110
|
-
author: parts[3],
|
|
111
|
-
date: parts[4]
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
return commits;
|
|
115
|
-
} catch {
|
|
116
|
-
return [];
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
function detectWorktree(options) {
|
|
120
|
-
const cwd = options?.cwd ?? process.cwd();
|
|
121
|
-
try {
|
|
122
|
-
const gitDir = execSync("git rev-parse --git-dir", {
|
|
123
|
-
cwd,
|
|
124
|
-
encoding: "utf-8",
|
|
125
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
126
|
-
}).trim();
|
|
127
|
-
const gitCommonDir = execSync("git rev-parse --git-common-dir", {
|
|
128
|
-
cwd,
|
|
129
|
-
encoding: "utf-8",
|
|
130
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
131
|
-
}).trim();
|
|
132
|
-
const resolvedGitDir = path.resolve(cwd, gitDir);
|
|
133
|
-
const resolvedCommonDir = path.resolve(cwd, gitCommonDir);
|
|
134
|
-
const isWorktree = resolvedGitDir !== resolvedCommonDir;
|
|
135
|
-
if (!isWorktree) {
|
|
136
|
-
return { isWorktree: false };
|
|
137
|
-
}
|
|
138
|
-
const worktreePath = execSync("git rev-parse --show-toplevel", {
|
|
139
|
-
cwd,
|
|
140
|
-
encoding: "utf-8",
|
|
141
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
142
|
-
}).trim();
|
|
143
|
-
const mainWorktreePath = path.dirname(resolvedCommonDir);
|
|
144
|
-
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
|
|
145
|
-
cwd,
|
|
146
|
-
encoding: "utf-8",
|
|
147
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
148
|
-
}).trim();
|
|
149
|
-
return {
|
|
150
|
-
isWorktree: true,
|
|
151
|
-
worktreePath,
|
|
152
|
-
mainWorktreePath,
|
|
153
|
-
branch: branch === "HEAD" ? void 0 : branch
|
|
154
|
-
};
|
|
155
|
-
} catch {
|
|
156
|
-
return { isWorktree: false };
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
function getUntrackedDiffs(cwd) {
|
|
160
|
-
let untrackedList;
|
|
161
|
-
try {
|
|
162
|
-
untrackedList = execSync(
|
|
163
|
-
"git ls-files --others --exclude-standard",
|
|
164
|
-
{ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
|
|
165
|
-
).trim();
|
|
166
|
-
} catch {
|
|
167
|
-
return "";
|
|
168
|
-
}
|
|
169
|
-
if (!untrackedList) return "";
|
|
170
|
-
const files = untrackedList.split("\n");
|
|
171
|
-
let result = "";
|
|
172
|
-
for (const file of files) {
|
|
173
|
-
const absPath = path.resolve(cwd, file);
|
|
174
|
-
let content;
|
|
175
|
-
try {
|
|
176
|
-
content = readFileSync(absPath, "utf-8");
|
|
177
|
-
} catch {
|
|
178
|
-
continue;
|
|
179
|
-
}
|
|
180
|
-
const lines = content.split("\n");
|
|
181
|
-
const hasTrailingNewline = content.length > 0 && content[content.length - 1] === "\n";
|
|
182
|
-
const contentLines = hasTrailingNewline ? lines.slice(0, -1) : lines;
|
|
183
|
-
result += `diff --git a/${file} b/${file}
|
|
184
|
-
`;
|
|
185
|
-
result += "new file mode 100644\n";
|
|
186
|
-
result += "--- /dev/null\n";
|
|
187
|
-
result += `+++ b/${file}
|
|
188
|
-
`;
|
|
189
|
-
result += `@@ -0,0 +1,${contentLines.length} @@
|
|
190
|
-
`;
|
|
191
|
-
for (const line of contentLines) {
|
|
192
|
-
result += `+${line}
|
|
193
|
-
`;
|
|
194
|
-
}
|
|
195
|
-
if (!hasTrailingNewline) {
|
|
196
|
-
result += "\\n";
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
return result;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// packages/git/src/parser.ts
|
|
203
|
-
import path2 from "path";
|
|
204
|
-
var EXTENSION_MAP = {
|
|
205
|
-
ts: "typescript",
|
|
206
|
-
tsx: "typescript",
|
|
207
|
-
js: "javascript",
|
|
208
|
-
jsx: "javascript",
|
|
209
|
-
py: "python",
|
|
210
|
-
rb: "ruby",
|
|
211
|
-
go: "go",
|
|
212
|
-
rs: "rust",
|
|
213
|
-
java: "java",
|
|
214
|
-
c: "c",
|
|
215
|
-
h: "c",
|
|
216
|
-
cpp: "cpp",
|
|
217
|
-
hpp: "cpp",
|
|
218
|
-
cc: "cpp",
|
|
219
|
-
cs: "csharp",
|
|
220
|
-
md: "markdown",
|
|
221
|
-
json: "json",
|
|
222
|
-
yaml: "yaml",
|
|
223
|
-
yml: "yaml",
|
|
224
|
-
html: "html",
|
|
225
|
-
css: "css",
|
|
226
|
-
scss: "scss",
|
|
227
|
-
sql: "sql",
|
|
228
|
-
sh: "shell",
|
|
229
|
-
bash: "shell",
|
|
230
|
-
zsh: "shell"
|
|
231
|
-
};
|
|
232
|
-
var FILENAME_MAP = {
|
|
233
|
-
Dockerfile: "dockerfile",
|
|
234
|
-
Makefile: "makefile"
|
|
235
|
-
};
|
|
236
|
-
function detectLanguage(filePath) {
|
|
237
|
-
const basename = path2.basename(filePath);
|
|
238
|
-
if (FILENAME_MAP[basename]) {
|
|
239
|
-
return FILENAME_MAP[basename];
|
|
240
|
-
}
|
|
241
|
-
const ext = basename.includes(".") ? basename.slice(basename.lastIndexOf(".") + 1) : "";
|
|
242
|
-
return EXTENSION_MAP[ext] ?? "text";
|
|
243
|
-
}
|
|
244
|
-
function stripPrefix(raw) {
|
|
245
|
-
if (raw === "/dev/null") return raw;
|
|
246
|
-
return raw.replace(/^[ab]\//, "");
|
|
247
|
-
}
|
|
248
|
-
function parseDiff(rawDiff, baseRef, headRef) {
|
|
249
|
-
if (!rawDiff.trim()) {
|
|
250
|
-
return { baseRef, headRef, files: [] };
|
|
251
|
-
}
|
|
252
|
-
const files = [];
|
|
253
|
-
const lines = rawDiff.split("\n");
|
|
254
|
-
let i = 0;
|
|
255
|
-
while (i < lines.length) {
|
|
256
|
-
if (!lines[i].startsWith("diff --git ")) {
|
|
257
|
-
i++;
|
|
258
|
-
continue;
|
|
259
|
-
}
|
|
260
|
-
let oldPath;
|
|
261
|
-
let newPath;
|
|
262
|
-
let status = "modified";
|
|
263
|
-
let binary = false;
|
|
264
|
-
let renameFrom;
|
|
265
|
-
let renameTo;
|
|
266
|
-
const diffLine = lines[i];
|
|
267
|
-
const gitPathMatch = diffLine.match(/^diff --git a\/(.*) b\/(.*)$/);
|
|
268
|
-
if (gitPathMatch) {
|
|
269
|
-
oldPath = gitPathMatch[1];
|
|
270
|
-
newPath = gitPathMatch[2];
|
|
271
|
-
}
|
|
272
|
-
i++;
|
|
273
|
-
while (i < lines.length && !lines[i].startsWith("diff --git ")) {
|
|
274
|
-
const line = lines[i];
|
|
275
|
-
if (line.startsWith("--- ")) {
|
|
276
|
-
const raw = line.slice(4);
|
|
277
|
-
oldPath = stripPrefix(raw);
|
|
278
|
-
if (raw === "/dev/null") {
|
|
279
|
-
status = "added";
|
|
280
|
-
}
|
|
281
|
-
} else if (line.startsWith("+++ ")) {
|
|
282
|
-
const raw = line.slice(4);
|
|
283
|
-
newPath = stripPrefix(raw);
|
|
284
|
-
if (raw === "/dev/null") {
|
|
285
|
-
status = "deleted";
|
|
286
|
-
}
|
|
287
|
-
} else if (line.startsWith("rename from ")) {
|
|
288
|
-
renameFrom = line.slice("rename from ".length);
|
|
289
|
-
status = "renamed";
|
|
290
|
-
} else if (line.startsWith("rename to ")) {
|
|
291
|
-
renameTo = line.slice("rename to ".length);
|
|
292
|
-
status = "renamed";
|
|
293
|
-
} else if (line.startsWith("new file mode")) {
|
|
294
|
-
status = "added";
|
|
295
|
-
} else if (line.startsWith("deleted file mode")) {
|
|
296
|
-
status = "deleted";
|
|
297
|
-
} else if (line.startsWith("Binary files") || line === "GIT binary patch") {
|
|
298
|
-
binary = true;
|
|
299
|
-
if (line.includes("/dev/null") && line.includes(" and b/")) {
|
|
300
|
-
status = "added";
|
|
301
|
-
} else if (line.includes("a/") && line.includes("/dev/null")) {
|
|
302
|
-
status = "deleted";
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
if (line.startsWith("@@ ")) {
|
|
306
|
-
break;
|
|
307
|
-
}
|
|
308
|
-
i++;
|
|
309
|
-
}
|
|
310
|
-
const filePath = status === "deleted" ? oldPath ?? newPath ?? "unknown" : newPath ?? oldPath ?? "unknown";
|
|
311
|
-
const fileOldPath = status === "renamed" ? renameFrom ?? oldPath : oldPath;
|
|
312
|
-
const hunks = [];
|
|
313
|
-
let additions = 0;
|
|
314
|
-
let deletions = 0;
|
|
315
|
-
while (i < lines.length && !lines[i].startsWith("diff --git ")) {
|
|
316
|
-
const line = lines[i];
|
|
317
|
-
if (line.startsWith("@@ ")) {
|
|
318
|
-
const hunkMatch = line.match(
|
|
319
|
-
/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/
|
|
320
|
-
);
|
|
321
|
-
if (!hunkMatch) {
|
|
322
|
-
i++;
|
|
323
|
-
continue;
|
|
324
|
-
}
|
|
325
|
-
const oldStart = parseInt(hunkMatch[1], 10);
|
|
326
|
-
const oldLines = hunkMatch[2] !== void 0 ? parseInt(hunkMatch[2], 10) : 1;
|
|
327
|
-
const newStart = parseInt(hunkMatch[3], 10);
|
|
328
|
-
const newLines = hunkMatch[4] !== void 0 ? parseInt(hunkMatch[4], 10) : 1;
|
|
329
|
-
const changes = [];
|
|
330
|
-
let oldLineNum = oldStart;
|
|
331
|
-
let newLineNum = newStart;
|
|
332
|
-
i++;
|
|
333
|
-
while (i < lines.length) {
|
|
334
|
-
const changeLine = lines[i];
|
|
335
|
-
if (changeLine.startsWith("@@ ") || changeLine.startsWith("diff --git ")) {
|
|
336
|
-
break;
|
|
337
|
-
}
|
|
338
|
-
if (changeLine.startsWith("\")) {
|
|
339
|
-
i++;
|
|
340
|
-
continue;
|
|
341
|
-
}
|
|
342
|
-
if (changeLine.startsWith("+")) {
|
|
343
|
-
changes.push({
|
|
344
|
-
type: "add",
|
|
345
|
-
lineNumber: newLineNum,
|
|
346
|
-
content: changeLine.slice(1)
|
|
347
|
-
});
|
|
348
|
-
newLineNum++;
|
|
349
|
-
additions++;
|
|
350
|
-
} else if (changeLine.startsWith("-")) {
|
|
351
|
-
changes.push({
|
|
352
|
-
type: "delete",
|
|
353
|
-
lineNumber: oldLineNum,
|
|
354
|
-
content: changeLine.slice(1)
|
|
355
|
-
});
|
|
356
|
-
oldLineNum++;
|
|
357
|
-
deletions++;
|
|
358
|
-
} else {
|
|
359
|
-
changes.push({
|
|
360
|
-
type: "context",
|
|
361
|
-
lineNumber: newLineNum,
|
|
362
|
-
content: changeLine.length > 0 ? changeLine.slice(1) : ""
|
|
363
|
-
});
|
|
364
|
-
oldLineNum++;
|
|
365
|
-
newLineNum++;
|
|
366
|
-
}
|
|
367
|
-
i++;
|
|
368
|
-
}
|
|
369
|
-
hunks.push({ oldStart, oldLines, newStart, newLines, changes });
|
|
370
|
-
} else {
|
|
371
|
-
i++;
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
const diffFile = {
|
|
375
|
-
path: filePath,
|
|
376
|
-
status,
|
|
377
|
-
hunks,
|
|
378
|
-
language: detectLanguage(filePath),
|
|
379
|
-
binary,
|
|
380
|
-
additions,
|
|
381
|
-
deletions
|
|
382
|
-
};
|
|
383
|
-
if (status === "renamed" && fileOldPath) {
|
|
384
|
-
diffFile.oldPath = fileOldPath;
|
|
385
|
-
}
|
|
386
|
-
files.push(diffFile);
|
|
387
|
-
}
|
|
388
|
-
return { baseRef, headRef, files };
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// packages/git/src/index.ts
|
|
392
|
-
function getDiff(ref, options) {
|
|
393
|
-
if (ref === "working-copy") {
|
|
394
|
-
return getWorkingCopyDiff(options);
|
|
395
|
-
}
|
|
396
|
-
const rawDiff = getGitDiff(ref, options);
|
|
397
|
-
let baseRef;
|
|
398
|
-
let headRef;
|
|
399
|
-
if (ref === "staged") {
|
|
400
|
-
baseRef = "HEAD";
|
|
401
|
-
headRef = "staged";
|
|
402
|
-
} else if (ref === "unstaged") {
|
|
403
|
-
baseRef = "staged";
|
|
404
|
-
headRef = "working tree";
|
|
405
|
-
} else if (ref.includes("..")) {
|
|
406
|
-
const [base, head] = ref.split("..");
|
|
407
|
-
baseRef = base;
|
|
408
|
-
headRef = head;
|
|
409
|
-
} else {
|
|
410
|
-
baseRef = ref;
|
|
411
|
-
headRef = "HEAD";
|
|
412
|
-
}
|
|
413
|
-
const diffSet = parseDiff(rawDiff, baseRef, headRef);
|
|
414
|
-
return { diffSet, rawDiff };
|
|
415
|
-
}
|
|
416
|
-
function getWorkingCopyDiff(options) {
|
|
417
|
-
const stagedRaw = getGitDiff("staged", options);
|
|
418
|
-
const unstagedRaw = getGitDiff("unstaged", options);
|
|
419
|
-
const stagedDiffSet = parseDiff(stagedRaw, "HEAD", "staged");
|
|
420
|
-
const unstagedDiffSet = parseDiff(unstagedRaw, "staged", "working tree");
|
|
421
|
-
const stagedFiles = stagedDiffSet.files.map((f) => ({
|
|
422
|
-
...f,
|
|
423
|
-
stage: "staged"
|
|
424
|
-
}));
|
|
425
|
-
const unstagedFiles = unstagedDiffSet.files.map((f) => ({
|
|
426
|
-
...f,
|
|
427
|
-
stage: "unstaged"
|
|
428
|
-
}));
|
|
429
|
-
const rawDiff = [stagedRaw, unstagedRaw].filter(Boolean).join("");
|
|
430
|
-
return {
|
|
431
|
-
diffSet: {
|
|
432
|
-
baseRef: "HEAD",
|
|
433
|
-
headRef: "working tree",
|
|
434
|
-
files: [...stagedFiles, ...unstagedFiles]
|
|
435
|
-
},
|
|
436
|
-
rawDiff
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
// packages/analysis/src/deterministic.ts
|
|
441
|
-
var MECHANICAL_CONFIG_PATTERNS = [
|
|
442
|
-
/\.config\./,
|
|
443
|
-
/\.eslintrc/,
|
|
444
|
-
/\.prettierrc/,
|
|
445
|
-
/tsconfig.*\.json$/,
|
|
446
|
-
/\.gitignore$/,
|
|
447
|
-
/\.lock$/
|
|
448
|
-
];
|
|
449
|
-
var API_SURFACE_PATTERNS = [
|
|
450
|
-
/\/api\//,
|
|
451
|
-
/\/routes\//
|
|
452
|
-
];
|
|
453
|
-
function isFormattingOnly(file) {
|
|
454
|
-
if (file.hunks.length === 0) return false;
|
|
455
|
-
for (const hunk of file.hunks) {
|
|
456
|
-
const adds = hunk.changes.filter((c) => c.type === "add").map((c) => c.content.replace(/\s/g, ""));
|
|
457
|
-
const deletes = hunk.changes.filter((c) => c.type === "delete").map((c) => c.content.replace(/\s/g, ""));
|
|
458
|
-
if (adds.length === 0 || deletes.length === 0) return false;
|
|
459
|
-
const deleteBag = [...deletes];
|
|
460
|
-
for (const add of adds) {
|
|
461
|
-
const idx = deleteBag.indexOf(add);
|
|
462
|
-
if (idx === -1) return false;
|
|
463
|
-
deleteBag.splice(idx, 1);
|
|
464
|
-
}
|
|
465
|
-
if (deleteBag.length > 0) return false;
|
|
466
|
-
}
|
|
467
|
-
return true;
|
|
468
|
-
}
|
|
469
|
-
function isImportOnly(file) {
|
|
470
|
-
if (file.hunks.length === 0) return false;
|
|
471
|
-
const importPattern = /^\s*(import\s|export\s.*from\s|const\s+\w+\s*=\s*require\(|require\()/;
|
|
472
|
-
for (const hunk of file.hunks) {
|
|
473
|
-
for (const change of hunk.changes) {
|
|
474
|
-
if (change.type === "context") continue;
|
|
475
|
-
const trimmed = change.content.trim();
|
|
476
|
-
if (trimmed === "") continue;
|
|
477
|
-
if (!importPattern.test(trimmed)) return false;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return true;
|
|
481
|
-
}
|
|
482
|
-
function isMechanicalConfigFile(path7) {
|
|
483
|
-
return MECHANICAL_CONFIG_PATTERNS.some((re) => re.test(path7));
|
|
484
|
-
}
|
|
485
|
-
function isApiSurface(file) {
|
|
486
|
-
if (API_SURFACE_PATTERNS.some((re) => re.test(file.path))) return true;
|
|
487
|
-
const basename = file.path.slice(file.path.lastIndexOf("/") + 1);
|
|
488
|
-
if ((basename === "index.ts" || basename === "index.js") && file.additions >= 10) {
|
|
489
|
-
return true;
|
|
490
|
-
}
|
|
491
|
-
return false;
|
|
492
|
-
}
|
|
493
|
-
function categorizeFiles(files) {
|
|
494
|
-
const critical = [];
|
|
495
|
-
const notable = [];
|
|
496
|
-
const mechanical = [];
|
|
497
|
-
const securityFlags = detectSecurityPatterns(files);
|
|
498
|
-
const complexityScores = computeComplexityScores(files);
|
|
499
|
-
const securityByFile = /* @__PURE__ */ new Map();
|
|
500
|
-
for (const flag of securityFlags) {
|
|
501
|
-
const existing = securityByFile.get(flag.file) || [];
|
|
502
|
-
existing.push(flag);
|
|
503
|
-
securityByFile.set(flag.file, existing);
|
|
504
|
-
}
|
|
505
|
-
const complexityByFile = /* @__PURE__ */ new Map();
|
|
506
|
-
for (const score of complexityScores) {
|
|
507
|
-
complexityByFile.set(score.path, score);
|
|
508
|
-
}
|
|
509
|
-
for (const file of files) {
|
|
510
|
-
const description = `${file.status} (${file.language || "unknown"}) +${file.additions} -${file.deletions}`;
|
|
511
|
-
const fileSecurityFlags = securityByFile.get(file.path);
|
|
512
|
-
const fileComplexity = complexityByFile.get(file.path);
|
|
513
|
-
const criticalReasons = [];
|
|
514
|
-
if (fileSecurityFlags && fileSecurityFlags.length > 0) {
|
|
515
|
-
const patterns = fileSecurityFlags.map((f) => f.pattern);
|
|
516
|
-
const unique = [...new Set(patterns)];
|
|
517
|
-
criticalReasons.push(`security patterns detected: ${unique.join(", ")}`);
|
|
518
|
-
}
|
|
519
|
-
if (fileComplexity && fileComplexity.score >= 8) {
|
|
520
|
-
criticalReasons.push(`high complexity score (${fileComplexity.score}/10)`);
|
|
521
|
-
}
|
|
522
|
-
if (isApiSurface(file)) {
|
|
523
|
-
criticalReasons.push("modifies public API surface");
|
|
524
|
-
}
|
|
525
|
-
if (criticalReasons.length > 0) {
|
|
526
|
-
critical.push({
|
|
527
|
-
file: file.path,
|
|
528
|
-
description,
|
|
529
|
-
reason: `Critical: ${criticalReasons.join("; ")}`
|
|
530
|
-
});
|
|
531
|
-
continue;
|
|
532
|
-
}
|
|
533
|
-
const isPureRename = file.status === "renamed" && file.additions === 0 && file.deletions === 0;
|
|
534
|
-
if (isPureRename) {
|
|
535
|
-
mechanical.push({
|
|
536
|
-
file: file.path,
|
|
537
|
-
description,
|
|
538
|
-
reason: "Mechanical: pure rename with no content changes"
|
|
539
|
-
});
|
|
540
|
-
continue;
|
|
541
|
-
}
|
|
542
|
-
if (isFormattingOnly(file)) {
|
|
543
|
-
mechanical.push({
|
|
544
|
-
file: file.path,
|
|
545
|
-
description,
|
|
546
|
-
reason: "Mechanical: formatting/whitespace-only changes"
|
|
547
|
-
});
|
|
548
|
-
continue;
|
|
549
|
-
}
|
|
550
|
-
if (isMechanicalConfigFile(file.path)) {
|
|
551
|
-
mechanical.push({
|
|
552
|
-
file: file.path,
|
|
553
|
-
description,
|
|
554
|
-
reason: "Mechanical: config file change"
|
|
555
|
-
});
|
|
556
|
-
continue;
|
|
557
|
-
}
|
|
558
|
-
if (file.hunks.length > 0 && isImportOnly(file)) {
|
|
559
|
-
mechanical.push({
|
|
560
|
-
file: file.path,
|
|
561
|
-
description,
|
|
562
|
-
reason: "Mechanical: import/require-only changes"
|
|
563
|
-
});
|
|
564
|
-
continue;
|
|
565
|
-
}
|
|
566
|
-
notable.push({
|
|
567
|
-
file: file.path,
|
|
568
|
-
description,
|
|
569
|
-
reason: "Notable: requires review"
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
return { critical, notable, mechanical };
|
|
573
|
-
}
|
|
574
|
-
function computeFileStats(files) {
|
|
575
|
-
return files.map((f) => ({
|
|
576
|
-
path: f.path,
|
|
577
|
-
language: f.language,
|
|
578
|
-
status: f.status,
|
|
579
|
-
additions: f.additions,
|
|
580
|
-
deletions: f.deletions
|
|
581
|
-
}));
|
|
582
|
-
}
|
|
583
|
-
function detectAffectedModules(files) {
|
|
584
|
-
const dirs = /* @__PURE__ */ new Set();
|
|
585
|
-
for (const f of files) {
|
|
586
|
-
const lastSlash = f.path.lastIndexOf("/");
|
|
587
|
-
if (lastSlash > 0) {
|
|
588
|
-
dirs.add(f.path.slice(0, lastSlash));
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
return [...dirs].sort();
|
|
592
|
-
}
|
|
593
|
-
var TEST_PATTERNS = [
|
|
594
|
-
/\.test\./,
|
|
595
|
-
/\.spec\./,
|
|
596
|
-
/\/__tests__\//,
|
|
597
|
-
/\/test\//
|
|
598
|
-
];
|
|
599
|
-
function detectAffectedTests(files) {
|
|
600
|
-
return files.filter((f) => TEST_PATTERNS.some((re) => re.test(f.path))).map((f) => f.path);
|
|
601
|
-
}
|
|
602
|
-
var DEPENDENCY_FIELDS = [
|
|
603
|
-
'"dependencies"',
|
|
604
|
-
'"devDependencies"',
|
|
605
|
-
'"peerDependencies"',
|
|
606
|
-
'"optionalDependencies"'
|
|
607
|
-
];
|
|
608
|
-
function detectNewDependencies(files) {
|
|
609
|
-
const deps = /* @__PURE__ */ new Set();
|
|
610
|
-
const packageFiles = files.filter(
|
|
611
|
-
(f) => f.path.endsWith("package.json") && f.hunks.length > 0
|
|
612
|
-
);
|
|
613
|
-
for (const file of packageFiles) {
|
|
614
|
-
for (const hunk of file.hunks) {
|
|
615
|
-
let inDependencyBlock = false;
|
|
616
|
-
for (const change of hunk.changes) {
|
|
617
|
-
const line = change.content;
|
|
618
|
-
if (DEPENDENCY_FIELDS.some((field) => line.includes(field))) {
|
|
619
|
-
inDependencyBlock = true;
|
|
620
|
-
continue;
|
|
621
|
-
}
|
|
622
|
-
if (inDependencyBlock && line.trim().startsWith("}")) {
|
|
623
|
-
inDependencyBlock = false;
|
|
624
|
-
continue;
|
|
625
|
-
}
|
|
626
|
-
if (change.type === "add" && inDependencyBlock) {
|
|
627
|
-
const match = line.match(/"([^"]+)"\s*:/);
|
|
628
|
-
if (match) {
|
|
629
|
-
deps.add(match[1]);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
return [...deps].sort();
|
|
636
|
-
}
|
|
637
|
-
function generateSummary(files) {
|
|
638
|
-
const totalFiles = files.length;
|
|
639
|
-
const counts = {
|
|
640
|
-
added: 0,
|
|
641
|
-
modified: 0,
|
|
642
|
-
deleted: 0,
|
|
643
|
-
renamed: 0
|
|
644
|
-
};
|
|
645
|
-
let totalAdditions = 0;
|
|
646
|
-
let totalDeletions = 0;
|
|
647
|
-
for (const f of files) {
|
|
648
|
-
counts[f.status]++;
|
|
649
|
-
totalAdditions += f.additions;
|
|
650
|
-
totalDeletions += f.deletions;
|
|
651
|
-
}
|
|
652
|
-
const parts = [];
|
|
653
|
-
if (counts.modified > 0) parts.push(`${counts.modified} modified`);
|
|
654
|
-
if (counts.added > 0) parts.push(`${counts.added} added`);
|
|
655
|
-
if (counts.deleted > 0) parts.push(`${counts.deleted} deleted`);
|
|
656
|
-
if (counts.renamed > 0) parts.push(`${counts.renamed} renamed`);
|
|
657
|
-
const breakdown = parts.length > 0 ? `: ${parts.join(", ")}` : "";
|
|
658
|
-
return `${totalFiles} files changed${breakdown} (+${totalAdditions} -${totalDeletions})`;
|
|
659
|
-
}
|
|
660
|
-
var BRANCH_PATTERN = /\b(if|else|switch|case|catch)\b|\?\s|&&|\|\|/;
|
|
661
|
-
function computeComplexityScores(files) {
|
|
662
|
-
const results = [];
|
|
663
|
-
for (const file of files) {
|
|
664
|
-
let score = 0;
|
|
665
|
-
const factors = [];
|
|
666
|
-
const totalChanges = file.additions + file.deletions;
|
|
667
|
-
if (totalChanges > 100) {
|
|
668
|
-
score += 3;
|
|
669
|
-
factors.push(`large diff (+${file.additions} -${file.deletions})`);
|
|
670
|
-
} else if (totalChanges > 50) {
|
|
671
|
-
score += 2;
|
|
672
|
-
factors.push(`medium diff (+${file.additions} -${file.deletions})`);
|
|
673
|
-
} else if (totalChanges > 20) {
|
|
674
|
-
score += 1;
|
|
675
|
-
factors.push(`moderate diff (+${file.additions} -${file.deletions})`);
|
|
676
|
-
}
|
|
677
|
-
const hunkCount = file.hunks.length;
|
|
678
|
-
if (hunkCount > 4) {
|
|
679
|
-
score += 2;
|
|
680
|
-
factors.push(`many hunks (${hunkCount})`);
|
|
681
|
-
} else if (hunkCount > 2) {
|
|
682
|
-
score += 1;
|
|
683
|
-
factors.push(`multiple hunks (${hunkCount})`);
|
|
684
|
-
}
|
|
685
|
-
let branchCount = 0;
|
|
686
|
-
let deepNestCount = 0;
|
|
687
|
-
for (const hunk of file.hunks) {
|
|
688
|
-
for (const change of hunk.changes) {
|
|
689
|
-
if (change.type !== "add") continue;
|
|
690
|
-
const line = change.content;
|
|
691
|
-
if (BRANCH_PATTERN.test(line)) {
|
|
692
|
-
branchCount++;
|
|
693
|
-
}
|
|
694
|
-
const leadingSpaces = line.match(/^(\s*)/);
|
|
695
|
-
if (leadingSpaces) {
|
|
696
|
-
const ws = leadingSpaces[1];
|
|
697
|
-
const tabCount = (ws.match(/\t/g) || []).length;
|
|
698
|
-
const spaceCount = ws.replace(/\t/g, "").length;
|
|
699
|
-
if (tabCount >= 4 || spaceCount >= 16) {
|
|
700
|
-
deepNestCount++;
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
const branchScore = Math.floor(branchCount / 5);
|
|
706
|
-
if (branchScore > 0) {
|
|
707
|
-
score += branchScore;
|
|
708
|
-
factors.push(`${branchCount} logic branches`);
|
|
709
|
-
}
|
|
710
|
-
const nestScore = Math.floor(deepNestCount / 5);
|
|
711
|
-
if (nestScore > 0) {
|
|
712
|
-
score += nestScore;
|
|
713
|
-
factors.push(`${deepNestCount} deeply nested lines`);
|
|
714
|
-
}
|
|
715
|
-
score = Math.max(1, Math.min(10, score));
|
|
716
|
-
results.push({ path: file.path, score, factors });
|
|
717
|
-
}
|
|
718
|
-
results.sort((a, b) => b.score - a.score);
|
|
719
|
-
return results;
|
|
720
|
-
}
|
|
721
|
-
var NON_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
722
|
-
".json",
|
|
723
|
-
".md",
|
|
724
|
-
".css",
|
|
725
|
-
".scss",
|
|
726
|
-
".less",
|
|
727
|
-
".svg",
|
|
728
|
-
".png",
|
|
729
|
-
".jpg",
|
|
730
|
-
".gif",
|
|
731
|
-
".ico",
|
|
732
|
-
".yaml",
|
|
733
|
-
".yml",
|
|
734
|
-
".toml",
|
|
735
|
-
".lock",
|
|
736
|
-
".html"
|
|
737
|
-
]);
|
|
738
|
-
var CONFIG_PATTERNS = [
|
|
739
|
-
/\.config\./,
|
|
740
|
-
/\.rc\./,
|
|
741
|
-
/eslint/,
|
|
742
|
-
/prettier/,
|
|
743
|
-
/tsconfig/,
|
|
744
|
-
/tailwind/,
|
|
745
|
-
/vite\.config/,
|
|
746
|
-
/vitest\.config/
|
|
747
|
-
];
|
|
748
|
-
function isTestFile(path7) {
|
|
749
|
-
return TEST_PATTERNS.some((re) => re.test(path7));
|
|
750
|
-
}
|
|
751
|
-
function isNonCodeFile(path7) {
|
|
752
|
-
const ext = path7.slice(path7.lastIndexOf("."));
|
|
753
|
-
return NON_CODE_EXTENSIONS.has(ext);
|
|
754
|
-
}
|
|
755
|
-
function isConfigFile(path7) {
|
|
756
|
-
return CONFIG_PATTERNS.some((re) => re.test(path7));
|
|
757
|
-
}
|
|
758
|
-
function detectTestCoverageGaps(files) {
|
|
759
|
-
const filePaths = new Set(files.map((f) => f.path));
|
|
760
|
-
const results = [];
|
|
761
|
-
for (const file of files) {
|
|
762
|
-
if (file.status !== "added" && file.status !== "modified") continue;
|
|
763
|
-
if (isTestFile(file.path)) continue;
|
|
764
|
-
if (isNonCodeFile(file.path)) continue;
|
|
765
|
-
if (isConfigFile(file.path)) continue;
|
|
766
|
-
const dir = file.path.slice(0, file.path.lastIndexOf("/") + 1);
|
|
767
|
-
const basename = file.path.slice(file.path.lastIndexOf("/") + 1);
|
|
768
|
-
const extDot = basename.lastIndexOf(".");
|
|
769
|
-
const name = extDot > 0 ? basename.slice(0, extDot) : basename;
|
|
770
|
-
const ext = extDot > 0 ? basename.slice(extDot) : "";
|
|
771
|
-
const candidates = [
|
|
772
|
-
`${dir}${name}.test${ext}`,
|
|
773
|
-
`${dir}${name}.spec${ext}`,
|
|
774
|
-
`${dir}__tests__/${name}${ext}`,
|
|
775
|
-
`${dir}__tests__/${name}.test${ext}`,
|
|
776
|
-
`${dir}__tests__/${name}.spec${ext}`
|
|
777
|
-
];
|
|
778
|
-
const matchedTest = candidates.find((c) => filePaths.has(c));
|
|
779
|
-
results.push({
|
|
780
|
-
sourceFile: file.path,
|
|
781
|
-
testFile: matchedTest ?? null
|
|
782
|
-
});
|
|
783
|
-
}
|
|
784
|
-
return results;
|
|
785
|
-
}
|
|
786
|
-
var PATTERN_MATCHERS = [
|
|
787
|
-
{ pattern: "todo", test: (l) => /\btodo\b/i.test(l) },
|
|
788
|
-
{ pattern: "fixme", test: (l) => /\bfixme\b/i.test(l) },
|
|
789
|
-
{ pattern: "hack", test: (l) => /\bhack\b/i.test(l) },
|
|
790
|
-
{
|
|
791
|
-
pattern: "console",
|
|
792
|
-
test: (l) => /\bconsole\.(log|debug|warn|error)\b/.test(l)
|
|
793
|
-
},
|
|
794
|
-
{ pattern: "debug", test: (l) => /\bdebugger\b/.test(l) },
|
|
795
|
-
{
|
|
796
|
-
pattern: "disabled_test",
|
|
797
|
-
test: (l) => /\.(skip)\(|(\bxit|xdescribe|xtest)\(/.test(l)
|
|
798
|
-
}
|
|
799
|
-
];
|
|
800
|
-
function detectPatterns(files) {
|
|
801
|
-
const results = [];
|
|
802
|
-
for (const file of files) {
|
|
803
|
-
if (file.status === "added" && file.additions > 500) {
|
|
804
|
-
results.push({
|
|
805
|
-
file: file.path,
|
|
806
|
-
line: 0,
|
|
807
|
-
pattern: "large_file",
|
|
808
|
-
content: `Large added file: ${file.additions} lines`
|
|
809
|
-
});
|
|
810
|
-
}
|
|
811
|
-
for (const hunk of file.hunks) {
|
|
812
|
-
for (const change of hunk.changes) {
|
|
813
|
-
if (change.type !== "add") continue;
|
|
814
|
-
for (const matcher of PATTERN_MATCHERS) {
|
|
815
|
-
if (matcher.test(change.content)) {
|
|
816
|
-
results.push({
|
|
817
|
-
file: file.path,
|
|
818
|
-
line: change.lineNumber,
|
|
819
|
-
pattern: matcher.pattern,
|
|
820
|
-
content: change.content.trim()
|
|
821
|
-
});
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
results.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
|
|
828
|
-
return results;
|
|
829
|
-
}
|
|
830
|
-
var SECURITY_MATCHERS = [
|
|
831
|
-
{
|
|
832
|
-
pattern: "eval",
|
|
833
|
-
severity: "critical",
|
|
834
|
-
test: (l) => /\beval\s*\(/.test(l)
|
|
835
|
-
},
|
|
836
|
-
{
|
|
837
|
-
pattern: "inner_html",
|
|
838
|
-
severity: "warning",
|
|
839
|
-
test: (l) => /\.innerHTML\b|dangerouslySetInnerHTML/.test(l)
|
|
840
|
-
},
|
|
841
|
-
{
|
|
842
|
-
pattern: "sql_injection",
|
|
843
|
-
severity: "critical",
|
|
844
|
-
test: (l) => /`[^`]*\b(SELECT|INSERT|UPDATE|DELETE)\b/i.test(l) || /\b(SELECT|INSERT|UPDATE|DELETE)\b[^`]*\$\{/i.test(l)
|
|
845
|
-
},
|
|
846
|
-
{
|
|
847
|
-
pattern: "exec",
|
|
848
|
-
severity: "critical",
|
|
849
|
-
test: (l) => /child_process/.test(l) || /\bexec\s*\(/.test(l) || /\bexecSync\s*\(/.test(l)
|
|
850
|
-
},
|
|
851
|
-
{
|
|
852
|
-
pattern: "hardcoded_secret",
|
|
853
|
-
severity: "critical",
|
|
854
|
-
test: (l) => /\b(token|secret|api_key|apikey|password|passwd|credential)\s*=\s*["']/i.test(l)
|
|
855
|
-
},
|
|
856
|
-
{
|
|
857
|
-
pattern: "insecure_url",
|
|
858
|
-
severity: "warning",
|
|
859
|
-
test: (l) => /http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0)/.test(l)
|
|
860
|
-
}
|
|
861
|
-
];
|
|
862
|
-
function detectSecurityPatterns(files) {
|
|
863
|
-
const results = [];
|
|
864
|
-
for (const file of files) {
|
|
865
|
-
for (const hunk of file.hunks) {
|
|
866
|
-
for (const change of hunk.changes) {
|
|
867
|
-
if (change.type !== "add") continue;
|
|
868
|
-
for (const matcher of SECURITY_MATCHERS) {
|
|
869
|
-
if (matcher.test(change.content)) {
|
|
870
|
-
results.push({
|
|
871
|
-
file: file.path,
|
|
872
|
-
line: change.lineNumber,
|
|
873
|
-
pattern: matcher.pattern,
|
|
874
|
-
content: change.content.trim(),
|
|
875
|
-
severity: matcher.severity
|
|
876
|
-
});
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
results.sort((a, b) => {
|
|
883
|
-
const severityOrder = { critical: 0, warning: 1 };
|
|
884
|
-
const aSev = severityOrder[a.severity];
|
|
885
|
-
const bSev = severityOrder[b.severity];
|
|
886
|
-
if (aSev !== bSev) return aSev - bSev;
|
|
887
|
-
return a.file.localeCompare(b.file) || a.line - b.line;
|
|
888
|
-
});
|
|
889
|
-
return results;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
// packages/analysis/src/index.ts
|
|
893
|
-
function analyze(diffSet) {
|
|
894
|
-
const { files } = diffSet;
|
|
895
|
-
const triage = categorizeFiles(files);
|
|
896
|
-
const fileStats = computeFileStats(files);
|
|
897
|
-
const affectedModules = detectAffectedModules(files);
|
|
898
|
-
const affectedTests = detectAffectedTests(files);
|
|
899
|
-
const newDependencies = detectNewDependencies(files);
|
|
900
|
-
const summary = generateSummary(files);
|
|
901
|
-
const complexity = computeComplexityScores(files);
|
|
902
|
-
const testCoverage = detectTestCoverageGaps(files);
|
|
903
|
-
const codePatterns = detectPatterns(files);
|
|
904
|
-
const securityPatterns = detectSecurityPatterns(files);
|
|
905
|
-
const patterns = [...securityPatterns, ...codePatterns];
|
|
906
|
-
return {
|
|
907
|
-
summary,
|
|
908
|
-
triage,
|
|
909
|
-
impact: {
|
|
910
|
-
affectedModules,
|
|
911
|
-
affectedTests,
|
|
912
|
-
publicApiChanges: false,
|
|
913
|
-
breakingChanges: [],
|
|
914
|
-
newDependencies
|
|
915
|
-
},
|
|
916
|
-
verification: {
|
|
917
|
-
testsPass: null,
|
|
918
|
-
typeCheck: null,
|
|
919
|
-
lintClean: null
|
|
920
|
-
},
|
|
921
|
-
fileStats,
|
|
922
|
-
complexity,
|
|
923
|
-
testCoverage,
|
|
924
|
-
patterns
|
|
925
|
-
};
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// packages/core/src/watch-file.ts
|
|
929
|
-
import fs from "fs";
|
|
930
|
-
import path3 from "path";
|
|
931
|
-
import { execSync as execSync2 } from "child_process";
|
|
932
|
-
function findGitRoot(cwd) {
|
|
933
|
-
const root = execSync2("git rev-parse --show-toplevel", {
|
|
934
|
-
cwd: cwd ?? process.cwd(),
|
|
935
|
-
encoding: "utf-8"
|
|
936
|
-
}).trim();
|
|
937
|
-
return root;
|
|
938
|
-
}
|
|
939
|
-
function watchFilePath(cwd) {
|
|
940
|
-
const gitRoot = findGitRoot(cwd);
|
|
941
|
-
return path3.join(gitRoot, ".diffprism", "watch.json");
|
|
942
|
-
}
|
|
943
|
-
function isPidAlive(pid) {
|
|
944
|
-
try {
|
|
945
|
-
process.kill(pid, 0);
|
|
946
|
-
return true;
|
|
947
|
-
} catch {
|
|
948
|
-
return false;
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
function writeWatchFile(cwd, info) {
|
|
952
|
-
const filePath = watchFilePath(cwd);
|
|
953
|
-
const dir = path3.dirname(filePath);
|
|
954
|
-
if (!fs.existsSync(dir)) {
|
|
955
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
956
|
-
}
|
|
957
|
-
fs.writeFileSync(filePath, JSON.stringify(info, null, 2) + "\n");
|
|
958
|
-
}
|
|
959
|
-
function readWatchFile(cwd) {
|
|
960
|
-
const filePath = watchFilePath(cwd);
|
|
961
|
-
if (!fs.existsSync(filePath)) {
|
|
962
|
-
return null;
|
|
963
|
-
}
|
|
964
|
-
try {
|
|
965
|
-
const raw = fs.readFileSync(filePath, "utf-8");
|
|
966
|
-
const info = JSON.parse(raw);
|
|
967
|
-
if (!isPidAlive(info.pid)) {
|
|
968
|
-
fs.unlinkSync(filePath);
|
|
969
|
-
return null;
|
|
970
|
-
}
|
|
971
|
-
return info;
|
|
972
|
-
} catch {
|
|
973
|
-
return null;
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
function removeWatchFile(cwd) {
|
|
977
|
-
try {
|
|
978
|
-
const filePath = watchFilePath(cwd);
|
|
979
|
-
if (fs.existsSync(filePath)) {
|
|
980
|
-
fs.unlinkSync(filePath);
|
|
981
|
-
}
|
|
982
|
-
} catch {
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
function reviewResultPath(cwd) {
|
|
986
|
-
const gitRoot = findGitRoot(cwd);
|
|
987
|
-
return path3.join(gitRoot, ".diffprism", "last-review.json");
|
|
988
|
-
}
|
|
989
|
-
function writeReviewResult(cwd, result) {
|
|
990
|
-
const filePath = reviewResultPath(cwd);
|
|
991
|
-
const dir = path3.dirname(filePath);
|
|
992
|
-
if (!fs.existsSync(dir)) {
|
|
993
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
994
|
-
}
|
|
995
|
-
const data = {
|
|
996
|
-
result,
|
|
997
|
-
timestamp: Date.now(),
|
|
998
|
-
consumed: false
|
|
999
|
-
};
|
|
1000
|
-
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
|
|
1001
|
-
}
|
|
1002
|
-
function readReviewResult(cwd) {
|
|
1003
|
-
try {
|
|
1004
|
-
const filePath = reviewResultPath(cwd);
|
|
1005
|
-
if (!fs.existsSync(filePath)) {
|
|
1006
|
-
return null;
|
|
1007
|
-
}
|
|
1008
|
-
const raw = fs.readFileSync(filePath, "utf-8");
|
|
1009
|
-
const data = JSON.parse(raw);
|
|
1010
|
-
if (data.consumed) {
|
|
1011
|
-
return null;
|
|
1012
|
-
}
|
|
1013
|
-
return data;
|
|
1014
|
-
} catch {
|
|
1015
|
-
return null;
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
function consumeReviewResult(cwd) {
|
|
1019
|
-
try {
|
|
1020
|
-
const filePath = reviewResultPath(cwd);
|
|
1021
|
-
if (!fs.existsSync(filePath)) {
|
|
1022
|
-
return;
|
|
1023
|
-
}
|
|
1024
|
-
const raw = fs.readFileSync(filePath, "utf-8");
|
|
1025
|
-
const data = JSON.parse(raw);
|
|
1026
|
-
data.consumed = true;
|
|
1027
|
-
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
|
|
1028
|
-
} catch {
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
// packages/core/src/pipeline.ts
|
|
1033
|
-
import getPort from "get-port";
|
|
1034
|
-
import open from "open";
|
|
1035
|
-
|
|
1036
|
-
// packages/core/src/watch-bridge.ts
|
|
1037
|
-
import http from "http";
|
|
1038
|
-
import { WebSocketServer, WebSocket } from "ws";
|
|
1039
|
-
function createWatchBridge(port, callbacks) {
|
|
1040
|
-
let client = null;
|
|
1041
|
-
let initPayload = null;
|
|
1042
|
-
let pendingInit = null;
|
|
1043
|
-
let closeTimer = null;
|
|
1044
|
-
let submitCallback = null;
|
|
1045
|
-
let resultReject = null;
|
|
1046
|
-
const httpServer = http.createServer(async (req, res) => {
|
|
1047
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
1048
|
-
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
1049
|
-
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
1050
|
-
if (req.method === "OPTIONS") {
|
|
1051
|
-
res.writeHead(204);
|
|
1052
|
-
res.end();
|
|
1053
|
-
return;
|
|
1054
|
-
}
|
|
1055
|
-
if (req.method === "GET" && req.url === "/api/status") {
|
|
1056
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1057
|
-
res.end(JSON.stringify({ running: true, pid: process.pid }));
|
|
1058
|
-
return;
|
|
1059
|
-
}
|
|
1060
|
-
if (req.method === "POST" && req.url === "/api/context") {
|
|
1061
|
-
let body = "";
|
|
1062
|
-
req.on("data", (chunk) => {
|
|
1063
|
-
body += chunk.toString();
|
|
1064
|
-
});
|
|
1065
|
-
req.on("end", () => {
|
|
1066
|
-
try {
|
|
1067
|
-
const payload = JSON.parse(body);
|
|
1068
|
-
callbacks.onContextUpdate(payload);
|
|
1069
|
-
sendToClient({ type: "context:update", payload });
|
|
1070
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1071
|
-
res.end(JSON.stringify({ ok: true }));
|
|
1072
|
-
} catch {
|
|
1073
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1074
|
-
res.end(JSON.stringify({ error: "Invalid JSON" }));
|
|
1075
|
-
}
|
|
1076
|
-
});
|
|
1077
|
-
return;
|
|
1078
|
-
}
|
|
1079
|
-
if (req.method === "POST" && req.url === "/api/refresh") {
|
|
1080
|
-
callbacks.onRefreshRequest();
|
|
1081
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1082
|
-
res.end(JSON.stringify({ ok: true }));
|
|
1083
|
-
return;
|
|
1084
|
-
}
|
|
1085
|
-
const pathname = (req.url ?? "").split("?")[0];
|
|
1086
|
-
if (req.method === "GET" && (pathname === "/api/refs" || /^\/api\/reviews\/[^/]+\/refs$/.test(pathname))) {
|
|
1087
|
-
if (callbacks.onRefsRequest) {
|
|
1088
|
-
const refsPayload = await callbacks.onRefsRequest();
|
|
1089
|
-
if (refsPayload) {
|
|
1090
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1091
|
-
res.end(JSON.stringify(refsPayload));
|
|
1092
|
-
} else {
|
|
1093
|
-
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1094
|
-
res.end(JSON.stringify({ error: "Failed to list git refs" }));
|
|
1095
|
-
}
|
|
1096
|
-
} else {
|
|
1097
|
-
res.writeHead(404);
|
|
1098
|
-
res.end("Not found");
|
|
1099
|
-
}
|
|
1100
|
-
return;
|
|
1101
|
-
}
|
|
1102
|
-
if (req.method === "POST" && (pathname === "/api/compare" || /^\/api\/reviews\/[^/]+\/compare$/.test(pathname))) {
|
|
1103
|
-
if (callbacks.onCompareRequest) {
|
|
1104
|
-
let body = "";
|
|
1105
|
-
req.on("data", (chunk) => {
|
|
1106
|
-
body += chunk.toString();
|
|
1107
|
-
});
|
|
1108
|
-
req.on("end", async () => {
|
|
1109
|
-
try {
|
|
1110
|
-
const { ref } = JSON.parse(body);
|
|
1111
|
-
if (!ref) {
|
|
1112
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1113
|
-
res.end(JSON.stringify({ error: "Missing ref" }));
|
|
1114
|
-
return;
|
|
1115
|
-
}
|
|
1116
|
-
const success = await callbacks.onCompareRequest(ref);
|
|
1117
|
-
if (success) {
|
|
1118
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1119
|
-
res.end(JSON.stringify({ ok: true }));
|
|
1120
|
-
} else {
|
|
1121
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1122
|
-
res.end(JSON.stringify({ error: "Failed to compute diff" }));
|
|
1123
|
-
}
|
|
1124
|
-
} catch {
|
|
1125
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1126
|
-
res.end(JSON.stringify({ error: "Invalid JSON" }));
|
|
1127
|
-
}
|
|
1128
|
-
});
|
|
1129
|
-
} else {
|
|
1130
|
-
res.writeHead(404);
|
|
1131
|
-
res.end("Not found");
|
|
1132
|
-
}
|
|
1133
|
-
return;
|
|
1134
|
-
}
|
|
1135
|
-
res.writeHead(404);
|
|
1136
|
-
res.end("Not found");
|
|
1137
|
-
});
|
|
1138
|
-
const wss2 = new WebSocketServer({ server: httpServer });
|
|
1139
|
-
function sendToClient(msg) {
|
|
1140
|
-
if (client && client.readyState === WebSocket.OPEN) {
|
|
1141
|
-
client.send(JSON.stringify(msg));
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
wss2.on("connection", (ws) => {
|
|
1145
|
-
if (closeTimer) {
|
|
1146
|
-
clearTimeout(closeTimer);
|
|
1147
|
-
closeTimer = null;
|
|
1148
|
-
}
|
|
1149
|
-
client = ws;
|
|
1150
|
-
const payload = pendingInit ?? initPayload;
|
|
1151
|
-
if (payload) {
|
|
1152
|
-
sendToClient({ type: "review:init", payload });
|
|
1153
|
-
pendingInit = null;
|
|
1154
|
-
}
|
|
1155
|
-
ws.on("message", (data) => {
|
|
1156
|
-
try {
|
|
1157
|
-
const msg = JSON.parse(data.toString());
|
|
1158
|
-
if (msg.type === "review:submit" && submitCallback) {
|
|
1159
|
-
submitCallback(msg.payload);
|
|
1160
|
-
} else if (msg.type === "diff:change_ref" && callbacks.onDiffRefChange) {
|
|
1161
|
-
callbacks.onDiffRefChange(msg.payload.diffRef);
|
|
1162
|
-
}
|
|
1163
|
-
} catch {
|
|
1164
|
-
}
|
|
1165
|
-
});
|
|
1166
|
-
ws.on("close", () => {
|
|
1167
|
-
client = null;
|
|
1168
|
-
if (resultReject) {
|
|
1169
|
-
closeTimer = setTimeout(() => {
|
|
1170
|
-
closeTimer = null;
|
|
1171
|
-
if (resultReject) {
|
|
1172
|
-
resultReject(new Error("Browser closed before review was submitted"));
|
|
1173
|
-
resultReject = null;
|
|
1174
|
-
submitCallback = null;
|
|
1175
|
-
}
|
|
1176
|
-
}, 2e3);
|
|
1177
|
-
} else {
|
|
1178
|
-
closeTimer = setTimeout(() => {
|
|
1179
|
-
closeTimer = null;
|
|
1180
|
-
}, 2e3);
|
|
1181
|
-
}
|
|
1182
|
-
});
|
|
1183
|
-
});
|
|
1184
|
-
return new Promise((resolve, reject) => {
|
|
1185
|
-
httpServer.on("error", reject);
|
|
1186
|
-
httpServer.listen(port, () => {
|
|
1187
|
-
resolve({
|
|
1188
|
-
port,
|
|
1189
|
-
sendInit(payload) {
|
|
1190
|
-
initPayload = payload;
|
|
1191
|
-
if (client && client.readyState === WebSocket.OPEN) {
|
|
1192
|
-
sendToClient({ type: "review:init", payload });
|
|
1193
|
-
} else {
|
|
1194
|
-
pendingInit = payload;
|
|
1195
|
-
}
|
|
1196
|
-
},
|
|
1197
|
-
storeInitPayload(payload) {
|
|
1198
|
-
initPayload = payload;
|
|
1199
|
-
},
|
|
1200
|
-
sendDiffUpdate(payload) {
|
|
1201
|
-
sendToClient({ type: "diff:update", payload });
|
|
1202
|
-
},
|
|
1203
|
-
sendContextUpdate(payload) {
|
|
1204
|
-
sendToClient({ type: "context:update", payload });
|
|
1205
|
-
},
|
|
1206
|
-
sendDiffError(payload) {
|
|
1207
|
-
sendToClient({ type: "diff:error", payload });
|
|
1208
|
-
},
|
|
1209
|
-
onSubmit(callback) {
|
|
1210
|
-
submitCallback = callback;
|
|
1211
|
-
},
|
|
1212
|
-
waitForResult() {
|
|
1213
|
-
return new Promise((resolve2, reject2) => {
|
|
1214
|
-
submitCallback = resolve2;
|
|
1215
|
-
resultReject = reject2;
|
|
1216
|
-
});
|
|
1217
|
-
},
|
|
1218
|
-
triggerRefresh() {
|
|
1219
|
-
callbacks.onRefreshRequest();
|
|
1220
|
-
},
|
|
1221
|
-
async close() {
|
|
1222
|
-
if (closeTimer) {
|
|
1223
|
-
clearTimeout(closeTimer);
|
|
1224
|
-
}
|
|
1225
|
-
for (const ws of wss2.clients) {
|
|
1226
|
-
ws.close();
|
|
1227
|
-
}
|
|
1228
|
-
wss2.close();
|
|
1229
|
-
await new Promise((resolve2) => {
|
|
1230
|
-
httpServer.close(() => resolve2());
|
|
1231
|
-
});
|
|
1232
|
-
}
|
|
1233
|
-
});
|
|
1234
|
-
});
|
|
1235
|
-
});
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
// packages/core/src/diff-utils.ts
|
|
1239
|
-
import { createHash } from "crypto";
|
|
1240
|
-
function hashDiff(rawDiff) {
|
|
1241
|
-
return createHash("sha256").update(rawDiff).digest("hex");
|
|
1242
|
-
}
|
|
1243
|
-
function fileKey(file) {
|
|
1244
|
-
return file.stage ? `${file.stage}:${file.path}` : file.path;
|
|
1245
|
-
}
|
|
1246
|
-
function detectChangedFiles(oldDiffSet, newDiffSet) {
|
|
1247
|
-
if (!oldDiffSet) {
|
|
1248
|
-
return newDiffSet.files.map(fileKey);
|
|
1249
|
-
}
|
|
1250
|
-
const oldFiles = new Map(
|
|
1251
|
-
oldDiffSet.files.map((f) => [fileKey(f), f])
|
|
1252
|
-
);
|
|
1253
|
-
const changed = [];
|
|
1254
|
-
for (const newFile of newDiffSet.files) {
|
|
1255
|
-
const key = fileKey(newFile);
|
|
1256
|
-
const oldFile = oldFiles.get(key);
|
|
1257
|
-
if (!oldFile) {
|
|
1258
|
-
changed.push(key);
|
|
1259
|
-
} else if (oldFile.additions !== newFile.additions || oldFile.deletions !== newFile.deletions) {
|
|
1260
|
-
changed.push(key);
|
|
1261
|
-
}
|
|
1262
|
-
}
|
|
1263
|
-
for (const oldFile of oldDiffSet.files) {
|
|
1264
|
-
if (!newDiffSet.files.some((f) => fileKey(f) === fileKey(oldFile))) {
|
|
1265
|
-
changed.push(fileKey(oldFile));
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
return changed;
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
// packages/core/src/diff-poller.ts
|
|
1272
|
-
function createDiffPoller(options) {
|
|
1273
|
-
let { diffRef } = options;
|
|
1274
|
-
const { cwd, pollInterval, onDiffChanged, onError, silent } = options;
|
|
1275
|
-
let lastDiffHash = null;
|
|
1276
|
-
let lastDiffSet = null;
|
|
1277
|
-
let refreshRequested = false;
|
|
1278
|
-
let interval = null;
|
|
1279
|
-
let running = false;
|
|
1280
|
-
function poll() {
|
|
1281
|
-
if (!running) return;
|
|
1282
|
-
try {
|
|
1283
|
-
const { diffSet: newDiffSet, rawDiff: newRawDiff } = getDiff(diffRef, { cwd });
|
|
1284
|
-
const newHash = hashDiff(newRawDiff);
|
|
1285
|
-
if (newHash !== lastDiffHash || refreshRequested) {
|
|
1286
|
-
refreshRequested = false;
|
|
1287
|
-
const newBriefing = analyze(newDiffSet);
|
|
1288
|
-
const changedFiles = detectChangedFiles(lastDiffSet, newDiffSet);
|
|
1289
|
-
lastDiffHash = newHash;
|
|
1290
|
-
lastDiffSet = newDiffSet;
|
|
1291
|
-
const updatePayload = {
|
|
1292
|
-
diffSet: newDiffSet,
|
|
1293
|
-
rawDiff: newRawDiff,
|
|
1294
|
-
briefing: newBriefing,
|
|
1295
|
-
changedFiles,
|
|
1296
|
-
timestamp: Date.now()
|
|
1297
|
-
};
|
|
1298
|
-
onDiffChanged(updatePayload);
|
|
1299
|
-
}
|
|
1300
|
-
} catch (err) {
|
|
1301
|
-
if (onError && err instanceof Error) {
|
|
1302
|
-
onError(err);
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
}
|
|
1306
|
-
return {
|
|
1307
|
-
start() {
|
|
1308
|
-
if (running) return;
|
|
1309
|
-
running = true;
|
|
1310
|
-
try {
|
|
1311
|
-
const { diffSet: initialDiffSet, rawDiff: initialRawDiff } = getDiff(diffRef, { cwd });
|
|
1312
|
-
lastDiffHash = hashDiff(initialRawDiff);
|
|
1313
|
-
lastDiffSet = initialDiffSet;
|
|
1314
|
-
} catch {
|
|
1315
|
-
}
|
|
1316
|
-
interval = setInterval(poll, pollInterval);
|
|
1317
|
-
},
|
|
1318
|
-
stop() {
|
|
1319
|
-
running = false;
|
|
1320
|
-
if (interval) {
|
|
1321
|
-
clearInterval(interval);
|
|
1322
|
-
interval = null;
|
|
1323
|
-
}
|
|
1324
|
-
},
|
|
1325
|
-
setDiffRef(newRef) {
|
|
1326
|
-
diffRef = newRef;
|
|
1327
|
-
lastDiffHash = null;
|
|
1328
|
-
lastDiffSet = null;
|
|
1329
|
-
},
|
|
1330
|
-
refresh() {
|
|
1331
|
-
refreshRequested = true;
|
|
1332
|
-
}
|
|
1333
|
-
};
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
// packages/core/src/review-manager.ts
|
|
1337
|
-
var sessions = /* @__PURE__ */ new Map();
|
|
1338
|
-
var idCounter = 0;
|
|
1339
|
-
function createSession(options) {
|
|
1340
|
-
const id = `review-${Date.now()}-${++idCounter}`;
|
|
1341
|
-
const session = {
|
|
1342
|
-
id,
|
|
1343
|
-
options,
|
|
1344
|
-
status: "pending",
|
|
1345
|
-
createdAt: Date.now()
|
|
1346
|
-
};
|
|
1347
|
-
sessions.set(id, session);
|
|
1348
|
-
return session;
|
|
1349
|
-
}
|
|
1350
|
-
function updateSession(id, update) {
|
|
1351
|
-
const session = sessions.get(id);
|
|
1352
|
-
if (session) {
|
|
1353
|
-
Object.assign(session, update);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
|
|
1357
|
-
// packages/core/src/ui-server.ts
|
|
1358
|
-
import http2 from "http";
|
|
1359
|
-
import fs2 from "fs";
|
|
1360
|
-
import path4 from "path";
|
|
1361
|
-
import { fileURLToPath } from "url";
|
|
1362
|
-
var MIME_TYPES = {
|
|
1363
|
-
".html": "text/html",
|
|
1364
|
-
".js": "application/javascript",
|
|
1365
|
-
".css": "text/css",
|
|
1366
|
-
".json": "application/json",
|
|
1367
|
-
".svg": "image/svg+xml",
|
|
1368
|
-
".png": "image/png",
|
|
1369
|
-
".ico": "image/x-icon",
|
|
1370
|
-
".woff": "font/woff",
|
|
1371
|
-
".woff2": "font/woff2"
|
|
1372
|
-
};
|
|
1373
|
-
function resolveUiDist() {
|
|
1374
|
-
const thisFile = fileURLToPath(import.meta.url);
|
|
1375
|
-
const thisDir = path4.dirname(thisFile);
|
|
1376
|
-
const publishedUiDist = path4.resolve(thisDir, "..", "ui-dist");
|
|
1377
|
-
if (fs2.existsSync(path4.join(publishedUiDist, "index.html"))) {
|
|
1378
|
-
return publishedUiDist;
|
|
1379
|
-
}
|
|
1380
|
-
const workspaceRoot = path4.resolve(thisDir, "..", "..", "..");
|
|
1381
|
-
const devUiDist = path4.join(workspaceRoot, "packages", "ui", "dist");
|
|
1382
|
-
if (fs2.existsSync(path4.join(devUiDist, "index.html"))) {
|
|
1383
|
-
return devUiDist;
|
|
1384
|
-
}
|
|
1385
|
-
throw new Error(
|
|
1386
|
-
"Could not find built UI. Run 'pnpm -F @diffprism/ui build' first."
|
|
1387
|
-
);
|
|
1388
|
-
}
|
|
1389
|
-
function resolveUiRoot() {
|
|
1390
|
-
const thisFile = fileURLToPath(import.meta.url);
|
|
1391
|
-
const thisDir = path4.dirname(thisFile);
|
|
1392
|
-
const workspaceRoot = path4.resolve(thisDir, "..", "..", "..");
|
|
1393
|
-
const uiRoot = path4.join(workspaceRoot, "packages", "ui");
|
|
1394
|
-
if (fs2.existsSync(path4.join(uiRoot, "index.html"))) {
|
|
1395
|
-
return uiRoot;
|
|
1396
|
-
}
|
|
1397
|
-
throw new Error(
|
|
1398
|
-
"Could not find UI source directory. Dev mode requires the diffprism workspace."
|
|
1399
|
-
);
|
|
1400
|
-
}
|
|
1401
|
-
async function startViteDevServer(uiRoot, port, silent) {
|
|
1402
|
-
const { createServer } = await import("vite");
|
|
1403
|
-
const vite = await createServer({
|
|
1404
|
-
root: uiRoot,
|
|
1405
|
-
server: { port, strictPort: true, open: false },
|
|
1406
|
-
logLevel: silent ? "silent" : "warn"
|
|
1407
|
-
});
|
|
1408
|
-
await vite.listen();
|
|
1409
|
-
return vite;
|
|
1410
|
-
}
|
|
1411
|
-
function createStaticServer(distPath, port) {
|
|
1412
|
-
const server = http2.createServer((req, res) => {
|
|
1413
|
-
const urlPath = req.url?.split("?")[0] ?? "/";
|
|
1414
|
-
let filePath = path4.join(distPath, urlPath === "/" ? "index.html" : urlPath);
|
|
1415
|
-
if (!fs2.existsSync(filePath)) {
|
|
1416
|
-
filePath = path4.join(distPath, "index.html");
|
|
1417
|
-
}
|
|
1418
|
-
const ext = path4.extname(filePath);
|
|
1419
|
-
const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
1420
|
-
try {
|
|
1421
|
-
const content = fs2.readFileSync(filePath);
|
|
1422
|
-
res.writeHead(200, { "Content-Type": contentType });
|
|
1423
|
-
res.end(content);
|
|
1424
|
-
} catch {
|
|
1425
|
-
res.writeHead(404);
|
|
1426
|
-
res.end("Not found");
|
|
1427
|
-
}
|
|
1428
|
-
});
|
|
1429
|
-
return new Promise((resolve, reject) => {
|
|
1430
|
-
server.on("error", reject);
|
|
1431
|
-
server.listen(port, () => resolve(server));
|
|
1432
|
-
});
|
|
1433
|
-
}
|
|
1434
|
-
|
|
1435
|
-
// packages/core/src/pipeline.ts
|
|
1436
|
-
async function startReview(options) {
|
|
1437
|
-
const { diffRef, title, description, reasoning, cwd, silent, dev } = options;
|
|
1438
|
-
const { diffSet, rawDiff } = getDiff(diffRef, { cwd });
|
|
1439
|
-
const currentBranch = getCurrentBranch({ cwd });
|
|
1440
|
-
if (diffSet.files.length === 0) {
|
|
1441
|
-
if (!silent) {
|
|
1442
|
-
console.log("No changes to review.");
|
|
1443
|
-
}
|
|
1444
|
-
return {
|
|
1445
|
-
decision: "approved",
|
|
1446
|
-
comments: [],
|
|
1447
|
-
summary: "No changes to review."
|
|
1448
|
-
};
|
|
1449
|
-
}
|
|
1450
|
-
const briefing = analyze(diffSet);
|
|
1451
|
-
const session = createSession(options);
|
|
1452
|
-
updateSession(session.id, { status: "in_progress" });
|
|
1453
|
-
const worktreeInfo = detectWorktree({ cwd });
|
|
1454
|
-
const metadata = {
|
|
1455
|
-
title,
|
|
1456
|
-
description,
|
|
1457
|
-
reasoning,
|
|
1458
|
-
currentBranch,
|
|
1459
|
-
worktree: worktreeInfo.isWorktree ? {
|
|
1460
|
-
isWorktree: true,
|
|
1461
|
-
worktreePath: worktreeInfo.worktreePath,
|
|
1462
|
-
mainWorktreePath: worktreeInfo.mainWorktreePath
|
|
1463
|
-
} : void 0
|
|
1464
|
-
};
|
|
1465
|
-
let poller = null;
|
|
1466
|
-
const [bridgePort, httpPort] = await Promise.all([
|
|
1467
|
-
getPort(),
|
|
1468
|
-
getPort()
|
|
1469
|
-
]);
|
|
1470
|
-
function handleDiffRefChange(newRef) {
|
|
1471
|
-
const { diffSet: newDiffSet, rawDiff: newRawDiff } = getDiff(newRef, { cwd });
|
|
1472
|
-
const newBriefing = analyze(newDiffSet);
|
|
1473
|
-
bridge.sendDiffUpdate({
|
|
1474
|
-
diffSet: newDiffSet,
|
|
1475
|
-
rawDiff: newRawDiff,
|
|
1476
|
-
briefing: newBriefing,
|
|
1477
|
-
changedFiles: newDiffSet.files.map((f) => f.path),
|
|
1478
|
-
timestamp: Date.now()
|
|
1479
|
-
});
|
|
1480
|
-
bridge.storeInitPayload({
|
|
1481
|
-
reviewId: session.id,
|
|
1482
|
-
diffSet: newDiffSet,
|
|
1483
|
-
rawDiff: newRawDiff,
|
|
1484
|
-
briefing: newBriefing,
|
|
1485
|
-
metadata,
|
|
1486
|
-
watchMode: true
|
|
1487
|
-
});
|
|
1488
|
-
poller?.setDiffRef(newRef);
|
|
1489
|
-
}
|
|
1490
|
-
const bridge = await createWatchBridge(bridgePort, {
|
|
1491
|
-
onRefreshRequest: () => {
|
|
1492
|
-
poller?.refresh();
|
|
1493
|
-
},
|
|
1494
|
-
onContextUpdate: (payload) => {
|
|
1495
|
-
if (payload.reasoning !== void 0) metadata.reasoning = payload.reasoning;
|
|
1496
|
-
if (payload.title !== void 0) metadata.title = payload.title;
|
|
1497
|
-
if (payload.description !== void 0) metadata.description = payload.description;
|
|
1498
|
-
},
|
|
1499
|
-
onDiffRefChange: (newRef) => {
|
|
1500
|
-
try {
|
|
1501
|
-
handleDiffRefChange(newRef);
|
|
1502
|
-
} catch (err) {
|
|
1503
|
-
bridge.sendDiffError({
|
|
1504
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1505
|
-
});
|
|
1506
|
-
}
|
|
1507
|
-
},
|
|
1508
|
-
onRefsRequest: async () => {
|
|
1509
|
-
try {
|
|
1510
|
-
const resolvedCwd = cwd ?? process.cwd();
|
|
1511
|
-
const branches = listBranches({ cwd: resolvedCwd });
|
|
1512
|
-
const commits = listCommits({ cwd: resolvedCwd });
|
|
1513
|
-
const branch = getCurrentBranch({ cwd: resolvedCwd });
|
|
1514
|
-
return { branches, commits, currentBranch: branch };
|
|
1515
|
-
} catch {
|
|
1516
|
-
return null;
|
|
1517
|
-
}
|
|
1518
|
-
},
|
|
1519
|
-
onCompareRequest: async (ref) => {
|
|
1520
|
-
try {
|
|
1521
|
-
handleDiffRefChange(ref);
|
|
1522
|
-
return true;
|
|
1523
|
-
} catch {
|
|
1524
|
-
return false;
|
|
1525
|
-
}
|
|
1526
|
-
}
|
|
1527
|
-
});
|
|
1528
|
-
let httpServer = null;
|
|
1529
|
-
let viteServer = null;
|
|
1530
|
-
try {
|
|
1531
|
-
if (dev) {
|
|
1532
|
-
const uiRoot = resolveUiRoot();
|
|
1533
|
-
viteServer = await startViteDevServer(uiRoot, httpPort, !!silent);
|
|
1534
|
-
} else {
|
|
1535
|
-
const uiDist = resolveUiDist();
|
|
1536
|
-
httpServer = await createStaticServer(uiDist, httpPort);
|
|
1537
|
-
}
|
|
1538
|
-
writeWatchFile(cwd, {
|
|
1539
|
-
wsPort: bridgePort,
|
|
1540
|
-
uiPort: httpPort,
|
|
1541
|
-
pid: process.pid,
|
|
1542
|
-
cwd: cwd ?? process.cwd(),
|
|
1543
|
-
diffRef,
|
|
1544
|
-
startedAt: Date.now()
|
|
1545
|
-
});
|
|
1546
|
-
const url = `http://localhost:${httpPort}?wsPort=${bridgePort}&httpPort=${bridgePort}&reviewId=${session.id}`;
|
|
1547
|
-
if (!silent) {
|
|
1548
|
-
console.log(`
|
|
1549
|
-
DiffPrism Review: ${title ?? briefing.summary}`);
|
|
1550
|
-
console.log(`Opening browser at ${url}
|
|
1551
|
-
`);
|
|
1552
|
-
}
|
|
1553
|
-
await open(url);
|
|
1554
|
-
const initPayload = {
|
|
1555
|
-
reviewId: session.id,
|
|
1556
|
-
diffSet,
|
|
1557
|
-
rawDiff,
|
|
1558
|
-
briefing,
|
|
1559
|
-
metadata,
|
|
1560
|
-
watchMode: true
|
|
1561
|
-
};
|
|
1562
|
-
bridge.sendInit(initPayload);
|
|
1563
|
-
poller = createDiffPoller({
|
|
1564
|
-
diffRef,
|
|
1565
|
-
cwd: cwd ?? process.cwd(),
|
|
1566
|
-
pollInterval: 1e3,
|
|
1567
|
-
onDiffChanged: (updatePayload) => {
|
|
1568
|
-
bridge.storeInitPayload({
|
|
1569
|
-
reviewId: session.id,
|
|
1570
|
-
diffSet: updatePayload.diffSet,
|
|
1571
|
-
rawDiff: updatePayload.rawDiff,
|
|
1572
|
-
briefing: updatePayload.briefing,
|
|
1573
|
-
metadata,
|
|
1574
|
-
watchMode: true
|
|
1575
|
-
});
|
|
1576
|
-
bridge.sendDiffUpdate(updatePayload);
|
|
1577
|
-
if (!silent && updatePayload.changedFiles.length > 0) {
|
|
1578
|
-
console.log(
|
|
1579
|
-
`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] Diff updated: ${updatePayload.changedFiles.length} file(s) changed`
|
|
1580
|
-
);
|
|
1581
|
-
}
|
|
1582
|
-
}
|
|
1583
|
-
});
|
|
1584
|
-
poller.start();
|
|
1585
|
-
const result = await bridge.waitForResult();
|
|
1586
|
-
poller.stop();
|
|
1587
|
-
updateSession(session.id, { status: "completed", result });
|
|
1588
|
-
return result;
|
|
1589
|
-
} finally {
|
|
1590
|
-
poller?.stop();
|
|
1591
|
-
await bridge.close();
|
|
1592
|
-
removeWatchFile(cwd);
|
|
1593
|
-
if (viteServer) {
|
|
1594
|
-
await viteServer.close();
|
|
1595
|
-
}
|
|
1596
|
-
if (httpServer) {
|
|
1597
|
-
httpServer.close();
|
|
1598
|
-
}
|
|
1599
|
-
}
|
|
1600
|
-
}
|
|
1601
|
-
|
|
1602
|
-
// packages/core/src/server-file.ts
|
|
1603
|
-
import fs3 from "fs";
|
|
1604
|
-
import path5 from "path";
|
|
1605
|
-
import os from "os";
|
|
1606
|
-
function serverDir() {
|
|
1607
|
-
return path5.join(os.homedir(), ".diffprism");
|
|
1608
|
-
}
|
|
1609
|
-
function serverFilePath() {
|
|
1610
|
-
return path5.join(serverDir(), "server.json");
|
|
1611
|
-
}
|
|
1612
|
-
function isPidAlive2(pid) {
|
|
1613
|
-
try {
|
|
1614
|
-
process.kill(pid, 0);
|
|
1615
|
-
return true;
|
|
1616
|
-
} catch {
|
|
1617
|
-
return false;
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
function writeServerFile(info) {
|
|
1621
|
-
const dir = serverDir();
|
|
1622
|
-
if (!fs3.existsSync(dir)) {
|
|
1623
|
-
fs3.mkdirSync(dir, { recursive: true });
|
|
1624
|
-
}
|
|
1625
|
-
fs3.writeFileSync(serverFilePath(), JSON.stringify(info, null, 2) + "\n");
|
|
1626
|
-
}
|
|
1627
|
-
function readServerFile() {
|
|
1628
|
-
const filePath = serverFilePath();
|
|
1629
|
-
if (!fs3.existsSync(filePath)) {
|
|
1630
|
-
return null;
|
|
1631
|
-
}
|
|
1632
|
-
try {
|
|
1633
|
-
const raw = fs3.readFileSync(filePath, "utf-8");
|
|
1634
|
-
const info = JSON.parse(raw);
|
|
1635
|
-
if (!isPidAlive2(info.pid)) {
|
|
1636
|
-
fs3.unlinkSync(filePath);
|
|
1637
|
-
return null;
|
|
1638
|
-
}
|
|
1639
|
-
return info;
|
|
1640
|
-
} catch {
|
|
1641
|
-
return null;
|
|
1642
|
-
}
|
|
1643
|
-
}
|
|
1644
|
-
function removeServerFile() {
|
|
1645
|
-
try {
|
|
1646
|
-
const filePath = serverFilePath();
|
|
1647
|
-
if (fs3.existsSync(filePath)) {
|
|
1648
|
-
fs3.unlinkSync(filePath);
|
|
1649
|
-
}
|
|
1650
|
-
} catch {
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
async function isServerAlive() {
|
|
1654
|
-
const info = readServerFile();
|
|
1655
|
-
if (!info) {
|
|
1656
|
-
return null;
|
|
1657
|
-
}
|
|
1658
|
-
try {
|
|
1659
|
-
const response = await fetch(`http://localhost:${info.httpPort}/api/status`, {
|
|
1660
|
-
signal: AbortSignal.timeout(2e3)
|
|
1661
|
-
});
|
|
1662
|
-
if (response.ok) {
|
|
1663
|
-
return info;
|
|
1664
|
-
}
|
|
1665
|
-
return null;
|
|
1666
|
-
} catch {
|
|
1667
|
-
removeServerFile();
|
|
1668
|
-
return null;
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
|
|
1672
|
-
// packages/core/src/watch.ts
|
|
1673
|
-
import getPort2 from "get-port";
|
|
1674
|
-
import open2 from "open";
|
|
1675
|
-
async function startWatch(options) {
|
|
1676
|
-
const {
|
|
1677
|
-
diffRef,
|
|
1678
|
-
title,
|
|
1679
|
-
description,
|
|
1680
|
-
reasoning,
|
|
1681
|
-
cwd,
|
|
1682
|
-
silent,
|
|
1683
|
-
dev,
|
|
1684
|
-
pollInterval = 1e3
|
|
1685
|
-
} = options;
|
|
1686
|
-
const { diffSet: initialDiffSet, rawDiff: initialRawDiff } = getDiff(diffRef, { cwd });
|
|
1687
|
-
const currentBranch = getCurrentBranch({ cwd });
|
|
1688
|
-
const initialBriefing = analyze(initialDiffSet);
|
|
1689
|
-
const metadata = {
|
|
1690
|
-
title,
|
|
1691
|
-
description,
|
|
1692
|
-
reasoning,
|
|
1693
|
-
currentBranch
|
|
1694
|
-
};
|
|
1695
|
-
const [bridgePort, uiPort] = await Promise.all([
|
|
1696
|
-
getPort2(),
|
|
1697
|
-
getPort2()
|
|
1698
|
-
]);
|
|
1699
|
-
const reviewId = "watch-session";
|
|
1700
|
-
function handleDiffRefChange(newRef) {
|
|
1701
|
-
const { diffSet: newDiffSet, rawDiff: newRawDiff } = getDiff(newRef, { cwd });
|
|
1702
|
-
const newBriefing = analyze(newDiffSet);
|
|
1703
|
-
bridge.sendDiffUpdate({
|
|
1704
|
-
diffSet: newDiffSet,
|
|
1705
|
-
rawDiff: newRawDiff,
|
|
1706
|
-
briefing: newBriefing,
|
|
1707
|
-
changedFiles: newDiffSet.files.map((f) => f.path),
|
|
1708
|
-
timestamp: Date.now()
|
|
1709
|
-
});
|
|
1710
|
-
bridge.storeInitPayload({
|
|
1711
|
-
reviewId,
|
|
1712
|
-
diffSet: newDiffSet,
|
|
1713
|
-
rawDiff: newRawDiff,
|
|
1714
|
-
briefing: newBriefing,
|
|
1715
|
-
metadata,
|
|
1716
|
-
watchMode: true
|
|
1717
|
-
});
|
|
1718
|
-
poller.setDiffRef(newRef);
|
|
1719
|
-
}
|
|
1720
|
-
const bridge = await createWatchBridge(bridgePort, {
|
|
1721
|
-
onRefreshRequest: () => {
|
|
1722
|
-
poller.refresh();
|
|
1723
|
-
},
|
|
1724
|
-
onContextUpdate: (payload) => {
|
|
1725
|
-
if (payload.reasoning !== void 0) metadata.reasoning = payload.reasoning;
|
|
1726
|
-
if (payload.title !== void 0) metadata.title = payload.title;
|
|
1727
|
-
if (payload.description !== void 0) metadata.description = payload.description;
|
|
1728
|
-
},
|
|
1729
|
-
onDiffRefChange: (newRef) => {
|
|
1730
|
-
try {
|
|
1731
|
-
handleDiffRefChange(newRef);
|
|
1732
|
-
} catch (err) {
|
|
1733
|
-
bridge.sendDiffError({
|
|
1734
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1735
|
-
});
|
|
1736
|
-
}
|
|
1737
|
-
},
|
|
1738
|
-
onRefsRequest: async () => {
|
|
1739
|
-
try {
|
|
1740
|
-
const resolvedCwd = cwd ?? process.cwd();
|
|
1741
|
-
const branches = listBranches({ cwd: resolvedCwd });
|
|
1742
|
-
const commits = listCommits({ cwd: resolvedCwd });
|
|
1743
|
-
const branch = getCurrentBranch({ cwd: resolvedCwd });
|
|
1744
|
-
return { branches, commits, currentBranch: branch };
|
|
1745
|
-
} catch {
|
|
1746
|
-
return null;
|
|
1747
|
-
}
|
|
1748
|
-
},
|
|
1749
|
-
onCompareRequest: async (ref) => {
|
|
1750
|
-
try {
|
|
1751
|
-
handleDiffRefChange(ref);
|
|
1752
|
-
return true;
|
|
1753
|
-
} catch {
|
|
1754
|
-
return false;
|
|
1755
|
-
}
|
|
1756
|
-
}
|
|
1757
|
-
});
|
|
1758
|
-
let httpServer = null;
|
|
1759
|
-
let viteServer = null;
|
|
1760
|
-
if (dev) {
|
|
1761
|
-
const uiRoot = resolveUiRoot();
|
|
1762
|
-
viteServer = await startViteDevServer(uiRoot, uiPort, !!silent);
|
|
1763
|
-
} else {
|
|
1764
|
-
const uiDist = resolveUiDist();
|
|
1765
|
-
httpServer = await createStaticServer(uiDist, uiPort);
|
|
1766
|
-
}
|
|
1767
|
-
writeWatchFile(cwd, {
|
|
1768
|
-
wsPort: bridgePort,
|
|
1769
|
-
uiPort,
|
|
1770
|
-
pid: process.pid,
|
|
1771
|
-
cwd: cwd ?? process.cwd(),
|
|
1772
|
-
diffRef,
|
|
1773
|
-
startedAt: Date.now()
|
|
1774
|
-
});
|
|
1775
|
-
const url = `http://localhost:${uiPort}?wsPort=${bridgePort}&httpPort=${bridgePort}&reviewId=${reviewId}`;
|
|
1776
|
-
if (!silent) {
|
|
1777
|
-
console.log(`
|
|
1778
|
-
DiffPrism Watch: ${title ?? `watching ${diffRef}`}`);
|
|
1779
|
-
console.log(`Browser: ${url}`);
|
|
1780
|
-
console.log(`API: http://localhost:${bridgePort}`);
|
|
1781
|
-
console.log(`Polling every ${pollInterval}ms
|
|
1782
|
-
`);
|
|
1783
|
-
}
|
|
1784
|
-
await open2(url);
|
|
1785
|
-
const initPayload = {
|
|
1786
|
-
reviewId,
|
|
1787
|
-
diffSet: initialDiffSet,
|
|
1788
|
-
rawDiff: initialRawDiff,
|
|
1789
|
-
briefing: initialBriefing,
|
|
1790
|
-
metadata,
|
|
1791
|
-
watchMode: true
|
|
1792
|
-
};
|
|
1793
|
-
bridge.sendInit(initPayload);
|
|
1794
|
-
bridge.onSubmit((result) => {
|
|
1795
|
-
if (!silent) {
|
|
1796
|
-
console.log(`
|
|
1797
|
-
Review submitted: ${result.decision}`);
|
|
1798
|
-
if (result.comments.length > 0) {
|
|
1799
|
-
console.log(` ${result.comments.length} comment(s)`);
|
|
1800
|
-
}
|
|
1801
|
-
console.log("Continuing to watch...\n");
|
|
1802
|
-
}
|
|
1803
|
-
writeReviewResult(cwd, result);
|
|
1804
|
-
});
|
|
1805
|
-
const poller = createDiffPoller({
|
|
1806
|
-
diffRef,
|
|
1807
|
-
cwd: cwd ?? process.cwd(),
|
|
1808
|
-
pollInterval,
|
|
1809
|
-
onDiffChanged: (updatePayload) => {
|
|
1810
|
-
bridge.storeInitPayload({
|
|
1811
|
-
reviewId,
|
|
1812
|
-
diffSet: updatePayload.diffSet,
|
|
1813
|
-
rawDiff: updatePayload.rawDiff,
|
|
1814
|
-
briefing: updatePayload.briefing,
|
|
1815
|
-
metadata,
|
|
1816
|
-
watchMode: true
|
|
1817
|
-
});
|
|
1818
|
-
bridge.sendDiffUpdate(updatePayload);
|
|
1819
|
-
if (!silent && updatePayload.changedFiles.length > 0) {
|
|
1820
|
-
console.log(
|
|
1821
|
-
`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] Diff updated: ${updatePayload.changedFiles.length} file(s) changed`
|
|
1822
|
-
);
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
});
|
|
1826
|
-
poller.start();
|
|
1827
|
-
async function stop() {
|
|
1828
|
-
poller.stop();
|
|
1829
|
-
await bridge.close();
|
|
1830
|
-
if (viteServer) {
|
|
1831
|
-
await viteServer.close();
|
|
1832
|
-
}
|
|
1833
|
-
if (httpServer) {
|
|
1834
|
-
httpServer.close();
|
|
1835
|
-
}
|
|
1836
|
-
removeWatchFile(cwd);
|
|
1837
|
-
}
|
|
1838
|
-
function updateContext(payload) {
|
|
1839
|
-
if (payload.reasoning !== void 0) metadata.reasoning = payload.reasoning;
|
|
1840
|
-
if (payload.title !== void 0) metadata.title = payload.title;
|
|
1841
|
-
if (payload.description !== void 0) metadata.description = payload.description;
|
|
1842
|
-
bridge.sendContextUpdate(payload);
|
|
1843
|
-
}
|
|
1844
|
-
return { stop, updateContext };
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
// packages/core/src/global-server.ts
|
|
1848
|
-
import http3 from "http";
|
|
1849
|
-
import { randomUUID } from "crypto";
|
|
1850
|
-
import getPort3 from "get-port";
|
|
1851
|
-
import open3 from "open";
|
|
1852
|
-
import { WebSocketServer as WebSocketServer2, WebSocket as WebSocket2 } from "ws";
|
|
1853
|
-
var SUBMITTED_TTL_MS = 5 * 60 * 1e3;
|
|
1854
|
-
var ABANDONED_TTL_MS = 60 * 60 * 1e3;
|
|
1855
|
-
var CLEANUP_INTERVAL_MS = 60 * 1e3;
|
|
1856
|
-
var sessions2 = /* @__PURE__ */ new Map();
|
|
1857
|
-
var clientSessions = /* @__PURE__ */ new Map();
|
|
1858
|
-
var sessionWatchers = /* @__PURE__ */ new Map();
|
|
1859
|
-
var serverPollInterval = 2e3;
|
|
1860
|
-
var reopenBrowserIfNeeded = null;
|
|
1861
|
-
function toSummary(session) {
|
|
1862
|
-
const { payload } = session;
|
|
1863
|
-
const fileCount = payload.diffSet.files.length;
|
|
1864
|
-
let additions = 0;
|
|
1865
|
-
let deletions = 0;
|
|
1866
|
-
for (const file of payload.diffSet.files) {
|
|
1867
|
-
additions += file.additions;
|
|
1868
|
-
deletions += file.deletions;
|
|
1869
|
-
}
|
|
1870
|
-
return {
|
|
1871
|
-
id: session.id,
|
|
1872
|
-
projectPath: session.projectPath,
|
|
1873
|
-
branch: payload.metadata.currentBranch,
|
|
1874
|
-
title: payload.metadata.title,
|
|
1875
|
-
fileCount,
|
|
1876
|
-
additions,
|
|
1877
|
-
deletions,
|
|
1878
|
-
status: session.status,
|
|
1879
|
-
decision: session.result?.decision,
|
|
1880
|
-
createdAt: session.createdAt,
|
|
1881
|
-
hasNewChanges: session.hasNewChanges
|
|
1882
|
-
};
|
|
1883
|
-
}
|
|
1884
|
-
function readBody(req) {
|
|
1885
|
-
return new Promise((resolve, reject) => {
|
|
1886
|
-
let body = "";
|
|
1887
|
-
req.on("data", (chunk) => {
|
|
1888
|
-
body += chunk.toString();
|
|
1889
|
-
});
|
|
1890
|
-
req.on("end", () => resolve(body));
|
|
1891
|
-
req.on("error", reject);
|
|
1892
|
-
});
|
|
1893
|
-
}
|
|
1894
|
-
function jsonResponse(res, status, data) {
|
|
1895
|
-
res.writeHead(status, { "Content-Type": "application/json" });
|
|
1896
|
-
res.end(JSON.stringify(data));
|
|
1897
|
-
}
|
|
1898
|
-
function matchRoute(method, url, expectedMethod, pattern) {
|
|
1899
|
-
if (method !== expectedMethod) return null;
|
|
1900
|
-
const patternParts = pattern.split("/");
|
|
1901
|
-
const urlParts = url.split("/");
|
|
1902
|
-
if (patternParts.length !== urlParts.length) return null;
|
|
1903
|
-
const params = {};
|
|
1904
|
-
for (let i = 0; i < patternParts.length; i++) {
|
|
1905
|
-
if (patternParts[i].startsWith(":")) {
|
|
1906
|
-
params[patternParts[i].slice(1)] = urlParts[i];
|
|
1907
|
-
} else if (patternParts[i] !== urlParts[i]) {
|
|
1908
|
-
return null;
|
|
1909
|
-
}
|
|
1910
|
-
}
|
|
1911
|
-
return params;
|
|
1912
|
-
}
|
|
1913
|
-
var wss = null;
|
|
1914
|
-
function broadcastToAll(msg) {
|
|
1915
|
-
if (!wss) return;
|
|
1916
|
-
const data = JSON.stringify(msg);
|
|
1917
|
-
for (const client of wss.clients) {
|
|
1918
|
-
if (client.readyState === WebSocket2.OPEN) {
|
|
1919
|
-
client.send(data);
|
|
1920
|
-
}
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
function sendToSessionClients(sessionId, msg) {
|
|
1924
|
-
if (!wss) return;
|
|
1925
|
-
const data = JSON.stringify(msg);
|
|
1926
|
-
for (const [client, sid] of clientSessions.entries()) {
|
|
1927
|
-
if (sid === sessionId && client.readyState === WebSocket2.OPEN) {
|
|
1928
|
-
client.send(data);
|
|
1929
|
-
}
|
|
1930
|
-
}
|
|
1931
|
-
}
|
|
1932
|
-
function broadcastSessionUpdate(session) {
|
|
1933
|
-
broadcastToAll({
|
|
1934
|
-
type: "session:updated",
|
|
1935
|
-
payload: toSummary(session)
|
|
1936
|
-
});
|
|
1937
|
-
}
|
|
1938
|
-
function broadcastSessionRemoved(sessionId) {
|
|
1939
|
-
for (const [client, sid] of clientSessions.entries()) {
|
|
1940
|
-
if (sid === sessionId) {
|
|
1941
|
-
clientSessions.delete(client);
|
|
1942
|
-
}
|
|
1943
|
-
}
|
|
1944
|
-
broadcastToAll({
|
|
1945
|
-
type: "session:removed",
|
|
1946
|
-
payload: { sessionId }
|
|
1947
|
-
});
|
|
1948
|
-
}
|
|
1949
|
-
function hasViewersForSession(sessionId) {
|
|
1950
|
-
for (const [client, sid] of clientSessions.entries()) {
|
|
1951
|
-
if (sid === sessionId && client.readyState === WebSocket2.OPEN) {
|
|
1952
|
-
return true;
|
|
1953
|
-
}
|
|
1954
|
-
}
|
|
1955
|
-
return false;
|
|
1956
|
-
}
|
|
1957
|
-
function startSessionWatcher(sessionId) {
|
|
1958
|
-
if (sessionWatchers.has(sessionId)) return;
|
|
1959
|
-
const session = sessions2.get(sessionId);
|
|
1960
|
-
if (!session?.diffRef) return;
|
|
1961
|
-
const poller = createDiffPoller({
|
|
1962
|
-
diffRef: session.diffRef,
|
|
1963
|
-
cwd: session.projectPath,
|
|
1964
|
-
pollInterval: serverPollInterval,
|
|
1965
|
-
onDiffChanged: (updatePayload) => {
|
|
1966
|
-
const s = sessions2.get(sessionId);
|
|
1967
|
-
if (!s) return;
|
|
1968
|
-
s.payload = {
|
|
1969
|
-
...s.payload,
|
|
1970
|
-
diffSet: updatePayload.diffSet,
|
|
1971
|
-
rawDiff: updatePayload.rawDiff,
|
|
1972
|
-
briefing: updatePayload.briefing
|
|
1973
|
-
};
|
|
1974
|
-
s.lastDiffHash = hashDiff(updatePayload.rawDiff);
|
|
1975
|
-
s.lastDiffSet = updatePayload.diffSet;
|
|
1976
|
-
if (hasViewersForSession(sessionId)) {
|
|
1977
|
-
sendToSessionClients(sessionId, {
|
|
1978
|
-
type: "diff:update",
|
|
1979
|
-
payload: updatePayload
|
|
1980
|
-
});
|
|
1981
|
-
s.hasNewChanges = false;
|
|
1982
|
-
} else {
|
|
1983
|
-
s.hasNewChanges = true;
|
|
1984
|
-
broadcastSessionList();
|
|
1985
|
-
}
|
|
1986
|
-
}
|
|
1987
|
-
});
|
|
1988
|
-
poller.start();
|
|
1989
|
-
sessionWatchers.set(sessionId, poller);
|
|
1990
|
-
}
|
|
1991
|
-
function stopSessionWatcher(sessionId) {
|
|
1992
|
-
const poller = sessionWatchers.get(sessionId);
|
|
1993
|
-
if (poller) {
|
|
1994
|
-
poller.stop();
|
|
1995
|
-
sessionWatchers.delete(sessionId);
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
function startAllWatchers() {
|
|
1999
|
-
for (const [id, session] of sessions2.entries()) {
|
|
2000
|
-
if (session.diffRef && !sessionWatchers.has(id)) {
|
|
2001
|
-
startSessionWatcher(id);
|
|
2002
|
-
}
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
function stopAllWatchers() {
|
|
2006
|
-
for (const [, poller] of sessionWatchers.entries()) {
|
|
2007
|
-
poller.stop();
|
|
2008
|
-
}
|
|
2009
|
-
sessionWatchers.clear();
|
|
2010
|
-
}
|
|
2011
|
-
function hasConnectedClients() {
|
|
2012
|
-
if (!wss) return false;
|
|
2013
|
-
for (const client of wss.clients) {
|
|
2014
|
-
if (client.readyState === WebSocket2.OPEN) return true;
|
|
2015
|
-
}
|
|
2016
|
-
return false;
|
|
2017
|
-
}
|
|
2018
|
-
function broadcastSessionList() {
|
|
2019
|
-
const summaries = Array.from(sessions2.values()).map(toSummary);
|
|
2020
|
-
broadcastToAll({ type: "session:list", payload: summaries });
|
|
2021
|
-
}
|
|
2022
|
-
async function handleApiRequest(req, res) {
|
|
2023
|
-
const method = req.method ?? "GET";
|
|
2024
|
-
const url = (req.url ?? "/").split("?")[0];
|
|
2025
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
2026
|
-
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
2027
|
-
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
2028
|
-
if (method === "OPTIONS") {
|
|
2029
|
-
res.writeHead(204);
|
|
2030
|
-
res.end();
|
|
2031
|
-
return true;
|
|
2032
|
-
}
|
|
2033
|
-
if (!url.startsWith("/api/")) {
|
|
2034
|
-
return false;
|
|
2035
|
-
}
|
|
2036
|
-
if (method === "GET" && url === "/api/status") {
|
|
2037
|
-
jsonResponse(res, 200, {
|
|
2038
|
-
running: true,
|
|
2039
|
-
pid: process.pid,
|
|
2040
|
-
sessions: sessions2.size,
|
|
2041
|
-
uptime: process.uptime()
|
|
2042
|
-
});
|
|
2043
|
-
return true;
|
|
2044
|
-
}
|
|
2045
|
-
if (method === "POST" && url === "/api/reviews") {
|
|
2046
|
-
try {
|
|
2047
|
-
const body = await readBody(req);
|
|
2048
|
-
const { payload, projectPath, diffRef } = JSON.parse(body);
|
|
2049
|
-
let existingSession;
|
|
2050
|
-
for (const session of sessions2.values()) {
|
|
2051
|
-
if (session.projectPath === projectPath) {
|
|
2052
|
-
existingSession = session;
|
|
2053
|
-
break;
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
if (existingSession) {
|
|
2057
|
-
const sessionId = existingSession.id;
|
|
2058
|
-
payload.reviewId = sessionId;
|
|
2059
|
-
if (diffRef) {
|
|
2060
|
-
payload.watchMode = true;
|
|
2061
|
-
}
|
|
2062
|
-
stopSessionWatcher(sessionId);
|
|
2063
|
-
existingSession.payload = payload;
|
|
2064
|
-
existingSession.status = "pending";
|
|
2065
|
-
existingSession.result = null;
|
|
2066
|
-
existingSession.createdAt = Date.now();
|
|
2067
|
-
existingSession.diffRef = diffRef;
|
|
2068
|
-
existingSession.lastDiffHash = diffRef ? hashDiff(payload.rawDiff) : void 0;
|
|
2069
|
-
existingSession.lastDiffSet = diffRef ? payload.diffSet : void 0;
|
|
2070
|
-
existingSession.hasNewChanges = false;
|
|
2071
|
-
existingSession.annotations = [];
|
|
2072
|
-
if (diffRef && hasConnectedClients()) {
|
|
2073
|
-
startSessionWatcher(sessionId);
|
|
2074
|
-
}
|
|
2075
|
-
if (hasViewersForSession(sessionId)) {
|
|
2076
|
-
sendToSessionClients(sessionId, {
|
|
2077
|
-
type: "review:init",
|
|
2078
|
-
payload
|
|
2079
|
-
});
|
|
2080
|
-
}
|
|
2081
|
-
broadcastSessionUpdate(existingSession);
|
|
2082
|
-
reopenBrowserIfNeeded?.();
|
|
2083
|
-
jsonResponse(res, 200, { sessionId });
|
|
2084
|
-
} else {
|
|
2085
|
-
const sessionId = `session-${randomUUID().slice(0, 8)}`;
|
|
2086
|
-
payload.reviewId = sessionId;
|
|
2087
|
-
if (diffRef) {
|
|
2088
|
-
payload.watchMode = true;
|
|
2089
|
-
}
|
|
2090
|
-
const session = {
|
|
2091
|
-
id: sessionId,
|
|
2092
|
-
payload,
|
|
2093
|
-
projectPath,
|
|
2094
|
-
status: "pending",
|
|
2095
|
-
createdAt: Date.now(),
|
|
2096
|
-
result: null,
|
|
2097
|
-
diffRef,
|
|
2098
|
-
lastDiffHash: diffRef ? hashDiff(payload.rawDiff) : void 0,
|
|
2099
|
-
lastDiffSet: diffRef ? payload.diffSet : void 0,
|
|
2100
|
-
hasNewChanges: false,
|
|
2101
|
-
annotations: []
|
|
2102
|
-
};
|
|
2103
|
-
sessions2.set(sessionId, session);
|
|
2104
|
-
if (diffRef && hasConnectedClients()) {
|
|
2105
|
-
startSessionWatcher(sessionId);
|
|
2106
|
-
}
|
|
2107
|
-
broadcastToAll({
|
|
2108
|
-
type: "session:added",
|
|
2109
|
-
payload: toSummary(session)
|
|
2110
|
-
});
|
|
2111
|
-
reopenBrowserIfNeeded?.();
|
|
2112
|
-
jsonResponse(res, 201, { sessionId });
|
|
2113
|
-
}
|
|
2114
|
-
} catch {
|
|
2115
|
-
jsonResponse(res, 400, { error: "Invalid request body" });
|
|
2116
|
-
}
|
|
2117
|
-
return true;
|
|
2118
|
-
}
|
|
2119
|
-
if (method === "GET" && url === "/api/reviews") {
|
|
2120
|
-
const summaries = Array.from(sessions2.values()).map(toSummary);
|
|
2121
|
-
jsonResponse(res, 200, { sessions: summaries });
|
|
2122
|
-
return true;
|
|
2123
|
-
}
|
|
2124
|
-
const getReviewParams = matchRoute(method, url, "GET", "/api/reviews/:id");
|
|
2125
|
-
if (getReviewParams) {
|
|
2126
|
-
const session = sessions2.get(getReviewParams.id);
|
|
2127
|
-
if (!session) {
|
|
2128
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2129
|
-
return true;
|
|
2130
|
-
}
|
|
2131
|
-
jsonResponse(res, 200, toSummary(session));
|
|
2132
|
-
return true;
|
|
2133
|
-
}
|
|
2134
|
-
const postResultParams = matchRoute(method, url, "POST", "/api/reviews/:id/result");
|
|
2135
|
-
if (postResultParams) {
|
|
2136
|
-
const session = sessions2.get(postResultParams.id);
|
|
2137
|
-
if (!session) {
|
|
2138
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2139
|
-
return true;
|
|
2140
|
-
}
|
|
2141
|
-
try {
|
|
2142
|
-
const body = await readBody(req);
|
|
2143
|
-
const result = JSON.parse(body);
|
|
2144
|
-
session.result = result;
|
|
2145
|
-
session.status = "submitted";
|
|
2146
|
-
if (result.decision === "dismissed") {
|
|
2147
|
-
broadcastSessionRemoved(postResultParams.id);
|
|
2148
|
-
} else {
|
|
2149
|
-
broadcastSessionUpdate(session);
|
|
2150
|
-
}
|
|
2151
|
-
jsonResponse(res, 200, { ok: true });
|
|
2152
|
-
} catch {
|
|
2153
|
-
jsonResponse(res, 400, { error: "Invalid request body" });
|
|
2154
|
-
}
|
|
2155
|
-
return true;
|
|
2156
|
-
}
|
|
2157
|
-
const getResultParams = matchRoute(method, url, "GET", "/api/reviews/:id/result");
|
|
2158
|
-
if (getResultParams) {
|
|
2159
|
-
const session = sessions2.get(getResultParams.id);
|
|
2160
|
-
if (!session) {
|
|
2161
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2162
|
-
return true;
|
|
2163
|
-
}
|
|
2164
|
-
if (session.result) {
|
|
2165
|
-
jsonResponse(res, 200, { result: session.result, status: "submitted" });
|
|
2166
|
-
} else {
|
|
2167
|
-
jsonResponse(res, 200, { result: null, status: session.status });
|
|
2168
|
-
}
|
|
2169
|
-
return true;
|
|
2170
|
-
}
|
|
2171
|
-
const postContextParams = matchRoute(method, url, "POST", "/api/reviews/:id/context");
|
|
2172
|
-
if (postContextParams) {
|
|
2173
|
-
const session = sessions2.get(postContextParams.id);
|
|
2174
|
-
if (!session) {
|
|
2175
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2176
|
-
return true;
|
|
2177
|
-
}
|
|
2178
|
-
try {
|
|
2179
|
-
const body = await readBody(req);
|
|
2180
|
-
const contextPayload = JSON.parse(body);
|
|
2181
|
-
if (contextPayload.reasoning !== void 0) {
|
|
2182
|
-
session.payload.metadata.reasoning = contextPayload.reasoning;
|
|
2183
|
-
}
|
|
2184
|
-
if (contextPayload.title !== void 0) {
|
|
2185
|
-
session.payload.metadata.title = contextPayload.title;
|
|
2186
|
-
}
|
|
2187
|
-
if (contextPayload.description !== void 0) {
|
|
2188
|
-
session.payload.metadata.description = contextPayload.description;
|
|
2189
|
-
}
|
|
2190
|
-
sendToSessionClients(session.id, {
|
|
2191
|
-
type: "context:update",
|
|
2192
|
-
payload: contextPayload
|
|
2193
|
-
});
|
|
2194
|
-
jsonResponse(res, 200, { ok: true });
|
|
2195
|
-
} catch {
|
|
2196
|
-
jsonResponse(res, 400, { error: "Invalid request body" });
|
|
2197
|
-
}
|
|
2198
|
-
return true;
|
|
2199
|
-
}
|
|
2200
|
-
const postAnnotationParams = matchRoute(method, url, "POST", "/api/reviews/:id/annotations");
|
|
2201
|
-
if (postAnnotationParams) {
|
|
2202
|
-
const session = sessions2.get(postAnnotationParams.id);
|
|
2203
|
-
if (!session) {
|
|
2204
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2205
|
-
return true;
|
|
2206
|
-
}
|
|
2207
|
-
try {
|
|
2208
|
-
const body = await readBody(req);
|
|
2209
|
-
const { file, line, body: annotationBody, type, confidence, category, source } = JSON.parse(body);
|
|
2210
|
-
const annotation = {
|
|
2211
|
-
id: randomUUID(),
|
|
2212
|
-
sessionId: session.id,
|
|
2213
|
-
file,
|
|
2214
|
-
line,
|
|
2215
|
-
body: annotationBody,
|
|
2216
|
-
type,
|
|
2217
|
-
confidence: confidence ?? 1,
|
|
2218
|
-
category: category ?? "other",
|
|
2219
|
-
source,
|
|
2220
|
-
createdAt: Date.now()
|
|
2221
|
-
};
|
|
2222
|
-
session.annotations.push(annotation);
|
|
2223
|
-
sendToSessionClients(session.id, {
|
|
2224
|
-
type: "annotation:added",
|
|
2225
|
-
payload: annotation
|
|
2226
|
-
});
|
|
2227
|
-
jsonResponse(res, 200, { annotationId: annotation.id });
|
|
2228
|
-
} catch {
|
|
2229
|
-
jsonResponse(res, 400, { error: "Invalid request body" });
|
|
2230
|
-
}
|
|
2231
|
-
return true;
|
|
2232
|
-
}
|
|
2233
|
-
const getAnnotationsParams = matchRoute(method, url, "GET", "/api/reviews/:id/annotations");
|
|
2234
|
-
if (getAnnotationsParams) {
|
|
2235
|
-
const session = sessions2.get(getAnnotationsParams.id);
|
|
2236
|
-
if (!session) {
|
|
2237
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2238
|
-
return true;
|
|
2239
|
-
}
|
|
2240
|
-
jsonResponse(res, 200, { annotations: session.annotations });
|
|
2241
|
-
return true;
|
|
2242
|
-
}
|
|
2243
|
-
const dismissAnnotationParams = matchRoute(method, url, "POST", "/api/reviews/:id/annotations/:annotationId/dismiss");
|
|
2244
|
-
if (dismissAnnotationParams) {
|
|
2245
|
-
const session = sessions2.get(dismissAnnotationParams.id);
|
|
2246
|
-
if (!session) {
|
|
2247
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2248
|
-
return true;
|
|
2249
|
-
}
|
|
2250
|
-
const annotation = session.annotations.find((a) => a.id === dismissAnnotationParams.annotationId);
|
|
2251
|
-
if (!annotation) {
|
|
2252
|
-
jsonResponse(res, 404, { error: "Annotation not found" });
|
|
2253
|
-
return true;
|
|
2254
|
-
}
|
|
2255
|
-
annotation.dismissed = true;
|
|
2256
|
-
jsonResponse(res, 200, { ok: true });
|
|
2257
|
-
return true;
|
|
2258
|
-
}
|
|
2259
|
-
const deleteParams = matchRoute(method, url, "DELETE", "/api/reviews/:id");
|
|
2260
|
-
if (deleteParams) {
|
|
2261
|
-
stopSessionWatcher(deleteParams.id);
|
|
2262
|
-
if (sessions2.delete(deleteParams.id)) {
|
|
2263
|
-
broadcastSessionRemoved(deleteParams.id);
|
|
2264
|
-
jsonResponse(res, 200, { ok: true });
|
|
2265
|
-
} else {
|
|
2266
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2267
|
-
}
|
|
2268
|
-
return true;
|
|
2269
|
-
}
|
|
2270
|
-
const getRefsParams = matchRoute(method, url, "GET", "/api/reviews/:id/refs");
|
|
2271
|
-
if (getRefsParams) {
|
|
2272
|
-
const session = sessions2.get(getRefsParams.id);
|
|
2273
|
-
if (!session) {
|
|
2274
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2275
|
-
return true;
|
|
2276
|
-
}
|
|
2277
|
-
try {
|
|
2278
|
-
const branches = listBranches({ cwd: session.projectPath });
|
|
2279
|
-
const commits = listCommits({ cwd: session.projectPath });
|
|
2280
|
-
const currentBranch = getCurrentBranch({ cwd: session.projectPath });
|
|
2281
|
-
jsonResponse(res, 200, { branches, commits, currentBranch });
|
|
2282
|
-
} catch {
|
|
2283
|
-
jsonResponse(res, 500, { error: "Failed to list git refs" });
|
|
2284
|
-
}
|
|
2285
|
-
return true;
|
|
2286
|
-
}
|
|
2287
|
-
const postCompareParams = matchRoute(method, url, "POST", "/api/reviews/:id/compare");
|
|
2288
|
-
if (postCompareParams) {
|
|
2289
|
-
const session = sessions2.get(postCompareParams.id);
|
|
2290
|
-
if (!session) {
|
|
2291
|
-
jsonResponse(res, 404, { error: "Session not found" });
|
|
2292
|
-
return true;
|
|
2293
|
-
}
|
|
2294
|
-
try {
|
|
2295
|
-
const body = await readBody(req);
|
|
2296
|
-
const { ref } = JSON.parse(body);
|
|
2297
|
-
if (!ref) {
|
|
2298
|
-
jsonResponse(res, 400, { error: "Missing ref in request body" });
|
|
2299
|
-
return true;
|
|
2300
|
-
}
|
|
2301
|
-
const { diffSet: newDiffSet, rawDiff: newRawDiff } = getDiff(ref, {
|
|
2302
|
-
cwd: session.projectPath
|
|
2303
|
-
});
|
|
2304
|
-
const newBriefing = analyze(newDiffSet);
|
|
2305
|
-
const changedFiles = detectChangedFiles(session.lastDiffSet ?? null, newDiffSet);
|
|
2306
|
-
session.payload = {
|
|
2307
|
-
...session.payload,
|
|
2308
|
-
diffSet: newDiffSet,
|
|
2309
|
-
rawDiff: newRawDiff,
|
|
2310
|
-
briefing: newBriefing
|
|
2311
|
-
};
|
|
2312
|
-
session.lastDiffHash = hashDiff(newRawDiff);
|
|
2313
|
-
session.lastDiffSet = newDiffSet;
|
|
2314
|
-
stopSessionWatcher(session.id);
|
|
2315
|
-
session.diffRef = ref;
|
|
2316
|
-
if (hasConnectedClients()) {
|
|
2317
|
-
startSessionWatcher(session.id);
|
|
2318
|
-
}
|
|
2319
|
-
sendToSessionClients(session.id, {
|
|
2320
|
-
type: "diff:update",
|
|
2321
|
-
payload: {
|
|
2322
|
-
diffSet: newDiffSet,
|
|
2323
|
-
rawDiff: newRawDiff,
|
|
2324
|
-
briefing: newBriefing,
|
|
2325
|
-
changedFiles,
|
|
2326
|
-
timestamp: Date.now()
|
|
2327
|
-
}
|
|
2328
|
-
});
|
|
2329
|
-
jsonResponse(res, 200, { ok: true, fileCount: newDiffSet.files.length });
|
|
2330
|
-
} catch {
|
|
2331
|
-
jsonResponse(res, 400, { error: "Failed to compute diff for the given ref" });
|
|
2332
|
-
}
|
|
2333
|
-
return true;
|
|
2334
|
-
}
|
|
2335
|
-
jsonResponse(res, 404, { error: "Not found" });
|
|
2336
|
-
return true;
|
|
2337
|
-
}
|
|
2338
|
-
async function startGlobalServer(options = {}) {
|
|
2339
|
-
const {
|
|
2340
|
-
httpPort: preferredHttpPort = 24680,
|
|
2341
|
-
wsPort: preferredWsPort = 24681,
|
|
2342
|
-
silent = false,
|
|
2343
|
-
dev = false,
|
|
2344
|
-
pollInterval = 2e3
|
|
2345
|
-
} = options;
|
|
2346
|
-
serverPollInterval = pollInterval;
|
|
2347
|
-
const [httpPort, wsPort] = await Promise.all([
|
|
2348
|
-
getPort3({ port: preferredHttpPort }),
|
|
2349
|
-
getPort3({ port: preferredWsPort })
|
|
2350
|
-
]);
|
|
2351
|
-
let uiPort;
|
|
2352
|
-
let uiHttpServer = null;
|
|
2353
|
-
let viteServer = null;
|
|
2354
|
-
if (dev) {
|
|
2355
|
-
uiPort = await getPort3();
|
|
2356
|
-
const uiRoot = resolveUiRoot();
|
|
2357
|
-
viteServer = await startViteDevServer(uiRoot, uiPort, silent);
|
|
2358
|
-
} else {
|
|
2359
|
-
uiPort = await getPort3();
|
|
2360
|
-
const uiDist = resolveUiDist();
|
|
2361
|
-
uiHttpServer = await createStaticServer(uiDist, uiPort);
|
|
2362
|
-
}
|
|
2363
|
-
const httpServer = http3.createServer(async (req, res) => {
|
|
2364
|
-
const handled = await handleApiRequest(req, res);
|
|
2365
|
-
if (!handled) {
|
|
2366
|
-
res.writeHead(404);
|
|
2367
|
-
res.end("Not found");
|
|
2368
|
-
}
|
|
2369
|
-
});
|
|
2370
|
-
wss = new WebSocketServer2({ port: wsPort });
|
|
2371
|
-
wss.on("connection", (ws, req) => {
|
|
2372
|
-
startAllWatchers();
|
|
2373
|
-
const url = new URL(req.url ?? "/", `http://localhost:${wsPort}`);
|
|
2374
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
2375
|
-
if (sessionId) {
|
|
2376
|
-
clientSessions.set(ws, sessionId);
|
|
2377
|
-
const session = sessions2.get(sessionId);
|
|
2378
|
-
if (session) {
|
|
2379
|
-
session.status = "in_review";
|
|
2380
|
-
session.hasNewChanges = false;
|
|
2381
|
-
broadcastSessionUpdate(session);
|
|
2382
|
-
const msg = {
|
|
2383
|
-
type: "review:init",
|
|
2384
|
-
payload: session.payload
|
|
2385
|
-
};
|
|
2386
|
-
ws.send(JSON.stringify(msg));
|
|
2387
|
-
}
|
|
2388
|
-
} else {
|
|
2389
|
-
const summaries = Array.from(sessions2.values()).map(toSummary);
|
|
2390
|
-
const msg = {
|
|
2391
|
-
type: "session:list",
|
|
2392
|
-
payload: summaries
|
|
2393
|
-
};
|
|
2394
|
-
ws.send(JSON.stringify(msg));
|
|
2395
|
-
if (summaries.length === 1) {
|
|
2396
|
-
const session = sessions2.get(summaries[0].id);
|
|
2397
|
-
if (session) {
|
|
2398
|
-
clientSessions.set(ws, session.id);
|
|
2399
|
-
session.status = "in_review";
|
|
2400
|
-
session.hasNewChanges = false;
|
|
2401
|
-
broadcastSessionUpdate(session);
|
|
2402
|
-
ws.send(JSON.stringify({
|
|
2403
|
-
type: "review:init",
|
|
2404
|
-
payload: session.payload
|
|
2405
|
-
}));
|
|
2406
|
-
}
|
|
2407
|
-
}
|
|
2408
|
-
}
|
|
2409
|
-
ws.on("message", (data) => {
|
|
2410
|
-
try {
|
|
2411
|
-
const msg = JSON.parse(data.toString());
|
|
2412
|
-
if (msg.type === "review:submit") {
|
|
2413
|
-
const sid = clientSessions.get(ws);
|
|
2414
|
-
if (sid) {
|
|
2415
|
-
const session = sessions2.get(sid);
|
|
2416
|
-
if (session) {
|
|
2417
|
-
session.result = msg.payload;
|
|
2418
|
-
session.status = "submitted";
|
|
2419
|
-
if (msg.payload.decision === "dismissed") {
|
|
2420
|
-
broadcastSessionRemoved(sid);
|
|
2421
|
-
} else {
|
|
2422
|
-
broadcastSessionUpdate(session);
|
|
2423
|
-
}
|
|
2424
|
-
}
|
|
2425
|
-
}
|
|
2426
|
-
} else if (msg.type === "session:select") {
|
|
2427
|
-
const session = sessions2.get(msg.payload.sessionId);
|
|
2428
|
-
if (session) {
|
|
2429
|
-
clientSessions.set(ws, session.id);
|
|
2430
|
-
session.status = "in_review";
|
|
2431
|
-
session.hasNewChanges = false;
|
|
2432
|
-
startSessionWatcher(session.id);
|
|
2433
|
-
broadcastSessionUpdate(session);
|
|
2434
|
-
ws.send(JSON.stringify({
|
|
2435
|
-
type: "review:init",
|
|
2436
|
-
payload: session.payload
|
|
2437
|
-
}));
|
|
2438
|
-
}
|
|
2439
|
-
} else if (msg.type === "session:close") {
|
|
2440
|
-
const closedId = msg.payload.sessionId;
|
|
2441
|
-
stopSessionWatcher(closedId);
|
|
2442
|
-
const closedSession = sessions2.get(closedId);
|
|
2443
|
-
if (closedSession && !closedSession.result) {
|
|
2444
|
-
closedSession.result = { decision: "dismissed", comments: [] };
|
|
2445
|
-
closedSession.status = "submitted";
|
|
2446
|
-
}
|
|
2447
|
-
broadcastSessionRemoved(closedId);
|
|
2448
|
-
} else if (msg.type === "diff:change_ref") {
|
|
2449
|
-
const sid = clientSessions.get(ws);
|
|
2450
|
-
if (sid) {
|
|
2451
|
-
const session = sessions2.get(sid);
|
|
2452
|
-
if (session) {
|
|
2453
|
-
const newRef = msg.payload.diffRef;
|
|
2454
|
-
try {
|
|
2455
|
-
const { diffSet: newDiffSet, rawDiff: newRawDiff } = getDiff(newRef, {
|
|
2456
|
-
cwd: session.projectPath
|
|
2457
|
-
});
|
|
2458
|
-
const newBriefing = analyze(newDiffSet);
|
|
2459
|
-
session.payload = {
|
|
2460
|
-
...session.payload,
|
|
2461
|
-
diffSet: newDiffSet,
|
|
2462
|
-
rawDiff: newRawDiff,
|
|
2463
|
-
briefing: newBriefing
|
|
2464
|
-
};
|
|
2465
|
-
session.diffRef = newRef;
|
|
2466
|
-
session.lastDiffHash = hashDiff(newRawDiff);
|
|
2467
|
-
session.lastDiffSet = newDiffSet;
|
|
2468
|
-
stopSessionWatcher(sid);
|
|
2469
|
-
startSessionWatcher(sid);
|
|
2470
|
-
sendToSessionClients(sid, {
|
|
2471
|
-
type: "diff:update",
|
|
2472
|
-
payload: {
|
|
2473
|
-
diffSet: newDiffSet,
|
|
2474
|
-
rawDiff: newRawDiff,
|
|
2475
|
-
briefing: newBriefing,
|
|
2476
|
-
changedFiles: newDiffSet.files.map((f) => f.path),
|
|
2477
|
-
timestamp: Date.now()
|
|
2478
|
-
}
|
|
2479
|
-
});
|
|
2480
|
-
} catch (err) {
|
|
2481
|
-
const errorMsg = {
|
|
2482
|
-
type: "diff:error",
|
|
2483
|
-
payload: {
|
|
2484
|
-
error: err instanceof Error ? err.message : String(err)
|
|
2485
|
-
}
|
|
2486
|
-
};
|
|
2487
|
-
ws.send(JSON.stringify(errorMsg));
|
|
2488
|
-
}
|
|
2489
|
-
}
|
|
2490
|
-
}
|
|
2491
|
-
}
|
|
2492
|
-
} catch {
|
|
2493
|
-
}
|
|
2494
|
-
});
|
|
2495
|
-
ws.on("close", () => {
|
|
2496
|
-
clientSessions.delete(ws);
|
|
2497
|
-
if (!hasConnectedClients()) {
|
|
2498
|
-
stopAllWatchers();
|
|
2499
|
-
}
|
|
2500
|
-
});
|
|
2501
|
-
});
|
|
2502
|
-
await new Promise((resolve, reject) => {
|
|
2503
|
-
httpServer.on("error", reject);
|
|
2504
|
-
httpServer.listen(httpPort, () => resolve());
|
|
2505
|
-
});
|
|
2506
|
-
function cleanupExpiredSessions() {
|
|
2507
|
-
const now = Date.now();
|
|
2508
|
-
for (const [id, session] of sessions2.entries()) {
|
|
2509
|
-
const age = now - session.createdAt;
|
|
2510
|
-
const expired = session.status === "submitted" && age > SUBMITTED_TTL_MS || session.status === "pending" && age > ABANDONED_TTL_MS;
|
|
2511
|
-
if (expired) {
|
|
2512
|
-
stopSessionWatcher(id);
|
|
2513
|
-
sessions2.delete(id);
|
|
2514
|
-
broadcastSessionRemoved(id);
|
|
2515
|
-
}
|
|
2516
|
-
}
|
|
2517
|
-
}
|
|
2518
|
-
const cleanupTimer = setInterval(cleanupExpiredSessions, CLEANUP_INTERVAL_MS);
|
|
2519
|
-
const serverInfo = {
|
|
2520
|
-
httpPort,
|
|
2521
|
-
wsPort,
|
|
2522
|
-
pid: process.pid,
|
|
2523
|
-
startedAt: Date.now()
|
|
2524
|
-
};
|
|
2525
|
-
writeServerFile(serverInfo);
|
|
2526
|
-
if (!silent) {
|
|
2527
|
-
console.log(`
|
|
2528
|
-
DiffPrism Global Server`);
|
|
2529
|
-
console.log(` API: http://localhost:${httpPort}`);
|
|
2530
|
-
console.log(` WS: ws://localhost:${wsPort}`);
|
|
2531
|
-
console.log(` UI: http://localhost:${uiPort}`);
|
|
2532
|
-
console.log(` PID: ${process.pid}`);
|
|
2533
|
-
console.log(`
|
|
2534
|
-
Waiting for reviews...
|
|
2535
|
-
`);
|
|
2536
|
-
}
|
|
2537
|
-
const uiUrl = `http://localhost:${uiPort}?wsPort=${wsPort}&httpPort=${httpPort}&serverMode=true`;
|
|
2538
|
-
await open3(uiUrl);
|
|
2539
|
-
reopenBrowserIfNeeded = () => {
|
|
2540
|
-
if (!hasConnectedClients()) {
|
|
2541
|
-
open3(uiUrl);
|
|
2542
|
-
}
|
|
2543
|
-
};
|
|
2544
|
-
async function stop() {
|
|
2545
|
-
clearInterval(cleanupTimer);
|
|
2546
|
-
stopAllWatchers();
|
|
2547
|
-
if (wss) {
|
|
2548
|
-
for (const client of wss.clients) {
|
|
2549
|
-
client.close();
|
|
2550
|
-
}
|
|
2551
|
-
wss.close();
|
|
2552
|
-
wss = null;
|
|
2553
|
-
}
|
|
2554
|
-
clientSessions.clear();
|
|
2555
|
-
sessions2.clear();
|
|
2556
|
-
reopenBrowserIfNeeded = null;
|
|
2557
|
-
await new Promise((resolve) => {
|
|
2558
|
-
httpServer.close(() => resolve());
|
|
2559
|
-
});
|
|
2560
|
-
if (viteServer) {
|
|
2561
|
-
await viteServer.close();
|
|
2562
|
-
}
|
|
2563
|
-
if (uiHttpServer) {
|
|
2564
|
-
uiHttpServer.close();
|
|
2565
|
-
}
|
|
2566
|
-
removeServerFile();
|
|
2567
|
-
}
|
|
2568
|
-
return { httpPort, wsPort, stop };
|
|
2569
|
-
}
|
|
2570
|
-
|
|
2571
|
-
// packages/core/src/review-history.ts
|
|
2572
|
-
import fs4 from "fs";
|
|
2573
|
-
import path6 from "path";
|
|
2574
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
2575
|
-
|
|
2576
|
-
export {
|
|
2577
|
-
getCurrentBranch,
|
|
2578
|
-
detectWorktree,
|
|
2579
|
-
getDiff,
|
|
2580
|
-
analyze,
|
|
2581
|
-
readWatchFile,
|
|
2582
|
-
readReviewResult,
|
|
2583
|
-
consumeReviewResult,
|
|
2584
|
-
startReview,
|
|
2585
|
-
startWatch,
|
|
2586
|
-
readServerFile,
|
|
2587
|
-
isServerAlive,
|
|
2588
|
-
startGlobalServer
|
|
2589
|
-
};
|