diffing 0.2.0 → 0.2.1

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.
Files changed (92) hide show
  1. package/README.md +28 -4
  2. package/dist/cli-agent-BLPX3oOP.mjs +443 -0
  3. package/dist/cli-agent-BNwY5lZE.mjs +446 -0
  4. package/dist/cli-agent-CbzXDSSF.mjs +446 -0
  5. package/dist/cli-agent-DsqbS3n7.mjs +443 -0
  6. package/dist/cli-agent-ZAkixf4c.mjs +446 -0
  7. package/dist/cli.mjs +539 -33
  8. package/dist/client/assets/{angular-html-fdYbuxHF.js → angular-html-DsssUIMZ.js} +1 -1
  9. package/dist/client/assets/{angular-ts-D3iFqR-R.js → angular-ts-dTg-sJ77.js} +1 -1
  10. package/dist/client/assets/{apl-MnBV-iQN.js → apl-C1yUKbqz.js} +1 -1
  11. package/dist/client/assets/{astro-BrpK01E7.js → astro-BI07ha2y.js} +1 -1
  12. package/dist/client/assets/{blade-CGmyBuwD.js → blade-DkzUGffS.js} +1 -1
  13. package/dist/client/assets/{c-xQnwtG9Y.js → c-KkuqqOvW.js} +1 -1
  14. package/dist/client/assets/{cobol-ypVzOIQu.js → cobol-DRh7-jLi.js} +1 -1
  15. package/dist/client/assets/{coffee-CrtE1uj2.js → coffee-wR_ZAh9a.js} +1 -1
  16. package/dist/client/assets/{cpp-DLd4XEKA.js → cpp-OD_qyywn.js} +1 -1
  17. package/dist/client/assets/{crystal-CJYvpLt_.js → crystal-E4ahAddE.js} +1 -1
  18. package/dist/client/assets/{css-DrX2B9os.js → css-2NgE_uxz.js} +1 -1
  19. package/dist/client/assets/{edge-BsQYk9OW.js → edge-8mbscxxD.js} +1 -1
  20. package/dist/client/assets/{elixir-DU_VfGYR.js → elixir-CJv1b3Q6.js} +1 -1
  21. package/dist/client/assets/{elm-W4eOLEDv.js → elm-DUPzqZ9H.js} +1 -1
  22. package/dist/client/assets/{erb-D9FdIJ2e.js → erb-ssvEF26z.js} +1 -1
  23. package/dist/client/assets/{git-rebase-BtPCXjbS.js → git-rebase-DiWIK1Oa.js} +1 -1
  24. package/dist/client/assets/{glimmer-js-BVfUGMUb.js → glimmer-js-DrHg6AuA.js} +1 -1
  25. package/dist/client/assets/{glimmer-ts-BZEaHDZL.js → glimmer-ts-wQSGOa8A.js} +1 -1
  26. package/dist/client/assets/{glsl-CSiNDuwt.js → glsl-OY27QGY0.js} +1 -1
  27. package/dist/client/assets/{graphql-Crf08Rhb.js → graphql-CSWSqe6f.js} +1 -1
  28. package/dist/client/assets/{hack-DUiQuO20.js → hack-Bi1v624Q.js} +1 -1
  29. package/dist/client/assets/{haml-BtvVTDRG.js → haml-CX94zV9m.js} +1 -1
  30. package/dist/client/assets/{handlebars-Bu_cdZA_.js → handlebars-C1j6wnjG.js} +1 -1
  31. package/dist/client/assets/{html-C4cun3zD.js → html-BcAjMlB7.js} +1 -1
  32. package/dist/client/assets/{html-derivative-CQnD80KV.js → html-derivative-DcEpOzdx.js} +1 -1
  33. package/dist/client/assets/{http-DuOJF9Kg.js → http-BBxxSc6S.js} +1 -1
  34. package/dist/client/assets/{hurl-DgrdYsYh.js → hurl-CpKRNTz4.js} +1 -1
  35. package/dist/client/assets/{index-CZZd7iTh.js → index-Bwv7BWUp.js} +156 -84
  36. package/dist/client/assets/index-CoZyJYkw.css +1 -0
  37. package/dist/client/assets/{java-D-vtFiv8.js → java-CFUlLvAA.js} +1 -1
  38. package/dist/client/assets/{javascript-CFYFXvdN.js → javascript-C-HnT3sE.js} +1 -1
  39. package/dist/client/assets/{jinja-fZvIg2_s.js → jinja-CPU8RwNP.js} +1 -1
  40. package/dist/client/assets/{jison-DEzxLq5g.js → jison-CW0TBQOs.js} +1 -1
  41. package/dist/client/assets/{json-QM4VBqMC.js → json-qUjlNuEJ.js} +1 -1
  42. package/dist/client/assets/{jsx-DLzUM_cC.js → jsx-KWeo60kf.js} +1 -1
  43. package/dist/client/assets/{julia-Dwt1SIpn.js → julia-CnJB8y2e.js} +1 -1
  44. package/dist/client/assets/{just-Dwp-hLcL.js → just-Do22d9PP.js} +1 -1
  45. package/dist/client/assets/{latex-CMF1JViz.js → latex-CCPgzvKn.js} +1 -1
  46. package/dist/client/assets/{liquid-czkpOZWY.js → liquid-B9btdZoI.js} +1 -1
  47. package/dist/client/assets/{lua-DE5PD0Vh.js → lua-IFRifurW.js} +1 -1
  48. package/dist/client/assets/{marko-DHeEvZiW.js → marko-CCaVBFq1.js} +1 -1
  49. package/dist/client/assets/{mdc-B941liUQ.js → mdc-BtbnOLUc.js} +1 -1
  50. package/dist/client/assets/{nginx-Pb9t8c-r.js → nginx-BkbFZHVt.js} +1 -1
  51. package/dist/client/assets/{nim-MMUvW_R1.js → nim-2uCd5j65.js} +1 -1
  52. package/dist/client/assets/{perl-DXwXRmuC.js → perl-C4ixqSNT.js} +1 -1
  53. package/dist/client/assets/{php-D42kv59r.js → php-DJ8WOtcI.js} +1 -1
  54. package/dist/client/assets/{pug-v0iesski.js → pug-BOaafhT5.js} +1 -1
  55. package/dist/client/assets/{qml-spxQQ-ei.js → qml-CURE-1y4.js} +1 -1
  56. package/dist/client/assets/{r-CobWTBG9.js → r-CPWmgzo3.js} +1 -1
  57. package/dist/client/assets/{razor-B-_Ww3MB.js → razor-DH83VP_d.js} +1 -1
  58. package/dist/client/assets/{regexp-BJMVs8R0.js → regexp-BXVWi-t_.js} +1 -1
  59. package/dist/client/assets/{rst-BHcaWsY0.js → rst-Bbxxs6E2.js} +1 -1
  60. package/dist/client/assets/{ruby-BCMT6kog.js → ruby-C-TuWES4.js} +1 -1
  61. package/dist/client/assets/{sas-DHfZnd3R.js → sas-njzNYNOq.js} +1 -1
  62. package/dist/client/assets/{scss-DjDsJvDO.js → scss-D2i6rHB8.js} +1 -1
  63. package/dist/client/assets/{shellscript-B6qaIiU-.js → shellscript-D6Bxi40C.js} +1 -1
  64. package/dist/client/assets/{shellsession-ByCeir2b.js → shellsession-Defxq-I6.js} +1 -1
  65. package/dist/client/assets/{soy-C6WpnMSF.js → soy-D0GKXrtT.js} +1 -1
  66. package/dist/client/assets/{sql-BIvSNLV_.js → sql-BRW_ADkU.js} +1 -1
  67. package/dist/client/assets/{stata-PG9iZ--I.js → stata-w7w59F48.js} +1 -1
  68. package/dist/client/assets/{surrealql-CmvCzG09.js → surrealql-O-lLuqz7.js} +1 -1
  69. package/dist/client/assets/{svelte-ChumG88s.js → svelte-DN3DR5-t.js} +1 -1
  70. package/dist/client/assets/{templ-CmzuRY_a.js → templ-CJ2JFoia.js} +1 -1
  71. package/dist/client/assets/{tex-DL8t-_eJ.js → tex-CpWrf5g9.js} +1 -1
  72. package/dist/client/assets/{ts-tags-BFfE0Egm.js → ts-tags-CZ6Af6Pe.js} +1 -1
  73. package/dist/client/assets/{tsx-C1bFyHcE.js → tsx-gIUSpRih.js} +1 -1
  74. package/dist/client/assets/{twig-DkIluZEQ.js → twig-DwZINhmw.js} +1 -1
  75. package/dist/client/assets/{typescript-Gc86Bc3j.js → typescript-Dj2aMECR.js} +1 -1
  76. package/dist/client/assets/{vue-C88JmL53.js → vue-B5K0aWrP.js} +1 -1
  77. package/dist/client/assets/{vue-html-Cry4aksC.js → vue-html-DKGgrypd.js} +1 -1
  78. package/dist/client/assets/{vue-vine-zlDkA3Ui.js → vue-vine-B5iDYTCh.js} +1 -1
  79. package/dist/client/assets/{xml-NvwpIFDy.js → xml-CbTzxfc-.js} +1 -1
  80. package/dist/client/assets/{xsl-CDjXvY9w.js → xsl-Dj-Be6nx.js} +1 -1
  81. package/dist/client/assets/{yaml-Bh-LPjcH.js → yaml-rTK8uEjh.js} +1 -1
  82. package/dist/client/index.html +2 -5
  83. package/dist/mcp-CE77qfjx.mjs +254 -0
  84. package/dist/mcp-CFeE13n-.mjs +254 -0
  85. package/dist/mcp-SGCrfYGo.mjs +254 -0
  86. package/dist/server-lock-B4crz9-_.mjs +708 -0
  87. package/dist/server-lock-DpCrvL-Z.mjs +714 -0
  88. package/dist/update-check-DJuFE9w6.mjs +128 -0
  89. package/dist/update-check-DSC02MWQ.mjs +129 -0
  90. package/dist/update-check-KL-2sGxE.mjs +129 -0
  91. package/package.json +12 -14
  92. package/dist/client/assets/index-CkC-EvWo.css +0 -1
@@ -0,0 +1,708 @@
1
+ import { basename, isAbsolute, join, resolve } from "node:path";
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { promisify } from "node:util";
4
+ import { execFile, execFileSync } from "node:child_process";
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { createHash } from "node:crypto";
8
+ import { parseSync } from "editorconfig";
9
+ //#region src/lib/path.ts
10
+ function decodeAndNormalize(p) {
11
+ let decoded = p;
12
+ try {
13
+ decoded = decodeURIComponent(p);
14
+ } catch {}
15
+ return decoded.replace(/\\/g, "/");
16
+ }
17
+ function isSafePath(relativePath, baseDir) {
18
+ const normalized = decodeAndNormalize(relativePath);
19
+ if (normalized.includes("..") || normalized.includes("\0") || isAbsolute(normalized)) return false;
20
+ const resolved = resolve(baseDir, normalized);
21
+ return resolved.startsWith(resolve(baseDir) + "/") || resolved === resolve(baseDir);
22
+ }
23
+ //#endregion
24
+ //#region src/lib/git.ts
25
+ const execFileAsync = promisify(execFile);
26
+ function isBinaryFile(absolutePath) {
27
+ try {
28
+ const buffer = readFileSync(absolutePath);
29
+ const bytesToCheck = Math.min(buffer.length, 8192);
30
+ for (let i = 0; i < bytesToCheck; i++) if (buffer[i] === 0) return true;
31
+ return false;
32
+ } catch {
33
+ return true;
34
+ }
35
+ }
36
+ function getFileContent(filePath, version) {
37
+ const root = getRepoRoot();
38
+ if (!isSafePath(filePath, root)) return null;
39
+ const resolved = resolve(root, filePath);
40
+ if (version === "new") try {
41
+ return readFileSync(resolved);
42
+ } catch {
43
+ return null;
44
+ }
45
+ try {
46
+ return execFileSync("git", ["show", `HEAD:${filePath}`], {
47
+ stdio: "pipe",
48
+ maxBuffer: 50 * 1024 * 1024
49
+ });
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ let cachedRepoRoot = null;
55
+ const editorConfigCache = /* @__PURE__ */ new Map();
56
+ function isGitRepo() {
57
+ try {
58
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { stdio: "pipe" });
59
+ return true;
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+ function getRepoRoot() {
65
+ if (cachedRepoRoot !== null) return cachedRepoRoot;
66
+ cachedRepoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf-8" }).trim();
67
+ return cachedRepoRoot;
68
+ }
69
+ function getRepoName() {
70
+ return basename(getRepoRoot());
71
+ }
72
+ function getBranchName() {
73
+ try {
74
+ return execFileSync("git", [
75
+ "rev-parse",
76
+ "--abbrev-ref",
77
+ "HEAD"
78
+ ], {
79
+ stdio: "pipe",
80
+ encoding: "utf-8"
81
+ }).trim();
82
+ } catch {
83
+ return "";
84
+ }
85
+ }
86
+ const DIFF_FLAGS = ["--no-ext-diff", "--no-color"];
87
+ function getTabSizeForFiles(filePaths) {
88
+ const root = getRepoRoot();
89
+ const result = {};
90
+ for (const filePath of filePaths) try {
91
+ const config = parseSync(join(root, filePath), { cache: editorConfigCache });
92
+ const size = config.tab_width ?? (config.indent_size === "tab" ? void 0 : config.indent_size);
93
+ if (typeof size === "number") result[filePath] = size;
94
+ } catch {}
95
+ return result;
96
+ }
97
+ async function getRepoRootAsync() {
98
+ if (cachedRepoRoot !== null) return cachedRepoRoot;
99
+ try {
100
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf-8" });
101
+ cachedRepoRoot = stdout.trim();
102
+ return cachedRepoRoot;
103
+ } catch {
104
+ return "";
105
+ }
106
+ }
107
+ async function getUntrackedFilePathsAsync() {
108
+ try {
109
+ const { stdout } = await execFileAsync("git", [
110
+ "ls-files",
111
+ "--others",
112
+ "--exclude-standard"
113
+ ], {
114
+ encoding: "utf-8",
115
+ maxBuffer: 50 * 1024 * 1024
116
+ });
117
+ const trimmed = stdout.trim();
118
+ return trimmed ? trimmed.split("\n") : [];
119
+ } catch {
120
+ return [];
121
+ }
122
+ }
123
+ async function getUntrackedFilesDiffAsync() {
124
+ const root = await getRepoRootAsync();
125
+ const filePaths = await getUntrackedFilePathsAsync();
126
+ if (filePaths.length === 0) return "";
127
+ const patches = [];
128
+ const fileDiffPromises = filePaths.map(async (file) => {
129
+ const absolutePath = join(root, file);
130
+ if (isBinaryFile(absolutePath)) return [
131
+ `diff --git a/${file} b/${file}`,
132
+ "new file mode 100644",
133
+ "index 0000000..0000001",
134
+ `Binary files /dev/null and b/${file} differ`
135
+ ].join("\n");
136
+ else try {
137
+ const lines = (await readFile(absolutePath, "utf-8")).split("\n");
138
+ const diffLines = lines.map((l) => `+${l}`);
139
+ return [
140
+ `diff --git a/${file} b/${file}`,
141
+ "new file mode 100644",
142
+ "index 0000000..0000001",
143
+ "--- /dev/null",
144
+ `+++ b/${file}`,
145
+ `@@ -0,0 +1,${lines.length} @@`,
146
+ ...diffLines
147
+ ].join("\n");
148
+ } catch {
149
+ return "";
150
+ }
151
+ });
152
+ const results = await Promise.all(fileDiffPromises);
153
+ for (const r of results) if (r) patches.push(r);
154
+ return patches.length > 0 ? "\n" + patches.join("\n") : "";
155
+ }
156
+ async function getCustomGitDiffAsync(args) {
157
+ try {
158
+ const { stdout } = await execFileAsync("git", [
159
+ "diff",
160
+ ...DIFF_FLAGS,
161
+ ...args
162
+ ], {
163
+ encoding: "utf-8",
164
+ maxBuffer: 50 * 1024 * 1024
165
+ });
166
+ return stdout;
167
+ } catch {
168
+ return "";
169
+ }
170
+ }
171
+ async function getGitDiffAsync(options = {}) {
172
+ const unstagedPromise = execFileAsync("git", ["diff", ...DIFF_FLAGS], {
173
+ encoding: "utf-8",
174
+ maxBuffer: 50 * 1024 * 1024
175
+ }).then(({ stdout }) => stdout).catch(() => "");
176
+ const stagedPromise = options.staged ? execFileAsync("git", [
177
+ "diff",
178
+ ...DIFF_FLAGS,
179
+ "--staged"
180
+ ], {
181
+ encoding: "utf-8",
182
+ maxBuffer: 50 * 1024 * 1024
183
+ }).then(({ stdout }) => stdout).catch(() => "") : Promise.resolve("");
184
+ const untrackedPromise = options.untracked ? getUntrackedFilesDiffAsync() : Promise.resolve("");
185
+ const [unstaged, staged, untrackedPatch] = await Promise.all([
186
+ unstagedPromise,
187
+ stagedPromise,
188
+ untrackedPromise
189
+ ]);
190
+ const parts = [];
191
+ if (unstaged) parts.push(unstaged);
192
+ if (staged) parts.push(staged);
193
+ if (untrackedPatch) parts.push(untrackedPatch);
194
+ return parts.join("\n");
195
+ }
196
+ /**
197
+ * Lists every file the working tree knows about (tracked + untracked,
198
+ * excluding standard-ignored paths). Used by the Phase D file viewer to
199
+ * power a path picker.
200
+ */
201
+ function listRepoFiles() {
202
+ try {
203
+ const tracked = execFileSync("git", ["ls-files"], {
204
+ encoding: "utf-8",
205
+ maxBuffer: 100 * 1024 * 1024
206
+ }).trim();
207
+ const untracked = execFileSync("git", [
208
+ "ls-files",
209
+ "--others",
210
+ "--exclude-standard"
211
+ ], {
212
+ encoding: "utf-8",
213
+ maxBuffer: 100 * 1024 * 1024
214
+ }).trim();
215
+ const set = /* @__PURE__ */ new Set();
216
+ for (const list of [tracked, untracked]) {
217
+ if (!list) continue;
218
+ for (const line of list.split("\n")) if (line) set.add(line);
219
+ }
220
+ return [...set].sort();
221
+ } catch {
222
+ return [];
223
+ }
224
+ }
225
+ /**
226
+ * Reports whether the repo is currently in the middle of a merge and which
227
+ * files have unresolved conflicts. Used by the Phase C merge-conflict UI to
228
+ * decide when to render the @pierre/diffs UnresolvedFile component.
229
+ */
230
+ function getMergeStatus() {
231
+ let root;
232
+ try {
233
+ root = getRepoRoot();
234
+ } catch {
235
+ return {
236
+ inMerge: false,
237
+ conflicts: []
238
+ };
239
+ }
240
+ const mergeHead = join(root, ".git", "MERGE_HEAD");
241
+ let inMerge = false;
242
+ try {
243
+ readFileSync(mergeHead);
244
+ inMerge = true;
245
+ } catch {
246
+ inMerge = false;
247
+ }
248
+ let conflicts = [];
249
+ try {
250
+ const out = execFileSync("git", [
251
+ "diff",
252
+ "--name-only",
253
+ "--diff-filter=U"
254
+ ], {
255
+ encoding: "utf-8",
256
+ maxBuffer: 50 * 1024 * 1024
257
+ }).trim();
258
+ conflicts = out ? out.split("\n") : [];
259
+ } catch {
260
+ conflicts = [];
261
+ }
262
+ return {
263
+ inMerge: inMerge || conflicts.length > 0,
264
+ conflicts
265
+ };
266
+ }
267
+ function gitAddFile(filePath) {
268
+ execFileSync("git", [
269
+ "add",
270
+ "--",
271
+ filePath
272
+ ], { stdio: "pipe" });
273
+ }
274
+ /**
275
+ * Returns a unified diff for a single working-tree file (covers unstaged
276
+ * and untracked changes). Used by the Phase E hunk-revert flow to derive
277
+ * the exact patch text we need to `git apply --reverse`.
278
+ */
279
+ function getFilePatch(filePath) {
280
+ try {
281
+ const unstaged = execFileSync("git", [
282
+ "diff",
283
+ ...DIFF_FLAGS,
284
+ "--",
285
+ filePath
286
+ ], {
287
+ encoding: "utf-8",
288
+ maxBuffer: 50 * 1024 * 1024
289
+ });
290
+ if (unstaged) return unstaged;
291
+ } catch {}
292
+ try {
293
+ const absolutePath = join(getRepoRoot(), filePath);
294
+ if (isBinaryFile(absolutePath)) return "";
295
+ const lines = readFileSync(absolutePath, "utf-8").split("\n");
296
+ return [
297
+ `diff --git a/${filePath} b/${filePath}`,
298
+ "new file mode 100644",
299
+ "index 0000000..0000001",
300
+ "--- /dev/null",
301
+ `+++ b/${filePath}`,
302
+ `@@ -0,0 +1,${lines.length} @@`,
303
+ ...lines.map((l) => `+${l}`)
304
+ ].join("\n");
305
+ } catch {
306
+ return "";
307
+ }
308
+ }
309
+ /**
310
+ * Extracts the Nth hunk text from a single-file patch. Returns the lines
311
+ * from `@@ ... @@` through the line before the next `@@` (or EOF).
312
+ */
313
+ function extractHunk(patch, hunkIndex) {
314
+ const lines = patch.split("\n");
315
+ const hunkStarts = [];
316
+ for (let i = 0; i < lines.length; i++) if (lines[i].startsWith("@@ ")) hunkStarts.push(i);
317
+ if (hunkIndex < 0 || hunkIndex >= hunkStarts.length) return null;
318
+ const start = hunkStarts[hunkIndex];
319
+ const end = hunkIndex + 1 < hunkStarts.length ? hunkStarts[hunkIndex + 1] : lines.length;
320
+ return lines.slice(start, end).join("\n");
321
+ }
322
+ /** Header lines that the per-file patch needs in order for `git apply` to
323
+ * recognize the target. Stops just before the first `@@` hunk header. */
324
+ function extractPatchHeader(patch) {
325
+ const lines = patch.split("\n");
326
+ const out = [];
327
+ for (const line of lines) {
328
+ if (line.startsWith("@@ ")) break;
329
+ out.push(line);
330
+ }
331
+ return out.join("\n");
332
+ }
333
+ /**
334
+ * Reverts a single hunk from the working tree by piping a minimal patch to
335
+ * `git apply --reverse`. Throws if git rejects the apply (typically because
336
+ * the file has shifted since the diff was rendered).
337
+ */
338
+ function revertHunk(filePath, hunkIndex) {
339
+ const patch = getFilePatch(filePath);
340
+ if (!patch) throw new Error("No diff available for this file");
341
+ const header = extractPatchHeader(patch);
342
+ const hunk = extractHunk(patch, hunkIndex);
343
+ if (!hunk) throw new Error(`Hunk ${hunkIndex} not found`);
344
+ execFileSync("git", [
345
+ "apply",
346
+ "--reverse",
347
+ "-"
348
+ ], {
349
+ input: `${header}\n${hunk}\n`,
350
+ stdio: [
351
+ "pipe",
352
+ "pipe",
353
+ "pipe"
354
+ ]
355
+ });
356
+ }
357
+ function getProjectStorageDir(customRepoRoot) {
358
+ const root = customRepoRoot || getRepoRoot();
359
+ const hash = createHash("sha256").update(root).digest("hex").slice(0, 8);
360
+ const repoName = basename(root);
361
+ return join(homedir(), ".diffing", `${repoName}-${hash}`);
362
+ }
363
+ /**
364
+ * Retrieves git blame for deleted lines and recent log history for the file,
365
+ * providing context on what commit introduced the deleted code.
366
+ */
367
+ function getHunkHistory(filePath, deletionStart, deletionCount, revision = "HEAD") {
368
+ if (!isSafePath(filePath, getRepoRoot())) throw new Error("Forbidden file path");
369
+ const blame = [];
370
+ if (deletionCount > 0) try {
371
+ const lines = execFileSync("git", [
372
+ "blame",
373
+ "--date=format:%Y-%m-%d",
374
+ "-L",
375
+ `${deletionStart},+${deletionCount}`,
376
+ revision,
377
+ "--",
378
+ filePath
379
+ ], {
380
+ encoding: "utf-8",
381
+ maxBuffer: 10 * 1024 * 1024
382
+ }).split("\n");
383
+ const commitHashes = /* @__PURE__ */ new Set();
384
+ for (const line of lines) {
385
+ if (!line.trim()) continue;
386
+ const match = line.match(/^(\^?[0-9a-fA-F]+) \((.*?) (\d{4}-\d{2}-\d{2}) (\d+)\)(?: (.*))?$/);
387
+ if (match) {
388
+ const [_, commit, author, date, lineNum, content] = match;
389
+ const cleanCommit = commit.startsWith("^") ? commit.slice(1) : commit;
390
+ blame.push({
391
+ commit: cleanCommit,
392
+ author: author.trim(),
393
+ date,
394
+ line: parseInt(lineNum, 10),
395
+ content: content || "",
396
+ summary: ""
397
+ });
398
+ commitHashes.add(cleanCommit);
399
+ }
400
+ }
401
+ const commitSummaries = {};
402
+ for (const hash of commitHashes) try {
403
+ commitSummaries[hash] = execFileSync("git", [
404
+ "show",
405
+ "-s",
406
+ "--format=%s",
407
+ hash
408
+ ], { encoding: "utf-8" }).trim();
409
+ } catch {
410
+ commitSummaries[hash] = "Unknown commit";
411
+ }
412
+ for (const entry of blame) entry.summary = commitSummaries[entry.commit] || "Unknown commit";
413
+ } catch (err) {
414
+ console.warn("Failed to get git blame for hunk history:", err.message);
415
+ }
416
+ const recentCommits = [];
417
+ try {
418
+ const logOut = execFileSync("git", [
419
+ "log",
420
+ "-n",
421
+ "5",
422
+ "--date=format:%Y-%m-%d",
423
+ "--format=%h|%an|%ad|%s",
424
+ "--",
425
+ filePath
426
+ ], { encoding: "utf-8" });
427
+ for (const line of logOut.split("\n")) {
428
+ if (!line.trim()) continue;
429
+ const [hash, author, date, summary] = line.split("|");
430
+ if (hash && author && date && summary) recentCommits.push({
431
+ hash,
432
+ author: author.trim(),
433
+ date,
434
+ summary: summary.trim()
435
+ });
436
+ }
437
+ } catch (err) {
438
+ console.warn("Failed to get git log for hunk history:", err.message);
439
+ }
440
+ return {
441
+ blame,
442
+ recentCommits
443
+ };
444
+ }
445
+ //#endregion
446
+ //#region src/lib/comment-format.ts
447
+ /** Plain-language guidance the agent should act on, derived from the verdict. */
448
+ function reviewDecisionSummary(decision) {
449
+ switch (decision) {
450
+ case "approved": return "The reviewer APPROVED these changes. Address any open comments below, then proceed — the overall direction is good.";
451
+ case "changes-requested": return "The reviewer REQUESTED EDITS. Address every open comment below and apply the requested changes before considering this review done.";
452
+ case "rejected": return "The reviewer REJECTED these changes. Do NOT keep building on this approach; reconsider it in light of the comments below before continuing.";
453
+ }
454
+ }
455
+ /**
456
+ * Render review comments as the `<code-review-comments>` XML envelope used to
457
+ * hand a review to an AI agent. Shared by the UI clipboard button
458
+ * (`useComments.formatAllComments`), the server's `/api/review/send` handoff,
459
+ * and the `diffing` CLI/MCP so every channel emits byte-identical output.
460
+ *
461
+ * A review may carry a headline `decision` (approve / request edits / reject)
462
+ * and/or an overall comment, so the envelope is emitted even with zero inline
463
+ * comments — letting a reviewer submit a verdict without annotating any line.
464
+ */
465
+ function formatComments(comments, generalComment, decision) {
466
+ const trimmedGeneral = generalComment?.trim();
467
+ if (comments.length === 0 && !decision && !trimmedGeneral) return "";
468
+ const grouped = /* @__PURE__ */ new Map();
469
+ for (const comment of comments) {
470
+ const list = grouped.get(comment.filePath) ?? [];
471
+ list.push(comment);
472
+ grouped.set(comment.filePath, list);
473
+ }
474
+ const lines = [];
475
+ lines.push(decision ? `<code-review-comments decision="${decision}">` : "<code-review-comments>");
476
+ lines.push(" <instructions>");
477
+ lines.push(" You are an AI coding assistant. You are receiving a structured list of code review comments to address in the repository.");
478
+ lines.push(" For each file, review the inline comments and apply the changes requested.");
479
+ if (decision) {
480
+ lines.push(" - The \"decision\" attribute on the root element is the reviewer's headline verdict: \"approved\", \"changes-requested\", or \"rejected\".");
481
+ lines.push(" - <decision-summary> tells you, in plain language, what to do next based on that verdict.");
482
+ }
483
+ lines.push(" - Target lines are specified by the \"line\" attribute (e.g. line=\"10\" or line=\"10-15\").");
484
+ lines.push(" - \"side\" indicates whether the comment is on \"additions\" (added/modified lines) or \"deletions\" (deleted/old lines).");
485
+ lines.push(" - \"status\" indicates whether the comment is \"open\" or \"resolved\". Only address comments with status=\"open\".");
486
+ lines.push(" - The <code> block contains the specific code context at the reviewed lines, prefixed with \"+\" or \"-\".");
487
+ lines.push(" - The <body> tag contains the review feedback or request.");
488
+ lines.push(" - If developers have replied to the comment, their discussion is captured under the <replies> element.");
489
+ lines.push(" - The comment \"id\" attribute can be used to reference or update the comment via API if available.");
490
+ lines.push("");
491
+ lines.push(" HOW TO REPLY OR ASK FOR CLARIFICATION:");
492
+ lines.push(" If you need to ask for clarification, explain what you did, or reply to any comment:");
493
+ lines.push("");
494
+ lines.push(" Option A: Via the diffing CLI or MCP (Preferred — port-agnostic, no copy-paste)");
495
+ lines.push(" diffing reply <comment-id> --body \"Your response\" --model \"<your-model-name>\"");
496
+ lines.push(" diffing resolve <comment-id>");
497
+ lines.push(" (Or the equivalent MCP tools: reply_to_comment, resolve_comment.)");
498
+ lines.push("");
499
+ lines.push(" Option B: Via the local HTTP API (if you know the running port)");
500
+ lines.push(" POST http://localhost:<port>/api/comments/<comment-id>/replies");
501
+ lines.push(" Payload: { \"body\": \"Your response or clarification request here\", \"model\": \"<your-model-name>\" }");
502
+ lines.push(" PUT http://localhost:<port>/api/comments/<comment-id> Payload: { \"status\": \"resolved\" }");
503
+ lines.push("");
504
+ lines.push(" Option C: Via Text Response (Offline / Chat Copy-Paste)");
505
+ lines.push(" If you do not have local API access, output your comments/replies inside a structured XML block at the end of your response:");
506
+ lines.push(" <comment-replies>");
507
+ lines.push(" <reply to=\"<comment-id>\" model=\"<your-model-name>\"><![CDATA[Your reply or clarification request here]]></reply>");
508
+ lines.push(" </comment-replies>");
509
+ lines.push(" </instructions>");
510
+ if (decision) lines.push(` <decision-summary><![CDATA[${reviewDecisionSummary(decision)}]]></decision-summary>`);
511
+ if (trimmedGeneral) {
512
+ lines.push(" <general-comment>");
513
+ lines.push(` <![CDATA[${trimmedGeneral}]]>`);
514
+ lines.push(" </general-comment>");
515
+ }
516
+ for (const [filePath, fileComments] of grouped) {
517
+ lines.push(` <file path="${filePath}">`);
518
+ for (const comment of fileComments) {
519
+ const lineAttr = comment.lineNumber === 0 ? "file" : comment.startLineNumber && comment.startLineNumber !== comment.lineNumber ? `${comment.startLineNumber}-${comment.lineNumber}` : `${comment.lineNumber}`;
520
+ const isoDate = new Date(comment.createdAt).toISOString();
521
+ lines.push(` <comment id="${comment.id}" line="${lineAttr}" side="${comment.side}" status="${comment.status}" created-at="${isoDate}">`);
522
+ if (comment.lineNumber !== 0) {
523
+ const prefix = comment.side === "additions" ? "+" : "-";
524
+ const isMultiLine = comment.lineContent && comment.lineContent.includes("\n");
525
+ let codeVal = "";
526
+ if (isMultiLine) codeVal = `\n${comment.lineContent.split("\n").map((l) => `${prefix} ${l}`).join("\n")}\n`;
527
+ else codeVal = `${prefix} ${comment.lineContent}`;
528
+ lines.push(` <code><![CDATA[${codeVal}]]></code>`);
529
+ }
530
+ lines.push(` <body><![CDATA[${comment.body}]]></body>`);
531
+ if (comment.replies && comment.replies.length > 0) {
532
+ lines.push(" <replies>");
533
+ for (const reply of comment.replies) {
534
+ const replyIsoDate = new Date(reply.createdAt).toISOString();
535
+ const roleAttr = reply.role ? ` role="${reply.role}"` : " role=\"agent\"";
536
+ const modelAttr = reply.model ? ` model="${reply.model}"` : "";
537
+ lines.push(` <reply id="${reply.id}" created-at="${replyIsoDate}"${roleAttr}${modelAttr}>`);
538
+ lines.push(` <![CDATA[${reply.body}]]>`);
539
+ lines.push(" </reply>");
540
+ }
541
+ lines.push(" </replies>");
542
+ }
543
+ lines.push(" </comment>");
544
+ }
545
+ lines.push(" </file>");
546
+ }
547
+ lines.push("</code-review-comments>");
548
+ return lines.join("\n");
549
+ }
550
+ //#endregion
551
+ //#region src/lib/plan-format.ts
552
+ /**
553
+ * Serialize a reviewed plan into the `<plan-review>` XML envelope handed back to
554
+ * a waiting agent. The diff-review counterpart is {@link formatComments}; this
555
+ * keeps the two handoffs structurally consistent so an agent learns one shape.
556
+ *
557
+ * Shared by the server's `/api/plan-review/await` handoff, the `diffing plan`
558
+ * CLI, and the MCP server so every channel emits byte-identical output.
559
+ */
560
+ function escapeAttr(value) {
561
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
562
+ }
563
+ /** Human-readable guidance the agent should act on, derived from the verdict. */
564
+ function decisionSummary(decision) {
565
+ switch (decision) {
566
+ case "approved": return "The reviewer APPROVED this plan. Proceed with implementation exactly as described, taking any inline comments into account.";
567
+ case "rejected": return "The reviewer REJECTED this plan. Do NOT proceed. Reconsider the approach based on the comments; only continue once a new plan is approved.";
568
+ case "changes-requested": return "The reviewer REQUESTED CHANGES. Revise the plan to address every open comment below, then resubmit the updated plan for re-review (do not start implementation yet).";
569
+ default: return "This plan has not been decided yet. Wait for the reviewer to approve, reject, or request changes.";
570
+ }
571
+ }
572
+ /**
573
+ * Resolve the line label for a plan comment: `plan` for whole-plan notes,
574
+ * `12-15` for a multi-line selection, otherwise the single line number.
575
+ */
576
+ function lineLabel(comment) {
577
+ if (comment.lineNumber === 0) return "plan";
578
+ if (comment.startLineNumber && comment.startLineNumber !== comment.lineNumber) return `${comment.startLineNumber}-${comment.lineNumber}`;
579
+ return `${comment.lineNumber}`;
580
+ }
581
+ function formatPlanReview(plan) {
582
+ const lines = [];
583
+ lines.push("<plan-review>");
584
+ lines.push(" <instructions>");
585
+ lines.push(" You are an AI coding assistant receiving a human review of a plan you submitted.");
586
+ lines.push(" - The \"decision\" attribute is the headline verdict: \"approved\", \"rejected\", \"changes-requested\", or \"pending\".");
587
+ lines.push(" - <decision-summary> tells you, in plain language, what to do next based on that verdict.");
588
+ lines.push(" - <decision-comment> is the reviewer's overall note (may be absent).");
589
+ lines.push(" - <plan-body> is the exact markdown of the plan being reviewed. Inline comments target lines within it.");
590
+ lines.push(" - Each <comment> targets a line (\"line=42\"), a range (\"line=12-15\"), or the whole plan (\"line=plan\").");
591
+ lines.push(" \"section\" names the nearest markdown heading for context. Only address comments with status=\"open\".");
592
+ lines.push(" - <context> contains the exact plan text the comment is anchored to.");
593
+ lines.push("");
594
+ lines.push(" HOW TO RESPOND:");
595
+ lines.push(" - If approved: proceed with the work.");
596
+ lines.push(" - If changes-requested: revise the plan and resubmit it for another review round.");
597
+ lines.push(" - If rejected: stop and rethink; do not implement.");
598
+ lines.push(" Prefer the diffing CLI or MCP (port-agnostic, no copy-paste):");
599
+ lines.push(" diffing plan reply <comment-id> --body \"...\" --model \"<your-model-name>\"");
600
+ lines.push(" diffing plan resolve <comment-id>");
601
+ lines.push(" diffing plan submit <revised-plan.md> --id <plan-id> # resubmit a new version for re-review");
602
+ lines.push(" (Or the equivalent MCP tools: reply_to_plan_comment, resolve_plan_comment, submit_plan.)");
603
+ lines.push(" </instructions>");
604
+ const decidedAttr = plan.decidedAt ? ` decided-at="${new Date(plan.decidedAt).toISOString()}"` : "";
605
+ lines.push(` <plan id="${escapeAttr(plan.id)}" title="${escapeAttr(plan.title)}" version="${plan.version}" decision="${plan.decision}"${decidedAttr}>`);
606
+ lines.push(` <decision-summary><![CDATA[${decisionSummary(plan.decision)}]]></decision-summary>`);
607
+ const trimmedDecisionComment = plan.decisionComment?.trim();
608
+ if (trimmedDecisionComment) lines.push(` <decision-comment><![CDATA[${trimmedDecisionComment}]]></decision-comment>`);
609
+ lines.push(` <plan-body><![CDATA[${plan.body}]]></plan-body>`);
610
+ const comments = plan.comments ?? [];
611
+ if (comments.length > 0) {
612
+ lines.push(" <comments>");
613
+ for (const comment of comments) {
614
+ const sectionAttr = comment.sectionTitle ? ` section="${escapeAttr(comment.sectionTitle)}"` : "";
615
+ const isoDate = new Date(comment.createdAt).toISOString();
616
+ lines.push(` <comment id="${escapeAttr(comment.id)}" line="${lineLabel(comment)}"${sectionAttr} status="${comment.status}" created-at="${isoDate}">`);
617
+ if (comment.lineNumber !== 0 && comment.lineContent) lines.push(` <context><![CDATA[${comment.lineContent}]]></context>`);
618
+ lines.push(` <body><![CDATA[${comment.body}]]></body>`);
619
+ if (comment.replies && comment.replies.length > 0) {
620
+ lines.push(" <replies>");
621
+ for (const reply of comment.replies) {
622
+ const replyIsoDate = new Date(reply.createdAt).toISOString();
623
+ const roleAttr = reply.role ? ` role="${reply.role}"` : " role=\"agent\"";
624
+ const modelAttr = reply.model ? ` model="${escapeAttr(reply.model)}"` : "";
625
+ lines.push(` <reply id="${escapeAttr(reply.id)}" created-at="${replyIsoDate}"${roleAttr}${modelAttr}>`);
626
+ lines.push(` <![CDATA[${reply.body}]]>`);
627
+ lines.push(" </reply>");
628
+ }
629
+ lines.push(" </replies>");
630
+ }
631
+ lines.push(" </comment>");
632
+ }
633
+ lines.push(" </comments>");
634
+ }
635
+ lines.push(" </plan>");
636
+ lines.push("</plan-review>");
637
+ return lines.join("\n");
638
+ }
639
+ /**
640
+ * Find the nearest markdown ATX heading at or above a 1-based line, so a comment
641
+ * can record which section of the plan it belongs to. Returns the heading text
642
+ * without the leading `#`s, or undefined when the line precedes any heading.
643
+ */
644
+ function sectionTitleForLine(body, lineNumber) {
645
+ if (lineNumber < 1) return void 0;
646
+ const lines = body.split("\n");
647
+ const end = Math.min(lineNumber, lines.length);
648
+ for (let i = end - 1; i >= 0; i--) {
649
+ const match = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(lines[i]);
650
+ if (match) return match[2].trim();
651
+ }
652
+ }
653
+ /**
654
+ * Snapshot the plan text spanned by a 1-based, inclusive [start, end] line
655
+ * range, used as the `lineContent` anchor when a comment is created without one
656
+ * (e.g. posted by an agent over the API).
657
+ */
658
+ function extractPlanLines(body, startLine, endLine) {
659
+ if (startLine < 1) return "";
660
+ const lines = body.split("\n");
661
+ const from = Math.max(1, startLine);
662
+ const to = Math.min(endLine, lines.length);
663
+ if (to < from) return "";
664
+ return lines.slice(from - 1, to).join("\n");
665
+ }
666
+ //#endregion
667
+ //#region src/lib/server-lock.ts
668
+ function lockPath(repoRoot) {
669
+ return join(getProjectStorageDir(repoRoot), "server.json");
670
+ }
671
+ function writeServerLock(lock) {
672
+ const path = lockPath(lock.repoRoot);
673
+ mkdirSync(join(path, ".."), { recursive: true });
674
+ writeFileSync(path, JSON.stringify(lock, null, 2), "utf-8");
675
+ }
676
+ function readServerLock(repoRoot) {
677
+ try {
678
+ const raw = readFileSync(lockPath(repoRoot), "utf-8");
679
+ const lock = JSON.parse(raw);
680
+ if (typeof lock.port !== "number" || typeof lock.pid !== "number") return null;
681
+ return lock;
682
+ } catch {
683
+ return null;
684
+ }
685
+ }
686
+ /**
687
+ * True if the process named by the lock is still alive and the lock belongs to
688
+ * this repo. `process.kill(pid, 0)` sends no signal — it just probes existence.
689
+ */
690
+ function isLockAlive(lock) {
691
+ try {
692
+ process.kill(lock.pid, 0);
693
+ } catch {
694
+ return false;
695
+ }
696
+ try {
697
+ return lock.repoRoot === getRepoRoot();
698
+ } catch {
699
+ return true;
700
+ }
701
+ }
702
+ function removeServerLock(repoRoot) {
703
+ try {
704
+ rmSync(lockPath(repoRoot), { force: true });
705
+ } catch {}
706
+ }
707
+ //#endregion
708
+ export { revertHunk as C, listRepoFiles as S, getRepoRoot as _, extractPlanLines as a, gitAddFile as b, formatComments as c, getFileContent as d, getGitDiffAsync as f, getRepoName as g, getProjectStorageDir as h, writeServerLock as i, getBranchName as l, getMergeStatus as m, readServerLock as n, formatPlanReview as o, getHunkHistory as p, removeServerLock as r, sectionTitleForLine as s, isLockAlive as t, getCustomGitDiffAsync as u, getTabSizeForFiles as v, isSafePath as w, isGitRepo as x, getUntrackedFilePathsAsync as y };