chat2diff 0.0.0-stage → 1.3.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/cli.js ADDED
@@ -0,0 +1,3184 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server/cli.ts
4
+ import crypto5 from "crypto";
5
+ import fs9 from "fs";
6
+ import net from "net";
7
+ import path10 from "path";
8
+ import { fileURLToPath as fileURLToPath2 } from "url";
9
+ import { serve } from "@hono/node-server";
10
+ import open from "open";
11
+ import { WebSocket, WebSocketServer } from "ws";
12
+
13
+ // src/shared/constants.ts
14
+ var APP_VERSION = "1.3.0";
15
+ var DEV_SESSION_TOKEN = "chat2diff-dev-token";
16
+ var DEFAULT_PORT = 4310;
17
+ var MAX_FILE_SIZE_BYTES = 250 * 1024;
18
+ var MODEL_LIMITS = {
19
+ chatgpt: 128e3,
20
+ claude: 2e5,
21
+ gemini: 1e6
22
+ };
23
+ var TASK_PRESETS = {
24
+ bug_fix: {
25
+ label: "Fix a Bug",
26
+ shortDesc: "Find the root cause and repair broken behavior",
27
+ instruction: "Identify the root cause of the bug described below and make the cleanest minimal fix without breaking existing functionality."
28
+ },
29
+ add_feature: {
30
+ label: "Add a Feature",
31
+ shortDesc: "Build new functionality matching the existing code style",
32
+ instruction: "Implement the requested feature cleanly, matching the project architecture, naming conventions, and coding patterns."
33
+ },
34
+ improve_code: {
35
+ label: "Improve Code",
36
+ shortDesc: "Refactor for clarity, speed, or better structure",
37
+ instruction: "Refactor and improve the selected code for readability, maintainability, and performance while preserving external behavior."
38
+ },
39
+ review_code: {
40
+ label: "Review Only",
41
+ shortDesc: "Spot bugs, security risks, or edge cases",
42
+ instruction: "Review the selected code carefully for bugs, edge cases, and security issues. Only include code edits if fixing clear defects."
43
+ }
44
+ };
45
+ var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
46
+ "node_modules",
47
+ ".git",
48
+ ".chat2diff",
49
+ ".next",
50
+ ".nuxt",
51
+ ".svelte-kit",
52
+ "dist",
53
+ "build",
54
+ "out",
55
+ "coverage",
56
+ ".venv",
57
+ "venv",
58
+ "__pycache__",
59
+ ".pytest_cache",
60
+ ".mypy_cache",
61
+ ".turbo",
62
+ ".cache",
63
+ "target",
64
+ "vendor"
65
+ ]);
66
+ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
67
+ ".png",
68
+ ".jpg",
69
+ ".jpeg",
70
+ ".gif",
71
+ ".webp",
72
+ ".bmp",
73
+ ".ico",
74
+ ".tiff",
75
+ ".svg",
76
+ ".pdf",
77
+ ".zip",
78
+ ".tar",
79
+ ".gz",
80
+ ".bz2",
81
+ ".7z",
82
+ ".rar",
83
+ ".exe",
84
+ ".dll",
85
+ ".so",
86
+ ".dylib",
87
+ ".bin",
88
+ ".obj",
89
+ ".o",
90
+ ".pyc",
91
+ ".pyo",
92
+ ".class",
93
+ ".jar",
94
+ ".war",
95
+ ".apk",
96
+ ".aab",
97
+ ".onnx",
98
+ ".tflite",
99
+ ".pt",
100
+ ".pth",
101
+ ".safetensors",
102
+ ".gguf",
103
+ ".woff",
104
+ ".woff2",
105
+ ".ttf",
106
+ ".otf",
107
+ ".eot",
108
+ ".mp3",
109
+ ".wav",
110
+ ".ogg",
111
+ ".flac",
112
+ ".mp4",
113
+ ".mkv",
114
+ ".mov",
115
+ ".avi",
116
+ ".db",
117
+ ".sqlite",
118
+ ".sqlite3",
119
+ ".parquet",
120
+ ".faiss",
121
+ ".pem",
122
+ ".key",
123
+ ".p12",
124
+ ".pfx",
125
+ ".keystore",
126
+ ".jks"
127
+ ]);
128
+ var SKIP_FILENAMES = /* @__PURE__ */ new Set([
129
+ "package-lock.json",
130
+ "yarn.lock",
131
+ "pnpm-lock.yaml",
132
+ "poetry.lock",
133
+ "cargo.lock",
134
+ "uv.lock",
135
+ "composer.lock",
136
+ "bun.lockb",
137
+ ".ds_store",
138
+ "thumbs.db"
139
+ ]);
140
+ var SENSITIVE_PATCH_PATTERNS = [
141
+ ".env",
142
+ ".github/workflows",
143
+ "package.json",
144
+ "dockerfile",
145
+ "mcp_config.json",
146
+ "id_rsa",
147
+ "credentials",
148
+ "secrets"
149
+ ];
150
+ function evaluateModelFit(estimatedTokens) {
151
+ const classify = (limit) => {
152
+ if (estimatedTokens <= limit * 0.6) return "great";
153
+ if (estimatedTokens <= limit * 0.88) return "tight";
154
+ return "too_large";
155
+ };
156
+ return {
157
+ chatgpt: classify(MODEL_LIMITS.chatgpt),
158
+ claude: classify(MODEL_LIMITS.claude),
159
+ gemini: classify(MODEL_LIMITS.gemini)
160
+ };
161
+ }
162
+
163
+ // src/server/app.ts
164
+ import crypto4 from "crypto";
165
+ import fs8 from "fs";
166
+ import path9 from "path";
167
+ import { fileURLToPath } from "url";
168
+ import { Hono } from "hono";
169
+ import { z } from "zod";
170
+
171
+ // src/server/core/configStore.ts
172
+ import fs from "fs";
173
+ import os from "os";
174
+ import path from "path";
175
+ var DEFAULT_CONFIG = {
176
+ version: 1,
177
+ defaultPatchFormat: "search_replace",
178
+ clipboardWatchEnabled: true,
179
+ recentRepos: []
180
+ };
181
+ function getConfigPath() {
182
+ const baseDir = process.env.CHAT2DIFF_CONFIG_DIR || path.join(os.homedir(), ".chat2diff");
183
+ return path.join(baseDir, "config.json");
184
+ }
185
+ function loadConfig() {
186
+ const filePath = getConfigPath();
187
+ try {
188
+ if (!fs.existsSync(filePath)) return { ...DEFAULT_CONFIG, recentRepos: [] };
189
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
190
+ return {
191
+ version: 1,
192
+ defaultPatchFormat: parsed.defaultPatchFormat === "unified_diff" ? "unified_diff" : "search_replace",
193
+ clipboardWatchEnabled: parsed.clipboardWatchEnabled ?? true,
194
+ recentRepos: Array.isArray(parsed.recentRepos) ? parsed.recentRepos.slice(0, 12) : []
195
+ };
196
+ } catch {
197
+ return { ...DEFAULT_CONFIG, recentRepos: [] };
198
+ }
199
+ }
200
+ function saveConfig(config) {
201
+ const filePath = getConfigPath();
202
+ const dir = path.dirname(filePath);
203
+ try {
204
+ fs.mkdirSync(dir, { recursive: true });
205
+ const tmpPath = `${filePath}.tmp`;
206
+ fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2), "utf8");
207
+ fs.renameSync(tmpPath, filePath);
208
+ } catch {
209
+ }
210
+ }
211
+ function recordRecentRepo(repoPath) {
212
+ const config = loadConfig();
213
+ const resolved = path.resolve(repoPath);
214
+ const name = path.basename(resolved);
215
+ const filtered = config.recentRepos.filter(
216
+ (item) => item.path.toLowerCase() !== resolved.toLowerCase()
217
+ );
218
+ config.recentRepos = [
219
+ { path: resolved, name, lastOpenedAt: (/* @__PURE__ */ new Date()).toISOString() },
220
+ ...filtered
221
+ ].slice(0, 10);
222
+ saveConfig(config);
223
+ return config;
224
+ }
225
+
226
+ // src/server/core/fileClipboard.ts
227
+ import { execFile, spawn } from "child_process";
228
+ import fs2 from "fs";
229
+ import os2 from "os";
230
+ import path2 from "path";
231
+ import { pathToFileURL } from "url";
232
+ import { promisify } from "util";
233
+ var execFileAsync = promisify(execFile);
234
+ function getCacheDir() {
235
+ const baseDir = process.env.CHAT2DIFF_CONFIG_DIR || path2.join(os2.homedir(), ".chat2diff");
236
+ return path2.join(baseDir, "cache");
237
+ }
238
+ function writeSingleCacheFile(fileName, content) {
239
+ const cacheDir = getCacheDir();
240
+ fs2.mkdirSync(cacheDir, { recursive: true });
241
+ const safeName = path2.basename(fileName).replace(/[^a-zA-Z0-9._-]/g, "-") || "chat2diff-context.txt";
242
+ const targetPath = path2.join(cacheDir, safeName);
243
+ try {
244
+ for (const entry of fs2.readdirSync(cacheDir)) {
245
+ if (entry !== safeName && entry.endsWith(".txt")) {
246
+ try {
247
+ fs2.unlinkSync(path2.join(cacheDir, entry));
248
+ } catch {
249
+ }
250
+ }
251
+ }
252
+ } catch {
253
+ }
254
+ fs2.writeFileSync(targetPath, content, "utf8");
255
+ return targetPath;
256
+ }
257
+ function cleanupCacheDir() {
258
+ const cacheDir = getCacheDir();
259
+ try {
260
+ if (!fs2.existsSync(cacheDir)) return;
261
+ for (const entry of fs2.readdirSync(cacheDir)) {
262
+ if (entry.endsWith(".txt")) {
263
+ try {
264
+ fs2.unlinkSync(path2.join(cacheDir, entry));
265
+ } catch {
266
+ }
267
+ }
268
+ }
269
+ } catch {
270
+ }
271
+ }
272
+ function runPipeCommand(cmd, args, input) {
273
+ return new Promise((resolve) => {
274
+ try {
275
+ const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "ignore"] });
276
+ let settled = false;
277
+ const done = (ok) => {
278
+ if (!settled) {
279
+ settled = true;
280
+ clearTimeout(timer);
281
+ resolve(ok);
282
+ }
283
+ };
284
+ const timer = setTimeout(() => {
285
+ try {
286
+ child.kill();
287
+ } catch {
288
+ }
289
+ done(false);
290
+ }, 4500);
291
+ child.on("error", () => done(false));
292
+ child.on("close", (code) => done(code === 0));
293
+ child.stdin.on("error", () => done(false));
294
+ child.stdin.end(input, "utf8");
295
+ } catch {
296
+ resolve(false);
297
+ }
298
+ });
299
+ }
300
+ function extractShortError(err) {
301
+ if (!err || typeof err !== "object") return String(err ?? "Unknown error");
302
+ const e = err;
303
+ if (e.killed) return "PowerShell timed out while accessing clipboard.";
304
+ const raw = (e.stderr || e.message || "Unknown clipboard error").replace(/\s+/g, " ").trim();
305
+ return raw.slice(0, 180);
306
+ }
307
+ async function copyFileToClipboard(filePath) {
308
+ const resolved = path2.resolve(filePath);
309
+ if (!fs2.existsSync(resolved)) {
310
+ return { copied: false, error: "Cached context file not found on disk." };
311
+ }
312
+ if (process.platform === "win32") {
313
+ const psScript = [
314
+ "$ErrorActionPreference = 'Stop'",
315
+ "$p = $env:CHAT2DIFF_CLIP_PATH",
316
+ "try {",
317
+ " Add-Type -AssemblyName System.Windows.Forms",
318
+ " $files = New-Object System.Collections.Specialized.StringCollection",
319
+ " [void]$files.Add($p)",
320
+ " $data = New-Object System.Windows.Forms.DataObject",
321
+ " $data.SetFileDropList($files)",
322
+ " [System.Windows.Forms.Clipboard]::SetDataObject($data, $true, 10, 120)",
323
+ "} catch {",
324
+ " Set-Clipboard -LiteralPath $p",
325
+ "}"
326
+ ].join("\n");
327
+ const encoded = Buffer.from(psScript, "utf16le").toString("base64");
328
+ const psArgs = [
329
+ "-NoProfile",
330
+ "-NonInteractive",
331
+ "-ExecutionPolicy",
332
+ "Bypass",
333
+ "-STA",
334
+ "-EncodedCommand",
335
+ encoded
336
+ ];
337
+ const env = { ...process.env, CHAT2DIFF_CLIP_PATH: resolved };
338
+ const sysPs = path2.join(
339
+ process.env.SystemRoot || "C:\\Windows",
340
+ "System32",
341
+ "WindowsPowerShell",
342
+ "v1.0",
343
+ "powershell.exe"
344
+ );
345
+ const candidates = Array.from(
346
+ /* @__PURE__ */ new Set([
347
+ ...fs2.existsSync(sysPs) ? [sysPs] : [],
348
+ "powershell.exe",
349
+ "pwsh"
350
+ ])
351
+ );
352
+ let lastErr = "";
353
+ for (const bin of candidates) {
354
+ try {
355
+ await execFileAsync(bin, psArgs, {
356
+ env,
357
+ timeout: 15e3,
358
+ windowsHide: true
359
+ });
360
+ return { copied: true };
361
+ } catch (err) {
362
+ lastErr = extractShortError(err);
363
+ }
364
+ }
365
+ console.warn("[Chat2Diff] File clipboard failed:", lastErr);
366
+ return {
367
+ copied: false,
368
+ error: `Could not copy file to Windows clipboard (${lastErr}). Use Copy Path or Save .txt.`
369
+ };
370
+ }
371
+ if (process.platform === "darwin") {
372
+ try {
373
+ await execFileAsync(
374
+ "osascript",
375
+ [
376
+ "-e",
377
+ "on run argv",
378
+ "-e",
379
+ "set the clipboard to POSIX file (item 1 of argv)",
380
+ "-e",
381
+ "end run",
382
+ "--",
383
+ resolved
384
+ ],
385
+ { timeout: 6e3 }
386
+ );
387
+ return { copied: true };
388
+ } catch (err) {
389
+ return {
390
+ copied: false,
391
+ error: `Could not copy file to macOS clipboard (${extractShortError(err)}). Use Copy Path or Save .txt.`
392
+ };
393
+ }
394
+ }
395
+ const uriPayload = `${pathToFileURL(resolved).href}\r
396
+ `;
397
+ if (process.env.WAYLAND_DISPLAY) {
398
+ if (await runPipeCommand("wl-copy", ["--type", "text/uri-list"], uriPayload)) {
399
+ return { copied: true };
400
+ }
401
+ }
402
+ if (await runPipeCommand("xclip", ["-selection", "clipboard", "-t", "text/uri-list"], uriPayload)) {
403
+ return { copied: true };
404
+ }
405
+ if (await runPipeCommand("wl-copy", ["--type", "text/uri-list"], uriPayload)) {
406
+ return { copied: true };
407
+ }
408
+ return {
409
+ copied: false,
410
+ error: "Install xclip or wl-clipboard for Ctrl+V file paste, or use Copy Path / Save .txt."
411
+ };
412
+ }
413
+
414
+ // src/server/core/patchEngine.ts
415
+ import crypto from "crypto";
416
+ import fs5 from "fs";
417
+ import path6 from "path";
418
+ import { applyPatch, diffLines } from "diff";
419
+
420
+ // src/server/core/pathGuard.ts
421
+ import fs3 from "fs";
422
+ import path3 from "path";
423
+ var PathSecurityError = class extends Error {
424
+ constructor(message) {
425
+ super(message);
426
+ this.name = "PathSecurityError";
427
+ }
428
+ };
429
+ function normalizeRepoRelPath(relPath) {
430
+ return relPath.replace(/\\/g, "/").replace(/^\.\//, "").trim();
431
+ }
432
+ function resolveSafeRepoPath(repoRoot, relPath) {
433
+ const normalized = normalizeRepoRelPath(relPath);
434
+ if (!normalized) {
435
+ throw new PathSecurityError("File path cannot be empty.");
436
+ }
437
+ if (normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) {
438
+ throw new PathSecurityError(`Absolute path blocked: ${relPath}`);
439
+ }
440
+ const parts = normalized.split("/").filter(Boolean);
441
+ if (parts.includes("..") || parts[0] === ".git" || parts[0] === ".chat2diff") {
442
+ throw new PathSecurityError(`Protected or unsafe path blocked: ${relPath}`);
443
+ }
444
+ const realRoot = fs3.realpathSync(repoRoot);
445
+ const candidate = path3.resolve(realRoot, normalized);
446
+ if (candidate !== realRoot && !candidate.startsWith(realRoot + path3.sep)) {
447
+ throw new PathSecurityError(`Path escapes project folder: ${relPath}`);
448
+ }
449
+ let ancestor = fs3.existsSync(candidate) ? candidate : path3.dirname(candidate);
450
+ while (!fs3.existsSync(ancestor) && ancestor !== realRoot) {
451
+ const next = path3.dirname(ancestor);
452
+ if (next === ancestor) break;
453
+ ancestor = next;
454
+ }
455
+ const realAncestor = fs3.realpathSync(ancestor);
456
+ if (realAncestor !== realRoot && !realAncestor.startsWith(realRoot + path3.sep)) {
457
+ throw new PathSecurityError(`Symlink pointing outside project blocked: ${relPath}`);
458
+ }
459
+ return candidate;
460
+ }
461
+
462
+ // src/server/core/repoScanner.ts
463
+ import { execFileSync } from "child_process";
464
+ import fs4 from "fs";
465
+ import os3 from "os";
466
+ import path5 from "path";
467
+ import ignore from "ignore";
468
+
469
+ // src/server/core/secretGuard.ts
470
+ import path4 from "path";
471
+ var SECRET_RULES = [
472
+ { label: "Private Key Block", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g },
473
+ { label: "OpenAI / Provider API Key", regex: /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g },
474
+ { label: "Google API Key", regex: /\bAIza[0-9A-Za-z_-]{35,}\b/g },
475
+ { label: "GitHub Token", regex: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b/g },
476
+ { label: "AWS Access Key", regex: /\bAKIA[0-9A-Z]{16}\b/g },
477
+ { label: "Groq API Key", regex: /\bgsk_[A-Za-z0-9]{24,}\b/g },
478
+ { label: "Slack Token", regex: /\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g }
479
+ ];
480
+ function isSecretFilename(relPosixPath) {
481
+ const base = path4.posix.basename(relPosixPath).toLowerCase();
482
+ if (base.startsWith(".env")) {
483
+ const allowedExamples = [".env.example", ".env.sample", ".env.template"];
484
+ return !allowedExamples.includes(base);
485
+ }
486
+ return base.includes("serviceaccount") || base === "id_rsa" || base === "id_ed25519" || base.endsWith(".pem") || base.endsWith(".key");
487
+ }
488
+ function scanAndRedactSecrets(content, redact) {
489
+ let result = content;
490
+ let count = 0;
491
+ const labels = /* @__PURE__ */ new Set();
492
+ for (const rule of SECRET_RULES) {
493
+ rule.regex.lastIndex = 0;
494
+ result = result.replace(rule.regex, (match) => {
495
+ count += 1;
496
+ labels.add(rule.label);
497
+ return redact ? `{{REDACTED_SECRET_${count}}}` : match;
498
+ });
499
+ }
500
+ return {
501
+ redactedContent: result,
502
+ count,
503
+ labels: Array.from(labels)
504
+ };
505
+ }
506
+
507
+ // src/server/core/repoScanner.ts
508
+ function detectGitInfo(repoPath) {
509
+ try {
510
+ const inside = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
511
+ cwd: repoPath,
512
+ encoding: "utf8",
513
+ stdio: ["ignore", "pipe", "ignore"]
514
+ }).trim();
515
+ if (inside !== "true") return { isGitRepo: false, gitBranch: null };
516
+ let branch = null;
517
+ try {
518
+ branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
519
+ cwd: repoPath,
520
+ encoding: "utf8",
521
+ stdio: ["ignore", "pipe", "ignore"]
522
+ }).trim();
523
+ } catch {
524
+ branch = "main";
525
+ }
526
+ return { isGitRepo: true, gitBranch: branch || null };
527
+ } catch {
528
+ return { isGitRepo: false, gitBranch: null };
529
+ }
530
+ }
531
+ function isBinaryBuffer(filePath) {
532
+ let fd = null;
533
+ try {
534
+ fd = fs4.openSync(filePath, "r");
535
+ const buf = Buffer.alloc(4096);
536
+ const bytesRead = fs4.readSync(fd, buf, 0, 4096, 0);
537
+ for (let i = 0; i < bytesRead; i++) {
538
+ if (buf[i] === 0) return true;
539
+ }
540
+ return false;
541
+ } catch {
542
+ return true;
543
+ } finally {
544
+ if (fd !== null) {
545
+ try {
546
+ fs4.closeSync(fd);
547
+ } catch {
548
+ }
549
+ }
550
+ }
551
+ }
552
+ function collectFilesViaGit(repoPath) {
553
+ try {
554
+ const output = execFileSync(
555
+ "git",
556
+ ["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
557
+ {
558
+ cwd: repoPath,
559
+ encoding: "utf8",
560
+ maxBuffer: 32 * 1024 * 1024,
561
+ stdio: ["ignore", "pipe", "ignore"]
562
+ }
563
+ );
564
+ return output.split("\0").filter(Boolean).map((p) => p.replace(/\\/g, "/"));
565
+ } catch {
566
+ return null;
567
+ }
568
+ }
569
+ function collectFilesViaFs(repoPath) {
570
+ const ig = ignore();
571
+ const gitignorePath = path5.join(repoPath, ".gitignore");
572
+ if (fs4.existsSync(gitignorePath)) {
573
+ try {
574
+ ig.add(fs4.readFileSync(gitignorePath, "utf8"));
575
+ } catch {
576
+ }
577
+ }
578
+ const found = [];
579
+ function walk(currentDir, relPrefix) {
580
+ let entries;
581
+ try {
582
+ entries = fs4.readdirSync(currentDir, { withFileTypes: true });
583
+ } catch {
584
+ return;
585
+ }
586
+ for (const entry of entries) {
587
+ const relPosix = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
588
+ if (entry.isDirectory()) {
589
+ if (SKIP_DIRECTORIES.has(entry.name) || ig.ignores(`${relPosix}/`)) continue;
590
+ walk(path5.join(currentDir, entry.name), relPosix);
591
+ } else if (entry.isFile()) {
592
+ if (ig.ignores(relPosix)) continue;
593
+ found.push(relPosix);
594
+ }
595
+ }
596
+ }
597
+ walk(repoPath, "");
598
+ return found;
599
+ }
600
+ function collectChangedFilesViaGit(repoPath) {
601
+ try {
602
+ const output = execFileSync("git", ["status", "--porcelain", "-z"], {
603
+ cwd: repoPath,
604
+ encoding: "utf8",
605
+ maxBuffer: 16 * 1024 * 1024,
606
+ stdio: ["ignore", "pipe", "ignore"]
607
+ });
608
+ const tokens = output.split("\0");
609
+ const changed = [];
610
+ for (let i = 0; i < tokens.length; i++) {
611
+ const entry = tokens[i];
612
+ if (!entry || entry.length < 4) continue;
613
+ const status = entry.slice(0, 2);
614
+ const filePath = entry.slice(3).replace(/\\/g, "/");
615
+ if (filePath) changed.push(filePath);
616
+ if (status.includes("R") || status.includes("C")) {
617
+ i += 1;
618
+ }
619
+ }
620
+ return changed;
621
+ } catch {
622
+ return [];
623
+ }
624
+ }
625
+ function collectRepoFilePaths(repoPath) {
626
+ const resolvedRoot = path5.resolve(repoPath);
627
+ const rawPaths = collectFilesViaGit(resolvedRoot) ?? collectFilesViaFs(resolvedRoot);
628
+ return rawPaths.filter((relPosix) => !relPosix.split("/").some((p) => SKIP_DIRECTORIES.has(p))).sort();
629
+ }
630
+ function scanRepositoryTree(repoPath) {
631
+ const resolvedRoot = path5.resolve(repoPath);
632
+ const rawPaths = collectFilesViaGit(resolvedRoot) ?? collectFilesViaFs(resolvedRoot);
633
+ const validFileSet = /* @__PURE__ */ new Set();
634
+ let skippedSecretsCount = 0;
635
+ let skippedBinaryCount = 0;
636
+ let totalFiles = 0;
637
+ const rootChildren = [];
638
+ const dirMap = /* @__PURE__ */ new Map();
639
+ function getOrCreateDir(dirRelPath) {
640
+ const existing = dirMap.get(dirRelPath);
641
+ if (existing) return existing;
642
+ const parts = dirRelPath.split("/");
643
+ const name = parts[parts.length - 1];
644
+ const node = {
645
+ path: dirRelPath,
646
+ name,
647
+ type: "directory",
648
+ estimatedTokens: 0,
649
+ fileCount: 0,
650
+ children: []
651
+ };
652
+ dirMap.set(dirRelPath, node);
653
+ if (parts.length === 1) {
654
+ rootChildren.push(node);
655
+ } else {
656
+ const parentPath = parts.slice(0, -1).join("/");
657
+ const parent = getOrCreateDir(parentPath);
658
+ parent.children.push(node);
659
+ }
660
+ return node;
661
+ }
662
+ for (const relPosix of rawPaths.sort()) {
663
+ const parts = relPosix.split("/");
664
+ if (parts.some((p) => SKIP_DIRECTORIES.has(p))) continue;
665
+ const fullPath = path5.join(resolvedRoot, ...parts);
666
+ let stat;
667
+ try {
668
+ stat = fs4.statSync(fullPath);
669
+ if (!stat.isFile()) continue;
670
+ } catch {
671
+ continue;
672
+ }
673
+ const baseLower = parts[parts.length - 1].toLowerCase();
674
+ const extLower = path5.extname(baseLower);
675
+ if (isSecretFilename(relPosix)) {
676
+ skippedSecretsCount += 1;
677
+ continue;
678
+ }
679
+ if (SKIP_FILENAMES.has(baseLower) || SKIP_EXTENSIONS.has(extLower) || stat.size > MAX_FILE_SIZE_BYTES || isBinaryBuffer(fullPath)) {
680
+ skippedBinaryCount += 1;
681
+ continue;
682
+ }
683
+ const estimatedTokens = Math.max(1, Math.ceil(stat.size / 4));
684
+ const fileNode = {
685
+ path: relPosix,
686
+ name: parts[parts.length - 1],
687
+ type: "file",
688
+ sizeBytes: stat.size,
689
+ estimatedTokens,
690
+ fileCount: 1
691
+ };
692
+ totalFiles += 1;
693
+ validFileSet.add(relPosix);
694
+ if (parts.length === 1) {
695
+ rootChildren.push(fileNode);
696
+ } else {
697
+ const parentDir = getOrCreateDir(parts.slice(0, -1).join("/"));
698
+ parentDir.children.push(fileNode);
699
+ }
700
+ }
701
+ function finalizeNode(nodes) {
702
+ nodes.sort((a, b) => {
703
+ if (a.type !== b.type) return a.type === "directory" ? -1 : 1;
704
+ return a.name.localeCompare(b.name);
705
+ });
706
+ let totalT = 0;
707
+ let totalF = 0;
708
+ for (const node of nodes) {
709
+ if (node.type === "directory" && node.children) {
710
+ const sub = finalizeNode(node.children);
711
+ node.estimatedTokens = sub.tokens;
712
+ node.fileCount = sub.files;
713
+ }
714
+ totalT += node.estimatedTokens;
715
+ totalF += node.fileCount;
716
+ }
717
+ return { tokens: totalT, files: totalF };
718
+ }
719
+ finalizeNode(rootChildren);
720
+ const changedPaths = collectChangedFilesViaGit(resolvedRoot).filter(
721
+ (p) => validFileSet.has(p)
722
+ );
723
+ return {
724
+ rootName: path5.basename(resolvedRoot),
725
+ totalFiles,
726
+ skippedSecretsCount,
727
+ skippedBinaryCount,
728
+ changedPaths,
729
+ tree: rootChildren
730
+ };
731
+ }
732
+ function listLocalDirectories(dirInput) {
733
+ let target;
734
+ try {
735
+ target = dirInput ? path5.resolve(dirInput) : os3.homedir();
736
+ if (!fs4.existsSync(target) || !fs4.statSync(target).isDirectory()) {
737
+ target = process.cwd();
738
+ }
739
+ } catch {
740
+ target = process.cwd();
741
+ }
742
+ const parent = path5.dirname(target);
743
+ const parentPath = parent !== target ? parent : null;
744
+ let dirents = [];
745
+ try {
746
+ dirents = fs4.readdirSync(target, { withFileTypes: true });
747
+ } catch {
748
+ }
749
+ const entries = [];
750
+ for (const d of dirents) {
751
+ if (!d.isDirectory()) continue;
752
+ if (d.name.startsWith(".") || d.name === "node_modules") continue;
753
+ const full = path5.join(target, d.name);
754
+ let hasGit = false;
755
+ try {
756
+ hasGit = fs4.existsSync(path5.join(full, ".git"));
757
+ } catch {
758
+ hasGit = false;
759
+ }
760
+ entries.push({ name: d.name, path: full, isGitRepo: hasGit });
761
+ }
762
+ entries.sort((a, b) => a.name.localeCompare(b.name));
763
+ return { currentPath: target, parentPath, entries };
764
+ }
765
+
766
+ // src/server/core/patchEngine.ts
767
+ var parseCache = /* @__PURE__ */ new Map();
768
+ var CACHE_TTL_MS = 30 * 60 * 1e3;
769
+ function pruneExpiredSessions() {
770
+ const now = Date.now();
771
+ for (const [id, session] of parseCache.entries()) {
772
+ if (now - session.createdAt > CACHE_TTL_MS) {
773
+ parseCache.delete(id);
774
+ }
775
+ }
776
+ }
777
+ function getStoredParseSession(parseId) {
778
+ pruneExpiredSessions();
779
+ return parseCache.get(parseId) ?? null;
780
+ }
781
+ function sha256(text) {
782
+ return crypto.createHash("sha256").update(text, "utf8").digest("hex");
783
+ }
784
+ function normalizeEol(text) {
785
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
786
+ }
787
+ function detectSecurityWarning(relPath) {
788
+ const lower = relPath.toLowerCase();
789
+ if (SENSITIVE_PATCH_PATTERNS.some((pat) => lower.includes(pat))) {
790
+ return "Touches a configuration, dependency, or sensitive file. Review carefully.";
791
+ }
792
+ return null;
793
+ }
794
+ function countDiffStats(original, proposed) {
795
+ const parts = diffLines(original, proposed);
796
+ let additions = 0;
797
+ let deletions = 0;
798
+ for (const p of parts) {
799
+ const count = p.count ?? 0;
800
+ if (p.added) additions += count;
801
+ if (p.removed) deletions += count;
802
+ }
803
+ return { additions, deletions };
804
+ }
805
+ function readDiskFile(repoPath, relPath) {
806
+ const abs = resolveSafeRepoPath(repoPath, relPath);
807
+ if (!fs5.existsSync(abs)) {
808
+ return { exists: false, contentLf: "", hadCrlf: false, rawSha256: null };
809
+ }
810
+ const raw = fs5.readFileSync(abs, "utf8");
811
+ return {
812
+ exists: true,
813
+ contentLf: normalizeEol(raw),
814
+ hadCrlf: raw.includes("\r\n"),
815
+ rawSha256: sha256(raw)
816
+ };
817
+ }
818
+ function stripDiffPathPrefixes(rawPath, repoName) {
819
+ let p = normalizeRepoRelPath(rawPath.replace(/^["'`]+|["'`]+$/g, ""));
820
+ if (/^(?:a|b)\//.test(p)) {
821
+ p = p.slice(2);
822
+ }
823
+ const repoPrefix = `${repoName.toLowerCase()}/`;
824
+ if (p.toLowerCase().startsWith(repoPrefix)) {
825
+ const stripped = p.slice(repoPrefix.length);
826
+ if (stripped) p = stripped;
827
+ }
828
+ return normalizeRepoRelPath(p);
829
+ }
830
+ function resolveSmartRepoFilePath(repoPath, rawPath, repoFiles) {
831
+ const repoName = path6.basename(path6.resolve(repoPath));
832
+ const direct = normalizeRepoRelPath(rawPath);
833
+ const cleaned = stripDiffPathPrefixes(rawPath, repoName);
834
+ for (const candidate of [direct, cleaned]) {
835
+ if (!candidate) continue;
836
+ try {
837
+ const abs = resolveSafeRepoPath(repoPath, candidate);
838
+ if (fs5.existsSync(abs) && fs5.statSync(abs).isFile()) {
839
+ return candidate;
840
+ }
841
+ } catch {
842
+ }
843
+ }
844
+ const targetLower = cleaned.toLowerCase();
845
+ const exactCi = repoFiles.find((f) => f.toLowerCase() === targetLower);
846
+ if (exactCi) return exactCi;
847
+ if (targetLower.includes("/") || targetLower.includes(".")) {
848
+ const suffixMatches = repoFiles.filter(
849
+ (f) => f.toLowerCase().endsWith(`/${targetLower}`) || f.toLowerCase() === targetLower
850
+ );
851
+ if (suffixMatches.length === 1) {
852
+ return suffixMatches[0];
853
+ }
854
+ }
855
+ return cleaned || direct;
856
+ }
857
+ function suggestClosestPaths(repoFiles, missingPath) {
858
+ const base = path6.posix.basename(missingPath).toLowerCase();
859
+ if (!base) return [];
860
+ const sameName = repoFiles.filter((f) => path6.posix.basename(f).toLowerCase() === base);
861
+ if (sameName.length > 0) return sameName.slice(0, 3);
862
+ const stem = base.replace(/\.[^.]+$/, "");
863
+ if (stem.length < 3) return [];
864
+ return repoFiles.filter((f) => path6.posix.basename(f).toLowerCase().includes(stem)).slice(0, 3);
865
+ }
866
+ function preserveTrailingNewline(original, updated) {
867
+ if (!original) return updated;
868
+ if (original.endsWith("\n") && !updated.endsWith("\n")) return `${updated}
869
+ `;
870
+ return updated;
871
+ }
872
+ function cleanHeaderPath(raw) {
873
+ let p = raw.trim();
874
+ p = p.replace(/\s*\([^)]*\)\s*$/, "");
875
+ p = p.replace(/^[\s*`"'#>\-:]+/, "").replace(/[\s*`"'#:]+$/, "").trim();
876
+ return normalizeRepoRelPath(p);
877
+ }
878
+ function stripSurroundingCodeFence(s) {
879
+ const lines = normalizeEol(s).split("\n");
880
+ if (lines.length < 2) return normalizeEol(s);
881
+ const openMatch = /^[ \t]*(`{3,})[a-zA-Z0-9_.-]*[ \t]*$/.exec(lines[0]);
882
+ const closeMatch = /^[ \t]*(`{3,})[ \t]*$/.exec(lines[lines.length - 1]);
883
+ if (openMatch && closeMatch && closeMatch[1].length >= openMatch[1].length) {
884
+ const fenceLen = openMatch[1].length;
885
+ const hasInnerFence = lines.slice(1, -1).some((l) => new RegExp(`^[ \\t]*\`{${fenceLen},}[ \\t]*$`).test(l));
886
+ if (!hasInnerFence) {
887
+ return lines.slice(1, -1).join("\n");
888
+ }
889
+ }
890
+ return normalizeEol(s);
891
+ }
892
+ function stripEdgeBlankLines(s) {
893
+ const lines = normalizeEol(s).split("\n");
894
+ while (lines.length > 0 && lines[0].trim() === "") lines.shift();
895
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
896
+ return lines.join("\n");
897
+ }
898
+ function getMinIndent(lines) {
899
+ let minIndent = null;
900
+ for (const line of lines) {
901
+ if (line.trim() === "") continue;
902
+ const match = /^[ \t]*/.exec(line);
903
+ const indent = match ? match[0] : "";
904
+ if (minIndent === null || indent.length < minIndent.length) {
905
+ minIndent = indent;
906
+ }
907
+ }
908
+ return minIndent ?? "";
909
+ }
910
+ function adjustReplacementIndent(replaceLines, matchedDiskLines, searchLines) {
911
+ const diskIndent = getMinIndent(matchedDiskLines);
912
+ const searchIndent = getMinIndent(searchLines);
913
+ if (diskIndent === searchIndent) return replaceLines;
914
+ const diskUsesTabs = diskIndent.includes(" ");
915
+ const searchUsesTabs = searchIndent.includes(" ");
916
+ const replaceMin = getMinIndent(replaceLines);
917
+ const baseIndent = replaceMin.length < searchIndent.length && searchIndent.startsWith(replaceMin) ? replaceMin : searchIndent;
918
+ return replaceLines.map((line) => {
919
+ if (line.trim() === "") return "";
920
+ let adjusted = line;
921
+ if (baseIndent && adjusted.startsWith(baseIndent)) {
922
+ adjusted = diskIndent + adjusted.slice(baseIndent.length);
923
+ } else if (!baseIndent) {
924
+ adjusted = diskIndent + adjusted;
925
+ }
926
+ if (diskUsesTabs && !searchUsesTabs) {
927
+ adjusted = adjusted.replace(/^( +)/, (spaces) => " ".repeat(Math.round(spaces.length / 2)));
928
+ }
929
+ return adjusted;
930
+ });
931
+ }
932
+ function normalizeSearchReplaceText(rawText) {
933
+ let text = normalizeEol(rawText);
934
+ text = text.replace(/^[ \t]*(?:>[ \t]*){4,12}[ \t]*REPLACE[^\n]*/gim, ">>>>>>> REPLACE");
935
+ text = text.replace(/^[ \t]*(?:<[ \t]*){4,12}[ \t]*SEARCH[^\n]*/gim, "<<<<<<< SEARCH");
936
+ text = text.replace(/^[ \t]*(?:=[ \t]*){5,12}[ \t]*(?:REPLACE)?[ \t]*$/gim, "=======");
937
+ return text;
938
+ }
939
+ function isPlausibleRepoPath(candidate) {
940
+ if (!candidate || candidate.length > 260) return false;
941
+ if (/[<>|?*\r\n]/.test(candidate)) return false;
942
+ if (/\s{2,}/.test(candidate)) return false;
943
+ if (candidate.split(/\s+/).length > 4) return false;
944
+ return candidate.includes("/") || candidate.includes(".") || /^[A-Za-z0-9_-]{2,64}$/.test(candidate);
945
+ }
946
+ function normalizePunctuation(str) {
947
+ return str.replace(/\r\n/g, "\n").replace(/[—–―\u2013\u2014\u2015]|—|–/g, "-").replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g, '"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g, "'").replace(/[\u00A0\u2000-\u200B]/g, " ").replace(/[ \t]+/g, " ").trim();
948
+ }
949
+ function normalizePunctuationRelaxed(str) {
950
+ return normalizePunctuation(str).replace(/[`'"]/g, "").replace(/[{}]/g, "").trim();
951
+ }
952
+ function lineMatches(searchLine, contentLine) {
953
+ if (searchLine === contentLine) return true;
954
+ const sNorm = normalizePunctuation(searchLine);
955
+ const cNorm = normalizePunctuation(contentLine);
956
+ if (sNorm === cNorm) return true;
957
+ const sRel = normalizePunctuationRelaxed(searchLine);
958
+ const cRel = normalizePunctuationRelaxed(contentLine);
959
+ if (sRel.length >= 6 && sRel === cRel) return true;
960
+ return false;
961
+ }
962
+ function extractFileHeaderFromLine(line) {
963
+ const stripped = line.replace(/^[ \t]*(?:(?:\/\/|#|<!--|[-*+]|\d+\.)[ \t]*)*(?:>[ \t]*)*/, "").trim();
964
+ if (!stripped) return null;
965
+ const delMatch = /^\*{0,2}(?:DELETE FILE|REMOVE FILE)\*{0,2}\s*:\s*\*{0,2}(.+)$/i.exec(stripped);
966
+ if (delMatch) {
967
+ const p = cleanHeaderPath(delMatch[1]);
968
+ if (isPlausibleRepoPath(p)) return { kind: "delete", filePath: p };
969
+ }
970
+ const createMatch = /^\*{0,2}(?:CREATE FILE|NEW FILE)\*{0,2}\s*:\s*\*{0,2}(.+)$/i.exec(stripped);
971
+ if (createMatch) {
972
+ const p = cleanHeaderPath(createMatch[1]);
973
+ if (isPlausibleRepoPath(p)) return { kind: "create", filePath: p };
974
+ }
975
+ const fileMatch = /^\*{0,2}(?:FILE|PATH|FILENAME)\*{0,2}\s*:\s*\*{0,2}(.+)$/i.exec(stripped);
976
+ if (fileMatch) {
977
+ const p = cleanHeaderPath(fileMatch[1]);
978
+ if (isPlausibleRepoPath(p)) return { kind: "file", filePath: p };
979
+ }
980
+ return null;
981
+ }
982
+ function extractImplicitPathBeforeSearch(line) {
983
+ const cleaned = cleanHeaderPath(line.replace(/^[ \t]*(?:#+|\d+\.|[-*+])[ \t]*/, ""));
984
+ if (!cleaned || cleaned.includes(" ")) return null;
985
+ if (/^[a-zA-Z0-9_./-]+\.[a-zA-Z0-9_-]{1,10}$/.test(cleaned)) {
986
+ return cleaned;
987
+ }
988
+ return null;
989
+ }
990
+ function isDirectiveOrDiffLine(line) {
991
+ return extractFileHeaderFromLine(line) !== null || /^diff --git /i.test(line.trim()) || /^<<<<<<< SEARCH$/.test(line.trim());
992
+ }
993
+ function parseSearchReplaceOps(rawText) {
994
+ const text = normalizeSearchReplaceText(rawText);
995
+ const lines = text.split("\n");
996
+ const ops = [];
997
+ let currentFile = null;
998
+ let i = 0;
999
+ while (i < lines.length) {
1000
+ const line = lines[i];
1001
+ const header = extractFileHeaderFromLine(line);
1002
+ if (header) {
1003
+ if (header.kind === "delete") {
1004
+ ops.push({ filePath: header.filePath, kind: "delete" });
1005
+ currentFile = null;
1006
+ i++;
1007
+ continue;
1008
+ }
1009
+ if (header.kind === "create") {
1010
+ currentFile = header.filePath;
1011
+ let j = i + 1;
1012
+ while (j < lines.length && lines[j].trim() === "") j++;
1013
+ if (j < lines.length) {
1014
+ const openFence = /^[ \t]*(`{3,})[^\n]*$/.exec(lines[j]);
1015
+ if (openFence) {
1016
+ const fenceLen = openFence[1].length;
1017
+ const closeRegex = new RegExp(`^[ \\t]*\`{${fenceLen},}[ \\t]*$`);
1018
+ let lastClose = -1;
1019
+ for (let k = j + 1; k < lines.length; k++) {
1020
+ if (closeRegex.test(lines[k])) {
1021
+ lastClose = k;
1022
+ let peek = k + 1;
1023
+ while (peek < lines.length && lines[peek].trim() === "") peek++;
1024
+ if (peek >= lines.length || isDirectiveOrDiffLine(lines[peek])) {
1025
+ break;
1026
+ }
1027
+ } else if (lastClose !== -1 && isDirectiveOrDiffLine(lines[k])) {
1028
+ break;
1029
+ }
1030
+ }
1031
+ if (lastClose !== -1) {
1032
+ ops.push({
1033
+ filePath: header.filePath,
1034
+ kind: "create",
1035
+ content: lines.slice(j + 1, lastClose).join("\n")
1036
+ });
1037
+ i = lastClose + 1;
1038
+ continue;
1039
+ }
1040
+ }
1041
+ }
1042
+ i++;
1043
+ continue;
1044
+ }
1045
+ currentFile = header.filePath;
1046
+ i++;
1047
+ continue;
1048
+ }
1049
+ if (line.trim() === "<<<<<<< SEARCH") {
1050
+ if (!currentFile) {
1051
+ for (let back = i - 1; back >= Math.max(0, i - 4); back--) {
1052
+ const prev = lines[back].trim();
1053
+ if (!prev || /^`{3,}/.test(prev)) continue;
1054
+ const implicit = extractImplicitPathBeforeSearch(prev);
1055
+ if (implicit) {
1056
+ currentFile = implicit;
1057
+ }
1058
+ break;
1059
+ }
1060
+ }
1061
+ let endIdx = -1;
1062
+ for (let j = i + 1; j < lines.length; j++) {
1063
+ if (lines[j].trim() === ">>>>>>> REPLACE") {
1064
+ endIdx = j;
1065
+ break;
1066
+ }
1067
+ if (lines[j].trim() === "<<<<<<< SEARCH") {
1068
+ break;
1069
+ }
1070
+ }
1071
+ if (!currentFile) {
1072
+ i++;
1073
+ continue;
1074
+ }
1075
+ if (endIdx === -1) {
1076
+ ops.push({
1077
+ filePath: currentFile,
1078
+ kind: "malformed",
1079
+ error: "Malformed SEARCH/REPLACE block: missing >>>>>>> REPLACE closing marker (make sure the AI wraps patches in a code block)."
1080
+ });
1081
+ i++;
1082
+ continue;
1083
+ }
1084
+ const innerLines = lines.slice(i + 1, endIdx);
1085
+ const sepIdx = innerLines.findIndex((l) => l.trim() === "=======");
1086
+ let searchText = "";
1087
+ let replaceText = "";
1088
+ if (sepIdx !== -1) {
1089
+ searchText = innerLines.slice(0, sepIdx).join("\n");
1090
+ replaceText = innerLines.slice(sepIdx + 1).join("\n");
1091
+ } else {
1092
+ const innerStr = innerLines.join("\n");
1093
+ const fenceMatch = /\n[ \t]*```[a-zA-Z0-9_.-]*\n([\s\S]*?)\n[ \t]*```[ \t]*(?:\n|$)/.exec(innerStr);
1094
+ if (fenceMatch) {
1095
+ searchText = innerStr.slice(0, fenceMatch.index);
1096
+ replaceText = fenceMatch[1];
1097
+ } else {
1098
+ ops.push({
1099
+ filePath: currentFile,
1100
+ kind: "malformed",
1101
+ error: "Malformed SEARCH/REPLACE block: missing ======= separator (likely stripped by Markdown rendering outside a code block)."
1102
+ });
1103
+ i = endIdx + 1;
1104
+ continue;
1105
+ }
1106
+ }
1107
+ const cleanSearch = stripSurroundingCodeFence(searchText);
1108
+ const cleanReplace = stripSurroundingCodeFence(replaceText);
1109
+ if (cleanSearch.trim() === "" && cleanReplace.trim() !== "") {
1110
+ ops.push({ filePath: currentFile, kind: "create", content: cleanReplace });
1111
+ } else {
1112
+ ops.push({
1113
+ filePath: currentFile,
1114
+ kind: "replace",
1115
+ search: cleanSearch,
1116
+ replace: cleanReplace
1117
+ });
1118
+ }
1119
+ i = endIdx + 1;
1120
+ continue;
1121
+ }
1122
+ i++;
1123
+ }
1124
+ return ops;
1125
+ }
1126
+ function pickUniqueOrHintedIndex(indices, hintLine) {
1127
+ if (indices.length === 1) return indices[0];
1128
+ if (indices.length === 0 || hintLine === void 0) return null;
1129
+ const target = Math.max(0, hintLine - 1);
1130
+ const sorted = [...indices].sort((a, b) => Math.abs(a - target) - Math.abs(b - target));
1131
+ const bestDist = Math.abs(sorted[0] - target);
1132
+ const secondDist = Math.abs(sorted[1] - target);
1133
+ if (bestDist <= 35 && bestDist * 2 + 5 < secondDist) {
1134
+ return sorted[0];
1135
+ }
1136
+ return null;
1137
+ }
1138
+ function applySingleSearchReplace(content, search, replace, hintLine) {
1139
+ for (const [sCand, rCand] of [
1140
+ [search, replace],
1141
+ [stripEdgeBlankLines(search), stripEdgeBlankLines(replace)]
1142
+ ]) {
1143
+ if (!sCand) continue;
1144
+ const exactPositions = [];
1145
+ let pos = content.indexOf(sCand);
1146
+ while (pos !== -1) {
1147
+ exactPositions.push(pos);
1148
+ pos = content.indexOf(sCand, pos + 1);
1149
+ }
1150
+ if (exactPositions.length === 1) {
1151
+ const idx = exactPositions[0];
1152
+ return {
1153
+ ok: true,
1154
+ next: content.slice(0, idx) + rCand + content.slice(idx + sCand.length),
1155
+ note: null
1156
+ };
1157
+ }
1158
+ if (exactPositions.length > 1) {
1159
+ const lineIndices = exactPositions.map((p) => content.slice(0, p).split("\n").length - 1);
1160
+ const chosen = pickUniqueOrHintedIndex(lineIndices, hintLine);
1161
+ if (chosen !== null) {
1162
+ const chosenPos = exactPositions[lineIndices.indexOf(chosen)];
1163
+ return {
1164
+ ok: true,
1165
+ next: content.slice(0, chosenPos) + rCand + content.slice(chosenPos + sCand.length),
1166
+ note: null
1167
+ };
1168
+ }
1169
+ return {
1170
+ ok: false,
1171
+ error: "The SEARCH block matched multiple places in this file. Include 2-3 extra surrounding lines."
1172
+ };
1173
+ }
1174
+ }
1175
+ const contentLines = content.split("\n");
1176
+ const cleanSearch = stripEdgeBlankLines(search);
1177
+ const cleanReplace = stripEdgeBlankLines(replace);
1178
+ const searchLines = cleanSearch.split("\n");
1179
+ const replaceLines = cleanReplace === "" ? [] : cleanReplace.split("\n");
1180
+ const trimmedSearch = searchLines.map((l) => l.trim());
1181
+ if (trimmedSearch.length === 0 || trimmedSearch.every((l) => l === "")) {
1182
+ return { ok: false, error: "Empty SEARCH block." };
1183
+ }
1184
+ const rtrimMatches = [];
1185
+ for (let i = 0; i <= contentLines.length - searchLines.length; i++) {
1186
+ let ok = true;
1187
+ for (let j = 0; j < searchLines.length; j++) {
1188
+ if (contentLines[i + j].trimEnd() !== searchLines[j].trimEnd()) {
1189
+ ok = false;
1190
+ break;
1191
+ }
1192
+ }
1193
+ if (ok) rtrimMatches.push(i);
1194
+ }
1195
+ const rtrimStart = pickUniqueOrHintedIndex(rtrimMatches, hintLine);
1196
+ if (rtrimStart !== null) {
1197
+ const nextLines = [
1198
+ ...contentLines.slice(0, rtrimStart),
1199
+ ...replaceLines,
1200
+ ...contentLines.slice(rtrimStart + searchLines.length)
1201
+ ];
1202
+ return { ok: true, next: nextLines.join("\n"), note: null };
1203
+ }
1204
+ const matches = [];
1205
+ for (let i = 0; i <= contentLines.length - trimmedSearch.length; i++) {
1206
+ let allMatch = true;
1207
+ for (let j = 0; j < trimmedSearch.length; j++) {
1208
+ if (contentLines[i + j].trim() !== trimmedSearch[j]) {
1209
+ allMatch = false;
1210
+ break;
1211
+ }
1212
+ }
1213
+ if (allMatch) matches.push(i);
1214
+ }
1215
+ const t2Start = pickUniqueOrHintedIndex(matches, hintLine);
1216
+ if (t2Start !== null) {
1217
+ const startLine = t2Start;
1218
+ const matchedSlice = contentLines.slice(startLine, startLine + trimmedSearch.length);
1219
+ const adjustedReplace = adjustReplacementIndent(
1220
+ replaceLines,
1221
+ matchedSlice,
1222
+ searchLines
1223
+ );
1224
+ const nextLines = [
1225
+ ...contentLines.slice(0, startLine),
1226
+ ...adjustedReplace,
1227
+ ...contentLines.slice(startLine + trimmedSearch.length)
1228
+ ];
1229
+ return {
1230
+ ok: true,
1231
+ next: nextLines.join("\n"),
1232
+ note: "Auto-matched with flexible spacing"
1233
+ };
1234
+ }
1235
+ if (matches.length > 1) {
1236
+ return {
1237
+ ok: false,
1238
+ error: "Flexible match found multiple locations. Ask the AI to include more surrounding lines."
1239
+ };
1240
+ }
1241
+ const nonBlankSearch = trimmedSearch.filter((l) => l !== "");
1242
+ if (nonBlankSearch.length >= 2) {
1243
+ const nonBlankContent = [];
1244
+ for (let i = 0; i < contentLines.length; i++) {
1245
+ const t = contentLines[i].trim();
1246
+ if (t !== "") nonBlankContent.push({ lineIdx: i, text: t });
1247
+ }
1248
+ const blankTolerantWindows = [];
1249
+ for (let i = 0; i <= nonBlankContent.length - nonBlankSearch.length; i++) {
1250
+ let allOk = true;
1251
+ for (let j = 0; j < nonBlankSearch.length; j++) {
1252
+ if (nonBlankContent[i + j].text !== nonBlankSearch[j]) {
1253
+ allOk = false;
1254
+ break;
1255
+ }
1256
+ }
1257
+ if (allOk) {
1258
+ const startLine = nonBlankContent[i].lineIdx;
1259
+ const endLine = nonBlankContent[i + nonBlankSearch.length - 1].lineIdx;
1260
+ if (endLine - startLine <= searchLines.length + 5) {
1261
+ blankTolerantWindows.push({ startLine, endLine });
1262
+ }
1263
+ }
1264
+ }
1265
+ const chosenBtIdx = pickUniqueOrHintedIndex(
1266
+ blankTolerantWindows.map((w) => w.startLine),
1267
+ hintLine
1268
+ );
1269
+ if (chosenBtIdx !== null) {
1270
+ const win = blankTolerantWindows.find((w) => w.startLine === chosenBtIdx);
1271
+ const matchedSlice = contentLines.slice(win.startLine, win.endLine + 1);
1272
+ const adjustedReplace = adjustReplacementIndent(
1273
+ replaceLines,
1274
+ matchedSlice,
1275
+ searchLines
1276
+ );
1277
+ const nextLines = [
1278
+ ...contentLines.slice(0, win.startLine),
1279
+ ...adjustedReplace,
1280
+ ...contentLines.slice(win.endLine + 1)
1281
+ ];
1282
+ return {
1283
+ ok: true,
1284
+ next: nextLines.join("\n"),
1285
+ note: "Auto-matched ignoring blank-line drift"
1286
+ };
1287
+ }
1288
+ }
1289
+ const normContentLines = contentLines.map(normalizePunctuation);
1290
+ const normSearchLines = searchLines.map(normalizePunctuation);
1291
+ const t3Matches = [];
1292
+ for (let i = 0; i <= normContentLines.length - normSearchLines.length; i++) {
1293
+ let allMatch = true;
1294
+ for (let j = 0; j < normSearchLines.length; j++) {
1295
+ if (normSearchLines[j] === "") {
1296
+ if (normContentLines[i + j] !== "") {
1297
+ allMatch = false;
1298
+ break;
1299
+ }
1300
+ } else if (normContentLines[i + j] !== normSearchLines[j]) {
1301
+ allMatch = false;
1302
+ break;
1303
+ }
1304
+ }
1305
+ if (allMatch) t3Matches.push(i);
1306
+ }
1307
+ const t3Start = pickUniqueOrHintedIndex(t3Matches, hintLine);
1308
+ if (t3Start !== null) {
1309
+ const startLine = t3Start;
1310
+ const matchedSlice = contentLines.slice(startLine, startLine + normSearchLines.length);
1311
+ const adjustedReplace = adjustReplacementIndent(
1312
+ replaceLines,
1313
+ matchedSlice,
1314
+ searchLines
1315
+ );
1316
+ const nextLines = [
1317
+ ...contentLines.slice(0, startLine),
1318
+ ...adjustedReplace,
1319
+ ...contentLines.slice(startLine + normSearchLines.length)
1320
+ ];
1321
+ return {
1322
+ ok: true,
1323
+ next: nextLines.join("\n"),
1324
+ note: "Auto-matched with punctuation normalization"
1325
+ };
1326
+ }
1327
+ if (t3Matches.length > 1) {
1328
+ return {
1329
+ ok: false,
1330
+ error: "Punctuation-relaxed match found multiple locations. Ask the AI to include more surrounding lines."
1331
+ };
1332
+ }
1333
+ const nonBlankSearchLines = searchLines.map((l) => l.trim()).filter((l) => l.length > 0);
1334
+ if (nonBlankSearchLines.length >= 2) {
1335
+ const candidateWindows = [];
1336
+ for (let c = 0; c < contentLines.length; c++) {
1337
+ if (!lineMatches(nonBlankSearchLines[0], contentLines[c])) continue;
1338
+ const firstMatch = c;
1339
+ let curr = c + 1;
1340
+ let matchedCount = 1;
1341
+ let lastMatch = c;
1342
+ for (let s = 1; s < nonBlankSearchLines.length; s++) {
1343
+ let found = false;
1344
+ while (curr < contentLines.length && curr <= lastMatch + 3) {
1345
+ if (lineMatches(nonBlankSearchLines[s], contentLines[curr])) {
1346
+ found = true;
1347
+ lastMatch = curr;
1348
+ curr++;
1349
+ break;
1350
+ }
1351
+ curr++;
1352
+ }
1353
+ if (found) {
1354
+ matchedCount++;
1355
+ } else {
1356
+ break;
1357
+ }
1358
+ }
1359
+ if (matchedCount === nonBlankSearchLines.length) {
1360
+ const span = lastMatch - firstMatch + 1;
1361
+ if (span <= searchLines.length + 4) {
1362
+ candidateWindows.push({ startLine: firstMatch, endLine: lastMatch });
1363
+ }
1364
+ }
1365
+ }
1366
+ const uniqueWindows = [];
1367
+ for (const win of candidateWindows) {
1368
+ if (!uniqueWindows.some((u) => u.startLine === win.startLine && u.endLine === win.endLine)) {
1369
+ uniqueWindows.push(win);
1370
+ }
1371
+ }
1372
+ const chosenT4Start = pickUniqueOrHintedIndex(
1373
+ uniqueWindows.map((w) => w.startLine),
1374
+ hintLine
1375
+ );
1376
+ if (chosenT4Start !== null) {
1377
+ const { startLine, endLine } = uniqueWindows.find((w) => w.startLine === chosenT4Start);
1378
+ const matchedSlice = contentLines.slice(startLine, endLine + 1);
1379
+ const adjustedReplace = adjustReplacementIndent(
1380
+ replaceLines,
1381
+ matchedSlice,
1382
+ searchLines
1383
+ );
1384
+ const nextLines = [
1385
+ ...contentLines.slice(0, startLine),
1386
+ ...adjustedReplace,
1387
+ ...contentLines.slice(endLine + 1)
1388
+ ];
1389
+ return {
1390
+ ok: true,
1391
+ next: nextLines.join("\n"),
1392
+ note: "Auto-matched with flexible line alignment"
1393
+ };
1394
+ }
1395
+ if (uniqueWindows.length > 1) {
1396
+ return {
1397
+ ok: false,
1398
+ error: "Flexible match found multiple locations. Ask the AI to include more surrounding lines."
1399
+ };
1400
+ }
1401
+ }
1402
+ return {
1403
+ ok: false,
1404
+ error: "Could not find the exact SEARCH lines in your current file."
1405
+ };
1406
+ }
1407
+ function looksLikeUnifiedDiff(block) {
1408
+ return /^--- .+\n\+\+\+ .+/m.test(block) && /^@@(?: -\d+(?:,\d+)? \+\d+(?:,\d+)? )?@@/m.test(block);
1409
+ }
1410
+ function stripTrailingFences(text) {
1411
+ const lines = text.split("\n");
1412
+ while (lines.length > 0 && /^\s*`{3,}\s*$/.test(lines[lines.length - 1])) {
1413
+ lines.pop();
1414
+ }
1415
+ return lines.join("\n").trim();
1416
+ }
1417
+ function extractUnifiedDiffText(rawText) {
1418
+ let text = normalizeEol(rawText).trim();
1419
+ if (!text.includes("@@")) return null;
1420
+ text = text.replace(/^(`{3,})[ \t]*(?:diff|patch|git)?[ \t]+(diff --git |--- )/gm, "$1diff\n$2");
1421
+ const lines = text.split("\n");
1422
+ const extractedBlocks = [];
1423
+ let i = 0;
1424
+ while (i < lines.length) {
1425
+ const openMatch = /^[ \t]*(`{3,})(?:diff|patch|git|udiff)?[ \t]*$/i.exec(lines[i]);
1426
+ if (!openMatch) {
1427
+ i++;
1428
+ continue;
1429
+ }
1430
+ const fenceLen = openMatch[1].length;
1431
+ const closeRegex = new RegExp(`^[ \\t]*\`{${fenceLen},}[ \\t]*$`);
1432
+ const body = [];
1433
+ let j = i + 1;
1434
+ let closedAt = -1;
1435
+ while (j < lines.length) {
1436
+ if (closeRegex.test(lines[j])) {
1437
+ let peek = j + 1;
1438
+ while (peek < lines.length && lines[peek].trim() === "") peek++;
1439
+ const nextLine = peek < lines.length ? lines[peek] : "";
1440
+ const continuesDiff = /^(?:diff --git |--- |@@ )/.test(nextLine) && !/^[ \t]*`{3,}/.test(nextLine);
1441
+ if (!continuesDiff) {
1442
+ closedAt = j;
1443
+ break;
1444
+ }
1445
+ }
1446
+ body.push(lines[j]);
1447
+ j++;
1448
+ }
1449
+ const candidate = stripTrailingFences(body.join("\n"));
1450
+ if (looksLikeUnifiedDiff(candidate)) {
1451
+ extractedBlocks.push(candidate);
1452
+ }
1453
+ i = closedAt !== -1 ? closedAt + 1 : j;
1454
+ }
1455
+ if (extractedBlocks.length > 0) {
1456
+ return extractedBlocks.join("\n") + "\n";
1457
+ }
1458
+ if (looksLikeUnifiedDiff(text)) {
1459
+ const startMatch = /^(?:diff --git |--- )/m.exec(text);
1460
+ if (startMatch && startMatch.index !== void 0) {
1461
+ return stripTrailingFences(text.slice(startMatch.index)) + "\n";
1462
+ }
1463
+ }
1464
+ return null;
1465
+ }
1466
+ function splitUnifiedDiffByFile(diffText) {
1467
+ const lines = diffText.split("\n");
1468
+ const rawChunks = [];
1469
+ let current = [];
1470
+ const flush = () => {
1471
+ if (current.length > 0) {
1472
+ rawChunks.push(current.join("\n"));
1473
+ current = [];
1474
+ }
1475
+ };
1476
+ for (let i = 0; i < lines.length; i++) {
1477
+ const line = lines[i];
1478
+ if (line.startsWith("diff --git ")) {
1479
+ flush();
1480
+ current.push(line);
1481
+ continue;
1482
+ }
1483
+ if (line.startsWith("--- ") && i + 1 < lines.length && lines[i + 1].startsWith("+++ ") && current.some((l) => l.startsWith("@@"))) {
1484
+ flush();
1485
+ }
1486
+ current.push(line);
1487
+ }
1488
+ flush();
1489
+ const out = [];
1490
+ for (const raw of rawChunks) {
1491
+ const chunk = stripTrailingFences(raw);
1492
+ if (!looksLikeUnifiedDiff(chunk)) continue;
1493
+ let filePath = "";
1494
+ const mGit = /^diff --git a\/(.+?) b\/(.+?)$/m.exec(chunk);
1495
+ if (mGit) {
1496
+ filePath = mGit[2].replace(/^"|"$/g, "");
1497
+ } else {
1498
+ const mPlus = /^\+\+\+ (?:b\/)?([^\t\n]+)/m.exec(chunk);
1499
+ const mMinus = /^--- (?:a\/)?([^\t\n]+)/m.exec(chunk);
1500
+ if (mPlus && mPlus[1].trim() !== "/dev/null") {
1501
+ filePath = mPlus[1].trim().replace(/^"|"$/g, "");
1502
+ } else if (mMinus) {
1503
+ filePath = mMinus[1].trim().replace(/^"|"$/g, "");
1504
+ }
1505
+ }
1506
+ if (filePath) {
1507
+ out.push({ filePath: normalizeRepoRelPath(filePath), chunk: chunk + "\n" });
1508
+ }
1509
+ }
1510
+ return out;
1511
+ }
1512
+ function repairUnifiedHunkLines(diskContentLf, chunk) {
1513
+ const diskLines = diskContentLf.split("\n");
1514
+ const diskSet = new Set(diskLines);
1515
+ const diskTrimEndSet = new Set(diskLines.map((l) => l.trimEnd()));
1516
+ const lines = chunk.split("\n");
1517
+ const out = [];
1518
+ let inHunk = false;
1519
+ for (const line of lines) {
1520
+ if (/^(?:diff --git |index |--- |\+\+\+ |new file |deleted file |old mode |new mode |rename )/.test(line)) {
1521
+ inHunk = false;
1522
+ out.push(line);
1523
+ continue;
1524
+ }
1525
+ if (/^@@(?: -\d+(?:,\d+)? \+\d+(?:,\d+)? )?@@/.test(line)) {
1526
+ inHunk = true;
1527
+ out.push(line);
1528
+ continue;
1529
+ }
1530
+ if (!inHunk) {
1531
+ out.push(line);
1532
+ continue;
1533
+ }
1534
+ if (line === "") {
1535
+ out.push(" ");
1536
+ } else if (line.startsWith(" ") || line.startsWith("\\")) {
1537
+ out.push(line);
1538
+ } else if (line.startsWith("-") && !line.startsWith("--")) {
1539
+ const inDisk = diskSet.has(line) || diskTrimEndSet.has(line.trimEnd());
1540
+ const strippedInDisk = diskSet.has(line.slice(1)) || diskTrimEndSet.has(line.slice(1).trimEnd());
1541
+ if (inDisk && !strippedInDisk) {
1542
+ out.push(" " + line);
1543
+ } else {
1544
+ out.push(line);
1545
+ }
1546
+ } else if (line.startsWith("+") && !line.startsWith("++")) {
1547
+ const inDisk = diskSet.has(line) || diskTrimEndSet.has(line.trimEnd());
1548
+ const strippedInDisk = diskSet.has(line.slice(1)) || diskTrimEndSet.has(line.slice(1).trimEnd());
1549
+ if (inDisk && !strippedInDisk) {
1550
+ out.push(" " + line);
1551
+ } else {
1552
+ out.push(line);
1553
+ }
1554
+ } else if (line.startsWith("--") || line.startsWith("++")) {
1555
+ out.push(line);
1556
+ } else if (diskSet.has(line) || diskTrimEndSet.has(line.trimEnd())) {
1557
+ out.push(" " + line);
1558
+ } else {
1559
+ out.push(line);
1560
+ }
1561
+ }
1562
+ return out.join("\n");
1563
+ }
1564
+ function recountHunkHeaders(chunk) {
1565
+ const lines = chunk.split("\n");
1566
+ const out = [];
1567
+ let i = 0;
1568
+ while (i < lines.length) {
1569
+ const line = lines[i];
1570
+ const m = /^@@(?: -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?)? @@(.*)$/.exec(line);
1571
+ if (!m) {
1572
+ out.push(line);
1573
+ i++;
1574
+ continue;
1575
+ }
1576
+ const oldStart = m[1] ?? "1";
1577
+ const newStart = m[2] ?? "1";
1578
+ const suffix = m[3] ?? "";
1579
+ const hunkBody = [];
1580
+ let oldCount = 0;
1581
+ let newCount = 0;
1582
+ i++;
1583
+ while (i < lines.length && !/^@@(?: -\d+(?:,\d+)? \+\d+(?:,\d+)?)? @@/.test(lines[i]) && !lines[i].startsWith("diff --git ")) {
1584
+ const b = lines[i] === "" ? " " : lines[i];
1585
+ hunkBody.push(b);
1586
+ if (b.startsWith(" ")) {
1587
+ oldCount++;
1588
+ newCount++;
1589
+ } else if (b.startsWith("-")) {
1590
+ oldCount++;
1591
+ } else if (b.startsWith("+")) {
1592
+ newCount++;
1593
+ }
1594
+ i++;
1595
+ }
1596
+ out.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@${suffix}`);
1597
+ out.push(...hunkBody);
1598
+ }
1599
+ return out.join("\n");
1600
+ }
1601
+ function applyUnifiedHunksFallback(baseContent, chunk) {
1602
+ const lines = chunk.split("\n");
1603
+ const hunks = [];
1604
+ let current = null;
1605
+ let lineOffset = 0;
1606
+ for (const line of lines) {
1607
+ const hm = /^@@(?: -(\d+)(?:,\d+)? \+\d+(?:,\d+)?)? @@/.exec(line);
1608
+ if (hm) {
1609
+ if (current) hunks.push(current);
1610
+ current = {
1611
+ oldStart: hm[1] ? Number(hm[1]) : 1,
1612
+ search: [],
1613
+ replace: []
1614
+ };
1615
+ continue;
1616
+ }
1617
+ if (!current) continue;
1618
+ if (line.startsWith("diff --git ")) break;
1619
+ if (line.startsWith("\\ No newline")) continue;
1620
+ if (line.startsWith(" ")) {
1621
+ current.search.push(line.slice(1));
1622
+ current.replace.push(line.slice(1));
1623
+ } else if (line.startsWith("-")) {
1624
+ current.search.push(line.slice(1));
1625
+ } else if (line.startsWith("+")) {
1626
+ current.replace.push(line.slice(1));
1627
+ }
1628
+ }
1629
+ if (current) hunks.push(current);
1630
+ if (hunks.length === 0) return { ok: false };
1631
+ let working = baseContent;
1632
+ for (const hunk of hunks) {
1633
+ if (hunk.search.length === 0) {
1634
+ if (working === "") {
1635
+ working = hunk.replace.join("\n");
1636
+ continue;
1637
+ }
1638
+ return { ok: false };
1639
+ }
1640
+ const res = applySingleSearchReplace(
1641
+ working,
1642
+ hunk.search.join("\n"),
1643
+ hunk.replace.join("\n"),
1644
+ hunk.oldStart + lineOffset
1645
+ );
1646
+ if (!res.ok) return { ok: false };
1647
+ working = res.next;
1648
+ lineOffset += hunk.replace.length - hunk.search.length;
1649
+ }
1650
+ return { ok: true, content: preserveTrailingNewline(baseContent, working) };
1651
+ }
1652
+ function hasDetectablePatch(rawText) {
1653
+ if (!rawText || rawText.length < 15) return false;
1654
+ const text = normalizeEol(rawText);
1655
+ if (/(?:<[ \t]*){4,12}[ \t]*SEARCH/i.test(text) && /(?:>[ \t]*){4,12}[ \t]*REPLACE/i.test(text)) return true;
1656
+ if (/^[ \t]*(?:[#*>\s\-\/\d.]*)(?:CREATE FILE|NEW FILE|DELETE FILE|REMOVE FILE)\*{0,2}\s*:/mi.test(text)) return true;
1657
+ if (text.includes("@@") && looksLikeUnifiedDiff(text)) return true;
1658
+ return false;
1659
+ }
1660
+ function parseAndPreviewPatch(repoPath, rawText, preferredFormat = "search_replace") {
1661
+ pruneExpiredSessions();
1662
+ const srOps = parseSearchReplaceOps(rawText);
1663
+ const unifiedText = extractUnifiedDiffText(rawText);
1664
+ const unifiedChunks = unifiedText ? splitUnifiedDiffByFile(unifiedText) : [];
1665
+ if (srOps.length === 0 && unifiedChunks.length === 0) {
1666
+ return null;
1667
+ }
1668
+ const detectedFormat = srOps.length > 0 && unifiedChunks.length > 0 ? "mixed" : srOps.length > 0 ? "search_replace" : "unified_diff";
1669
+ const parseId = `prs_${crypto.randomBytes(8).toString("hex")}`;
1670
+ const files = [];
1671
+ const plans = /* @__PURE__ */ new Map();
1672
+ const handledPaths = /* @__PURE__ */ new Set();
1673
+ const repoFiles = collectRepoFilePaths(repoPath);
1674
+ const srGrouped = /* @__PURE__ */ new Map();
1675
+ for (const op of srOps) {
1676
+ const resolvedPath = op.kind === "create" ? normalizeRepoRelPath(op.filePath) : resolveSmartRepoFilePath(repoPath, op.filePath, repoFiles);
1677
+ const list = srGrouped.get(resolvedPath) ?? [];
1678
+ list.push({ ...op, filePath: resolvedPath });
1679
+ srGrouped.set(resolvedPath, list);
1680
+ }
1681
+ for (const [filePath, ops] of srGrouped.entries()) {
1682
+ handledPaths.add(filePath);
1683
+ const securityWarning = detectSecurityWarning(filePath);
1684
+ try {
1685
+ resolveSafeRepoPath(repoPath, filePath);
1686
+ } catch (err) {
1687
+ const msg = err instanceof PathSecurityError ? err.message : "Unsafe file path blocked.";
1688
+ files.push({
1689
+ filePath,
1690
+ action: "modify",
1691
+ status: "blocked",
1692
+ repairNote: null,
1693
+ securityWarning: msg,
1694
+ errorReason: msg,
1695
+ originalContent: "",
1696
+ proposedContent: "",
1697
+ additions: 0,
1698
+ deletions: 0
1699
+ });
1700
+ continue;
1701
+ }
1702
+ const disk = readDiskFile(repoPath, filePath);
1703
+ const malformedOp = ops.find((o) => o.kind === "malformed");
1704
+ if (malformedOp) {
1705
+ files.push({
1706
+ filePath,
1707
+ action: "modify",
1708
+ status: "failed",
1709
+ repairNote: null,
1710
+ securityWarning,
1711
+ errorReason: malformedOp.error ?? "Malformed SEARCH/REPLACE block.",
1712
+ originalContent: disk.contentLf,
1713
+ proposedContent: disk.contentLf,
1714
+ additions: 0,
1715
+ deletions: 0
1716
+ });
1717
+ continue;
1718
+ }
1719
+ if (ops.some((o) => o.kind === "delete")) {
1720
+ if (!disk.exists) {
1721
+ files.push({
1722
+ filePath,
1723
+ action: "delete",
1724
+ status: "failed",
1725
+ repairNote: null,
1726
+ securityWarning,
1727
+ errorReason: "File does not exist on disk.",
1728
+ originalContent: "",
1729
+ proposedContent: "",
1730
+ additions: 0,
1731
+ deletions: 0
1732
+ });
1733
+ continue;
1734
+ }
1735
+ const stats2 = countDiffStats(disk.contentLf, "");
1736
+ files.push({
1737
+ filePath,
1738
+ action: "delete",
1739
+ status: "ready",
1740
+ repairNote: null,
1741
+ securityWarning,
1742
+ errorReason: null,
1743
+ originalContent: disk.contentLf,
1744
+ proposedContent: "",
1745
+ ...stats2
1746
+ });
1747
+ plans.set(filePath, {
1748
+ filePath,
1749
+ action: "delete",
1750
+ status: "ready",
1751
+ proposedContent: "",
1752
+ expectedDiskSha256: disk.rawSha256,
1753
+ existedBefore: true,
1754
+ hadCrlf: disk.hadCrlf
1755
+ });
1756
+ continue;
1757
+ }
1758
+ const createOp = ops.find((o) => o.kind === "create");
1759
+ if (createOp) {
1760
+ const nextLf = normalizeEol(createOp.content ?? "");
1761
+ const stats2 = countDiffStats(disk.contentLf, nextLf);
1762
+ const action = disk.exists ? "modify" : "create";
1763
+ files.push({
1764
+ filePath,
1765
+ action,
1766
+ status: "ready",
1767
+ repairNote: null,
1768
+ securityWarning,
1769
+ errorReason: null,
1770
+ originalContent: disk.contentLf,
1771
+ proposedContent: nextLf,
1772
+ ...stats2
1773
+ });
1774
+ plans.set(filePath, {
1775
+ filePath,
1776
+ action,
1777
+ status: "ready",
1778
+ proposedContent: disk.hadCrlf ? nextLf.replace(/\n/g, "\r\n") : nextLf,
1779
+ expectedDiskSha256: disk.rawSha256,
1780
+ existedBefore: disk.exists,
1781
+ hadCrlf: disk.hadCrlf
1782
+ });
1783
+ continue;
1784
+ }
1785
+ if (!disk.exists) {
1786
+ const hints = suggestClosestPaths(repoFiles, filePath);
1787
+ const hintMsg = hints.length > 0 ? ` Did you mean: ${hints.join(", ")}?` : "";
1788
+ files.push({
1789
+ filePath,
1790
+ action: "modify",
1791
+ status: "failed",
1792
+ repairNote: null,
1793
+ securityWarning,
1794
+ errorReason: `File not found in your project.${hintMsg} Use CREATE FILE for brand-new files.`,
1795
+ originalContent: "",
1796
+ proposedContent: "",
1797
+ additions: 0,
1798
+ deletions: 0
1799
+ });
1800
+ continue;
1801
+ }
1802
+ let working = disk.contentLf;
1803
+ const repairNotes = /* @__PURE__ */ new Set();
1804
+ let failedReason = null;
1805
+ for (let idx = 0; idx < ops.length; idx++) {
1806
+ const op = ops[idx];
1807
+ const applied = applySingleSearchReplace(working, op.search ?? "", op.replace ?? "");
1808
+ if (!applied.ok) {
1809
+ const previewLine = (op.search ?? "").split("\n").find((l) => l.trim().length > 0)?.trim() ?? "";
1810
+ const snippet = previewLine ? ` Near: "${previewLine.slice(0, 70)}"` : "";
1811
+ failedReason = ops.length > 1 ? `Block ${idx + 1} of ${ops.length} failed: ${applied.error}${snippet}` : `${applied.error}${snippet}`;
1812
+ break;
1813
+ }
1814
+ working = applied.next;
1815
+ if (applied.note) repairNotes.add(applied.note);
1816
+ }
1817
+ if (failedReason) {
1818
+ files.push({
1819
+ filePath,
1820
+ action: "modify",
1821
+ status: "failed",
1822
+ repairNote: null,
1823
+ securityWarning,
1824
+ errorReason: failedReason,
1825
+ originalContent: disk.contentLf,
1826
+ proposedContent: disk.contentLf,
1827
+ additions: 0,
1828
+ deletions: 0
1829
+ });
1830
+ continue;
1831
+ }
1832
+ const stats = countDiffStats(disk.contentLf, working);
1833
+ files.push({
1834
+ filePath,
1835
+ action: "modify",
1836
+ status: "ready",
1837
+ repairNote: repairNotes.size > 0 ? Array.from(repairNotes).join("; ") : null,
1838
+ securityWarning,
1839
+ errorReason: null,
1840
+ originalContent: disk.contentLf,
1841
+ proposedContent: working,
1842
+ ...stats
1843
+ });
1844
+ plans.set(filePath, {
1845
+ filePath,
1846
+ action: "modify",
1847
+ status: "ready",
1848
+ proposedContent: disk.hadCrlf ? working.replace(/\n/g, "\r\n") : working,
1849
+ expectedDiskSha256: disk.rawSha256,
1850
+ existedBefore: true,
1851
+ hadCrlf: disk.hadCrlf
1852
+ });
1853
+ }
1854
+ const unifiedGrouped = /* @__PURE__ */ new Map();
1855
+ for (const { filePath, chunk } of unifiedChunks) {
1856
+ const isNew = /^--- \/dev\/null/m.test(chunk);
1857
+ const resolvedPath = isNew ? normalizeRepoRelPath(filePath) : resolveSmartRepoFilePath(repoPath, filePath, repoFiles);
1858
+ const list = unifiedGrouped.get(resolvedPath) ?? [];
1859
+ list.push(chunk);
1860
+ unifiedGrouped.set(resolvedPath, list);
1861
+ }
1862
+ for (const [filePath, chunks] of unifiedGrouped.entries()) {
1863
+ if (handledPaths.has(filePath)) continue;
1864
+ handledPaths.add(filePath);
1865
+ const securityWarning = detectSecurityWarning(filePath);
1866
+ try {
1867
+ resolveSafeRepoPath(repoPath, filePath);
1868
+ } catch (err) {
1869
+ const msg = err instanceof PathSecurityError ? err.message : "Unsafe file path blocked.";
1870
+ files.push({
1871
+ filePath,
1872
+ action: "modify",
1873
+ status: "blocked",
1874
+ repairNote: null,
1875
+ securityWarning: msg,
1876
+ errorReason: msg,
1877
+ originalContent: "",
1878
+ proposedContent: "",
1879
+ additions: 0,
1880
+ deletions: 0
1881
+ });
1882
+ continue;
1883
+ }
1884
+ const firstChunk = chunks[0];
1885
+ const isDeleteFile = chunks.some((c) => /^\+\+\+ \/dev\/null/m.test(c));
1886
+ const disk = readDiskFile(repoPath, filePath);
1887
+ const isNewFile = /^--- \/dev\/null/m.test(firstChunk) || !disk.exists && /^@@ -0,0 \+1/m.test(firstChunk);
1888
+ if (isDeleteFile) {
1889
+ if (!disk.exists) {
1890
+ files.push({
1891
+ filePath,
1892
+ action: "delete",
1893
+ status: "failed",
1894
+ repairNote: null,
1895
+ securityWarning,
1896
+ errorReason: "File to delete does not exist on disk.",
1897
+ originalContent: "",
1898
+ proposedContent: "",
1899
+ additions: 0,
1900
+ deletions: 0
1901
+ });
1902
+ continue;
1903
+ }
1904
+ const stats2 = countDiffStats(disk.contentLf, "");
1905
+ files.push({
1906
+ filePath,
1907
+ action: "delete",
1908
+ status: "ready",
1909
+ repairNote: null,
1910
+ securityWarning,
1911
+ errorReason: null,
1912
+ originalContent: disk.contentLf,
1913
+ proposedContent: "",
1914
+ ...stats2
1915
+ });
1916
+ plans.set(filePath, {
1917
+ filePath,
1918
+ action: "delete",
1919
+ status: "ready",
1920
+ proposedContent: "",
1921
+ expectedDiskSha256: disk.rawSha256,
1922
+ existedBefore: true,
1923
+ hadCrlf: disk.hadCrlf
1924
+ });
1925
+ continue;
1926
+ }
1927
+ const baseContent = isNewFile ? "" : disk.contentLf;
1928
+ if (!isNewFile && !disk.exists) {
1929
+ const hints = suggestClosestPaths(repoFiles, filePath);
1930
+ const hintMsg = hints.length > 0 ? ` Did you mean: ${hints.join(", ")}?` : "";
1931
+ files.push({
1932
+ filePath,
1933
+ action: "modify",
1934
+ status: "failed",
1935
+ repairNote: null,
1936
+ securityWarning,
1937
+ errorReason: `File not found in your active project folder.${hintMsg}`,
1938
+ originalContent: "",
1939
+ proposedContent: "",
1940
+ additions: 0,
1941
+ deletions: 0
1942
+ });
1943
+ continue;
1944
+ }
1945
+ let working = baseContent;
1946
+ const repairNotes = /* @__PURE__ */ new Set();
1947
+ let chunkFailed = false;
1948
+ for (const chunk of chunks) {
1949
+ const baseNormalized = chunk.replace(/\r\n/g, "\n");
1950
+ const repairedChunk = recountHunkHeaders(baseNormalized);
1951
+ let patched = applyPatch(working, repairedChunk, { fuzzFactor: 2 });
1952
+ if (patched === false) {
1953
+ const mdFixed = recountHunkHeaders(repairUnifiedHunkLines(working, baseNormalized));
1954
+ patched = applyPatch(working, mdFixed, { fuzzFactor: 2 });
1955
+ if (patched !== false) {
1956
+ repairNotes.add("Auto-fixed minor AI diff formatting");
1957
+ } else {
1958
+ const fallback = applyUnifiedHunksFallback(working, mdFixed);
1959
+ if (fallback.ok) {
1960
+ patched = fallback.content;
1961
+ repairNotes.add("Auto-aligned drifted diff hunks");
1962
+ }
1963
+ }
1964
+ }
1965
+ if (patched === false) {
1966
+ chunkFailed = true;
1967
+ break;
1968
+ }
1969
+ working = preserveTrailingNewline(working, patched);
1970
+ }
1971
+ if (chunkFailed) {
1972
+ files.push({
1973
+ filePath,
1974
+ action: isNewFile ? "create" : "modify",
1975
+ status: "failed",
1976
+ repairNote: null,
1977
+ securityWarning,
1978
+ errorReason: "Diff context lines did not match your current file on disk.",
1979
+ originalContent: disk.contentLf,
1980
+ proposedContent: disk.contentLf,
1981
+ additions: 0,
1982
+ deletions: 0
1983
+ });
1984
+ continue;
1985
+ }
1986
+ const action = isNewFile && !disk.exists ? "create" : "modify";
1987
+ const stats = countDiffStats(disk.contentLf, working);
1988
+ files.push({
1989
+ filePath,
1990
+ action,
1991
+ status: "ready",
1992
+ repairNote: repairNotes.size > 0 ? Array.from(repairNotes).join("; ") : null,
1993
+ securityWarning,
1994
+ errorReason: null,
1995
+ originalContent: disk.contentLf,
1996
+ proposedContent: working,
1997
+ ...stats
1998
+ });
1999
+ plans.set(filePath, {
2000
+ filePath,
2001
+ action,
2002
+ status: "ready",
2003
+ proposedContent: disk.hadCrlf ? working.replace(/\n/g, "\r\n") : working,
2004
+ expectedDiskSha256: disk.rawSha256,
2005
+ existedBefore: disk.exists,
2006
+ hadCrlf: disk.hadCrlf
2007
+ });
2008
+ }
2009
+ parseCache.set(parseId, {
2010
+ parseId,
2011
+ repoPath,
2012
+ createdAt: Date.now(),
2013
+ plans
2014
+ });
2015
+ const readyCount = files.filter((f) => f.status === "ready").length;
2016
+ const readyFiles = files.filter((f) => f.status === "ready");
2017
+ const failedFiles = files.filter((f) => f.status === "failed");
2018
+ const blockedCount = files.filter((f) => f.status === "blocked").length;
2019
+ let retryPrompt = null;
2020
+ if (failedFiles.length > 0) {
2021
+ const lines = [
2022
+ "================================================================================",
2023
+ "CORRECTION REQUIRED: PATCH ENGINE COULD NOT APPLY EDITS TO THE FOLLOWING FILE(S)",
2024
+ "================================================================================"
2025
+ ];
2026
+ if (readyFiles.length > 0) {
2027
+ lines.push(
2028
+ `ALREADY PARSED CLEANLY (DO NOT REGENERATE THESE): ${readyFiles.map((f) => f.filePath).join(", ")}`
2029
+ );
2030
+ lines.push("");
2031
+ }
2032
+ lines.push("FAILED FILES (REGENERATE EDITS ONLY FOR THESE):");
2033
+ for (const ff of failedFiles) {
2034
+ lines.push(`- File: \`${ff.filePath}\``);
2035
+ lines.push(` Failure Reason: ${ff.errorReason}`);
2036
+ }
2037
+ lines.push("");
2038
+ const attachedSources = [];
2039
+ for (const ff of failedFiles) {
2040
+ if (!ff.originalContent) continue;
2041
+ const scanned = scanAndRedactSecrets(ff.originalContent, true).redactedContent;
2042
+ const capped = scanned.length > 45e3 ? `${scanned.slice(0, 45e3)}
2043
+ /* ... truncated at 45KB ... */` : scanned;
2044
+ attachedSources.push(`<file path="${ff.filePath}">
2045
+ ${capped.trimEnd()}
2046
+ </file>`);
2047
+ }
2048
+ if (attachedSources.length > 0) {
2049
+ lines.push("CURRENT ON-DISK SOURCE OF FAILED FILE(S) (USE THESE EXACT LINES):");
2050
+ lines.push("");
2051
+ lines.push(...attachedSources);
2052
+ lines.push("");
2053
+ }
2054
+ if (preferredFormat === "unified_diff") {
2055
+ lines.push("Regenerate a valid unified `git diff` inside ONE ```diff ... ``` code block ONLY for the failed file(s) above:");
2056
+ lines.push('- Start unchanged context lines with a single leading space " ".');
2057
+ lines.push("- Copy context and removed lines verbatim from the attached <file> block.");
2058
+ lines.push("- Include 3 unchanged lines above and below every edit. Never use placeholders.");
2059
+ } else {
2060
+ const outerFence = "`".repeat(4);
2061
+ lines.push(`Regenerate edits ONLY for the failed file(s) above inside ONE ${outerFence}patch ... ${outerFence} code block:`);
2062
+ lines.push("");
2063
+ lines.push(`${outerFence}patch`);
2064
+ lines.push("FILE: path/to/file.ext");
2065
+ lines.push("<<<<<<< SEARCH");
2066
+ lines.push("[exact lines copied verbatim from the <file> block above, with 3 lines of context]");
2067
+ lines.push("=======");
2068
+ lines.push("[new replacement lines]");
2069
+ lines.push(">>>>>>> REPLACE");
2070
+ lines.push(outerFence);
2071
+ lines.push("");
2072
+ lines.push(`RULES: Always wrap ALL blocks inside ONE ${outerFence}patch code block (never raw Markdown so ======= and >>>>>>> are not mangled), exact indentation, never omit =======, no placeholder comments.`);
2073
+ }
2074
+ lines.push("================================================================================");
2075
+ retryPrompt = lines.join("\n");
2076
+ }
2077
+ return {
2078
+ parseId,
2079
+ detectedFormat,
2080
+ summary: {
2081
+ totalFiles: files.length,
2082
+ readyCount,
2083
+ failedCount: failedFiles.length,
2084
+ blockedCount
2085
+ },
2086
+ files,
2087
+ retryPrompt
2088
+ };
2089
+ }
2090
+
2091
+ // src/server/core/promptBuilder.ts
2092
+ import crypto2 from "crypto";
2093
+ import fs6 from "fs";
2094
+ import os4 from "os";
2095
+ import path7 from "path";
2096
+ var FENCE = "```";
2097
+ var OUTER_FENCE = "`".repeat(4);
2098
+ var lastSentHashesByRepo = /* @__PURE__ */ new Map();
2099
+ var diskHashesLoaded = false;
2100
+ function getSentHashesPath() {
2101
+ const baseDir = process.env.CHAT2DIFF_CONFIG_DIR || path7.join(os4.homedir(), ".chat2diff");
2102
+ return path7.join(baseDir, "sent-hashes.json");
2103
+ }
2104
+ function hydrateSentHashesFromDisk() {
2105
+ if (diskHashesLoaded) return;
2106
+ diskHashesLoaded = true;
2107
+ const filePath = getSentHashesPath();
2108
+ try {
2109
+ if (!fs6.existsSync(filePath)) return;
2110
+ const parsed = JSON.parse(fs6.readFileSync(filePath, "utf8"));
2111
+ if (!parsed.repos || typeof parsed.repos !== "object") return;
2112
+ for (const [repoKey, entry] of Object.entries(parsed.repos)) {
2113
+ if (entry && entry.hashes && typeof entry.hashes === "object") {
2114
+ lastSentHashesByRepo.set(repoKey, new Map(Object.entries(entry.hashes)));
2115
+ }
2116
+ }
2117
+ } catch {
2118
+ }
2119
+ }
2120
+ function saveRepoSentHashes(repoKey, hashes) {
2121
+ lastSentHashesByRepo.set(repoKey, hashes);
2122
+ const filePath = getSentHashesPath();
2123
+ const dir = path7.dirname(filePath);
2124
+ try {
2125
+ let existingRepos = {};
2126
+ if (fs6.existsSync(filePath)) {
2127
+ try {
2128
+ const parsed = JSON.parse(fs6.readFileSync(filePath, "utf8"));
2129
+ if (parsed.repos && typeof parsed.repos === "object") {
2130
+ existingRepos = { ...parsed.repos };
2131
+ }
2132
+ } catch {
2133
+ existingRepos = {};
2134
+ }
2135
+ }
2136
+ existingRepos[repoKey] = {
2137
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2138
+ hashes: Object.fromEntries(hashes.entries())
2139
+ };
2140
+ const recentEntries = Object.entries(existingRepos).sort((a, b) => (b[1]?.updatedAt ?? "").localeCompare(a[1]?.updatedAt ?? "")).slice(0, 15);
2141
+ const payload = {
2142
+ version: 1,
2143
+ repos: Object.fromEntries(recentEntries)
2144
+ };
2145
+ fs6.mkdirSync(dir, { recursive: true });
2146
+ const tmpPath = `${filePath}.tmp`;
2147
+ fs6.writeFileSync(tmpPath, JSON.stringify(payload), "utf8");
2148
+ fs6.renameSync(tmpPath, filePath);
2149
+ } catch {
2150
+ }
2151
+ }
2152
+ function hashText(text) {
2153
+ return crypto2.createHash("sha256").update(text, "utf8").digest("hex");
2154
+ }
2155
+ function getFormatInstructions(format) {
2156
+ if (format === "unified_diff") {
2157
+ return [
2158
+ "================================================================================",
2159
+ "OUTPUT SPECIFICATION: UNIFIED GIT DIFF FORMAT (STRICT AUTOMATED PARSER)",
2160
+ "================================================================================",
2161
+ "Your output will be parsed directly by an automated local patch engine.",
2162
+ "You MUST adhere strictly to the following syntax rules:",
2163
+ "",
2164
+ "1. Start with a concise 2-4 bullet summary of what you are changing and why.",
2165
+ `2. Put ALL code changes inside a SINGLE ${FENCE}diff ... ${FENCE} code block.`,
2166
+ "3. For each modified file:",
2167
+ " diff --git a/path/to/file.ext b/path/to/file.ext",
2168
+ " --- a/path/to/file.ext",
2169
+ " +++ b/path/to/file.ext",
2170
+ " @@ -<start_line>,<count> +<start_line>,<count> @@",
2171
+ "4. For brand-new files:",
2172
+ " --- /dev/null",
2173
+ " +++ b/path/to/newfile.ext",
2174
+ "5. For deleted files:",
2175
+ " --- a/path/to/oldfile.ext",
2176
+ " +++ /dev/null",
2177
+ "6. STRICT LINE RULES:",
2178
+ ' - Unchanged context lines MUST start with a literal single space: " "',
2179
+ ' - Deleted lines MUST start with a minus sign: "-"',
2180
+ ' - Added lines MUST start with a plus sign: "+"',
2181
+ " - Include 3 unchanged context lines above and below each change.",
2182
+ " - NEVER use placeholder comments like `// ... existing code ...` or `// ... rest of file ...`.",
2183
+ "================================================================================"
2184
+ ].join("\n");
2185
+ }
2186
+ return [
2187
+ "================================================================================",
2188
+ "OUTPUT SPECIFICATION: SEARCH/REPLACE BLOCKS (STRICT AUTOMATED PARSER)",
2189
+ "================================================================================",
2190
+ "Your output is parsed directly by an automated local patch engine.",
2191
+ `You MUST put ALL code modifications inside ONE single ${OUTER_FENCE}patch ... ${OUTER_FENCE} code block.`,
2192
+ "(Using a 4-backtick outer code block prevents Markdown from eating ======= or mangling JSX/types.)",
2193
+ "",
2194
+ "### MANDATORY SYNTAX STRUCTURE:",
2195
+ "",
2196
+ `${OUTER_FENCE}patch`,
2197
+ "FILE: path/to/file.ext",
2198
+ "<<<<<<< SEARCH",
2199
+ "[exact existing lines to replace, with 2-3 surrounding context lines]",
2200
+ "=======",
2201
+ "[new replacement lines to put in their place]",
2202
+ ">>>>>>> REPLACE",
2203
+ "",
2204
+ "CREATE FILE: path/to/new-file.ext",
2205
+ "<<<<<<< SEARCH",
2206
+ "=======",
2207
+ "[full file content]",
2208
+ ">>>>>>> REPLACE",
2209
+ "",
2210
+ "DELETE FILE: path/to/file-to-delete.ext",
2211
+ `${OUTER_FENCE}`,
2212
+ "",
2213
+ "### 6 STRICT RULES FOR 100% ACCURACY:",
2214
+ `1. WRAP EVERYTHING IN ONE ${OUTER_FENCE}patch CODE BLOCK:`,
2215
+ ` - Start with ${OUTER_FENCE}patch on its own line and end with ${OUTER_FENCE} on its own line.`,
2216
+ " - Never output raw unfenced SEARCH/REPLACE blocks outside the code block.",
2217
+ "",
2218
+ "2. EXACT VERBATIM SEARCH BLOCKS:",
2219
+ " - Copy exact indentation, quotes, brackets, and ALL HTML/JSX/type syntax byte-for-byte.",
2220
+ "",
2221
+ "3. NO PLACEHOLDERS OR ELLIPSES:",
2222
+ " - NEVER write comments like `// ... existing code ...` or `// ... rest of file ...`.",
2223
+ "",
2224
+ "4. NO LINE NUMBERS OR ANNOTATIONS:",
2225
+ " - Output only clean source lines (never prefix with line numbers).",
2226
+ "",
2227
+ "5. EXACT 7-CHARACTER DELIMITERS:",
2228
+ " - `<<<<<<< SEARCH`, `=======`, and `>>>>>>> REPLACE` each on their own line.",
2229
+ " - NEVER omit `=======`.",
2230
+ "",
2231
+ "6. CONTEXT FOR UNIQUENESS:",
2232
+ " - Include 2-3 unchanged lines immediately above and below every change so the match is unique.",
2233
+ "================================================================================"
2234
+ ].join("\n");
2235
+ }
2236
+ function getCompactFollowUpFormatReminder(format) {
2237
+ if (format === "unified_diff") {
2238
+ return [
2239
+ "OUTPUT FORMAT: Return ALL code changes inside ONE ```diff ... ``` block with exact relative paths (`a/path`, `b/path`), single leading space on unchanged lines, 3 context lines, and zero placeholders."
2240
+ ].join("\n");
2241
+ }
2242
+ return [
2243
+ `OUTPUT FORMAT: Return ALL code changes inside ONE ${OUTER_FENCE}patch ... ${OUTER_FENCE} code block using \`FILE: path/to/file.ext\`, \`<<<<<<< SEARCH\`, verbatim lines with 2-3 lines context, \`=======\`, replacement lines, \`>>>>>>> REPLACE\` (or \`CREATE FILE:\` / \`DELETE FILE:\`). Never output unfenced blocks and never use placeholders.`
2244
+ ].join("\n");
2245
+ }
2246
+ function buildTurnSyncSection(turnSync, attachedPaths, attachLocationLabel) {
2247
+ if (!turnSync) return "";
2248
+ const parts = [];
2249
+ if (turnSync.appliedFiles.length > 0) {
2250
+ parts.push(
2251
+ `- APPLIED TO DISK (ground your next edits on these updated versions): ${turnSync.appliedFiles.join(", ")}`
2252
+ );
2253
+ }
2254
+ if (turnSync.partiallyAppliedFiles.length > 0) {
2255
+ const anyAttached = turnSync.partiallyAppliedFiles.some(
2256
+ (p) => attachedPaths.has(normalizeRepoRelPath(p))
2257
+ );
2258
+ parts.push(
2259
+ `- PARTIALLY APPLIED (${anyAttached ? `only some change blocks applied; ${attachLocationLabel}` : "only some change blocks applied on disk"}): ${turnSync.partiallyAppliedFiles.join(", ")}`
2260
+ );
2261
+ }
2262
+ if (turnSync.notAppliedFiles.length > 0) {
2263
+ parts.push(
2264
+ `- NOT APPLIED / SKIPPED BY USER (still at their previous version on disk \u2014 do NOT assume these edits exist): ${turnSync.notAppliedFiles.join(", ")}`
2265
+ );
2266
+ }
2267
+ if (turnSync.failedFiles.length > 0) {
2268
+ const anyAttached = turnSync.failedFiles.some(
2269
+ (f) => attachedPaths.has(normalizeRepoRelPath(f.filePath))
2270
+ );
2271
+ const list = turnSync.failedFiles.map((f) => `${f.filePath} (${f.reason})`).join("; ");
2272
+ parts.push(
2273
+ `- FAILED TO APPLY (${anyAttached ? `not written to disk; ${attachLocationLabel}` : "not written to disk"}): ${list}`
2274
+ );
2275
+ }
2276
+ if (turnSync.undoneFiles.length > 0) {
2277
+ const anyAttached = turnSync.undoneFiles.some(
2278
+ (p) => attachedPaths.has(normalizeRepoRelPath(p))
2279
+ );
2280
+ parts.push(
2281
+ `- REVERTED / UNDONE BY USER (${anyAttached ? `restored to pre-patch state; ${attachLocationLabel}` : "restored to pre-patch state on disk"}): ${turnSync.undoneFiles.join(", ")}`
2282
+ );
2283
+ }
2284
+ if (parts.length === 0) return "";
2285
+ return [
2286
+ "================================================================================",
2287
+ "WORKSPACE SYNC STATUS (EXACT GROUND TRUTH FROM PREVIOUS TURN):",
2288
+ "================================================================================",
2289
+ ...parts,
2290
+ "================================================================================"
2291
+ ].join("\n");
2292
+ }
2293
+ function buildPackResponse(repoPath, req) {
2294
+ hydrateSentHashesFromDisk();
2295
+ const resolvedRepo = path7.resolve(repoPath);
2296
+ const repoKey = resolvedRepo.toLowerCase();
2297
+ const repoName = path7.basename(resolvedRepo);
2298
+ const safeSlug = repoName.replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase() || "project";
2299
+ const contextFileName = `chat2diff-context-${safeSlug}.txt`;
2300
+ const chatMode = req.chatMode ?? "new_chat";
2301
+ const attachMode = req.followUpAttachMode ?? (req.includeSelectedInFollowUp ? "all" : "smart");
2302
+ const fileBundleStyle = req.fileBundleStyle ?? "all_in_one";
2303
+ const isAllInOneFile = req.mode === "file_attachment" && fileBundleStyle === "all_in_one";
2304
+ const fileBlocks = [];
2305
+ const includedPaths = [];
2306
+ const warnings = [];
2307
+ let totalRedacted = 0;
2308
+ const uniqueSelected = Array.from(new Set(req.selectedPaths.map(normalizeRepoRelPath))).sort();
2309
+ const existingMap = lastSentHashesByRepo.get(repoKey);
2310
+ const hadPriorHashes = Boolean(existingMap && existingMap.size > 0);
2311
+ const prevHashes = chatMode === "follow_up" ? new Map(existingMap ?? []) : /* @__PURE__ */ new Map();
2312
+ let pathsToRead;
2313
+ if (chatMode === "new_chat" || attachMode === "all") {
2314
+ pathsToRead = uniqueSelected;
2315
+ } else {
2316
+ const appliedSet = new Set((req.turnSync?.appliedFiles ?? []).map(normalizeRepoRelPath));
2317
+ for (const p of appliedSet) {
2318
+ try {
2319
+ const abs = resolveSafeRepoPath(repoPath, p);
2320
+ if (fs6.existsSync(abs) && fs6.statSync(abs).isFile()) {
2321
+ const raw = fs6.readFileSync(abs, "utf8").replace(/\r\n/g, "\n");
2322
+ prevHashes.set(p, hashText(raw));
2323
+ }
2324
+ } catch {
2325
+ }
2326
+ }
2327
+ if (attachMode === "none") {
2328
+ pathsToRead = [];
2329
+ } else {
2330
+ const mustAttach = /* @__PURE__ */ new Set();
2331
+ for (const p of req.turnSync?.partiallyAppliedFiles ?? []) {
2332
+ mustAttach.add(normalizeRepoRelPath(p));
2333
+ }
2334
+ for (const ff of req.turnSync?.failedFiles ?? []) {
2335
+ mustAttach.add(normalizeRepoRelPath(ff.filePath));
2336
+ }
2337
+ for (const p of req.turnSync?.undoneFiles ?? []) {
2338
+ mustAttach.add(normalizeRepoRelPath(p));
2339
+ }
2340
+ if (hadPriorHashes) {
2341
+ for (const relPath of uniqueSelected) {
2342
+ if (appliedSet.has(relPath) || mustAttach.has(relPath)) continue;
2343
+ try {
2344
+ const abs = resolveSafeRepoPath(repoPath, relPath);
2345
+ if (!fs6.existsSync(abs) || !fs6.statSync(abs).isFile()) continue;
2346
+ const raw = fs6.readFileSync(abs, "utf8").replace(/\r\n/g, "\n");
2347
+ const currentHash = hashText(raw);
2348
+ const lastHash = prevHashes.get(relPath);
2349
+ if (!lastHash || lastHash !== currentHash) {
2350
+ mustAttach.add(relPath);
2351
+ }
2352
+ } catch {
2353
+ }
2354
+ }
2355
+ }
2356
+ pathsToRead = Array.from(mustAttach).sort();
2357
+ }
2358
+ }
2359
+ for (const relPath of pathsToRead) {
2360
+ const absPath = resolveSafeRepoPath(repoPath, relPath);
2361
+ if (!fs6.existsSync(absPath) || !fs6.statSync(absPath).isFile()) {
2362
+ continue;
2363
+ }
2364
+ const raw = fs6.readFileSync(absPath, "utf8").replace(/\r\n/g, "\n");
2365
+ prevHashes.set(relPath, hashText(raw));
2366
+ const secretScan = scanAndRedactSecrets(raw, req.redactSecrets);
2367
+ if (secretScan.count > 0) {
2368
+ totalRedacted += secretScan.count;
2369
+ warnings.push({
2370
+ filePath: relPath,
2371
+ reason: req.redactSecrets ? `Masked ${secretScan.count} possible secret(s): ${secretScan.labels.join(", ")}` : `Detected ${secretScan.count} possible secret(s) (unmasked): ${secretScan.labels.join(", ")}`
2372
+ });
2373
+ }
2374
+ includedPaths.push(relPath);
2375
+ fileBlocks.push(`<file path="${relPath}">
2376
+ ${secretScan.redactedContent.trimEnd()}
2377
+ </file>`);
2378
+ }
2379
+ saveRepoSentHashes(repoKey, prevHashes);
2380
+ const contextBody = includedPaths.length > 0 ? [
2381
+ `# PROJECT CONTEXT: ${repoName}`,
2382
+ `# Files included: ${includedPaths.length}`,
2383
+ "",
2384
+ "<file_list>",
2385
+ ...includedPaths,
2386
+ "</file_list>",
2387
+ "",
2388
+ "",
2389
+ ...fileBlocks,
2390
+ ""
2391
+ ].join("\n") : "";
2392
+ const presetMeta = TASK_PRESETS[req.preset];
2393
+ const errorSection = req.errorLog?.trim() ? `
2394
+ ERROR / TERMINAL OUTPUT:
2395
+ ${FENCE}
2396
+ ${req.errorLog.trim()}
2397
+ ${FENCE}
2398
+ ` : "";
2399
+ const attachLocationLabel = req.mode === "file_attachment" && !isAllInOneFile ? `current on-disk source attached in ${contextFileName}` : "current on-disk source attached below";
2400
+ const syncSection = chatMode === "follow_up" ? buildTurnSyncSection(req.turnSync, new Set(includedPaths), attachLocationLabel) : "";
2401
+ let instructionsBlock;
2402
+ if (chatMode === "follow_up") {
2403
+ instructionsBlock = [
2404
+ `FOLLOW-UP REQUEST (${repoName}) \u2014 continuing this existing conversation.`,
2405
+ "",
2406
+ syncSection,
2407
+ syncSection ? "" : void 0,
2408
+ `GOAL: ${presetMeta.instruction}`,
2409
+ "",
2410
+ "NEXT REQUEST:",
2411
+ req.taskDescription.trim(),
2412
+ errorSection || void 0,
2413
+ "",
2414
+ includedPaths.length > 0 ? req.mode === "file_attachment" && !isAllInOneFile ? `Updated/relevant file(s) attached in \`${contextFileName}\` (${includedPaths.length} file(s)). Read that attached file first and use those exact lines as ground truth.` : `Updated/relevant file(s) included below (${includedPaths.length} file(s)). Use those exact lines as ground truth.` : "No full project re-upload needed \u2014 base your edits on the sync status above and our conversation history.",
2415
+ "",
2416
+ getCompactFollowUpFormatReminder(req.patchFormatPreference)
2417
+ ].filter((line) => line !== void 0).join("\n").trim();
2418
+ } else {
2419
+ instructionsBlock = [
2420
+ `You are an expert Principal software engineer generating code changes for the "${repoName}" project.`,
2421
+ "Your output will be applied automatically by a local patch engine.",
2422
+ "",
2423
+ `GOAL: ${presetMeta.instruction}`,
2424
+ "",
2425
+ getFormatInstructions(req.patchFormatPreference),
2426
+ "",
2427
+ "================================================================================",
2428
+ "USER TASK / REQUEST:",
2429
+ "================================================================================",
2430
+ req.taskDescription.trim(),
2431
+ errorSection,
2432
+ "",
2433
+ "================================================================================",
2434
+ "SOURCE FILES INSTRUCTION:",
2435
+ "================================================================================",
2436
+ req.mode === "file_attachment" && !isAllInOneFile ? `Project files are attached in \`${contextFileName}\`. Read the relevant files first before generating patches.` : 'Project files are provided below inside `<file path="...">...</file>` tags.',
2437
+ req.patchFormatPreference === "unified_diff" ? "When targeting a file, copy its exact relative path from the `path` attribute into `diff --git a/path b/path`, `--- a/path`, and `+++ b/path`." : "When targeting a file, copy its exact relative path from the `path` attribute (e.g. `FILE: path/to/file.ext`).",
2438
+ req.patchFormatPreference === "unified_diff" ? "Copy all unchanged context and removed lines verbatim from the source file, with a single leading space on unchanged lines." : "Copy SEARCH lines verbatim from the actual file contents (including indentation, brackets, and JSX tags).",
2439
+ "================================================================================"
2440
+ ].filter((line) => line !== void 0).join("\n").trim();
2441
+ }
2442
+ let promptText;
2443
+ let contextFileContent = null;
2444
+ if (req.mode === "file_attachment" && contextBody) {
2445
+ if (isAllInOneFile) {
2446
+ contextFileContent = `${instructionsBlock}
2447
+
2448
+ PROJECT FILES:
2449
+
2450
+ ${contextBody}
2451
+ `;
2452
+ promptText = `Follow all instructions and rules inside the attached \`${contextFileName}\` file.`;
2453
+ } else {
2454
+ contextFileContent = contextBody + "\n";
2455
+ promptText = [
2456
+ chatMode === "follow_up" ? `I have attached ${includedPaths.length} updated/relevant file(s) in \`${contextFileName}\`. Read it first before answering.` : `I have attached my project files in \`${contextFileName}\`. Read the relevant files first before answering.`,
2457
+ "",
2458
+ instructionsBlock
2459
+ ].join("\n");
2460
+ }
2461
+ } else if (contextBody) {
2462
+ promptText = `${instructionsBlock}
2463
+
2464
+ PROJECT FILES:
2465
+
2466
+ ${contextBody}
2467
+ `;
2468
+ } else {
2469
+ promptText = `${instructionsBlock}
2470
+ `;
2471
+ }
2472
+ const totalChars = isAllInOneFile && contextFileContent ? contextFileContent.length : promptText.length + (contextFileContent ? contextFileContent.length : 0);
2473
+ const estimatedTokens = Math.max(1, Math.ceil(totalChars / 4));
2474
+ return {
2475
+ promptText,
2476
+ contextFileContent,
2477
+ contextFileName,
2478
+ fileBundleStyle,
2479
+ stats: {
2480
+ fileCount: includedPaths.length,
2481
+ estimatedTokens,
2482
+ redactedSecretsCount: totalRedacted,
2483
+ modelFit: evaluateModelFit(estimatedTokens),
2484
+ chatMode,
2485
+ attachedFiles: includedPaths
2486
+ },
2487
+ warnings
2488
+ };
2489
+ }
2490
+
2491
+ // src/server/core/snapshotManager.ts
2492
+ import crypto3 from "crypto";
2493
+ import fs7 from "fs";
2494
+ import path8 from "path";
2495
+ function getSnapshotsRoot(repoPath) {
2496
+ const gitDir = path8.join(repoPath, ".git");
2497
+ if (fs7.existsSync(gitDir) && fs7.statSync(gitDir).isDirectory()) {
2498
+ return path8.join(gitDir, "chat2diff", "snapshots");
2499
+ }
2500
+ return path8.join(repoPath, ".chat2diff", "snapshots");
2501
+ }
2502
+ function formatSummary(files) {
2503
+ const mod = files.filter((f) => f.action === "modify").length;
2504
+ const cre = files.filter((f) => f.action === "create").length;
2505
+ const del = files.filter((f) => f.action === "delete").length;
2506
+ const parts = [];
2507
+ if (mod > 0) parts.push(`Updated ${mod} file${mod > 1 ? "s" : ""}`);
2508
+ if (cre > 0) parts.push(`Created ${cre} file${cre > 1 ? "s" : ""}`);
2509
+ if (del > 0) parts.push(`Deleted ${del} file${del > 1 ? "s" : ""}`);
2510
+ return parts.join(", ") || "No files changed";
2511
+ }
2512
+ function applySelectedFiles(repoPath, parseId, selectedFilePaths, customContents) {
2513
+ const session = getStoredParseSession(parseId);
2514
+ if (!session || path8.resolve(session.repoPath) !== path8.resolve(repoPath)) {
2515
+ throw new Error("EXPIRED_PARSE_ID: Preview expired or belongs to another project. Please re-preview.");
2516
+ }
2517
+ const plansToApply = selectedFilePaths.map((p) => session.plans.get(p)).filter((p) => Boolean(p && p.status === "ready"));
2518
+ if (plansToApply.length === 0) {
2519
+ throw new Error("NO_FILES_SELECTED: Select at least one ready file to apply.");
2520
+ }
2521
+ for (const plan of plansToApply) {
2522
+ const absPath = resolveSafeRepoPath(repoPath, plan.filePath);
2523
+ const existsNow = fs7.existsSync(absPath);
2524
+ if (plan.existedBefore && !existsNow) {
2525
+ throw new Error(`FILE_CHANGED_ON_DISK: "${plan.filePath}" was removed after preview.`);
2526
+ }
2527
+ if (existsNow && plan.expectedDiskSha256) {
2528
+ const currentHash = sha256(fs7.readFileSync(absPath, "utf8"));
2529
+ if (currentHash !== plan.expectedDiskSha256) {
2530
+ throw new Error(`FILE_CHANGED_ON_DISK: "${plan.filePath}" changed on disk after preview. Re-preview first.`);
2531
+ }
2532
+ }
2533
+ }
2534
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 14);
2535
+ const snapshotId = `snap_${ts}_${crypto3.randomBytes(3).toString("hex")}`;
2536
+ const snapshotDir = path8.join(getSnapshotsRoot(repoPath), snapshotId);
2537
+ fs7.mkdirSync(snapshotDir, { recursive: true });
2538
+ const manifestFiles = [];
2539
+ const appliedFiles = [];
2540
+ for (let idx = 0; idx < plansToApply.length; idx++) {
2541
+ const plan = plansToApply[idx];
2542
+ const absPath = resolveSafeRepoPath(repoPath, plan.filePath);
2543
+ const existedBefore = plan.existedBefore;
2544
+ let backupBlobName = null;
2545
+ if (existedBefore && fs7.existsSync(absPath)) {
2546
+ backupBlobName = `${String(idx).padStart(3, "0")}_${path8.basename(plan.filePath)}.bak`;
2547
+ fs7.copyFileSync(absPath, path8.join(snapshotDir, backupBlobName));
2548
+ }
2549
+ if (plan.action === "delete") {
2550
+ if (fs7.existsSync(absPath)) {
2551
+ fs7.unlinkSync(absPath);
2552
+ }
2553
+ plan.expectedDiskSha256 = null;
2554
+ plan.existedBefore = false;
2555
+ } else {
2556
+ const overrideLf = customContents?.[plan.filePath];
2557
+ const contentToWrite = overrideLf !== void 0 ? plan.hadCrlf ? overrideLf.replace(/\r\n/g, "\n").replace(/\n/g, "\r\n") : overrideLf.replace(/\r\n/g, "\n") : plan.proposedContent;
2558
+ fs7.mkdirSync(path8.dirname(absPath), { recursive: true });
2559
+ fs7.writeFileSync(absPath, contentToWrite, "utf8");
2560
+ plan.expectedDiskSha256 = sha256(contentToWrite);
2561
+ plan.existedBefore = true;
2562
+ }
2563
+ manifestFiles.push({
2564
+ filePath: plan.filePath,
2565
+ action: plan.action,
2566
+ existedBefore,
2567
+ backupBlobName
2568
+ });
2569
+ appliedFiles.push(plan.filePath);
2570
+ }
2571
+ const appliedAt = (/* @__PURE__ */ new Date()).toISOString();
2572
+ const manifest = {
2573
+ snapshotId,
2574
+ appliedAt,
2575
+ reverted: false,
2576
+ revertedAt: null,
2577
+ files: manifestFiles
2578
+ };
2579
+ fs7.writeFileSync(
2580
+ path8.join(snapshotDir, "manifest.json"),
2581
+ JSON.stringify(manifest, null, 2),
2582
+ "utf8"
2583
+ );
2584
+ return { snapshotId, appliedFiles, appliedAt };
2585
+ }
2586
+ function listSnapshots(repoPath) {
2587
+ const root = getSnapshotsRoot(repoPath);
2588
+ if (!fs7.existsSync(root)) return [];
2589
+ const dirs = fs7.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory());
2590
+ const snapshots = [];
2591
+ for (const d of dirs) {
2592
+ const manifestPath = path8.join(root, d.name, "manifest.json");
2593
+ if (!fs7.existsSync(manifestPath)) continue;
2594
+ try {
2595
+ const m = JSON.parse(fs7.readFileSync(manifestPath, "utf8"));
2596
+ snapshots.push({
2597
+ snapshotId: m.snapshotId,
2598
+ appliedAt: m.appliedAt,
2599
+ summary: formatSummary(m.files),
2600
+ files: m.files.map((f) => ({ filePath: f.filePath, action: f.action })),
2601
+ reverted: m.reverted
2602
+ });
2603
+ } catch {
2604
+ }
2605
+ }
2606
+ snapshots.sort((a, b) => b.appliedAt.localeCompare(a.appliedAt));
2607
+ return snapshots.slice(0, 40);
2608
+ }
2609
+ function undoSnapshot(repoPath, snapshotId) {
2610
+ if (!/^snap_[a-zA-Z0-9_]+$/.test(snapshotId)) {
2611
+ throw new Error("NOT_FOUND: Invalid snapshot ID.");
2612
+ }
2613
+ const snapshotDir = path8.join(getSnapshotsRoot(repoPath), snapshotId);
2614
+ const manifestPath = path8.join(snapshotDir, "manifest.json");
2615
+ if (!fs7.existsSync(manifestPath)) {
2616
+ throw new Error("NOT_FOUND: Snapshot does not exist.");
2617
+ }
2618
+ const manifest = JSON.parse(fs7.readFileSync(manifestPath, "utf8"));
2619
+ if (manifest.reverted) {
2620
+ throw new Error("ALREADY_REVERTED: This change has already been undone.");
2621
+ }
2622
+ const restoredFiles = [];
2623
+ const removedCreatedFiles = [];
2624
+ for (const entry of manifest.files) {
2625
+ const absPath = resolveSafeRepoPath(repoPath, entry.filePath);
2626
+ if (entry.existedBefore && entry.backupBlobName) {
2627
+ const backupPath = path8.join(snapshotDir, entry.backupBlobName);
2628
+ if (fs7.existsSync(backupPath)) {
2629
+ fs7.mkdirSync(path8.dirname(absPath), { recursive: true });
2630
+ fs7.copyFileSync(backupPath, absPath);
2631
+ restoredFiles.push(entry.filePath);
2632
+ }
2633
+ } else if (!entry.existedBefore) {
2634
+ if (fs7.existsSync(absPath)) {
2635
+ fs7.unlinkSync(absPath);
2636
+ removedCreatedFiles.push(entry.filePath);
2637
+ }
2638
+ }
2639
+ }
2640
+ manifest.reverted = true;
2641
+ manifest.revertedAt = (/* @__PURE__ */ new Date()).toISOString();
2642
+ fs7.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), "utf8");
2643
+ return { snapshotId, restoredFiles, removedCreatedFiles };
2644
+ }
2645
+
2646
+ // src/server/app.ts
2647
+ var MIME_TYPES = {
2648
+ ".html": "text/html; charset=utf-8",
2649
+ ".js": "application/javascript; charset=utf-8",
2650
+ ".css": "text/css; charset=utf-8",
2651
+ ".json": "application/json; charset=utf-8",
2652
+ ".svg": "image/svg+xml",
2653
+ ".png": "image/png",
2654
+ ".ico": "image/x-icon",
2655
+ ".woff2": "font/woff2"
2656
+ };
2657
+ var TurnSyncSchema = z.object({
2658
+ appliedFiles: z.array(z.string()).default([]),
2659
+ partiallyAppliedFiles: z.array(z.string()).default([]),
2660
+ notAppliedFiles: z.array(z.string()).default([]),
2661
+ failedFiles: z.array(z.object({ filePath: z.string(), reason: z.string() })).default([]),
2662
+ undoneFiles: z.array(z.string()).default([])
2663
+ });
2664
+ var PackSchema = z.object({
2665
+ selectedPaths: z.array(z.string().min(1)),
2666
+ preset: z.enum(["bug_fix", "add_feature", "improve_code", "review_code"]),
2667
+ taskDescription: z.string().min(1).max(25e3),
2668
+ errorLog: z.string().max(6e4).optional(),
2669
+ patchFormatPreference: z.enum(["search_replace", "unified_diff"]),
2670
+ redactSecrets: z.boolean().default(true),
2671
+ mode: z.enum(["inline_copy", "file_attachment"]),
2672
+ chatMode: z.enum(["new_chat", "follow_up"]).default("new_chat"),
2673
+ turnSync: TurnSyncSchema.nullable().optional(),
2674
+ includeSelectedInFollowUp: z.boolean().optional(),
2675
+ followUpAttachMode: z.enum(["smart", "all", "none"]).optional(),
2676
+ fileBundleStyle: z.enum(["all_in_one", "separate_prompt"]).optional(),
2677
+ copyFileToClipboard: z.boolean().optional()
2678
+ }).refine((val) => val.chatMode === "follow_up" || val.selectedPaths.length > 0, {
2679
+ message: "Select at least one file when starting a new chat."
2680
+ });
2681
+ var ParseSchema = z.object({
2682
+ rawText: z.string().min(10).max(5e6)
2683
+ });
2684
+ var ApplySchema = z.object({
2685
+ parseId: z.string().min(1),
2686
+ selectedFilePaths: z.array(z.string().min(1)).min(1),
2687
+ customContents: z.record(z.string(), z.string()).optional()
2688
+ });
2689
+ var OpenRepoSchema = z.object({
2690
+ repoPath: z.string().min(1)
2691
+ });
2692
+ var ToggleWatcherSchema = z.object({
2693
+ enabled: z.boolean()
2694
+ });
2695
+ function isValidLocalHost(hostHeader) {
2696
+ if (!hostHeader) return false;
2697
+ return /^(localhost|127.0.0.1)(:\d+)?$/i.test(hostHeader.trim());
2698
+ }
2699
+ function verifySessionToken(provided, expected) {
2700
+ if (!provided) return false;
2701
+ const a = Buffer.from(provided, "utf8");
2702
+ const b = Buffer.from(expected, "utf8");
2703
+ return a.length === b.length && crypto4.timingSafeEqual(a, b);
2704
+ }
2705
+ function createApp(state) {
2706
+ const app = new Hono();
2707
+ app.use("*", async (c, next) => {
2708
+ if (!isValidLocalHost(c.req.header("host"))) {
2709
+ return c.json({ error: "FORBIDDEN_HOST", message: "Localhost access only." }, 403);
2710
+ }
2711
+ if (c.req.path.startsWith("/api/")) {
2712
+ const provided = c.req.header("x-chat2diff-token");
2713
+ if (!verifySessionToken(provided, state.sessionToken)) {
2714
+ return c.json({ error: "UNAUTHORIZED", message: "Missing or invalid session token." }, 401);
2715
+ }
2716
+ }
2717
+ await next();
2718
+ });
2719
+ app.get("/api/v1/workspace", (c) => {
2720
+ const git = detectGitInfo(state.repoPath);
2721
+ const config = loadConfig();
2722
+ const watch = state.watcher.getStatus();
2723
+ return c.json({
2724
+ data: {
2725
+ repoPath: state.repoPath,
2726
+ repoName: path9.basename(state.repoPath),
2727
+ isGitRepo: git.isGitRepo,
2728
+ gitBranch: git.gitBranch,
2729
+ clipboardWatchEnabled: watch.enabled,
2730
+ clipboardAvailable: watch.available,
2731
+ defaultPatchFormat: config.defaultPatchFormat,
2732
+ recentRepos: config.recentRepos
2733
+ }
2734
+ });
2735
+ });
2736
+ app.get("/api/v1/filesystem/list", (c) => {
2737
+ try {
2738
+ const dir = c.req.query("dir") || path9.dirname(state.repoPath);
2739
+ return c.json({ data: listLocalDirectories(dir) });
2740
+ } catch (err) {
2741
+ return c.json(
2742
+ { error: "INVALID_PATH", message: err instanceof Error ? err.message : "Cannot read folder." },
2743
+ 400
2744
+ );
2745
+ }
2746
+ });
2747
+ app.post("/api/v1/workspace/open", async (c) => {
2748
+ const parsed = OpenRepoSchema.safeParse(await c.req.json().catch(() => null));
2749
+ if (!parsed.success) {
2750
+ return c.json({ error: "VALIDATION_ERROR", message: "Valid project folder path is required." }, 400);
2751
+ }
2752
+ const target = path9.resolve(parsed.data.repoPath);
2753
+ if (!fs8.existsSync(target) || !fs8.statSync(target).isDirectory()) {
2754
+ return c.json({ error: "INVALID_REPO", message: "Selected path is not an accessible folder." }, 400);
2755
+ }
2756
+ state.repoPath = target;
2757
+ recordRecentRepo(target);
2758
+ const git = detectGitInfo(target);
2759
+ return c.json({
2760
+ data: {
2761
+ repoPath: target,
2762
+ repoName: path9.basename(target),
2763
+ isGitRepo: git.isGitRepo,
2764
+ gitBranch: git.gitBranch
2765
+ }
2766
+ });
2767
+ });
2768
+ app.get("/api/v1/files/tree", (c) => {
2769
+ try {
2770
+ return c.json({ data: scanRepositoryTree(state.repoPath) });
2771
+ } catch (err) {
2772
+ return c.json(
2773
+ { error: "SCAN_FAILED", message: err instanceof Error ? err.message : "Failed to scan folder." },
2774
+ 500
2775
+ );
2776
+ }
2777
+ });
2778
+ app.post("/api/v1/pack", async (c) => {
2779
+ const parsed = PackSchema.safeParse(await c.req.json().catch(() => null));
2780
+ if (!parsed.success) {
2781
+ return c.json(
2782
+ { error: "VALIDATION_ERROR", message: "Select at least one file and describe your task." },
2783
+ 400
2784
+ );
2785
+ }
2786
+ try {
2787
+ const result = buildPackResponse(state.repoPath, parsed.data);
2788
+ const config = loadConfig();
2789
+ if (config.defaultPatchFormat !== parsed.data.patchFormatPreference) {
2790
+ config.defaultPatchFormat = parsed.data.patchFormatPreference;
2791
+ saveConfig(config);
2792
+ }
2793
+ state.watcher.ignoreText(result.promptText);
2794
+ if (result.contextFileContent) {
2795
+ state.watcher.ignoreText(result.contextFileContent);
2796
+ if (parsed.data.mode === "file_attachment") {
2797
+ const cachedFilePath = writeSingleCacheFile(
2798
+ result.contextFileName,
2799
+ result.contextFileContent
2800
+ );
2801
+ result.cachedFilePath = cachedFilePath;
2802
+ state.watcher.ignoreText(cachedFilePath);
2803
+ if (parsed.data.copyFileToClipboard) {
2804
+ const clip = await copyFileToClipboard(cachedFilePath);
2805
+ result.fileCopiedToClipboard = clip.copied;
2806
+ result.fileClipboardError = clip.error ?? null;
2807
+ }
2808
+ }
2809
+ }
2810
+ return c.json({ data: result });
2811
+ } catch (err) {
2812
+ if (err instanceof PathSecurityError) {
2813
+ return c.json({ error: "PATH_FORBIDDEN", message: err.message }, 403);
2814
+ }
2815
+ return c.json(
2816
+ { error: "PACK_FAILED", message: err instanceof Error ? err.message : "Packing failed." },
2817
+ 500
2818
+ );
2819
+ }
2820
+ });
2821
+ app.post("/api/v1/patch/parse", async (c) => {
2822
+ const parsed = ParseSchema.safeParse(await c.req.json().catch(() => null));
2823
+ if (!parsed.success) {
2824
+ return c.json({ error: "VALIDATION_ERROR", message: "Paste an AI response containing code changes." }, 400);
2825
+ }
2826
+ const config = loadConfig();
2827
+ const result = parseAndPreviewPatch(state.repoPath, parsed.data.rawText, config.defaultPatchFormat);
2828
+ if (!result) {
2829
+ return c.json(
2830
+ {
2831
+ error: "NO_PATCH_FOUND",
2832
+ message: "No recognizable code edits were found. Make sure you copied the full AI reply."
2833
+ },
2834
+ 400
2835
+ );
2836
+ }
2837
+ if (result.retryPrompt) {
2838
+ state.watcher.ignoreText(result.retryPrompt);
2839
+ }
2840
+ return c.json({ data: result });
2841
+ });
2842
+ app.post("/api/v1/patch/apply", async (c) => {
2843
+ const parsed = ApplySchema.safeParse(await c.req.json().catch(() => null));
2844
+ if (!parsed.success) {
2845
+ return c.json({ error: "VALIDATION_ERROR", message: "Select at least one file to apply." }, 400);
2846
+ }
2847
+ try {
2848
+ const result = applySelectedFiles(
2849
+ state.repoPath,
2850
+ parsed.data.parseId,
2851
+ parsed.data.selectedFilePaths,
2852
+ parsed.data.customContents
2853
+ );
2854
+ return c.json({ data: result });
2855
+ } catch (err) {
2856
+ const msg = err instanceof Error ? err.message : "Apply failed.";
2857
+ if (msg.startsWith("FILE_CHANGED_ON_DISK:")) {
2858
+ return c.json({ error: "FILE_CHANGED_ON_DISK", message: msg.slice(21).trim() }, 409);
2859
+ }
2860
+ if (err instanceof PathSecurityError) {
2861
+ return c.json({ error: "PATH_FORBIDDEN", message: msg }, 403);
2862
+ }
2863
+ return c.json({ error: "APPLY_ERROR", message: msg.replace(/^[A-Z_]+:\s*/, "") }, 400);
2864
+ }
2865
+ });
2866
+ app.get("/api/v1/history", (c) => {
2867
+ return c.json({ data: { snapshots: listSnapshots(state.repoPath) } });
2868
+ });
2869
+ app.post("/api/v1/history/:snapshotId/undo", (c) => {
2870
+ try {
2871
+ const result = undoSnapshot(state.repoPath, c.req.param("snapshotId"));
2872
+ return c.json({ data: result });
2873
+ } catch (err) {
2874
+ const msg = err instanceof Error ? err.message : "Undo failed.";
2875
+ if (msg.startsWith("NOT_FOUND:")) {
2876
+ return c.json({ error: "NOT_FOUND", message: msg.slice(10).trim() }, 404);
2877
+ }
2878
+ if (msg.startsWith("ALREADY_REVERTED:")) {
2879
+ return c.json({ error: "ALREADY_REVERTED", message: msg.slice(17).trim() }, 409);
2880
+ }
2881
+ return c.json({ error: "UNDO_ERROR", message: msg }, 400);
2882
+ }
2883
+ });
2884
+ app.post("/api/v1/watcher/toggle", async (c) => {
2885
+ const parsed = ToggleWatcherSchema.safeParse(await c.req.json().catch(() => null));
2886
+ if (!parsed.success) {
2887
+ return c.json({ error: "VALIDATION_ERROR", message: "Boolean enabled flag required." }, 400);
2888
+ }
2889
+ const status = state.watcher.setEnabled(parsed.data.enabled);
2890
+ const config = loadConfig();
2891
+ config.clipboardWatchEnabled = status.enabled;
2892
+ saveConfig(config);
2893
+ state.broadcastWatcherStatus();
2894
+ return c.json({ data: status });
2895
+ });
2896
+ const currentDir = path9.dirname(fileURLToPath(import.meta.url));
2897
+ const publicDir = path9.resolve(currentDir, "public");
2898
+ app.get("*", (c) => {
2899
+ if (!fs8.existsSync(publicDir)) {
2900
+ return c.text("Chat2Diff API is running. In dev mode, open http://localhost:5173", 200);
2901
+ }
2902
+ const reqPath = c.req.path === "/" ? "/index.html" : c.req.path;
2903
+ const candidate = path9.resolve(publicDir, reqPath.replace(/^\/+/, ""));
2904
+ const safeFile = (candidate === publicDir || candidate.startsWith(publicDir + path9.sep)) && fs8.existsSync(candidate) && fs8.statSync(candidate).isFile() ? candidate : path9.join(publicDir, "index.html");
2905
+ const ext = path9.extname(safeFile).toLowerCase();
2906
+ const mime = MIME_TYPES[ext] || "application/octet-stream";
2907
+ const body = fs8.readFileSync(safeFile);
2908
+ return new Response(body, { status: 200, headers: { "Content-Type": mime } });
2909
+ });
2910
+ return app;
2911
+ }
2912
+
2913
+ // src/server/core/clipboardWatcher.ts
2914
+ import clipboard from "clipboardy";
2915
+ function normalizeClipboardText(text) {
2916
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();
2917
+ }
2918
+ var ClipboardWatcher = class {
2919
+ timer = null;
2920
+ lastHash = "";
2921
+ enabled;
2922
+ available = true;
2923
+ isPolling = false;
2924
+ ignoredHashes = /* @__PURE__ */ new Set();
2925
+ onPatchText;
2926
+ constructor(initialEnabled, onPatchText) {
2927
+ this.enabled = initialEnabled;
2928
+ this.onPatchText = onPatchText;
2929
+ }
2930
+ ignoreText(text) {
2931
+ if (!text) return;
2932
+ const hash = sha256(normalizeClipboardText(text));
2933
+ this.ignoredHashes.add(hash);
2934
+ if (this.ignoredHashes.size > 30) {
2935
+ const oldest = this.ignoredHashes.values().next().value;
2936
+ if (oldest) this.ignoredHashes.delete(oldest);
2937
+ }
2938
+ }
2939
+ async start() {
2940
+ try {
2941
+ const seed = await clipboard.read() ?? "";
2942
+ this.lastHash = sha256(normalizeClipboardText(seed));
2943
+ this.available = true;
2944
+ } catch {
2945
+ this.available = false;
2946
+ this.enabled = false;
2947
+ return;
2948
+ }
2949
+ if (this.timer) return;
2950
+ this.timer = setInterval(() => {
2951
+ void this.pollOnce();
2952
+ }, 850);
2953
+ }
2954
+ async pollOnce() {
2955
+ if (!this.enabled || !this.available || this.isPolling) return;
2956
+ this.isPolling = true;
2957
+ try {
2958
+ const current = await clipboard.read() ?? "";
2959
+ const hash = sha256(normalizeClipboardText(current));
2960
+ if (hash === this.lastHash) return;
2961
+ this.lastHash = hash;
2962
+ if (this.ignoredHashes.has(hash)) return;
2963
+ if (hasDetectablePatch(current)) {
2964
+ this.onPatchText(current);
2965
+ }
2966
+ } catch {
2967
+ } finally {
2968
+ this.isPolling = false;
2969
+ }
2970
+ }
2971
+ setEnabled(next) {
2972
+ if (!this.available) {
2973
+ this.enabled = false;
2974
+ return { enabled: false, available: false };
2975
+ }
2976
+ this.enabled = next;
2977
+ return { enabled: this.enabled, available: this.available };
2978
+ }
2979
+ getStatus() {
2980
+ return { enabled: this.enabled, available: this.available };
2981
+ }
2982
+ stop() {
2983
+ if (this.timer) {
2984
+ clearInterval(this.timer);
2985
+ this.timer = null;
2986
+ }
2987
+ }
2988
+ };
2989
+
2990
+ // src/server/cli.ts
2991
+ function getAppVersion() {
2992
+ const currentDir = path10.dirname(fileURLToPath2(import.meta.url));
2993
+ for (const rel of ["../package.json", "../../package.json"]) {
2994
+ try {
2995
+ const pkgPath = path10.resolve(currentDir, rel);
2996
+ if (fs9.existsSync(pkgPath)) {
2997
+ const pkg = JSON.parse(fs9.readFileSync(pkgPath, "utf8"));
2998
+ if (pkg.name === "chat2diff" && pkg.version) {
2999
+ return pkg.version;
3000
+ }
3001
+ }
3002
+ } catch {
3003
+ }
3004
+ }
3005
+ return APP_VERSION;
3006
+ }
3007
+ function printHelp(version) {
3008
+ console.log(`
3009
+ Chat2Diff v${version} \u2014 Use any AI chatbot safely on your local codebase.
3010
+
3011
+ Usage:
3012
+ npx chat2diff [directory] [options]
3013
+
3014
+ Arguments:
3015
+ directory Target project folder (default: current working directory)
3016
+
3017
+ Options:
3018
+ -p, --port <num> Localhost port to bind (default: ${DEFAULT_PORT}, auto-increments if busy)
3019
+ --no-open Start server without auto-opening your browser
3020
+ --no-watch Start with automatic clipboard listener paused
3021
+ -v, --version Print Chat2Diff version
3022
+ -h, --help Show this help message
3023
+
3024
+ Examples:
3025
+ npx chat2diff
3026
+ npx chat2diff ./my-project
3027
+ npx chat2diff --port 4500 --no-open
3028
+ `);
3029
+ }
3030
+ function parseCliArgs(argv) {
3031
+ let targetDir = process.cwd();
3032
+ let port = Number(process.env.CHAT2DIFF_PORT) || DEFAULT_PORT;
3033
+ let noOpen = process.env.CHAT2DIFF_NO_OPEN === "1";
3034
+ let noWatch = false;
3035
+ let devMode = false;
3036
+ let showHelp = false;
3037
+ let showVersion = false;
3038
+ for (let i = 0; i < argv.length; i++) {
3039
+ const arg = argv[i];
3040
+ if (arg === "-h" || arg === "--help") showHelp = true;
3041
+ else if (arg === "-v" || arg === "--version") showVersion = true;
3042
+ else if (arg === "--no-open") noOpen = true;
3043
+ else if (arg === "--no-watch") noWatch = true;
3044
+ else if (arg === "--dev") devMode = true;
3045
+ else if ((arg === "-p" || arg === "--port") && argv[i + 1]) {
3046
+ const parsedPort = Number(argv[++i]);
3047
+ if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
3048
+ console.error(`Error: Invalid port number. Use a value between 1 and 65535.`);
3049
+ process.exit(1);
3050
+ }
3051
+ port = parsedPort;
3052
+ } else if (arg.startsWith("-")) {
3053
+ console.error(`Error: Unknown option "${arg}". Run "chat2diff --help" for usage.`);
3054
+ process.exit(1);
3055
+ } else {
3056
+ targetDir = path10.resolve(arg);
3057
+ }
3058
+ }
3059
+ return { targetDir, port, noOpen, noWatch, devMode, showHelp, showVersion };
3060
+ }
3061
+ function findAvailablePort(startPort) {
3062
+ return new Promise((resolve, reject) => {
3063
+ const tryPort = (port) => {
3064
+ const tester = net.createServer();
3065
+ tester.once("error", (err) => {
3066
+ if (err.code === "EADDRINUSE" && port < startPort + 30) {
3067
+ tryPort(port + 1);
3068
+ } else {
3069
+ reject(err);
3070
+ }
3071
+ });
3072
+ tester.once("listening", () => {
3073
+ tester.close(() => resolve(port));
3074
+ });
3075
+ tester.listen(port, "127.0.0.1");
3076
+ };
3077
+ tryPort(startPort);
3078
+ });
3079
+ }
3080
+ async function main() {
3081
+ const version = getAppVersion();
3082
+ const opts = parseCliArgs(process.argv.slice(2));
3083
+ if (opts.showHelp) {
3084
+ printHelp(version);
3085
+ process.exit(0);
3086
+ }
3087
+ if (opts.showVersion) {
3088
+ console.log(version);
3089
+ process.exit(0);
3090
+ }
3091
+ if (!fs9.existsSync(opts.targetDir) || !fs9.statSync(opts.targetDir).isDirectory()) {
3092
+ console.error(`Error: Directory not found: ${opts.targetDir}`);
3093
+ process.exit(1);
3094
+ }
3095
+ recordRecentRepo(opts.targetDir);
3096
+ const config = loadConfig();
3097
+ const sessionToken = opts.devMode ? DEV_SESSION_TOKEN : crypto5.randomBytes(24).toString("hex");
3098
+ const port = opts.devMode ? opts.port : await findAvailablePort(opts.port);
3099
+ const wss = new WebSocketServer({ noServer: true });
3100
+ const broadcast = (event) => {
3101
+ const payload = JSON.stringify(event);
3102
+ for (const client of wss.clients) {
3103
+ if (client.readyState === WebSocket.OPEN) {
3104
+ client.send(payload);
3105
+ }
3106
+ }
3107
+ };
3108
+ let serverState;
3109
+ const watcher = new ClipboardWatcher(
3110
+ opts.noWatch ? false : config.clipboardWatchEnabled,
3111
+ (rawText) => {
3112
+ const parseResult = parseAndPreviewPatch(
3113
+ serverState.repoPath,
3114
+ rawText,
3115
+ loadConfig().defaultPatchFormat
3116
+ );
3117
+ if (parseResult) {
3118
+ if (parseResult.retryPrompt) {
3119
+ watcher.ignoreText(parseResult.retryPrompt);
3120
+ }
3121
+ broadcast({ type: "PATCH_DETECTED", payload: { parseResult } });
3122
+ }
3123
+ }
3124
+ );
3125
+ serverState = {
3126
+ repoPath: opts.targetDir,
3127
+ sessionToken,
3128
+ watcher,
3129
+ broadcastWatcherStatus: () => {
3130
+ broadcast({ type: "WATCHER_STATUS", payload: watcher.getStatus() });
3131
+ }
3132
+ };
3133
+ const app = createApp(serverState);
3134
+ const httpServer = serve({
3135
+ fetch: app.fetch,
3136
+ hostname: "127.0.0.1",
3137
+ port
3138
+ });
3139
+ httpServer.on("upgrade", (req, socket, head) => {
3140
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
3141
+ const token = url.searchParams.get("token") ?? void 0;
3142
+ if (url.pathname !== "/ws" || !isValidLocalHost(req.headers.host) || !verifySessionToken(token, sessionToken)) {
3143
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
3144
+ socket.destroy();
3145
+ return;
3146
+ }
3147
+ wss.handleUpgrade(req, socket, head, (ws) => {
3148
+ wss.emit("connection", ws, req);
3149
+ });
3150
+ });
3151
+ await watcher.start();
3152
+ const launchUrl = `http://127.0.0.1:${port}/#token=${sessionToken}`;
3153
+ console.log("");
3154
+ console.log(` Chat2Diff v${version} is running locally`);
3155
+ console.log(` Project: ${serverState.repoPath}`);
3156
+ if (opts.devMode) {
3157
+ console.log(` API: http://127.0.0.1:${port}`);
3158
+ console.log(" Dev UI: http://localhost:5173");
3159
+ } else {
3160
+ console.log(` Open: ${launchUrl}`);
3161
+ }
3162
+ console.log(" Press Ctrl+C to stop.");
3163
+ console.log("");
3164
+ if (!opts.noOpen && !opts.devMode) {
3165
+ await open(launchUrl).catch(() => {
3166
+ });
3167
+ }
3168
+ let shuttingDown = false;
3169
+ const shutdown = () => {
3170
+ if (shuttingDown) return;
3171
+ shuttingDown = true;
3172
+ watcher.stop();
3173
+ cleanupCacheDir();
3174
+ wss.close();
3175
+ httpServer.close(() => process.exit(0));
3176
+ setTimeout(() => process.exit(0), 1500).unref();
3177
+ };
3178
+ process.on("SIGINT", shutdown);
3179
+ process.on("SIGTERM", shutdown);
3180
+ }
3181
+ main().catch((err) => {
3182
+ console.error("Failed to start Chat2Diff:", err);
3183
+ process.exit(1);
3184
+ });