diffing 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +4 -0
  2. package/dist/cli-agent-BkkRbKqq.mjs +513 -0
  3. package/dist/cli-gh-DgqscIkg.mjs +147 -0
  4. package/dist/cli.mjs +4 -4
  5. package/dist/client/assets/{angular-html-BotC7B4-.js → angular-html-Dg8frIKA.js} +1 -1
  6. package/dist/client/assets/{angular-ts-DQTHeTJm.js → angular-ts-BgXWv16g.js} +1 -1
  7. package/dist/client/assets/{apl-Bwz5Dpd_.js → apl-uFl-_xI6.js} +1 -1
  8. package/dist/client/assets/{arc-D-TSgv-7.js → arc-2DyFlUoQ.js} +1 -1
  9. package/dist/client/assets/{architectureDiagram-3BPJPVTR-DLe25t8t.js → architectureDiagram-3BPJPVTR-Cpo5XnQh.js} +1 -1
  10. package/dist/client/assets/{astro-DjkoD2fR.js → astro-CsSgohj_.js} +1 -1
  11. package/dist/client/assets/{blade-Cap2uJIA.js → blade-tmMbmea0.js} +1 -1
  12. package/dist/client/assets/{blockDiagram-GPEHLZMM-B-bihLYO.js → blockDiagram-GPEHLZMM-C2j4VeON.js} +1 -1
  13. package/dist/client/assets/{c-C7JoAATL.js → c-CYFchk-Y.js} +1 -1
  14. package/dist/client/assets/{c4Diagram-AAUBKEIU-CoCcjXEC.js → c4Diagram-AAUBKEIU-B9Iu60rg.js} +1 -1
  15. package/dist/client/assets/channel-Br3gV-0C.js +1 -0
  16. package/dist/client/assets/{chunk-2J33WTMH-Sm_uQrGq.js → chunk-2J33WTMH-CYF5wgmI.js} +1 -1
  17. package/dist/client/assets/{chunk-3OPIFGDE-Ct83Sp4P.js → chunk-3OPIFGDE-BsCKEfSk.js} +1 -1
  18. package/dist/client/assets/{chunk-4BX2VUAB-DrqChk1a.js → chunk-4BX2VUAB-CKaohpWW.js} +1 -1
  19. package/dist/client/assets/{chunk-55IACEB6-CodeFb9E.js → chunk-55IACEB6-CPg0c8fY.js} +1 -1
  20. package/dist/client/assets/{chunk-5ZQYHXKU-CpEx4dmS.js → chunk-5ZQYHXKU-qstslfP1.js} +1 -1
  21. package/dist/client/assets/{chunk-727SXJPM-D3U6TUmk.js → chunk-727SXJPM-C1WRwOi2.js} +1 -1
  22. package/dist/client/assets/{chunk-AQP2D5EJ-Dr-_DyBy.js → chunk-AQP2D5EJ-_jbfFh_H.js} +1 -1
  23. package/dist/client/assets/{chunk-BSJP7CBP-Bnyml8mU.js → chunk-BSJP7CBP-CjQkUxwj.js} +1 -1
  24. package/dist/client/assets/{chunk-CSCIHK7Q-BJSFGTlk.js → chunk-CSCIHK7Q-D4khYgW5.js} +1 -1
  25. package/dist/client/assets/{chunk-FMBD7UC4-BqiwDIwx.js → chunk-FMBD7UC4-B1r9As4X.js} +1 -1
  26. package/dist/client/assets/{chunk-KSCS5N6A-D-H-HBRn.js → chunk-KSCS5N6A-XehlazPT.js} +1 -1
  27. package/dist/client/assets/{chunk-L5ZTLDWV-CVMSAF7h.js → chunk-L5ZTLDWV-5KMCRmgT.js} +1 -1
  28. package/dist/client/assets/{chunk-LZXEDZCA-BQsF6HF3.js → chunk-LZXEDZCA--x7aE-36.js} +2 -2
  29. package/dist/client/assets/{chunk-ND2GUHAM-eoM20ySO.js → chunk-ND2GUHAM-BcUeNQF6.js} +1 -1
  30. package/dist/client/assets/{chunk-NZK2D7GU-B1iU0i4a.js → chunk-NZK2D7GU-HdA4zA81.js} +1 -1
  31. package/dist/client/assets/{chunk-O5CBEL6O-CcIPuHUC.js → chunk-O5CBEL6O-BbkpkgBW.js} +1 -1
  32. package/dist/client/assets/chunk-QZHKN3VN-yNyHmFLj.js +1 -0
  33. package/dist/client/assets/chunk-WU5MYG2G-DOSgjhZV.js +1 -0
  34. package/dist/client/assets/{chunk-XPW4576I-jSj3E63-.js → chunk-XPW4576I-BrjJtb92.js} +1 -1
  35. package/dist/client/assets/classDiagram-4FO5ZUOK-BV8x1oiD.js +1 -0
  36. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-AibFxRy2.js +1 -0
  37. package/dist/client/assets/{cobol-DkiK_msx.js → cobol-CbEdzJpe.js} +1 -1
  38. package/dist/client/assets/{coffee-f7z4wIqP.js → coffee-BYBPPvKf.js} +1 -1
  39. package/dist/client/assets/{cose-bilkent-S5V4N54A-Dikk-RXu.js → cose-bilkent-S5V4N54A-C2UlmvWG.js} +1 -1
  40. package/dist/client/assets/{cpp-DB_FV8ps.js → cpp-Cy1Wnp8d.js} +1 -1
  41. package/dist/client/assets/{crystal-BRBnyZFz.js → crystal-Bg1sUJya.js} +1 -1
  42. package/dist/client/assets/{css-GpNBLqRF.js → css-C6iyzRBi.js} +1 -1
  43. package/dist/client/assets/{dagre-BM42HDAG-tErJNBcm.js → dagre-BM42HDAG-CLP5IYO3.js} +1 -1
  44. package/dist/client/assets/{diagram-2AECGRRQ-D0-DgitC.js → diagram-2AECGRRQ-Dg8GXMUD.js} +1 -1
  45. package/dist/client/assets/{diagram-5GNKFQAL-DqMjQTtW.js → diagram-5GNKFQAL-D5eskvC7.js} +1 -1
  46. package/dist/client/assets/{diagram-KO2AKTUF-CP7V9tqS.js → diagram-KO2AKTUF-SO-9Apcj.js} +1 -1
  47. package/dist/client/assets/{diagram-LMA3HP47-tCGdsz4p.js → diagram-LMA3HP47-Dz15-yRy.js} +1 -1
  48. package/dist/client/assets/{diagram-OG6HWLK6-DtDnaqso.js → diagram-OG6HWLK6-BuQK0W1m.js} +1 -1
  49. package/dist/client/assets/{dist-B5Eb-OKZ.js → dist-CZ555WMx.js} +1 -1
  50. package/dist/client/assets/{edge-DqnWvViE.js → edge-CmOR4HCT.js} +1 -1
  51. package/dist/client/assets/{elixir-BSuxOIIa.js → elixir-CK9qhOZG.js} +1 -1
  52. package/dist/client/assets/{elm-B6U1Is0L.js → elm-DZWlTp8-.js} +1 -1
  53. package/dist/client/assets/{erDiagram-TEJ5UH35-C5S0U2x3.js → erDiagram-TEJ5UH35-D7vADGZy.js} +1 -1
  54. package/dist/client/assets/{erb-kK3QM18H.js → erb-CTTGdXJ0.js} +1 -1
  55. package/dist/client/assets/{flowDiagram-I6XJVG4X-NNqmBYk2.js → flowDiagram-I6XJVG4X-BwcgAtP3.js} +1 -1
  56. package/dist/client/assets/{ganttDiagram-6RSMTGT7-8ng09X8S.js → ganttDiagram-6RSMTGT7-kInginE9.js} +1 -1
  57. package/dist/client/assets/{git-rebase-BDKTWtxr.js → git-rebase-B_sSbVaY.js} +1 -1
  58. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-D_HBvwVl.js → gitGraphDiagram-PVQCEYII-C4pDDMLO.js} +1 -1
  59. package/dist/client/assets/{glimmer-js-BthGlRra.js → glimmer-js-BaLXlo90.js} +1 -1
  60. package/dist/client/assets/{glimmer-ts-CS8Z9z2h.js → glimmer-ts-ugNWY62Y.js} +1 -1
  61. package/dist/client/assets/{glsl-C5ERhU2v.js → glsl-CDofiyvf.js} +1 -1
  62. package/dist/client/assets/{graphql-sfgTqbIp.js → graphql-lRTsx6gb.js} +1 -1
  63. package/dist/client/assets/{hack-EeOmOf4N.js → hack-DG646xxf.js} +1 -1
  64. package/dist/client/assets/{haml-DVf5-Ndq.js → haml-CjNyEqTY.js} +1 -1
  65. package/dist/client/assets/{handlebars-BSLgW49o.js → handlebars-DmTlsycc.js} +1 -1
  66. package/dist/client/assets/{html-DoOSf-hz.js → html-CYKa0iGt.js} +1 -1
  67. package/dist/client/assets/{html-derivative-BM0DLd1Z.js → html-derivative-CJrmldEy.js} +1 -1
  68. package/dist/client/assets/{http-d2p18QI6.js → http-Dv_sB6KO.js} +1 -1
  69. package/dist/client/assets/{hurl-CH2I2f66.js → hurl-aIa6gC3s.js} +1 -1
  70. package/dist/client/assets/index-CkjX2qPW.css +1 -0
  71. package/dist/client/assets/{index-CJI1E0bV.js → index-DLwFuHoH.js} +96 -101
  72. package/dist/client/assets/{infoDiagram-5YYISTIA-Cgg2FsCN.js → infoDiagram-5YYISTIA-DE1yaqeG.js} +1 -1
  73. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-pYRQFecr.js → ishikawaDiagram-YF4QCWOH-D61KC690.js} +1 -1
  74. package/dist/client/assets/{java-BFiqhlWm.js → java--GCJC5Ht.js} +1 -1
  75. package/dist/client/assets/{javascript-YWa7zRPZ.js → javascript-CLU-vrsL.js} +1 -1
  76. package/dist/client/assets/{jinja-h_UdmDAn.js → jinja-DpKxO4hN.js} +1 -1
  77. package/dist/client/assets/{jison-cOvcjPYz.js → jison-DAzEKgwk.js} +1 -1
  78. package/dist/client/assets/{journeyDiagram-JHISSGLW-D3EBlW7m.js → journeyDiagram-JHISSGLW-Bt37oidm.js} +1 -1
  79. package/dist/client/assets/{json-DT0GjoRi.js → json-CoxC1kMn.js} +1 -1
  80. package/dist/client/assets/{jsx-BaYjgZVH.js → jsx-Bjv8cqXv.js} +1 -1
  81. package/dist/client/assets/{julia-Cg36ySxC.js → julia-2HI5Piu6.js} +1 -1
  82. package/dist/client/assets/{just-KYC4U1y4.js → just-AUrPjdB4.js} +1 -1
  83. package/dist/client/assets/{kanban-definition-UN3LZRKU-DA42mt4M.js → kanban-definition-UN3LZRKU-D46QdRYJ.js} +1 -1
  84. package/dist/client/assets/{latex-DpuXxlsH.js → latex-DjzDlfkY.js} +1 -1
  85. package/dist/client/assets/{line-D91vf_Yl.js → line-D_rKDTVX.js} +1 -1
  86. package/dist/client/assets/{linear-CL7WzrL5.js → linear-DCm3ZWOL.js} +1 -1
  87. package/dist/client/assets/{liquid-Dua3sjBU.js → liquid-DZ8JEV93.js} +1 -1
  88. package/dist/client/assets/{lua-CpDMEbOh.js → lua-iKYCK6sd.js} +1 -1
  89. package/dist/client/assets/{marko-rM0rxrJ5.js → marko-CrhrBZpj.js} +1 -1
  90. package/dist/client/assets/{mdc-D-E4W6ne.js → mdc-M6YkRqT_.js} +1 -1
  91. package/dist/client/assets/{mermaid-parser.core-BLQDdrsf.js → mermaid-parser.core-DOlZkAUl.js} +1 -1
  92. package/dist/client/assets/{mermaid.core-BBR2Otc_.js → mermaid.core-B5kraaYr.js} +3 -3
  93. package/dist/client/assets/{mindmap-definition-RKZ34NQL-DMrApv-_.js → mindmap-definition-RKZ34NQL-CG-S_0Tm.js} +1 -1
  94. package/dist/client/assets/{nginx-wZWgcQLM.js → nginx-DGSv66H3.js} +1 -1
  95. package/dist/client/assets/{nim-Bh7OZsZh.js → nim-wTb9iFPK.js} +1 -1
  96. package/dist/client/assets/{perl-DtEqNC_V.js → perl-BrLOtih-.js} +1 -1
  97. package/dist/client/assets/{php-DX7bHce8.js → php-BpG59zED.js} +1 -1
  98. package/dist/client/assets/{pieDiagram-4H26LBE5-B2f9_PO6.js → pieDiagram-4H26LBE5-BSsvT950.js} +1 -1
  99. package/dist/client/assets/{pug-r67inScB.js → pug-L7QegceF.js} +1 -1
  100. package/dist/client/assets/{qml-f1bOqUwX.js → qml-Bhe1hZ7B.js} +1 -1
  101. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-DgdKno5G.js → quadrantDiagram-W4KKPZXB-Bxs1ZIId.js} +1 -1
  102. package/dist/client/assets/{r-Cpm-_vkr.js → r-D1TBw_pw.js} +1 -1
  103. package/dist/client/assets/{razor-CEymfLfo.js → razor-CQm1uFKr.js} +1 -1
  104. package/dist/client/assets/{regexp-DCnAJwuE.js → regexp--jRne08M.js} +1 -1
  105. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BIRl56-J.js → requirementDiagram-4Y6WPE33-BvrwIHRn.js} +1 -1
  106. package/dist/client/assets/{rst-Cm1M2uc8.js → rst-DojkdR69.js} +1 -1
  107. package/dist/client/assets/{ruby-B49kkGT0.js → ruby-CihGsdWE.js} +1 -1
  108. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-7XZZmV9N.js → sankeyDiagram-5OEKKPKP-ChVx7-uL.js} +1 -1
  109. package/dist/client/assets/{sas-BOXC9Iq4.js → sas-De9KOrSF.js} +1 -1
  110. package/dist/client/assets/{scss-DU2HGWZP.js → scss-s1VsrZAM.js} +1 -1
  111. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CtIjo3i9.js → sequenceDiagram-3UESZ5HK-DfGXu7Db.js} +1 -1
  112. package/dist/client/assets/{shellscript-YFjx1NBH.js → shellscript-BQarhH5B.js} +1 -1
  113. package/dist/client/assets/{shellsession-4zfyiKm-.js → shellsession-DudKTKQ_.js} +1 -1
  114. package/dist/client/assets/{soy-CRExh-ql.js → soy-CQggW1_P.js} +1 -1
  115. package/dist/client/assets/{sql-2Iw6Ta1F.js → sql-CyxjmxEX.js} +1 -1
  116. package/dist/client/assets/{src-Dn3_YOHM.js → src-Be3tFbq6.js} +1 -1
  117. package/dist/client/assets/{stata-DflAcpzB.js → stata-Baq2oukf.js} +1 -1
  118. package/dist/client/assets/{stateDiagram-AJRCARHV-D_w9F0BN.js → stateDiagram-AJRCARHV-DUsSkWi-.js} +1 -1
  119. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-DczGQieS.js +1 -0
  120. package/dist/client/assets/{surrealql-CMprrxj1.js → surrealql-DY_lPQU6.js} +1 -1
  121. package/dist/client/assets/{svelte-Bb_Bxt4a.js → svelte-oBaORrzD.js} +1 -1
  122. package/dist/client/assets/{templ-MJ_5gYAf.js → templ-WpkyVGPg.js} +1 -1
  123. package/dist/client/assets/{tex-BQ33E56K.js → tex-t_gMyObp.js} +1 -1
  124. package/dist/client/assets/{timeline-definition-PNZ67QCA-BzgsTjf8.js → timeline-definition-PNZ67QCA-DO30eyIk.js} +1 -1
  125. package/dist/client/assets/{ts-tags-Cddttr6f.js → ts-tags-Dn6NjJLA.js} +1 -1
  126. package/dist/client/assets/{tsx-BFchi_eS.js → tsx-DDWp_p5y.js} +1 -1
  127. package/dist/client/assets/{twig-CA8ssIYI.js → twig-FBY22xUa.js} +1 -1
  128. package/dist/client/assets/{typescript-tdiTR9sY.js → typescript-BHZBosYe.js} +1 -1
  129. package/dist/client/assets/{vennDiagram-CIIHVFJN-CMjPo4Qf.js → vennDiagram-CIIHVFJN-DbE8UKE1.js} +1 -1
  130. package/dist/client/assets/{vue-BbZNP0Rd.js → vue-CrOmWBlh.js} +1 -1
  131. package/dist/client/assets/{vue-html-02g5ipYx.js → vue-html-jBuGpXgg.js} +1 -1
  132. package/dist/client/assets/{vue-vine-9lCbaeLR.js → vue-vine-DEzqOkvG.js} +1 -1
  133. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-Cy6qwCgU.js → wardleyDiagram-YWT4CUSO-BqhSY5Qs.js} +1 -1
  134. package/dist/client/assets/{xml-BPPCB2P8.js → xml-DkWImCZV.js} +1 -1
  135. package/dist/client/assets/{xsl-1-u1Beet.js → xsl-BotuNSYU.js} +1 -1
  136. package/dist/client/assets/{xychartDiagram-2RQKCTM6-q9ysdRiS.js → xychartDiagram-2RQKCTM6-DA2pXGD9.js} +1 -1
  137. package/dist/client/assets/{yaml-79W-bav7.js → yaml-8lMTQUH5.js} +1 -1
  138. package/dist/client/favicon.svg +40 -0
  139. package/dist/client/index.html +7 -3
  140. package/dist/mcp-BgZO-iXI.mjs +1047 -0
  141. package/dist/mcp-BxBm3d5l.mjs +1047 -0
  142. package/dist/mcp-CphIUJUg.mjs +1047 -0
  143. package/dist/server-BZBFquG8.mjs +3875 -0
  144. package/dist/server-Bmt57wV5.mjs +3875 -0
  145. package/dist/server-D2xEbakj.mjs +3874 -0
  146. package/dist/server-lock-DaSx7DjW.mjs +1049 -0
  147. package/package.json +1 -1
  148. package/dist/client/assets/channel-h7e2aSOW.js +0 -1
  149. package/dist/client/assets/chunk-QZHKN3VN-HzjMGBiA.js +0 -1
  150. package/dist/client/assets/chunk-WU5MYG2G-D_yZ0nqc.js +0 -1
  151. package/dist/client/assets/classDiagram-4FO5ZUOK-eToeXGJV.js +0 -1
  152. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-D_EfzX89.js +0 -1
  153. package/dist/client/assets/index-Ct9zZxJ5.css +0 -1
  154. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-Brvg0TWH.js +0 -1
@@ -0,0 +1,3875 @@
1
+ import { C as isGitRepo, D as toSafeRelativePath, E as isSafePath, S as gitAddFile, T as revertHunk, _ as getRepoName, b as getTabSizeForFiles, c as formatComments, d as getCustomGitDiffAsync, f as getFileContent, g as getProjectStorageDir, h as getMergeStatus, l as getBranchName, m as getHunkHistory, p as getGitDiffAsync, u as getCommitSeriesSummary, v as getRepoRoot, w as listRepoFiles, x as getUntrackedFilePathsAsync, y as getShowDiff } from "./server-lock-DaSx7DjW.mjs";
2
+ import { n as formatPlanReview, r as sectionTitleForLine, t as extractPlanLines } from "./plan-format-B6nbAw_c.mjs";
3
+ import { execFile, execFileSync } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
5
+ import { dirname, extname, join, resolve } from "node:path";
6
+ import { existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
7
+ import { parseArgs, promisify } from "node:util";
8
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { homedir } from "node:os";
10
+ import { Hono } from "hono";
11
+ import { streamSSE } from "hono/streaming";
12
+ import { serve } from "@hono/node-server";
13
+ //#region src/lib/diff-options.ts
14
+ const DEFAULTS$1 = {
15
+ revisions: [],
16
+ staged: false,
17
+ merge: false,
18
+ pathspecs: [],
19
+ indentHeuristic: true,
20
+ noIndentHeuristic: false,
21
+ ignoreSpaceChange: false,
22
+ ignoreAllSpace: false,
23
+ ignoreBlankLines: false,
24
+ ignoreCrAtEol: false,
25
+ functionContext: false,
26
+ patchWithRaw: false,
27
+ patchWithStat: false,
28
+ compactSummary: false,
29
+ cumulative: false,
30
+ pickaxeAll: false,
31
+ exitCode: false,
32
+ quiet: false,
33
+ noPrefix: false,
34
+ binary: false,
35
+ fullIndex: false,
36
+ text: false,
37
+ textconv: false,
38
+ noExtDiff: false,
39
+ itaVisible: false,
40
+ noRelative: false,
41
+ findCopiesHarder: false,
42
+ noRenames: false,
43
+ base: false,
44
+ ours: false,
45
+ theirs: false,
46
+ check: false,
47
+ outputMode: "auto",
48
+ host: "127.0.0.1",
49
+ noOpen: false,
50
+ help: false,
51
+ version: false,
52
+ includeUnstaged: true,
53
+ includeUntracked: true,
54
+ tui: false,
55
+ gpu: false,
56
+ showMode: false,
57
+ showRevspecs: []
58
+ };
59
+ /**
60
+ * All git-diff option definitions for `node:util.parseArgs`.
61
+ * Categorised to match `git diff --help`.
62
+ */
63
+ const GIT_DIFF_OPTIONS = {
64
+ staged: { type: "boolean" },
65
+ cached: { type: "boolean" },
66
+ merge: { type: "boolean" },
67
+ "diff-algorithm": { type: "string" },
68
+ "indent-heuristic": {
69
+ type: "boolean",
70
+ default: true
71
+ },
72
+ "no-indent-heuristic": { type: "boolean" },
73
+ anchored: { type: "string" },
74
+ "ignore-space-change": {
75
+ type: "boolean",
76
+ short: "b"
77
+ },
78
+ "ignore-all-space": {
79
+ type: "boolean",
80
+ short: "w"
81
+ },
82
+ "ignore-blank-lines": { type: "boolean" },
83
+ "ignore-cr-at-eol": { type: "boolean" },
84
+ "ws-error-highlight": { type: "string" },
85
+ "unified": {
86
+ type: "string",
87
+ short: "U"
88
+ },
89
+ "inter-hunk-context": { type: "string" },
90
+ "function-context": {
91
+ type: "boolean",
92
+ short: "W"
93
+ },
94
+ "word-diff": { type: "string" },
95
+ "word-diff-regex": { type: "string" },
96
+ "color-words": { type: "string" },
97
+ "color-moved": { type: "string" },
98
+ "color-moved-ws": { type: "string" },
99
+ "find-copies": {
100
+ type: "string",
101
+ short: "C"
102
+ },
103
+ "find-copies-harder": { type: "boolean" },
104
+ "find-renames": {
105
+ type: "string",
106
+ short: "M"
107
+ },
108
+ "break-rewrites": {
109
+ type: "string",
110
+ short: "B"
111
+ },
112
+ "no-renames": { type: "boolean" },
113
+ patch: {
114
+ type: "boolean",
115
+ short: "p"
116
+ },
117
+ "no-patch": {
118
+ type: "boolean",
119
+ short: "s"
120
+ },
121
+ raw: { type: "boolean" },
122
+ "patch-with-raw": { type: "boolean" },
123
+ "patch-with-stat": { type: "boolean" },
124
+ numstat: { type: "boolean" },
125
+ shortstat: { type: "boolean" },
126
+ stat: { type: "string" },
127
+ summary: { type: "boolean" },
128
+ "name-only": { type: "boolean" },
129
+ "name-status": { type: "boolean" },
130
+ check: { type: "boolean" },
131
+ "compact-summary": { type: "boolean" },
132
+ dirstat: { type: "string" },
133
+ "dirstat-by-file": { type: "string" },
134
+ cumulative: { type: "boolean" },
135
+ "diff-filter": { type: "string" },
136
+ S: { type: "string" },
137
+ G: { type: "string" },
138
+ "pickaxe-all": { type: "boolean" },
139
+ output: {
140
+ type: "string",
141
+ short: "o"
142
+ },
143
+ "exit-code": { type: "boolean" },
144
+ quiet: { type: "boolean" },
145
+ "src-prefix": { type: "string" },
146
+ "dst-prefix": { type: "string" },
147
+ "no-prefix": { type: "boolean" },
148
+ "line-prefix": { type: "string" },
149
+ submodule: { type: "string" },
150
+ binary: { type: "boolean" },
151
+ "no-binary": { type: "boolean" },
152
+ "full-index": { type: "boolean" },
153
+ text: {
154
+ type: "boolean",
155
+ short: "a"
156
+ },
157
+ textconv: { type: "boolean" },
158
+ "no-textconv": { type: "boolean" },
159
+ "no-ext-diff": { type: "boolean" },
160
+ "ext-diff": { type: "string" },
161
+ "ita-visible": { type: "boolean" },
162
+ "ita-invisible-in-index": { type: "boolean" },
163
+ relative: { type: "string" },
164
+ "no-relative": { type: "boolean" },
165
+ "ignore-submodules": { type: "string" },
166
+ base: { type: "boolean" },
167
+ ours: { type: "boolean" },
168
+ theirs: { type: "boolean" }
169
+ };
170
+ /** Options that are diffing-specific, not git-diff options. */
171
+ const DIFFING_OPTIONS = {
172
+ port: { type: "string" },
173
+ host: { type: "string" },
174
+ "no-open": {
175
+ type: "boolean",
176
+ default: false
177
+ },
178
+ web: {
179
+ type: "boolean",
180
+ default: false
181
+ },
182
+ terminal: {
183
+ type: "boolean",
184
+ default: false
185
+ },
186
+ tui: {
187
+ type: "boolean",
188
+ default: false
189
+ },
190
+ gpu: {
191
+ type: "boolean",
192
+ default: false
193
+ },
194
+ "gh-pr": { type: "string" },
195
+ help: {
196
+ type: "boolean",
197
+ short: "h"
198
+ },
199
+ version: { type: "boolean" }
200
+ };
201
+ function getVersion() {
202
+ try {
203
+ const __dirname = dirname(fileURLToPath(import.meta.url));
204
+ return JSON.parse(readFileSync(resolve(__dirname, "..", "..", "package.json"), "utf-8")).version;
205
+ } catch {
206
+ return "unknown";
207
+ }
208
+ }
209
+ function printHelp() {
210
+ const version = getVersion();
211
+ console.log(`diffing v${version} – Local code review tool for git diffs
212
+
213
+ Usage: diffing [<git diff options>] [<revision>...] [-- <path>...]
214
+ diffing --web [<git diff options>] [<revision>...] [-- <path>...]
215
+ diffing [server options]
216
+
217
+ Git Diff Options (drop-in replacement for git diff):`);
218
+ printGitDiffHelp();
219
+ console.log(`
220
+ Diffing Server Options:
221
+ --port <port> Port to run the server on (default: random available port)
222
+ --host <host> Host address to bind to (default: 127.0.0.1). Pass
223
+ 0.0.0.0 to expose the server to the local network.
224
+ --no-open Don't open the browser automatically
225
+
226
+ Output Modes:
227
+ By default diffing auto-selects the best output mode:
228
+ - Terminal mode: when output is a pipe, redirect, or non-TTY
229
+ - Web mode: when output is a TTY (interactive terminal)
230
+
231
+ Force a mode with --web, --terminal, or --tui flags.
232
+ --tui is experimental and opt-in. It opens a native-Rust terminal
233
+ interface that mirrors the web dashboard. Falls back to git diff
234
+ output if the environment cannot support a TUI (piped stdin, CI,
235
+ missing binary).
236
+
237
+ Subcommands:
238
+ show <revspec>... Drop-in for 'git show'. Renders commit metadata
239
+ (subject, author, date, message body) above the
240
+ diff in the web UI. Accepts single commits,
241
+ ranges (a..b, a...b), tags, and multiple SHAs.
242
+ Use '--' to separate revspecs from pathspecs.
243
+
244
+ Custom ranges (e.g. main..feature) and 'gh pr' sessions also display a
245
+ "what is this diff" banner in the web UI summarising the diff source.
246
+
247
+ Examples:
248
+ diffing Review uncommitted changes (web UI)
249
+ diffing --staged Review staged changes
250
+ diffing HEAD~3 Review last 3 commits
251
+ diffing main..feature Compare branches
252
+ diffing show HEAD Review a single commit's metadata + diff
253
+ diffing show HEAD~3..HEAD Review the last 3 commits as a series
254
+ diffing show HEAD -- src/ Limit a commit review to a directory
255
+ diffing --diff-algorithm=patience src/ Diff with patience algorithm
256
+ diffing -U10 Diff with 10 context lines
257
+ diffing --word-diff=color Word-level diff in color
258
+ diffing -b -w Ignore whitespace changes
259
+ diffing --host 0.0.0.0 Allow other machines on the LAN to review
260
+ diffing --tui Open the experimental TUI (native Rust)
261
+
262
+ Note: 'diffing <sha>' runs 'git diff <sha>' (working tree vs <sha>); it
263
+ is not the same as 'diffing show <sha>'. Use 'show' when you want to
264
+ review a commit's changes.`);
265
+ }
266
+ function printGitDiffHelp() {
267
+ console.log(`
268
+ Revision / Range:
269
+ --staged, --cached Show staged changes
270
+ --merge Show merge conflicts
271
+
272
+ Diff Algorithm:
273
+ --diff-algorithm=<A> Choose diff algorithm (minimal, patience, histogram, myers)
274
+ --indent-heuristic Enable indent heuristic (default: on)
275
+ --no-indent-heuristic Disable indent heuristic
276
+ --anchored=<TEXT> Anchor diff algorithm to <TEXT>
277
+
278
+ Whitespace:
279
+ -b, --ignore-space-change Ignore changes in amount of whitespace
280
+ -w, --ignore-all-space Ignore whitespace when comparing lines
281
+ --ignore-blank-lines Ignore blank lines
282
+ --ignore-cr-at-eol Ignore carriage-return at EOL
283
+ --ws-error-highlight=<KIND> Highlight whitespace errors (none, default, all)
284
+
285
+ Context:
286
+ -U<n>, --unified=<n> Generate diffs with <n> lines of context
287
+ --inter-hunk-context=<n> Show <n> lines between diff hunks
288
+ -W, --function-context Show whole function as context
289
+
290
+ Word Diff:
291
+ --word-diff=<MODE> Word diff (color, plain, porcelain, none)
292
+ --word-diff-regex=<REGEX> Regex to determine a word
293
+ --color-words[=<REGEX>] Word diff with color
294
+
295
+ Moved / Copied Detection:
296
+ --color-moved=<MODE> Color moved lines (no, default, plain, blocks, zebra, dimmed-zebra)
297
+ --color-moved-ws=<MODE> How whitespace is treated in --color-moved
298
+ -C[<n>], --find-copies[=<n>] Detect copies
299
+ --find-copies-harder Spend extra cycles to find copies
300
+ -M[<n>], --find-renames[=<n>] Detect renames
301
+ -B[<n>], --break-rewrites[=<n>] Break complete rewrite changes into delete/add pairs
302
+ --no-renames Turn off rename detection
303
+
304
+ Merge / Conflict:
305
+ --base Compare with merge base (stage 1)
306
+ --ours Compare with our branch (stage 2)
307
+ --theirs Compare with their branch (stage 3)
308
+
309
+ Output Format:
310
+ -p, --patch Generate patch (default)
311
+ -s, --no-patch Suppress diff output
312
+ --raw Generate raw diff
313
+ --patch-with-raw Both patch and raw output
314
+ --patch-with-stat Both patch and stat
315
+ --numstat Machine-friendly stat: additions/deletions per file
316
+ --shortstat Summary of additions/deletions
317
+ --stat[=<width>] Diffstat with graph
318
+ --summary Extended header summary
319
+ --name-only Show only names of changed files
320
+ --name-status Show only names and status of changed files
321
+ --check Check if diff introduces whitespace errors
322
+ --compact-summary Compact summary for submodule changes
323
+ --dirstat[=<param>] Directory-level change stats
324
+ --dirstat-by-file[=<param>] Per-file directory stats
325
+ --cumulative Cumulative directory stats
326
+
327
+ Filtering:
328
+ --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]]
329
+ -S<string> Look for differences that change number of occurrences of <string>
330
+ -G<regex> Look for differences whose patch text contains <regex>
331
+ --pickaxe-all Show all changes with -S or -G
332
+
333
+ Output Control:
334
+ -o, --output=<file> Write diff to <file>
335
+ --exit-code Exit with 1 if differences, 0 if not
336
+ --quiet Disable all output, imply --exit-code
337
+
338
+ Prefixes:
339
+ --src-prefix=<PREFIX> Source prefix (default: "a/")
340
+ --dst-prefix=<PREFIX> Destination prefix (default: "b/")
341
+ --no-prefix Do not show source/destination prefixes
342
+ --line-prefix=<PREFIX> Prepend <PREFIX> to every line
343
+
344
+ Submodule:
345
+ --submodule=<FORMAT> Submodule diff format (diff, log, short)
346
+
347
+ Miscellaneous:
348
+ --binary Output binary diff (apply patch to binary files)
349
+ --no-binary Don't output binary diff
350
+ --full-index Show full blob object names
351
+ -a, --text Treat all files as text
352
+ --textconv Allow external text conversion filters
353
+ --no-textconv Disallow external text conversion filters
354
+ --no-ext-diff Disallow external diff drivers
355
+ --ext-diff=<CMD> Allow external diff driver
356
+ --ita-visible Include intent-to-add files
357
+ --ignore-submodules=<WHEN> Ignore submodule changes
358
+ --relative[=<path>] Show changes relative to <path>
359
+ --no-relative Don't show relative paths`);
360
+ }
361
+ /**
362
+ * Pre-process argv to handle git's optional-value flags.
363
+ *
364
+ * `-C`, `-M`, `-B` and their long forms (`--find-copies`, `--find-renames`,
365
+ * `--break-rewrites`) take an **optional** numeric argument in git — when the
366
+ * value is omitted, git uses the default similarity threshold (40%, 50%, 50%
367
+ * respectively for `-B`'s percentage component, 60% for the `x` part of
368
+ * `Bx/y`). `node:util.parseArgs` always consumes the next token as the value
369
+ * for `type: 'string'`, which means `diffing -C main..feature` would
370
+ * swallow `main..feature` as the `-C` value instead of treating it as a
371
+ * revision.
372
+ *
373
+ * This function rewrites the input argv so that:
374
+ * - `-C` (no attached value) followed by a non-digit → `--find-copies=40`
375
+ * - `-C` (no attached value) followed by a digit → left as-is so
376
+ * parseArgs consumes
377
+ * the numeric value
378
+ * - `-C40` (attached value) → left as-is
379
+ * - `--find-copies` (no value) followed by a digit → `--find-copies=<n>`
380
+ * - `--find-copies=40` (attached value) → left as-is
381
+ *
382
+ * The defaults mirror git's own behaviour: 40, 50, 50/60.
383
+ */
384
+ function preprocessOptionalValueArgs(rawArgs) {
385
+ const SHORTS = {
386
+ C: {
387
+ long: "find-copies",
388
+ def: "40"
389
+ },
390
+ M: {
391
+ long: "find-renames",
392
+ def: "50"
393
+ },
394
+ B: {
395
+ long: "break-rewrites",
396
+ def: "50/60"
397
+ }
398
+ };
399
+ const LONGS = new Set([
400
+ "find-copies",
401
+ "find-renames",
402
+ "break-rewrites"
403
+ ]);
404
+ const startsWithDigit = (s) => typeof s === "string" && /^[0-9]/.test(s);
405
+ const out = [];
406
+ for (let i = 0; i < rawArgs.length; i++) {
407
+ const arg = rawArgs[i];
408
+ if (arg.length === 2 && arg[0] === "-" && SHORTS[arg[1]]) {
409
+ const cfg = SHORTS[arg[1]];
410
+ const next = rawArgs[i + 1];
411
+ if (startsWithDigit(next)) out.push(arg);
412
+ else out.push(`--${cfg.long}=${cfg.def}`);
413
+ continue;
414
+ }
415
+ const longMatch = /^--(find-copies|find-renames|break-rewrites)$/.exec(arg);
416
+ if (longMatch) {
417
+ const name = longMatch[1];
418
+ if (!LONGS.has(name)) {
419
+ out.push(arg);
420
+ continue;
421
+ }
422
+ const next = rawArgs[i + 1];
423
+ if (startsWithDigit(next)) {
424
+ out.push(`--${name}=${next}`);
425
+ i++;
426
+ } else {
427
+ const def = name === "find-copies" ? "40" : name === "find-renames" ? "50" : "50/60";
428
+ out.push(`--${name}=${def}`);
429
+ }
430
+ continue;
431
+ }
432
+ out.push(arg);
433
+ }
434
+ return out;
435
+ }
436
+ /**
437
+ * Parse raw `process.argv` slice into typed DiffOptions.
438
+ *
439
+ * Strategy:
440
+ * 1. Pre-process optional-value args (`-C`, `-M`, `-B`, long forms) so they
441
+ * don't swallow following revisions like `main..feature`.
442
+ * 2. Split argv into: [diffing options] [git revisions] [-- pathspecs]
443
+ * 3. Parse known flags via node:util.parseArgs
444
+ * 4. Anything unknown / positional becomes a revision or pathspec
445
+ */
446
+ function parseDiffOptions(rawArgs) {
447
+ const { values, positionals } = parseArgs({
448
+ options: {
449
+ ...GIT_DIFF_OPTIONS,
450
+ ...DIFFING_OPTIONS
451
+ },
452
+ allowPositionals: true,
453
+ strict: false,
454
+ args: preprocessOptionalValueArgs(rawArgs)
455
+ });
456
+ const opts = {
457
+ ...DEFAULTS$1,
458
+ revisions: [],
459
+ pathspecs: [],
460
+ showRevspecs: []
461
+ };
462
+ if (values.help) opts.help = true;
463
+ if (values.version) opts.version = true;
464
+ if (values.port) opts.port = parseInt(values.port, 10);
465
+ if (values.host) opts.host = values.host;
466
+ if (values["no-open"]) opts.noOpen = true;
467
+ if (values.staged || values.cached) opts.staged = true;
468
+ if (values.merge) opts.merge = true;
469
+ const algo = values["diff-algorithm"];
470
+ if (algo && [
471
+ "minimal",
472
+ "patience",
473
+ "histogram",
474
+ "myers"
475
+ ].includes(algo)) opts.algorithm = algo;
476
+ if (values["no-indent-heuristic"]) {
477
+ opts.noIndentHeuristic = true;
478
+ opts.indentHeuristic = false;
479
+ }
480
+ if (values.anchored) opts.anchored = values.anchored;
481
+ if (values["ignore-space-change"]) opts.ignoreSpaceChange = true;
482
+ if (values["ignore-all-space"]) opts.ignoreAllSpace = true;
483
+ if (values["ignore-blank-lines"]) opts.ignoreBlankLines = true;
484
+ if (values["ignore-cr-at-eol"]) opts.ignoreCrAtEol = true;
485
+ const wsh = values["ws-error-highlight"];
486
+ if (wsh && [
487
+ "none",
488
+ "default",
489
+ "all"
490
+ ].includes(wsh)) opts.wsErrorHighlight = wsh;
491
+ if (values.unified) opts.unifiedContext = parseInt(values.unified, 10);
492
+ if (values["inter-hunk-context"]) opts.interHunkContext = parseInt(values["inter-hunk-context"], 10);
493
+ if (values["function-context"]) opts.functionContext = true;
494
+ const wd = values["word-diff"];
495
+ if (wd && [
496
+ "color",
497
+ "plain",
498
+ "porcelain",
499
+ "none"
500
+ ].includes(wd)) opts.wordDiff = wd;
501
+ if (values["word-diff-regex"]) opts.wordDiffRegex = values["word-diff-regex"];
502
+ if (values["color-words"]) {
503
+ opts.wordDiff = "color";
504
+ opts.wordDiffRegex = values["color-words"] || void 0;
505
+ }
506
+ const cm = values["color-moved"];
507
+ if (cm && [
508
+ "default",
509
+ "plain",
510
+ "blocks",
511
+ "zebra",
512
+ "dimmed-zebra",
513
+ "no"
514
+ ].includes(cm)) opts.colorMoved = cm;
515
+ const cmw = values["color-moved-ws"];
516
+ if (cmw && [
517
+ "no",
518
+ "ignore-space-at-eol",
519
+ "ignore-space-change",
520
+ "ignore-all-space",
521
+ "allow-indentation-change"
522
+ ].includes(cmw)) opts.colorMovedWs = cmw;
523
+ if (values["find-copies"] !== void 0) {
524
+ const v = values["find-copies"];
525
+ opts.findCopies = v ? parseInt(v, 10) : 40;
526
+ }
527
+ if (values["find-copies-harder"]) opts.findCopiesHarder = true;
528
+ if (values["find-renames"] !== void 0) {
529
+ const v = values["find-renames"];
530
+ opts.findRenames = v ? parseInt(v, 10) : 50;
531
+ }
532
+ if (values["break-rewrites"] !== void 0) opts.breakRewrites = values["break-rewrites"];
533
+ if (values["no-renames"]) opts.noRenames = true;
534
+ if (values.base) opts.base = true;
535
+ if (values.ours) opts.ours = true;
536
+ if (values.theirs) opts.theirs = true;
537
+ if (values.raw) opts.outputFormat = "raw";
538
+ if (values.numstat) opts.outputFormat = "numstat";
539
+ if (values.shortstat) opts.outputFormat = "shortstat";
540
+ if (values.stat !== void 0) opts.outputFormat = "stat";
541
+ if (values.summary) opts.outputFormat = "summary";
542
+ if (values["name-only"]) opts.outputFormat = "name-only";
543
+ if (values["name-status"]) opts.outputFormat = "name-status";
544
+ if (values["patch-with-raw"]) opts.patchWithRaw = true;
545
+ if (values["patch-with-stat"]) opts.patchWithStat = true;
546
+ if (values["compact-summary"]) opts.compactSummary = true;
547
+ if (values.dirstat) opts.dirstat = values.dirstat;
548
+ if (values["dirstat-by-file"]) opts.dirstatByFile = values["dirstat-by-file"];
549
+ if (values.cumulative) opts.cumulative = true;
550
+ if (values["no-patch"]) opts.outputFormat = void 0;
551
+ if (values.check) opts.outputFormat = void 0;
552
+ if (values["diff-filter"]) opts.diffFilter = values["diff-filter"];
553
+ if (values.S) opts.pickaxeString = values.S;
554
+ if (values.G) opts.pickaxeRegex = values.G;
555
+ if (values["pickaxe-all"]) opts.pickaxeAll = true;
556
+ if (values.output) opts.outputFile = values.output;
557
+ if (values["exit-code"]) opts.exitCode = true;
558
+ if (values.quiet) {
559
+ opts.quiet = true;
560
+ opts.exitCode = true;
561
+ }
562
+ if (values["src-prefix"]) opts.srcPrefix = values["src-prefix"];
563
+ if (values["dst-prefix"]) opts.dstPrefix = values["dst-prefix"];
564
+ if (values["no-prefix"]) opts.noPrefix = true;
565
+ if (values["line-prefix"]) opts.linePrefix = values["line-prefix"];
566
+ const sm = values.submodule;
567
+ if (sm && [
568
+ "diff",
569
+ "log",
570
+ "short"
571
+ ].includes(sm)) opts.submodule = sm;
572
+ if (values.binary) opts.binary = true;
573
+ if (values["no-binary"]) opts.binary = false;
574
+ if (values["full-index"]) opts.fullIndex = true;
575
+ if (values.text) opts.text = true;
576
+ if (values.textconv) opts.textconv = true;
577
+ if (values["no-textconv"]) opts.textconv = false;
578
+ if (values["no-ext-diff"]) opts.noExtDiff = true;
579
+ if (values["ext-diff"]) opts.extDiff = values["ext-diff"];
580
+ if (values["ita-visible"] || values["ita-invisible-in-index"]) opts.itaVisible = true;
581
+ if (values.relative !== void 0) opts.relative = values.relative || void 0;
582
+ if (values["no-relative"]) opts.noRelative = true;
583
+ if (values["ignore-submodules"]) {
584
+ const ig = values["ignore-submodules"];
585
+ if ([
586
+ "none",
587
+ "untracked",
588
+ "dirty",
589
+ "all"
590
+ ].includes(ig)) opts.ignoreSubmodules = ig;
591
+ }
592
+ const dashDashIdx = rawArgs.indexOf("--");
593
+ if (dashDashIdx >= 0) {
594
+ for (let i = 0; i < dashDashIdx; i++) {
595
+ const arg = rawArgs[i];
596
+ if (!arg.startsWith("-")) opts.revisions.push(arg);
597
+ }
598
+ for (let i = dashDashIdx + 1; i < rawArgs.length; i++) opts.pathspecs.push(rawArgs[i]);
599
+ } else for (const p of positionals) opts.revisions.push(p);
600
+ if (values.tui) opts.outputMode = "tui";
601
+ else if (values.web) opts.outputMode = "web";
602
+ else if (values.terminal) opts.outputMode = "terminal";
603
+ if (process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "web";
604
+ else if (!process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "terminal";
605
+ if (opts.outputFormat || opts.patchWithRaw || opts.patchWithStat || opts.exitCode || opts.quiet || opts.outputFile) opts.outputMode = "terminal";
606
+ return opts;
607
+ }
608
+ /**
609
+ * Build the `git diff` argument array from parsed options.
610
+ * Returns args that can be spread into `git diff <args>`.
611
+ */
612
+ function buildGitDiffArgs(opts) {
613
+ const args = [];
614
+ if (opts.algorithm) args.push(`--diff-algorithm=${opts.algorithm}`);
615
+ if (opts.noIndentHeuristic) args.push("--no-indent-heuristic");
616
+ if (opts.anchored) args.push(`--anchored=${opts.anchored}`);
617
+ if (opts.staged) args.push("--staged");
618
+ if (opts.merge) args.push("--merge");
619
+ if (opts.base) args.push("--base");
620
+ if (opts.ours) args.push("--ours");
621
+ if (opts.theirs) args.push("--theirs");
622
+ if (opts.ignoreSpaceChange) args.push("--ignore-space-change");
623
+ if (opts.ignoreAllSpace) args.push("--ignore-all-space");
624
+ if (opts.ignoreBlankLines) args.push("--ignore-blank-lines");
625
+ if (opts.ignoreCrAtEol) args.push("--ignore-cr-at-eol");
626
+ if (opts.wsErrorHighlight) args.push(`--ws-error-highlight=${opts.wsErrorHighlight}`);
627
+ if (opts.unifiedContext !== void 0) args.push(`--unified=${opts.unifiedContext}`);
628
+ if (opts.interHunkContext !== void 0) args.push(`--inter-hunk-context=${opts.interHunkContext}`);
629
+ if (opts.functionContext) args.push("--function-context");
630
+ if (opts.wordDiff) if (opts.wordDiff === "color" && opts.wordDiffRegex && !opts.colorWords) {
631
+ args.push(`--word-diff=color`);
632
+ args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
633
+ } else if (opts.wordDiff === "color" && opts.colorWords) args.push(`--color-words=${opts.wordDiffRegex || "."}`);
634
+ else args.push(`--word-diff=${opts.wordDiff}`);
635
+ if (opts.wordDiffRegex && opts.wordDiff !== "color") args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
636
+ if (opts.colorMoved) args.push(`--color-moved=${opts.colorMoved}`);
637
+ if (opts.colorMovedWs) args.push(`--color-moved-ws=${opts.colorMovedWs}`);
638
+ if (opts.findCopies !== void 0) args.push(opts.findCopies === 40 ? "-C" : `-C${opts.findCopies}`);
639
+ if (opts.findCopiesHarder) args.push("--find-copies-harder");
640
+ if (opts.findRenames !== void 0) args.push(opts.findRenames === 50 ? "-M" : `-M${opts.findRenames}`);
641
+ if (opts.breakRewrites !== void 0) args.push(`-B${opts.breakRewrites}`);
642
+ if (opts.noRenames) args.push("--no-renames");
643
+ if (opts.outputFormat === "raw") args.push("--raw");
644
+ if (opts.outputFormat === "numstat") args.push("--numstat");
645
+ if (opts.outputFormat === "shortstat") args.push("--shortstat");
646
+ if (opts.outputFormat === "stat") args.push("--stat");
647
+ if (opts.outputFormat === "summary") args.push("--summary");
648
+ if (opts.outputFormat === "name-only") args.push("--name-only");
649
+ if (opts.outputFormat === "name-status") args.push("--name-status");
650
+ if (opts.patchWithRaw) args.push("--patch-with-raw");
651
+ if (opts.patchWithStat) args.push("--patch-with-stat");
652
+ if (opts.compactSummary) args.push("--compact-summary");
653
+ if (opts.dirstat) args.push(`--dirstat=${opts.dirstat}`);
654
+ if (opts.dirstatByFile) args.push(`--dirstat-by-file=${opts.dirstatByFile}`);
655
+ if (opts.cumulative) args.push("--cumulative");
656
+ if (opts.check) args.push("--check");
657
+ if (opts.diffFilter) args.push(`--diff-filter=${opts.diffFilter}`);
658
+ if (opts.pickaxeString) args.push(`-S${opts.pickaxeString}`);
659
+ if (opts.pickaxeRegex) args.push(`-G${opts.pickaxeRegex}`);
660
+ if (opts.pickaxeAll) args.push("--pickaxe-all");
661
+ if (opts.outputFile) args.push(`--output=${opts.outputFile}`);
662
+ if (opts.exitCode) args.push("--exit-code");
663
+ if (opts.quiet) args.push("--quiet");
664
+ if (opts.srcPrefix) args.push(`--src-prefix=${opts.srcPrefix}`);
665
+ if (opts.dstPrefix) args.push(`--dst-prefix=${opts.dstPrefix}`);
666
+ if (opts.noPrefix) args.push("--no-prefix");
667
+ if (opts.linePrefix) args.push(`--line-prefix=${opts.linePrefix}`);
668
+ if (opts.submodule) args.push(`--submodule=${opts.submodule}`);
669
+ if (opts.binary) args.push("--binary");
670
+ if (opts.fullIndex) args.push("--full-index");
671
+ if (opts.text) args.push("--text");
672
+ if (opts.textconv) args.push("--textconv");
673
+ if (opts.noExtDiff) args.push("--no-ext-diff");
674
+ if (opts.extDiff) args.push(`--ext-diff=${opts.extDiff}`);
675
+ if (opts.itaVisible) args.push("--ita-visible");
676
+ if (opts.relative !== void 0) args.push(opts.relative ? `--relative=${opts.relative}` : "--relative");
677
+ if (opts.noRelative) args.push("--no-relative");
678
+ if (opts.ignoreSubmodules) args.push(`--ignore-submodules=${opts.ignoreSubmodules}`);
679
+ for (const rev of opts.revisions) args.push(rev);
680
+ if (opts.pathspecs.length > 0) {
681
+ args.push("--");
682
+ args.push(...opts.pathspecs);
683
+ }
684
+ return args;
685
+ }
686
+ /**
687
+ * Transform a `parseDiffOptions(...)` result into a "show mode" variant:
688
+ * moves any parsed revisions into `showRevspecs`, clears `revisions` (so the
689
+ * existing diff-engine path does not try to `git diff` them), and sets the
690
+ * `showMode` flag. Pathspecs and every other flag survive unchanged.
691
+ *
692
+ * Returns the same object for callsite ergonomics — the mutation is in-place
693
+ * because `parseDiffOptions` always returns a fresh object.
694
+ */
695
+ function intoShowMode(opts) {
696
+ opts.showRevspecs = opts.revisions;
697
+ opts.revisions = [];
698
+ opts.showMode = true;
699
+ return opts;
700
+ }
701
+ //#endregion
702
+ //#region src/lib/diff-overview.ts
703
+ /**
704
+ * Compose the working-tree banner. Used by the default `git diff` (unstaged +
705
+ * optionally staged + optionally untracked) flow.
706
+ */
707
+ function buildWorkingTreeOverview(input) {
708
+ const { branch, staged, untracked, untrackedCount, fileCount } = input;
709
+ const fileLabel = fileCount === 1 ? "file" : "files";
710
+ const headline = `Working-tree changes${branch ? ` on ${branch}` : ""}`;
711
+ const parts = [`${fileCount} ${fileLabel} changed`];
712
+ if (staged) parts.push("staged included");
713
+ if (untracked) {
714
+ const u = untrackedCount === 1 ? "1 untracked file" : `${untrackedCount} untracked files`;
715
+ parts.push(u);
716
+ }
717
+ return {
718
+ kind: "working-tree",
719
+ headline,
720
+ subtitle: parts.join(" · "),
721
+ commitSubjects: [],
722
+ commitCount: 0,
723
+ truncated: 0,
724
+ authors: []
725
+ };
726
+ }
727
+ /**
728
+ * Staged-only banner: only `--staged` is on, no untracked, no revisions.
729
+ * Shown when the user reviews a clean staging area.
730
+ */
731
+ function buildStagedOnlyOverview(input) {
732
+ const { branch, fileCount } = input;
733
+ const fileLabel = fileCount === 1 ? "file" : "files";
734
+ return {
735
+ kind: "staged-only",
736
+ headline: `Staged changes${branch ? ` on ${branch}` : ""}`,
737
+ subtitle: `${fileCount} ${fileLabel} staged for commit`,
738
+ commitSubjects: [],
739
+ commitCount: 0,
740
+ truncated: 0,
741
+ authors: []
742
+ };
743
+ }
744
+ /**
745
+ * Range banner: user-supplied revisions like `main..feature`, `HEAD~3..HEAD`,
746
+ * or multiple SHAs/tags. `revspecs` are joined into the `rangeLabel` verbatim
747
+ * (preserving `..` / `...` form the user typed).
748
+ */
749
+ function buildRangeOverview(input) {
750
+ const { revspecs, branch, commitSeries } = input;
751
+ const rangeLabel = revspecs.join(" ");
752
+ const { commitCount, truncated, subjects, authors, fromDate, toDate } = summariseCommitSeries(commitSeries);
753
+ const plural = commitCount === 1 ? "commit" : "commits";
754
+ return {
755
+ kind: "range",
756
+ headline: `Comparing ${rangeLabel}${branch ? ` (current: ${branch})` : ""}`,
757
+ subtitle: truncated > 0 ? `${commitCount} of ${commitCount + truncated} ${plural} shown` : `${commitCount} ${plural}`,
758
+ commitSubjects: subjects,
759
+ commitCount,
760
+ truncated,
761
+ fromDate,
762
+ toDate,
763
+ authors,
764
+ rangeLabel
765
+ };
766
+ }
767
+ /**
768
+ * Commit banner: invoked by `diffing show <rev>` — single SHA or series. The
769
+ * kind branches on `commits.length` so a single-commit review gets a tighter
770
+ * headline than a series.
771
+ */
772
+ function buildCommitOverview(input) {
773
+ const { commits, truncated, rangeLabel } = input;
774
+ const { commitCount, subjects, authors, fromDate, toDate } = summariseCommitRows(commits);
775
+ const isSingle = commitCount === 1;
776
+ const kind = isSingle ? "commit-single" : "commit-series";
777
+ let headline;
778
+ let subtitle;
779
+ if (isSingle) {
780
+ headline = subjects[0] ? `Commit: ${subjects[0]}` : "Single commit";
781
+ const subParts = [];
782
+ if (rangeLabel) subParts.push(rangeLabel);
783
+ if (authors[0]) subParts.push(authors[0]);
784
+ if (fromDate) subParts.push(formatDateShort(fromDate));
785
+ if (truncated > 0) subParts.push(`${commitCount} of ${commitCount + truncated} commits shown`);
786
+ subtitle = subParts.length > 0 ? subParts.join(" · ") : void 0;
787
+ } else {
788
+ const plural = "commits";
789
+ headline = `Reviewing ${commitCount} ${plural}`;
790
+ const subParts = [];
791
+ if (rangeLabel) subParts.push(rangeLabel);
792
+ if (authors.length > 0) subParts.push(authors.join(", "));
793
+ if (fromDate && toDate) subParts.push(`${formatDateShort(fromDate)} – ${formatDateShort(toDate)}`);
794
+ if (truncated > 0) subParts.push(`${commitCount} of ${commitCount + truncated} ${plural} shown`);
795
+ subtitle = subParts.length > 0 ? subParts.join(" · ") : void 0;
796
+ }
797
+ return {
798
+ kind,
799
+ headline,
800
+ subtitle,
801
+ commitSubjects: subjects,
802
+ commitCount,
803
+ truncated,
804
+ fromDate,
805
+ toDate,
806
+ authors,
807
+ rangeLabel
808
+ };
809
+ }
810
+ function formatDateShort(iso) {
811
+ try {
812
+ const d = new Date(iso);
813
+ if (Number.isNaN(d.getTime())) return iso;
814
+ return d.toLocaleDateString(void 0, {
815
+ year: "numeric",
816
+ month: "short",
817
+ day: "numeric"
818
+ });
819
+ } catch {
820
+ return iso;
821
+ }
822
+ }
823
+ /**
824
+ * PR banner: built from fields already in `pr-session.json`. No extra git or
825
+ * GitHub calls — the server's PR-mode branch hands us the headline shape and
826
+ * we keep the field set minimal so the banner never lies about counts.
827
+ */
828
+ function buildPrOverview(input) {
829
+ const { prNumber, prTitle, prAuthor, additions, deletions } = input;
830
+ const subParts = [];
831
+ if (prAuthor) subParts.push(`by ${prAuthor}`);
832
+ if (additions || deletions) subParts.push(`+${additions} / -${deletions}`);
833
+ return {
834
+ kind: "pr",
835
+ headline: `PR #${prNumber}: ${prTitle}`,
836
+ subtitle: subParts.length > 0 ? subParts.join(" · ") : void 0,
837
+ commitSubjects: [],
838
+ commitCount: 0,
839
+ truncated: 0,
840
+ authors: prAuthor ? [prAuthor] : [],
841
+ prNumber,
842
+ prTitle
843
+ };
844
+ }
845
+ /**
846
+ * Normalise a list of commit rows for the banner. Aggregates author + date
847
+ * ranges and trims subjects past the cap (so the banner never tries to render
848
+ * thousands of rows). The caller is responsible for passing the *visible*
849
+ * slice; `truncated` is preserved as-is.
850
+ */
851
+ function summariseCommitRows(rows) {
852
+ return summariseCommitSeries({
853
+ subjects: rows.map((r) => r.subject),
854
+ authors: [],
855
+ commitCount: rows.length,
856
+ truncated: 0
857
+ }, rows);
858
+ }
859
+ /**
860
+ * Internal helper used by both the row-list and the pre-aggregated series
861
+ * shape. When the caller already has aggregated metadata, it passes that
862
+ * directly; the rows are only used to recover authors + dates if the caller
863
+ * didn't supply them.
864
+ */
865
+ function summariseCommitSeries(series, rows) {
866
+ const subjects = series.subjects.filter((s) => s.length > 0);
867
+ let authors = series.authors;
868
+ let fromDate = series.fromDate;
869
+ let toDate = series.toDate;
870
+ if (rows && (authors.length === 0 || !fromDate || !toDate)) {
871
+ const seen = new Set(authors);
872
+ for (const r of rows) {
873
+ if (r.author && !seen.has(r.author)) {
874
+ seen.add(r.author);
875
+ authors = [...authors, r.author];
876
+ }
877
+ if (r.date) {
878
+ if (!fromDate || r.date < fromDate) fromDate = r.date;
879
+ if (!toDate || r.date > toDate) toDate = r.date;
880
+ }
881
+ }
882
+ }
883
+ return {
884
+ commitCount: series.commitCount,
885
+ subjects,
886
+ authors,
887
+ fromDate,
888
+ toDate,
889
+ truncated: series.truncated
890
+ };
891
+ }
892
+ //#endregion
893
+ //#region src/lib/diff-engine.ts
894
+ const MAX_BUFFER = 50 * 1024 * 1024;
895
+ /**
896
+ * Determine whether to use the "standard" web mode (unstaged+staged+untracked)
897
+ * or a "custom" mode (specific revisions / pathspecs).
898
+ *
899
+ * Custom mode is used when the user provides explicit revisions or pathspecs
900
+ * beyond just toggling staged/untracked. `showMode` is *also* a custom mode
901
+ * — the "Show staged / Show untracked" toggles don't apply to a commit view.
902
+ */
903
+ function isCustomMode$1(opts) {
904
+ return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
905
+ }
906
+ function parseFilePaths(patch) {
907
+ const paths = /* @__PURE__ */ new Set();
908
+ for (const line of patch.split("\n")) {
909
+ const match = line.match(/^diff --git a\/.+ b\/(.+)$/);
910
+ if (match) paths.add(match[1]);
911
+ }
912
+ return [...paths];
913
+ }
914
+ function parseBinaryFiles(patch, untrackedFiles) {
915
+ const binaryFiles = [];
916
+ const lines = patch.split("\n");
917
+ for (let i = 0; i < lines.length; i++) {
918
+ const line = lines[i];
919
+ if (!line.startsWith("Binary files ") || !line.includes(" differ")) continue;
920
+ let filePath = "";
921
+ for (let j = i - 1; j >= 0; j--) {
922
+ const match = lines[j].match(/^diff --git a\/.+ b\/(.+)$/);
923
+ if (match) {
924
+ filePath = match[1];
925
+ break;
926
+ }
927
+ }
928
+ if (!filePath) continue;
929
+ let changeType = "changed";
930
+ for (let j = i - 1; j >= 0; j--) {
931
+ if (lines[j].startsWith("diff --git")) break;
932
+ if (lines[j].startsWith("new file mode")) {
933
+ changeType = "added";
934
+ break;
935
+ }
936
+ if (lines[j].startsWith("deleted file mode")) {
937
+ changeType = "deleted";
938
+ break;
939
+ }
940
+ }
941
+ if (changeType === "added" && untrackedFiles?.has(filePath)) changeType = "untracked";
942
+ binaryFiles.push({
943
+ path: filePath,
944
+ type: changeType
945
+ });
946
+ }
947
+ return binaryFiles;
948
+ }
949
+ /**
950
+ * Execute a diff asynchronously — used by the server.
951
+ *
952
+ * Show mode bypasses the normal `git diff` path entirely: it resolves
953
+ * revspecs to a commit list and fetches per-commit metadata + patches in
954
+ * one `git log` call. The concatenated patch is returned in the same shape
955
+ * the existing UI pipeline expects (so file tree, binary detection, and
956
+ * tab-size detection all keep working unchanged); the per-commit data
957
+ * rides along on `commits` for the metadata banners.
958
+ */
959
+ async function executeDiffAsync(opts) {
960
+ if (opts.showMode) {
961
+ const { commits, patch, truncated } = await getShowDiff(opts.showRevspecs, opts.pathspecs);
962
+ return {
963
+ patch,
964
+ args: [],
965
+ commits,
966
+ truncated
967
+ };
968
+ }
969
+ if (isCustomMode$1(opts)) {
970
+ const args = buildGitDiffArgs(opts);
971
+ return {
972
+ patch: await getCustomGitDiffAsync(args),
973
+ args
974
+ };
975
+ }
976
+ return {
977
+ patch: await getGitDiffAsync({
978
+ staged: opts.staged,
979
+ untracked: opts.includeUntracked
980
+ }),
981
+ args: []
982
+ };
983
+ }
984
+ /**
985
+ * Execute a diff and produce the full enriched result used by the web API.
986
+ */
987
+ async function executeDiffWithMeta(opts) {
988
+ const { patch, commits, truncated } = await executeDiffAsync(opts);
989
+ const repoName = getRepoName();
990
+ const branch = getBranchName();
991
+ const untrackedFiles = opts.includeUntracked && !opts.showMode ? await getUntrackedFilePathsAsync() : [];
992
+ const binaryFiles = parseBinaryFiles(patch, new Set(untrackedFiles));
993
+ const filePaths = parseFilePaths(patch);
994
+ const tabSizeMap = getTabSizeForFiles(filePaths);
995
+ let overview;
996
+ if (opts.showMode && commits && commits.length > 0) overview = buildCommitOverview({
997
+ commits: commits.map((c) => ({
998
+ subject: c.subject,
999
+ author: c.authorName,
1000
+ date: c.authorDate
1001
+ })),
1002
+ truncated: truncated ?? 0,
1003
+ rangeLabel: deriveShowRangeLabel(opts.showRevspecs)
1004
+ });
1005
+ else if (!opts.showMode && opts.revisions.length > 0) {
1006
+ const series = await getCommitSeriesSummary(opts.revisions, opts.pathspecs);
1007
+ overview = buildRangeOverview({
1008
+ revspecs: opts.revisions,
1009
+ branch,
1010
+ commitSeries: {
1011
+ subjects: series.subjects,
1012
+ authors: series.authors,
1013
+ fromDate: series.fromDate,
1014
+ toDate: series.toDate,
1015
+ commitCount: series.commitCount,
1016
+ truncated: series.truncated
1017
+ }
1018
+ });
1019
+ } else if (!opts.showMode && opts.staged && !opts.includeUntracked && opts.revisions.length === 0) overview = buildStagedOnlyOverview({
1020
+ branch,
1021
+ fileCount: filePaths.length
1022
+ });
1023
+ else if (!opts.showMode) overview = buildWorkingTreeOverview({
1024
+ branch,
1025
+ staged: opts.staged,
1026
+ untracked: opts.includeUntracked,
1027
+ untrackedCount: untrackedFiles.length,
1028
+ fileCount: filePaths.length
1029
+ });
1030
+ return {
1031
+ patch,
1032
+ binaryFiles,
1033
+ filePaths,
1034
+ tabSizeMap,
1035
+ untrackedFiles,
1036
+ repoName,
1037
+ branch,
1038
+ ...commits ? { commits } : {},
1039
+ ...truncated ? { truncated } : {},
1040
+ ...overview ? { overview } : {}
1041
+ };
1042
+ }
1043
+ /**
1044
+ * Derive a display label for `diffing show` revspecs. Multi-revspecs and
1045
+ * range-like expressions (`A..B`, `A...B`) keep their raw form so the banner
1046
+ * subtitle tells the reviewer exactly what range is being shown. A plain
1047
+ * single SHA/tag is omitted because the headline already names the commit.
1048
+ */
1049
+ function deriveShowRangeLabel(revspecs) {
1050
+ if (revspecs.length === 0) return void 0;
1051
+ if (revspecs.length > 1) return revspecs.join(" ");
1052
+ const single = revspecs[0];
1053
+ if (single && (single.includes("..") || single.includes("..."))) return single;
1054
+ }
1055
+ /**
1056
+ * Run the diff in terminal mode: forward to git diff with full flags,
1057
+ * output to stdout. Behaves identically to `git diff`. In show mode this
1058
+ * delegates to `git show` instead so `diffing show <rev>... --terminal`
1059
+ * is a drop-in for `git show <rev>...`.
1060
+ */
1061
+ function runTerminalDiff(opts) {
1062
+ if (opts.showMode) return runTerminalShow(opts);
1063
+ const args = buildGitDiffArgs(opts);
1064
+ const enforceDefaults = !opts.outputFormat && !opts.quiet;
1065
+ const finalArgs = [];
1066
+ if (enforceDefaults) {
1067
+ if (!args.includes("--no-ext-diff") && !opts.extDiff) finalArgs.push("--no-ext-diff");
1068
+ }
1069
+ finalArgs.push(...args);
1070
+ try {
1071
+ execFileSync("git", ["diff", ...finalArgs], {
1072
+ encoding: "utf-8",
1073
+ maxBuffer: MAX_BUFFER,
1074
+ stdio: "inherit"
1075
+ });
1076
+ return 0;
1077
+ } catch (err) {
1078
+ if (err.status === 1 && opts.exitCode) return 1;
1079
+ return err.status ?? 1;
1080
+ }
1081
+ }
1082
+ /**
1083
+ * Terminal mode for `diffing show`: spawn `git show` with the user's revspecs
1084
+ * and pathspecs, inherit stdio, propagate exit code. We pass `--no-ext-diff`
1085
+ * so the output is a clean unified diff regardless of the user's git config
1086
+ * (matches the web-mode pipeline), but otherwise hand everything to git.
1087
+ */
1088
+ function runTerminalShow(opts) {
1089
+ const args = [
1090
+ "show",
1091
+ "--no-ext-diff",
1092
+ ...opts.showRevspecs
1093
+ ];
1094
+ if (opts.pathspecs.length > 0) args.push("--", ...opts.pathspecs);
1095
+ try {
1096
+ execFileSync("git", args, {
1097
+ encoding: "utf-8",
1098
+ maxBuffer: MAX_BUFFER,
1099
+ stdio: "inherit"
1100
+ });
1101
+ return 0;
1102
+ } catch (err) {
1103
+ return err.status ?? 1;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * Validate the environment: check that we're in a git repo.
1108
+ * Returns an error message or null.
1109
+ */
1110
+ function validateEnvironment() {
1111
+ if (!isGitRepo()) return "Error: not inside a git repository";
1112
+ return null;
1113
+ }
1114
+ //#endregion
1115
+ //#region src/lib/symbols.ts
1116
+ const SYMBOL_PATTERNS = [
1117
+ {
1118
+ pattern: /^\s*(?:export\s+)?(?:async\s+)?function\s+(\w[\w$]*)\s*[<(]/i,
1119
+ kind: "function",
1120
+ nameGroup: 1
1121
+ },
1122
+ {
1123
+ pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=\s*(?:async\s*)?\(/i,
1124
+ kind: "function",
1125
+ nameGroup: 1
1126
+ },
1127
+ {
1128
+ pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=\s*(?:async\s+)?function/i,
1129
+ kind: "function",
1130
+ nameGroup: 1
1131
+ },
1132
+ {
1133
+ pattern: /^\s*(?:export\s+)?class\s+(\w[\w$]*)/i,
1134
+ kind: "class",
1135
+ nameGroup: 1
1136
+ },
1137
+ {
1138
+ pattern: /^\s*(?:export\s+)?interface\s+(\w[\w$]*)/i,
1139
+ kind: "interface",
1140
+ nameGroup: 1
1141
+ },
1142
+ {
1143
+ pattern: /^\s*(?:export\s+)?type\s+(\w[\w$]*)\s*=/i,
1144
+ kind: "type",
1145
+ nameGroup: 1
1146
+ },
1147
+ {
1148
+ pattern: /^\s*(?:export\s+)?enum\s+(\w[\w$]*)/i,
1149
+ kind: "enum",
1150
+ nameGroup: 1
1151
+ },
1152
+ {
1153
+ pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=/i,
1154
+ kind: "variable",
1155
+ nameGroup: 1
1156
+ },
1157
+ {
1158
+ pattern: /^\s*def\s+(\w[\w$]*)\s*\(/i,
1159
+ kind: "function",
1160
+ nameGroup: 1
1161
+ },
1162
+ {
1163
+ pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?fn\s+(\w[\w$]*)\s*[<(]/i,
1164
+ kind: "function",
1165
+ nameGroup: 1
1166
+ },
1167
+ {
1168
+ pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?struct\s+(\w[\w$]*)/i,
1169
+ kind: "struct",
1170
+ nameGroup: 1
1171
+ },
1172
+ {
1173
+ pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?enum\s+(\w[\w$]*)/i,
1174
+ kind: "enum",
1175
+ nameGroup: 1
1176
+ },
1177
+ {
1178
+ pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?impl\s+(\w[\w$]*)/i,
1179
+ kind: "impl",
1180
+ nameGroup: 1
1181
+ },
1182
+ {
1183
+ pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?trait\s+(\w[\w$]*)/i,
1184
+ kind: "trait",
1185
+ nameGroup: 1
1186
+ },
1187
+ {
1188
+ pattern: /^\s*func\s+(\w[\w$]*)\s*\(/i,
1189
+ kind: "function",
1190
+ nameGroup: 1
1191
+ },
1192
+ {
1193
+ pattern: /^\s*(?:func\s+)?\((\w[\w$]*)\s+\*?\w+\)\s+(\w[\w$]*)\s*\(/i,
1194
+ kind: "method",
1195
+ nameGroup: 2
1196
+ }
1197
+ ];
1198
+ /**
1199
+ * Returns the symbol defined on this line (name + kind), or null if the line
1200
+ * is not a recognizable definition. The first matching pattern wins.
1201
+ */
1202
+ function classifySymbolLine(line) {
1203
+ for (const { pattern, kind, nameGroup } of SYMBOL_PATTERNS) {
1204
+ const match = pattern.exec(line);
1205
+ if (match) {
1206
+ const name = match[nameGroup];
1207
+ if (name) return {
1208
+ name,
1209
+ kind
1210
+ };
1211
+ }
1212
+ }
1213
+ return null;
1214
+ }
1215
+ //#endregion
1216
+ //#region src/lib/search.ts
1217
+ /**
1218
+ * Server-side code search powered by `@ff-labs/fff-node` — a native (Rust)
1219
+ * fuzzy file finder + live grep. Because it is a native Node addon it cannot
1220
+ * run in the browser, so the React client calls the `/api/search` endpoint and
1221
+ * this module owns the single long-lived `FileFinder` instance for the repo.
1222
+ *
1223
+ * Design notes:
1224
+ * - The native binary is loaded lazily via dynamic import inside `init()` so a
1225
+ * missing/incompatible platform binary degrades gracefully (search returns
1226
+ * an error) instead of crashing the whole server at module load.
1227
+ * - One finder per process, keyed implicitly to the repo root. Its frecency /
1228
+ * history databases live under the project's `~/.diffing/<repo>` storage dir
1229
+ * so we never write stray files into the user's repository.
1230
+ * - fff runs its own file-system watcher, so the index stays fresh as the
1231
+ * working tree changes during a review.
1232
+ * - "Symbols" search is plain grep for the identifier, then each hit line is
1233
+ * classified with the shared {@link classifySymbolLine} patterns — fff 0.8.x
1234
+ * does not populate `isDefinition`, so we do the classification ourselves.
1235
+ */
1236
+ const DEFAULT_LIMIT = 60;
1237
+ const MAX_LIMIT = 200;
1238
+ /** Internal page size when no path filter — generous so diff-first client
1239
+ * ranking has enough to work with. */
1240
+ const SCAN_PAGE = 200;
1241
+ /** Larger page size when filtering to a path set, so the post-filter is
1242
+ * effectively complete for normal-sized diffs/repos. */
1243
+ const SCAN_PAGE_FILTERED = 1e3;
1244
+ let finder = null;
1245
+ let initPromise = null;
1246
+ let initError = null;
1247
+ let shutdownHooked = false;
1248
+ function clampLimit(limit) {
1249
+ if (!limit || limit < 1) return DEFAULT_LIMIT;
1250
+ return Math.min(limit, MAX_LIMIT);
1251
+ }
1252
+ async function init() {
1253
+ try {
1254
+ const { FileFinder } = await import("@ff-labs/fff-node");
1255
+ const root = getRepoRoot();
1256
+ const dbDir = join(getProjectStorageDir(root), "fff");
1257
+ mkdirSync(dbDir, { recursive: true });
1258
+ const created = FileFinder.create({
1259
+ basePath: root,
1260
+ frecencyDbPath: join(dbDir, "frecency.db"),
1261
+ historyDbPath: join(dbDir, "history.db"),
1262
+ logLevel: "error"
1263
+ });
1264
+ if (!created.ok) {
1265
+ initError = created.error;
1266
+ return null;
1267
+ }
1268
+ const f = created.value;
1269
+ if (!shutdownHooked) {
1270
+ shutdownHooked = true;
1271
+ process.once("exit", () => {
1272
+ try {
1273
+ f.destroy();
1274
+ } catch {}
1275
+ });
1276
+ }
1277
+ await f.waitForScan(8e3);
1278
+ finder = f;
1279
+ return f;
1280
+ } catch (err) {
1281
+ initError = err?.message ?? String(err);
1282
+ return null;
1283
+ }
1284
+ }
1285
+ async function getFinder() {
1286
+ if (finder) return finder;
1287
+ if (initError) return null;
1288
+ if (!initPromise) initPromise = init();
1289
+ return initPromise;
1290
+ }
1291
+ function isIndexing(f) {
1292
+ try {
1293
+ return f.isScanning();
1294
+ } catch {
1295
+ return false;
1296
+ }
1297
+ }
1298
+ async function searchFiles(query, opts = {}) {
1299
+ const f = await getFinder();
1300
+ if (!f) return {
1301
+ scope: "files",
1302
+ items: [],
1303
+ total: 0,
1304
+ indexing: false,
1305
+ error: initError ?? "Search unavailable"
1306
+ };
1307
+ const limit = clampLimit(opts.limit);
1308
+ const pathSet = opts.paths ? new Set(opts.paths) : null;
1309
+ const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE, limit);
1310
+ const res = f.fileSearch(query, { pageSize });
1311
+ if (!res.ok) return {
1312
+ scope: "files",
1313
+ items: [],
1314
+ total: 0,
1315
+ indexing: isIndexing(f),
1316
+ error: res.error
1317
+ };
1318
+ const items = [];
1319
+ const { items: raw, scores } = res.value;
1320
+ for (let i = 0; i < raw.length && items.length < limit; i++) {
1321
+ const it = raw[i];
1322
+ if (pathSet && !pathSet.has(it.relativePath)) continue;
1323
+ const score = scores[i];
1324
+ items.push({
1325
+ path: it.relativePath,
1326
+ fileName: it.fileName,
1327
+ gitStatus: it.gitStatus,
1328
+ matchType: score?.matchType ?? "",
1329
+ exact: !!score?.exactMatch
1330
+ });
1331
+ }
1332
+ return {
1333
+ scope: "files",
1334
+ items,
1335
+ total: res.value.totalMatched,
1336
+ indexing: isIndexing(f)
1337
+ };
1338
+ }
1339
+ async function searchContent(query, opts = {}) {
1340
+ const f = await getFinder();
1341
+ if (!f) return {
1342
+ scope: "text",
1343
+ items: [],
1344
+ total: 0,
1345
+ indexing: false,
1346
+ error: initError ?? "Search unavailable"
1347
+ };
1348
+ if (!query) return {
1349
+ scope: "text",
1350
+ items: [],
1351
+ total: 0,
1352
+ indexing: isIndexing(f)
1353
+ };
1354
+ const limit = clampLimit(opts.limit);
1355
+ const pathSet = opts.paths ? new Set(opts.paths) : null;
1356
+ const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE, limit);
1357
+ const res = f.grep(query, {
1358
+ mode: opts.regex ? "regex" : "plain",
1359
+ smartCase: true,
1360
+ beforeContext: 0,
1361
+ afterContext: 0,
1362
+ pageSize
1363
+ });
1364
+ if (!res.ok) return {
1365
+ scope: "text",
1366
+ items: [],
1367
+ total: 0,
1368
+ indexing: isIndexing(f),
1369
+ error: res.error
1370
+ };
1371
+ const items = [];
1372
+ for (const m of res.value.items) {
1373
+ if (items.length >= limit) break;
1374
+ if (pathSet && !pathSet.has(m.relativePath)) continue;
1375
+ items.push(toContentHit(m));
1376
+ }
1377
+ return {
1378
+ scope: "text",
1379
+ items,
1380
+ total: res.value.totalMatched,
1381
+ indexing: isIndexing(f),
1382
+ regexError: res.value.regexFallbackError || void 0
1383
+ };
1384
+ }
1385
+ function toContentHit(m) {
1386
+ return {
1387
+ path: m.relativePath,
1388
+ fileName: m.fileName,
1389
+ line: m.lineNumber,
1390
+ col: m.col,
1391
+ content: m.lineContent,
1392
+ matchRanges: m.matchRanges ?? [],
1393
+ gitStatus: m.gitStatus
1394
+ };
1395
+ }
1396
+ async function searchSymbols(query, opts = {}) {
1397
+ const f = await getFinder();
1398
+ if (!f) return {
1399
+ scope: "symbols",
1400
+ items: [],
1401
+ total: 0,
1402
+ indexing: false,
1403
+ error: initError ?? "Search unavailable"
1404
+ };
1405
+ if (!query) return {
1406
+ scope: "symbols",
1407
+ items: [],
1408
+ total: 0,
1409
+ indexing: isIndexing(f)
1410
+ };
1411
+ const limit = clampLimit(opts.limit);
1412
+ const pathSet = opts.paths ? new Set(opts.paths) : null;
1413
+ const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE_FILTERED, limit * 8);
1414
+ const res = f.grep(query, {
1415
+ mode: "plain",
1416
+ smartCase: true,
1417
+ beforeContext: 0,
1418
+ afterContext: 0,
1419
+ pageSize
1420
+ });
1421
+ if (!res.ok) return {
1422
+ scope: "symbols",
1423
+ items: [],
1424
+ total: 0,
1425
+ indexing: isIndexing(f),
1426
+ error: res.error
1427
+ };
1428
+ const items = [];
1429
+ const ql = query.toLowerCase();
1430
+ const seen = /* @__PURE__ */ new Set();
1431
+ for (const m of res.value.items) {
1432
+ if (items.length >= limit) break;
1433
+ if (pathSet && !pathSet.has(m.relativePath)) continue;
1434
+ const sym = classifySymbolLine(m.lineContent);
1435
+ if (!sym) continue;
1436
+ if (!sym.name.toLowerCase().includes(ql)) continue;
1437
+ const key = `${m.relativePath}:${m.lineNumber}:${sym.name}`;
1438
+ if (seen.has(key)) continue;
1439
+ seen.add(key);
1440
+ const nameIdx = m.lineContent.indexOf(sym.name);
1441
+ const matchRanges = nameIdx >= 0 ? [[nameIdx, nameIdx + sym.name.length]] : m.matchRanges ?? [];
1442
+ items.push({
1443
+ name: sym.name,
1444
+ kind: sym.kind,
1445
+ path: m.relativePath,
1446
+ fileName: m.fileName,
1447
+ line: m.lineNumber,
1448
+ content: m.lineContent,
1449
+ matchRanges,
1450
+ gitStatus: m.gitStatus
1451
+ });
1452
+ }
1453
+ return {
1454
+ scope: "symbols",
1455
+ items,
1456
+ total: items.length,
1457
+ indexing: isIndexing(f)
1458
+ };
1459
+ }
1460
+ async function searchAll(query, opts = {}) {
1461
+ const limit = clampLimit(opts.limit);
1462
+ const [filesRes, contentRes, symbolsRes] = await Promise.all([
1463
+ searchFiles(query, {
1464
+ ...opts,
1465
+ limit
1466
+ }),
1467
+ searchContent(query, {
1468
+ ...opts,
1469
+ limit
1470
+ }),
1471
+ searchSymbols(query, {
1472
+ ...opts,
1473
+ limit
1474
+ })
1475
+ ]);
1476
+ const items = [];
1477
+ for (const hit of filesRes.items) items.push({
1478
+ kind: "file",
1479
+ hit
1480
+ });
1481
+ for (const hit of symbolsRes.items) items.push({
1482
+ kind: "symbol",
1483
+ hit
1484
+ });
1485
+ for (const hit of contentRes.items) items.push({
1486
+ kind: "text",
1487
+ hit
1488
+ });
1489
+ const total = (filesRes.total || 0) + (contentRes.total || 0) + (symbolsRes.total || 0);
1490
+ const indexing = filesRes.indexing || contentRes.indexing || symbolsRes.indexing;
1491
+ const error = filesRes.error || contentRes.error || symbolsRes.error;
1492
+ const regexError = contentRes.regexError;
1493
+ return {
1494
+ scope: "all",
1495
+ items: items.slice(0, limit),
1496
+ total,
1497
+ indexing,
1498
+ error,
1499
+ regexError
1500
+ };
1501
+ }
1502
+ async function getSearchStatus() {
1503
+ const f = await getFinder();
1504
+ if (!f) return {
1505
+ available: false,
1506
+ indexing: false,
1507
+ indexedFiles: 0,
1508
+ error: initError ?? "Search unavailable"
1509
+ };
1510
+ let indexedFiles = 0;
1511
+ let indexing = false;
1512
+ try {
1513
+ const prog = f.getScanProgress();
1514
+ if (prog.ok) {
1515
+ indexedFiles = prog.value.scannedFilesCount;
1516
+ indexing = prog.value.isScanning;
1517
+ }
1518
+ } catch {}
1519
+ return {
1520
+ available: true,
1521
+ indexing,
1522
+ indexedFiles
1523
+ };
1524
+ }
1525
+ /** Record that the user opened `path` from a query, improving fff's frecency
1526
+ * ranking for future searches. Best-effort, never throws. */
1527
+ async function trackSelection(query, path) {
1528
+ const f = await getFinder();
1529
+ if (!f) return;
1530
+ try {
1531
+ f.trackQuery(query, path);
1532
+ } catch {}
1533
+ }
1534
+ //#endregion
1535
+ //#region src/lib/settings.ts
1536
+ const CONFIG_DIR = join(homedir(), ".config", "diffing");
1537
+ const SETTINGS_FILE = join(CONFIG_DIR, "settings.json");
1538
+ const DEFAULTS = {
1539
+ staged: true,
1540
+ untracked: true,
1541
+ diffStyle: "split",
1542
+ defaultTabSize: 4,
1543
+ theme: "nord",
1544
+ editorIDE: "default",
1545
+ lineDiffType: "word",
1546
+ lineWrap: false,
1547
+ diffIndicators: "classic",
1548
+ showLineNumbers: true,
1549
+ hunkSeparators: "line-info",
1550
+ lineHoverHighlight: "both",
1551
+ fontSize: 13,
1552
+ expandContextByDefault: false,
1553
+ collapsedContextThreshold: 10,
1554
+ expansionLineCount: 20,
1555
+ haptics: true,
1556
+ sounds: true,
1557
+ uiFont: null,
1558
+ monoFont: null,
1559
+ density: "comfortable",
1560
+ autoCollapseLineThreshold: 400,
1561
+ requireViewAllBeforeSend: false,
1562
+ showStatusBar: true
1563
+ };
1564
+ function loadSettings() {
1565
+ try {
1566
+ const data = readFileSync(SETTINGS_FILE, "utf-8");
1567
+ return {
1568
+ ...DEFAULTS,
1569
+ ...JSON.parse(data)
1570
+ };
1571
+ } catch {
1572
+ return { ...DEFAULTS };
1573
+ }
1574
+ }
1575
+ function saveSettings(settings) {
1576
+ const merged = {
1577
+ ...loadSettings(),
1578
+ ...settings
1579
+ };
1580
+ mkdirSync(CONFIG_DIR, { recursive: true });
1581
+ writeFileSync(SETTINGS_FILE, JSON.stringify(merged, null, 2));
1582
+ return merged;
1583
+ }
1584
+ //#endregion
1585
+ //#region src/lib/comments.ts
1586
+ var FileCommentStore = class {
1587
+ dirPath;
1588
+ filePath;
1589
+ /**
1590
+ * @param storageDir Absolute directory to persist `comments.json` in.
1591
+ * Defaults to the per-repo storage dir under `~/.diffing` — comments are
1592
+ * NEVER written inside the reviewed (consumer) repo, so a consumer project
1593
+ * stays free of any diffing-specific artifacts. The override exists only so
1594
+ * tests can point at a throwaway temp dir.
1595
+ */
1596
+ constructor(storageDir) {
1597
+ this.dirPath = storageDir ?? getProjectStorageDir();
1598
+ this.filePath = join(this.dirPath, "comments.json");
1599
+ }
1600
+ async getAll() {
1601
+ try {
1602
+ const data = await readFile(this.filePath, "utf-8");
1603
+ return JSON.parse(data);
1604
+ } catch {
1605
+ return [];
1606
+ }
1607
+ }
1608
+ async save(comments) {
1609
+ try {
1610
+ await mkdir(this.dirPath, { recursive: true });
1611
+ try {
1612
+ const repoRoot = getRepoRoot();
1613
+ await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1614
+ } catch {}
1615
+ await writeFile(this.filePath, JSON.stringify(comments, null, 2), "utf-8");
1616
+ } catch (err) {
1617
+ console.error("Failed to save comments to file:", err);
1618
+ }
1619
+ }
1620
+ async add(comment) {
1621
+ const comments = await this.getAll();
1622
+ comments.push(comment);
1623
+ await this.save(comments);
1624
+ return comment;
1625
+ }
1626
+ async update(id, fields) {
1627
+ const comments = await this.getAll();
1628
+ const index = comments.findIndex((c) => c.id === id);
1629
+ if (index === -1) return null;
1630
+ const comment = comments[index];
1631
+ if (fields.body !== void 0) comment.body = fields.body;
1632
+ if (fields.status !== void 0) comment.status = fields.status;
1633
+ await this.save(comments);
1634
+ return comment;
1635
+ }
1636
+ async resolveAllOpen() {
1637
+ const comments = await this.getAll();
1638
+ let n = 0;
1639
+ for (const c of comments) if (c.status === "open") {
1640
+ c.status = "resolved";
1641
+ n++;
1642
+ }
1643
+ if (n > 0) await this.save(comments);
1644
+ return n;
1645
+ }
1646
+ async remove(id) {
1647
+ const comments = await this.getAll();
1648
+ const index = comments.findIndex((c) => c.id === id);
1649
+ if (index === -1) return false;
1650
+ comments.splice(index, 1);
1651
+ await this.save(comments);
1652
+ return true;
1653
+ }
1654
+ async addReply(commentId, reply) {
1655
+ const comments = await this.getAll();
1656
+ const index = comments.findIndex((c) => c.id === commentId);
1657
+ if (index === -1) return null;
1658
+ const comment = comments[index];
1659
+ if (!comment.replies) comment.replies = [];
1660
+ comment.replies.push(reply);
1661
+ await this.save(comments);
1662
+ return comment;
1663
+ }
1664
+ async removeReply(commentId, replyId) {
1665
+ const comments = await this.getAll();
1666
+ const index = comments.findIndex((c) => c.id === commentId);
1667
+ if (index === -1) return null;
1668
+ const comment = comments[index];
1669
+ const replyIndex = comment.replies.findIndex((r) => r.id === replyId);
1670
+ if (replyIndex === -1) return null;
1671
+ comment.replies.splice(replyIndex, 1);
1672
+ await this.save(comments);
1673
+ return comment;
1674
+ }
1675
+ async updateReply(commentId, replyId, body) {
1676
+ const comments = await this.getAll();
1677
+ const index = comments.findIndex((c) => c.id === commentId);
1678
+ if (index === -1) return null;
1679
+ const comment = comments[index];
1680
+ const reply = comment.replies.find((r) => r.id === replyId);
1681
+ if (!reply) return null;
1682
+ reply.body = body;
1683
+ await this.save(comments);
1684
+ return comment;
1685
+ }
1686
+ };
1687
+ //#endregion
1688
+ //#region src/lib/plans.ts
1689
+ function newId() {
1690
+ return crypto.randomUUID();
1691
+ }
1692
+ /**
1693
+ * Backfill / repair a plan loaded from disk so it matches the current schema.
1694
+ * Older persisted plans may be missing `versions` and `createdAtPlanVersion`;
1695
+ * we synthesize sensible values so callers can always rely on the new fields.
1696
+ */
1697
+ function backfillPlan(plan) {
1698
+ const currentVersion = plan.version ?? 1;
1699
+ const have = Array.isArray(plan.versions) ? plan.versions.length : 0;
1700
+ if (!plan.versions || have === 0 || have < currentVersion) {
1701
+ const createdAt = plan.updatedAt ?? plan.createdAt ?? Date.now();
1702
+ const haveEntries = Array.isArray(plan.versions) ? plan.versions : [];
1703
+ const present = new Set(haveEntries.map((v) => v.version));
1704
+ const next = [];
1705
+ for (let i = 1; i <= currentVersion; i++) {
1706
+ const existing = haveEntries.find((v) => v.version === i);
1707
+ if (existing) next.push(existing);
1708
+ else next.push({
1709
+ version: i,
1710
+ body: plan.body,
1711
+ title: plan.title,
1712
+ source: plan.source,
1713
+ model: plan.model,
1714
+ createdAt
1715
+ });
1716
+ }
1717
+ plan.versions = next.filter((v) => v.version >= 1 && v.version <= currentVersion);
1718
+ if (have < currentVersion || !present.has(currentVersion)) markBackfilled(plan);
1719
+ }
1720
+ if (plan.comments) {
1721
+ for (const c of plan.comments) if (typeof c.createdAtPlanVersion !== "number") c.createdAtPlanVersion = plan.version ?? 1;
1722
+ }
1723
+ if (!plan.comments) plan.comments = [];
1724
+ }
1725
+ function markBackfilled(plan) {
1726
+ plan.__backfilledVersions = true;
1727
+ }
1728
+ /** Shared mutation helpers so both stores behave identically. */
1729
+ function applyUpsert(plans, input, now) {
1730
+ if (input.id) {
1731
+ const existing = plans.find((p) => p.id === input.id);
1732
+ if (existing) {
1733
+ existing.title = input.title;
1734
+ existing.body = input.body;
1735
+ if (input.source !== void 0) existing.source = input.source;
1736
+ if (input.model !== void 0) existing.model = input.model;
1737
+ existing.version += 1;
1738
+ existing.updatedAt = now;
1739
+ if (!existing.versions) existing.versions = [];
1740
+ existing.versions.push({
1741
+ version: existing.version,
1742
+ body: existing.body,
1743
+ title: existing.title,
1744
+ source: existing.source,
1745
+ model: existing.model,
1746
+ createdAt: now
1747
+ });
1748
+ existing.decision = "pending";
1749
+ existing.decisionComment = void 0;
1750
+ existing.decidedAt = void 0;
1751
+ return existing;
1752
+ }
1753
+ }
1754
+ const plan = {
1755
+ id: input.id || newId(),
1756
+ title: input.title,
1757
+ body: input.body,
1758
+ source: input.source,
1759
+ model: input.model,
1760
+ createdAt: now,
1761
+ updatedAt: now,
1762
+ version: 1,
1763
+ decision: "pending",
1764
+ comments: [],
1765
+ versions: [{
1766
+ version: 1,
1767
+ body: input.body,
1768
+ title: input.title,
1769
+ source: input.source,
1770
+ model: input.model,
1771
+ createdAt: now
1772
+ }]
1773
+ };
1774
+ plans.push(plan);
1775
+ return plan;
1776
+ }
1777
+ /**
1778
+ * Keep the most-recent `PlanVersion` snapshot in sync with the current `Plan`
1779
+ * fields after a non-resubmit edit (PUT). Doesn't add a new entry — that only
1780
+ * happens via `upsert` (the resubmit flow).
1781
+ */
1782
+ function syncCurrentVersion(plan) {
1783
+ if (!plan.versions || plan.versions.length === 0) plan.versions = [];
1784
+ if (plan.versions.length === 0) {
1785
+ plan.versions.push({
1786
+ version: plan.version,
1787
+ body: plan.body,
1788
+ title: plan.title,
1789
+ source: plan.source,
1790
+ model: plan.model,
1791
+ createdAt: plan.updatedAt
1792
+ });
1793
+ return;
1794
+ }
1795
+ const last = plan.versions[plan.versions.length - 1];
1796
+ last.body = plan.body;
1797
+ last.title = plan.title;
1798
+ last.source = plan.source;
1799
+ last.model = plan.model;
1800
+ }
1801
+ var FilePlanStore = class {
1802
+ dirPath;
1803
+ filePath;
1804
+ /**
1805
+ * @param storageDir Absolute directory to persist `plans.json` in. Defaults
1806
+ * to the per-repo storage dir under `~/.diffing`, the same place comments
1807
+ * and media live — plans are NEVER written inside the reviewed (consumer)
1808
+ * repo, so a consumer project stays free of any diffing-specific artifacts.
1809
+ * The override exists only so tests can point at a throwaway temp dir.
1810
+ */
1811
+ constructor(storageDir) {
1812
+ this.dirPath = storageDir ?? getProjectStorageDir();
1813
+ this.filePath = join(this.dirPath, "plans.json");
1814
+ }
1815
+ async getAll() {
1816
+ try {
1817
+ const data = await readFile(this.filePath, "utf-8");
1818
+ const plans = JSON.parse(data);
1819
+ let anyBackfilled = false;
1820
+ for (const p of plans) {
1821
+ const before = Array.isArray(p.versions) ? p.versions.length : 0;
1822
+ const beforeValid = Array.isArray(p.versions) && p.versions.length > 0;
1823
+ backfillPlan(p);
1824
+ const after = Array.isArray(p.versions) ? p.versions.length : 0;
1825
+ if ((!beforeValid || before < (p.version ?? 1)) && after > before) anyBackfilled = true;
1826
+ }
1827
+ if (anyBackfilled) try {
1828
+ await this.save(plans);
1829
+ } catch {}
1830
+ return plans;
1831
+ } catch {
1832
+ return [];
1833
+ }
1834
+ }
1835
+ async get(id) {
1836
+ return (await this.getAll()).find((p) => p.id === id) ?? null;
1837
+ }
1838
+ async getVersion(id, version) {
1839
+ const plan = await this.get(id);
1840
+ if (!plan) return null;
1841
+ return plan.versions.find((v) => v.version === version) ?? null;
1842
+ }
1843
+ async save(plans) {
1844
+ try {
1845
+ await mkdir(this.dirPath, { recursive: true });
1846
+ try {
1847
+ const repoRoot = getRepoRoot();
1848
+ await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1849
+ } catch {}
1850
+ const clean = plans.map((p) => {
1851
+ const copy = { ...p };
1852
+ delete copy.__backfilledVersions;
1853
+ return copy;
1854
+ });
1855
+ await writeFile(this.filePath, JSON.stringify(clean, null, 2), "utf-8");
1856
+ } catch (err) {
1857
+ console.error("Failed to save plans to file:", err);
1858
+ }
1859
+ }
1860
+ async upsert(input) {
1861
+ const plans = await this.getAll();
1862
+ const plan = applyUpsert(plans, input, Date.now());
1863
+ backfillPlan(plan);
1864
+ await this.save(plans);
1865
+ return plan;
1866
+ }
1867
+ async update(id, fields) {
1868
+ const plans = await this.getAll();
1869
+ const plan = plans.find((p) => p.id === id);
1870
+ if (!plan) return null;
1871
+ if (fields.title !== void 0) plan.title = fields.title;
1872
+ if (fields.body !== void 0) plan.body = fields.body;
1873
+ if (fields.source !== void 0) plan.source = fields.source;
1874
+ if (fields.model !== void 0) plan.model = fields.model;
1875
+ plan.updatedAt = Date.now();
1876
+ syncCurrentVersion(plan);
1877
+ backfillPlan(plan);
1878
+ await this.save(plans);
1879
+ return plan;
1880
+ }
1881
+ async remove(id) {
1882
+ const plans = await this.getAll();
1883
+ const idx = plans.findIndex((p) => p.id === id);
1884
+ if (idx === -1) return false;
1885
+ plans.splice(idx, 1);
1886
+ await this.save(plans);
1887
+ return true;
1888
+ }
1889
+ async setDecision(id, decision, decisionComment) {
1890
+ const plans = await this.getAll();
1891
+ const plan = plans.find((p) => p.id === id);
1892
+ if (!plan) return null;
1893
+ plan.decision = decision;
1894
+ plan.decisionComment = decisionComment?.trim() || void 0;
1895
+ plan.decidedAt = Date.now();
1896
+ plan.updatedAt = plan.decidedAt;
1897
+ await this.save(plans);
1898
+ return plan;
1899
+ }
1900
+ async mutate(planId, fn) {
1901
+ const plans = await this.getAll();
1902
+ const plan = plans.find((p) => p.id === planId);
1903
+ if (!plan) return null;
1904
+ if (!plan.comments) plan.comments = [];
1905
+ if (!fn(plan)) return null;
1906
+ backfillPlan(plan);
1907
+ await this.save(plans);
1908
+ return plan;
1909
+ }
1910
+ async addComment(planId, comment) {
1911
+ return this.mutate(planId, (plan) => {
1912
+ if (typeof comment.createdAtPlanVersion !== "number") comment.createdAtPlanVersion = plan.version ?? 1;
1913
+ plan.comments.push(comment);
1914
+ return true;
1915
+ });
1916
+ }
1917
+ async updateComment(planId, commentId, fields) {
1918
+ return this.mutate(planId, (plan) => {
1919
+ const c = plan.comments.find((x) => x.id === commentId);
1920
+ if (!c) return false;
1921
+ if (fields.body !== void 0) c.body = fields.body;
1922
+ if (fields.status !== void 0) c.status = fields.status;
1923
+ return true;
1924
+ });
1925
+ }
1926
+ async removeComment(planId, commentId) {
1927
+ return this.mutate(planId, (plan) => {
1928
+ const idx = plan.comments.findIndex((x) => x.id === commentId);
1929
+ if (idx === -1) return false;
1930
+ plan.comments.splice(idx, 1);
1931
+ return true;
1932
+ });
1933
+ }
1934
+ async addReply(planId, commentId, reply) {
1935
+ return this.mutate(planId, (plan) => {
1936
+ const c = plan.comments.find((x) => x.id === commentId);
1937
+ if (!c) return false;
1938
+ if (typeof c.createdAtPlanVersion === "number" && typeof reply.createdAtPlanVersion !== "number") reply.createdAtPlanVersion = c.createdAtPlanVersion;
1939
+ if (!c.replies) c.replies = [];
1940
+ c.replies.push(reply);
1941
+ return true;
1942
+ });
1943
+ }
1944
+ async removeReply(planId, commentId, replyId) {
1945
+ return this.mutate(planId, (plan) => {
1946
+ const c = plan.comments.find((x) => x.id === commentId);
1947
+ if (!c) return false;
1948
+ const idx = c.replies.findIndex((r) => r.id === replyId);
1949
+ if (idx === -1) return false;
1950
+ c.replies.splice(idx, 1);
1951
+ return true;
1952
+ });
1953
+ }
1954
+ async updateReply(planId, commentId, replyId, body) {
1955
+ return this.mutate(planId, (plan) => {
1956
+ const c = plan.comments.find((x) => x.id === commentId);
1957
+ if (!c) return false;
1958
+ const reply = c.replies.find((r) => r.id === replyId);
1959
+ if (!reply) return false;
1960
+ reply.body = body;
1961
+ return true;
1962
+ });
1963
+ }
1964
+ };
1965
+ //#endregion
1966
+ //#region src/lib/state.ts
1967
+ var FileUiStateStore = class {
1968
+ dirPath;
1969
+ filePath;
1970
+ constructor(storageDir) {
1971
+ this.dirPath = storageDir ?? getProjectStorageDir();
1972
+ this.filePath = join(this.dirPath, "ui-state.json");
1973
+ }
1974
+ async getAll() {
1975
+ try {
1976
+ const data = await readFile(this.filePath, "utf-8");
1977
+ return JSON.parse(data);
1978
+ } catch {
1979
+ return {};
1980
+ }
1981
+ }
1982
+ async setAll(state) {
1983
+ await this.save(state);
1984
+ }
1985
+ async save(state) {
1986
+ try {
1987
+ await mkdir(this.dirPath, { recursive: true });
1988
+ try {
1989
+ const repoRoot = getRepoRoot();
1990
+ await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1991
+ } catch {}
1992
+ await writeFile(this.filePath, JSON.stringify(state, null, 2), "utf-8");
1993
+ } catch (err) {
1994
+ console.error("Failed to save UI state to file:", err);
1995
+ }
1996
+ }
1997
+ };
1998
+ //#endregion
1999
+ //#region src/lib/editor-launcher.ts
2000
+ function resolveEditorCommand(editor, absolutePath, platform = process.platform, env = process.env) {
2001
+ switch (editor) {
2002
+ case "vscode": return guiEditorCommand("code", absolutePath, platform);
2003
+ case "zed": return guiEditorCommand("zed", absolutePath, platform);
2004
+ case "vim": return terminalEditorCommand("vim", absolutePath, platform, env);
2005
+ case "neovim": return terminalEditorCommand("nvim", absolutePath, platform, env);
2006
+ default: return null;
2007
+ }
2008
+ }
2009
+ function guiEditorCommand(bin, absolutePath, platform) {
2010
+ if (platform === "win32") return {
2011
+ cmd: `${bin}.cmd`,
2012
+ args: [absolutePath]
2013
+ };
2014
+ return {
2015
+ cmd: bin,
2016
+ args: [absolutePath]
2017
+ };
2018
+ }
2019
+ function terminalEditorCommand(bin, absolutePath, platform, env) {
2020
+ if (platform === "darwin") return {
2021
+ cmd: "osascript",
2022
+ args: ["-e", `tell application "Terminal" to do script "${bin} \\"${absolutePath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}\\""`]
2023
+ };
2024
+ if (platform === "win32") return {
2025
+ cmd: "cmd.exe",
2026
+ args: [
2027
+ "/c",
2028
+ "start",
2029
+ "\"\"",
2030
+ "cmd.exe",
2031
+ "/k",
2032
+ bin,
2033
+ absolutePath
2034
+ ]
2035
+ };
2036
+ const term = env.TERMINAL?.trim();
2037
+ if (term) return {
2038
+ cmd: term,
2039
+ args: [
2040
+ "-e",
2041
+ bin,
2042
+ absolutePath
2043
+ ]
2044
+ };
2045
+ return {
2046
+ cmd: "x-terminal-emulator",
2047
+ args: [
2048
+ "-e",
2049
+ bin,
2050
+ absolutePath
2051
+ ]
2052
+ };
2053
+ }
2054
+ //#endregion
2055
+ //#region src/lib/review-session.ts
2056
+ const MAX_ROUND_HISTORY = 20;
2057
+ var ReviewSession = class {
2058
+ round = 0;
2059
+ lastSentAt = null;
2060
+ lastPayload = null;
2061
+ history = [];
2062
+ waiters = /* @__PURE__ */ new Set();
2063
+ onStatusChange;
2064
+ constructor(onStatusChange) {
2065
+ this.onStatusChange = onStatusChange;
2066
+ }
2067
+ /**
2068
+ * Block until the next `send()` or until `timeoutMs` elapses.
2069
+ *
2070
+ * If `sinceRound` is provided and is behind the current round, a send already
2071
+ * happened since the client last checked → resolve immediately with the
2072
+ * cached payload (the race guard). Otherwise register a waiter.
2073
+ */
2074
+ await(opts) {
2075
+ const { sinceRound, timeoutMs, signal } = opts;
2076
+ if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
2077
+ status: "released",
2078
+ payload: this.lastPayload
2079
+ });
2080
+ if (signal?.aborted) return Promise.resolve({
2081
+ status: "keep-waiting",
2082
+ round: this.round
2083
+ });
2084
+ return new Promise((resolve) => {
2085
+ const waiter = {
2086
+ resolve,
2087
+ timer: setTimeout(() => {
2088
+ this.removeWaiter(waiter);
2089
+ resolve({
2090
+ status: "keep-waiting",
2091
+ round: this.round
2092
+ });
2093
+ }, timeoutMs),
2094
+ cleanup: () => {}
2095
+ };
2096
+ if (signal) {
2097
+ const onAbort = () => {
2098
+ this.removeWaiter(waiter);
2099
+ resolve({
2100
+ status: "keep-waiting",
2101
+ round: this.round
2102
+ });
2103
+ };
2104
+ signal.addEventListener("abort", onAbort, { once: true });
2105
+ waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
2106
+ }
2107
+ this.waiters.add(waiter);
2108
+ this.emitStatus();
2109
+ });
2110
+ }
2111
+ /** Capture a review batch and release every blocked waiter. */
2112
+ send(input) {
2113
+ this.round += 1;
2114
+ this.lastSentAt = input.sentAt;
2115
+ const mode = input.mode ?? "standard";
2116
+ const payload = {
2117
+ round: this.round,
2118
+ sentAt: input.sentAt,
2119
+ commentXml: input.commentXml,
2120
+ openCount: input.openCount,
2121
+ comments: input.comments,
2122
+ decision: input.decision,
2123
+ mode
2124
+ };
2125
+ this.lastPayload = payload;
2126
+ const filePaths = [...new Set(input.comments.map((c) => c.filePath))].sort();
2127
+ this.history.push({
2128
+ round: this.round,
2129
+ sentAt: input.sentAt,
2130
+ openCount: input.openCount,
2131
+ decision: input.decision,
2132
+ mode,
2133
+ filePaths
2134
+ });
2135
+ if (this.history.length > MAX_ROUND_HISTORY) this.history.splice(0, this.history.length - MAX_ROUND_HISTORY);
2136
+ const waiters = [...this.waiters];
2137
+ this.waiters.clear();
2138
+ for (const waiter of waiters) {
2139
+ clearTimeout(waiter.timer);
2140
+ waiter.cleanup();
2141
+ waiter.resolve({
2142
+ status: "released",
2143
+ payload
2144
+ });
2145
+ }
2146
+ this.emitStatus();
2147
+ return payload;
2148
+ }
2149
+ snapshot() {
2150
+ const last = this.history[this.history.length - 1];
2151
+ return {
2152
+ round: this.round,
2153
+ waiters: this.waiters.size,
2154
+ lastSentAt: this.lastSentAt,
2155
+ lastDecision: last?.decision,
2156
+ lastOpenCount: last?.openCount
2157
+ };
2158
+ }
2159
+ /** Newest-first round summaries for the UI timeline. */
2160
+ getHistory() {
2161
+ return [...this.history].reverse();
2162
+ }
2163
+ removeWaiter(waiter) {
2164
+ if (!this.waiters.delete(waiter)) return;
2165
+ clearTimeout(waiter.timer);
2166
+ waiter.cleanup();
2167
+ this.emitStatus();
2168
+ }
2169
+ emitStatus() {
2170
+ this.onStatusChange?.(this.snapshot());
2171
+ }
2172
+ };
2173
+ //#endregion
2174
+ //#region src/lib/plan-review-session.ts
2175
+ var PlanReviewSession = class {
2176
+ round = 0;
2177
+ lastDecidedAt = null;
2178
+ lastPayload = null;
2179
+ waiters = /* @__PURE__ */ new Set();
2180
+ onStatusChange;
2181
+ constructor(onStatusChange) {
2182
+ this.onStatusChange = onStatusChange;
2183
+ }
2184
+ /** Block until the next `decide()` or until `timeoutMs` elapses. */
2185
+ await(opts) {
2186
+ const { sinceRound, timeoutMs, signal } = opts;
2187
+ if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
2188
+ status: "released",
2189
+ payload: this.lastPayload
2190
+ });
2191
+ if (signal?.aborted) return Promise.resolve({
2192
+ status: "keep-waiting",
2193
+ round: this.round
2194
+ });
2195
+ return new Promise((resolve) => {
2196
+ const waiter = {
2197
+ resolve,
2198
+ timer: setTimeout(() => {
2199
+ this.removeWaiter(waiter);
2200
+ resolve({
2201
+ status: "keep-waiting",
2202
+ round: this.round
2203
+ });
2204
+ }, timeoutMs),
2205
+ cleanup: () => {}
2206
+ };
2207
+ if (signal) {
2208
+ const onAbort = () => {
2209
+ this.removeWaiter(waiter);
2210
+ resolve({
2211
+ status: "keep-waiting",
2212
+ round: this.round
2213
+ });
2214
+ };
2215
+ signal.addEventListener("abort", onAbort, { once: true });
2216
+ waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
2217
+ }
2218
+ this.waiters.add(waiter);
2219
+ this.emitStatus();
2220
+ });
2221
+ }
2222
+ /** Capture a decision and release every blocked waiter. */
2223
+ decide(input) {
2224
+ this.round += 1;
2225
+ this.lastDecidedAt = input.sentAt;
2226
+ const payload = {
2227
+ round: this.round,
2228
+ sentAt: input.sentAt,
2229
+ planId: input.planId,
2230
+ decision: input.decision,
2231
+ decisionComment: input.decisionComment,
2232
+ reviewXml: input.reviewXml,
2233
+ openCommentCount: input.openCommentCount,
2234
+ plan: input.plan,
2235
+ mode: input.mode ?? "standard"
2236
+ };
2237
+ this.lastPayload = payload;
2238
+ const waiters = [...this.waiters];
2239
+ this.waiters.clear();
2240
+ for (const waiter of waiters) {
2241
+ clearTimeout(waiter.timer);
2242
+ waiter.cleanup();
2243
+ waiter.resolve({
2244
+ status: "released",
2245
+ payload
2246
+ });
2247
+ }
2248
+ this.emitStatus();
2249
+ return payload;
2250
+ }
2251
+ snapshot() {
2252
+ return {
2253
+ round: this.round,
2254
+ waiters: this.waiters.size,
2255
+ lastDecidedAt: this.lastDecidedAt
2256
+ };
2257
+ }
2258
+ removeWaiter(waiter) {
2259
+ if (!this.waiters.delete(waiter)) return;
2260
+ clearTimeout(waiter.timer);
2261
+ waiter.cleanup();
2262
+ this.emitStatus();
2263
+ }
2264
+ emitStatus() {
2265
+ this.onStatusChange?.(this.snapshot());
2266
+ }
2267
+ };
2268
+ //#endregion
2269
+ //#region src/lib/secrets-scan.ts
2270
+ const RULES = [
2271
+ {
2272
+ id: "aws-access-key",
2273
+ re: /\b(AKIA[0-9A-Z]{16})\b/g,
2274
+ redact: (m) => `${m[0].slice(0, 4)}…${m[0].slice(-4)}`
2275
+ },
2276
+ {
2277
+ id: "github-token",
2278
+ re: /\b(gh[pousr]_[A-Za-z0-9_]{20,})\b/g,
2279
+ redact: (m) => `${m[0].slice(0, 7)}…`
2280
+ },
2281
+ {
2282
+ id: "slack-token",
2283
+ re: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/g,
2284
+ redact: (m) => `${m[0].slice(0, 8)}…`
2285
+ },
2286
+ {
2287
+ id: "private-key",
2288
+ re: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,
2289
+ redact: () => "-----BEGIN PRIVATE KEY-----"
2290
+ },
2291
+ {
2292
+ id: "generic-api-key",
2293
+ re: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token)\s*[:=]\s*['"]?([A-Za-z0-9_\-]{16,})['"]?/gi,
2294
+ redact: (m) => `…${(m[1] ?? "").slice(-4)}`
2295
+ },
2296
+ {
2297
+ id: "jwt",
2298
+ re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
2299
+ redact: (m) => `${m[0].slice(0, 12)}…`
2300
+ },
2301
+ {
2302
+ id: "connection-string",
2303
+ re: /\b(?:postgres|mysql|mongodb(?:\+srv)?|redis):\/\/[^\s'"]+/gi,
2304
+ redact: (m) => {
2305
+ try {
2306
+ const u = new URL(m[0]);
2307
+ if (u.password) u.password = "***";
2308
+ return u.toString();
2309
+ } catch {
2310
+ return m[0].replace(/:([^:@/]+)@/, ":***@");
2311
+ }
2312
+ }
2313
+ }
2314
+ ];
2315
+ function scanTextForSecrets(text, source) {
2316
+ if (!text) return [];
2317
+ const findings = [];
2318
+ for (const rule of RULES) {
2319
+ rule.re.lastIndex = 0;
2320
+ let match;
2321
+ while ((match = rule.re.exec(text)) !== null) {
2322
+ findings.push({
2323
+ rule: rule.id,
2324
+ snippet: rule.redact(match),
2325
+ source
2326
+ });
2327
+ if (match.index === rule.re.lastIndex) rule.re.lastIndex++;
2328
+ }
2329
+ }
2330
+ return findings;
2331
+ }
2332
+ function scanReviewForSecrets(input) {
2333
+ const out = [];
2334
+ if (input.generalComment) out.push(...scanTextForSecrets(input.generalComment, "overall comment"));
2335
+ for (const c of input.comments) {
2336
+ out.push(...scanTextForSecrets(c.body, `comment ${c.id} (${c.filePath})`));
2337
+ if (c.lineContent) out.push(...scanTextForSecrets(c.lineContent, `code at ${c.filePath}`));
2338
+ }
2339
+ const seen = /* @__PURE__ */ new Set();
2340
+ return out.filter((f) => {
2341
+ const k = `${f.rule}|${f.snippet}|${f.source}`;
2342
+ if (seen.has(k)) return false;
2343
+ seen.add(k);
2344
+ return true;
2345
+ });
2346
+ }
2347
+ //#endregion
2348
+ //#region src/lib/pr-session.ts
2349
+ var FilePrSessionStore = class {
2350
+ dirPath;
2351
+ filePath;
2352
+ constructor(storageDir) {
2353
+ this.dirPath = storageDir ?? getProjectStorageDir();
2354
+ this.filePath = join(this.dirPath, "pr-session.json");
2355
+ }
2356
+ async get() {
2357
+ try {
2358
+ const data = await readFile(this.filePath, "utf-8");
2359
+ return JSON.parse(data);
2360
+ } catch {
2361
+ return null;
2362
+ }
2363
+ }
2364
+ async save(session) {
2365
+ try {
2366
+ await mkdir(this.dirPath, { recursive: true });
2367
+ await writeFile(this.filePath, JSON.stringify(session, null, 2), "utf-8");
2368
+ } catch (err) {
2369
+ console.error("Failed to save pr-session to file:", err);
2370
+ }
2371
+ }
2372
+ async set(session) {
2373
+ await this.save(session);
2374
+ }
2375
+ async update(fields) {
2376
+ const current = await this.get();
2377
+ if (!current) return null;
2378
+ const next = {
2379
+ ...current,
2380
+ ...fields
2381
+ };
2382
+ await this.save(next);
2383
+ return next;
2384
+ }
2385
+ async clear() {
2386
+ try {
2387
+ const { unlink } = await import("node:fs/promises");
2388
+ await unlink(this.filePath);
2389
+ } catch {}
2390
+ }
2391
+ };
2392
+ //#endregion
2393
+ //#region src/lib/github.ts
2394
+ const execFileAsync = promisify(execFile);
2395
+ /**
2396
+ * Probe the `gh` CLI: is it on `$PATH`, and is the user authenticated?
2397
+ * Never throws — returns a permissive `available: false` on any failure.
2398
+ */
2399
+ async function detectGhCli() {
2400
+ try {
2401
+ const { stdout } = await execFileAsync("gh", ["--version"], { encoding: "utf-8" });
2402
+ const version = stdout.split("\n")[0]?.trim() || void 0;
2403
+ try {
2404
+ const result = await execFileAsync("gh", ["auth", "status"], { encoding: "utf-8" });
2405
+ return {
2406
+ available: true,
2407
+ authenticated: true,
2408
+ version,
2409
+ user: parseGhAuthStatusUser(`${result.stdout ?? ""}\n${result.stderr ?? ""}`)
2410
+ };
2411
+ } catch {
2412
+ return {
2413
+ available: true,
2414
+ authenticated: false,
2415
+ version
2416
+ };
2417
+ }
2418
+ } catch {
2419
+ return {
2420
+ available: false,
2421
+ authenticated: false
2422
+ };
2423
+ }
2424
+ }
2425
+ /**
2426
+ * Extract the GitHub username from `gh auth status` output. Exported for
2427
+ * unit tests — see `__tests__/github-auth.test.ts`.
2428
+ *
2429
+ * Real-world samples:
2430
+ * `✓ Logged in to github.com account octocat (keyring)` (gh 2.40+)
2431
+ * `Logged in to github.com as octocat (oauth_token)` (older gh)
2432
+ * ` ✓ Logged in to github.com as octocat (~/.config/gh/hosts.yml)`
2433
+ */
2434
+ function parseGhAuthStatusUser(output) {
2435
+ const account = /Logged in to [^\s]+ account\s+([^\s(]+)/.exec(output);
2436
+ if (account) return account[1];
2437
+ return /Logged in to [^\s]+ as\s+([^\s(]+)/.exec(output)?.[1];
2438
+ }
2439
+ /** Read the most-preferred GitHub token from the env. */
2440
+ function readGithubToken() {
2441
+ const env = process.env;
2442
+ return env.GH_TOKEN || env.GITHUB_TOKEN || env.GITHUB_API_TOKEN || null;
2443
+ }
2444
+ function parsePrRef(input, cwdRepo) {
2445
+ const trimmed = input.trim();
2446
+ const urlMatch = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/i.exec(trimmed);
2447
+ if (urlMatch) return {
2448
+ owner: urlMatch[1],
2449
+ repo: urlMatch[2],
2450
+ pullNumber: Number(urlMatch[3]),
2451
+ ref: trimmed
2452
+ };
2453
+ const shorthand = /^([^/\s]+)\/([^#\s]+)#(\d+)$/.exec(trimmed);
2454
+ if (shorthand) return {
2455
+ owner: shorthand[1],
2456
+ repo: shorthand[2],
2457
+ pullNumber: Number(shorthand[3]),
2458
+ ref: trimmed
2459
+ };
2460
+ const bare = /^#?(\d+)$/.exec(trimmed);
2461
+ if (bare && cwdRepo) return {
2462
+ owner: cwdRepo.owner,
2463
+ repo: cwdRepo.repo,
2464
+ pullNumber: Number(bare[1]),
2465
+ ref: trimmed
2466
+ };
2467
+ if (bare) throw new Error(`Cannot resolve bare PR number "${trimmed}" — run from inside the target repo, or pass a full URL or \`owner/repo#1234\`.`);
2468
+ throw new Error(`Unrecognised PR ref: ${trimmed}`);
2469
+ }
2470
+ /**
2471
+ * Best-effort: derive `{ owner, repo }` for the current working directory
2472
+ * from `git remote get-url origin`. Falls back to throwing.
2473
+ */
2474
+ async function detectCwdRepo() {
2475
+ try {
2476
+ const { stdout } = await execFileAsync("git", [
2477
+ "remote",
2478
+ "get-url",
2479
+ "origin"
2480
+ ], { encoding: "utf-8" });
2481
+ const url = stdout.trim();
2482
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\s*$/.exec(url);
2483
+ if (m) return {
2484
+ owner: m[1],
2485
+ repo: m[2]
2486
+ };
2487
+ } catch {}
2488
+ return null;
2489
+ }
2490
+ /**
2491
+ * Fetch PR metadata + diff + existing review comments using `gh`.
2492
+ * Throws with a user-readable message on failure.
2493
+ */
2494
+ async function fetchPrMetadataViaGh(resolved) {
2495
+ const args = ["-R", `${resolved.owner}/${resolved.repo}`];
2496
+ let metaJson;
2497
+ try {
2498
+ const { stdout } = await execFileAsync("gh", [
2499
+ "pr",
2500
+ "view",
2501
+ String(resolved.pullNumber),
2502
+ ...args,
2503
+ "--json",
2504
+ "number,title,url,author,baseRefOid,headRefOid,additions,deletions,changedFiles,headRepositoryOwner,headRepository"
2505
+ ], {
2506
+ encoding: "utf-8",
2507
+ maxBuffer: 20 * 1024 * 1024
2508
+ });
2509
+ metaJson = JSON.parse(stdout);
2510
+ } catch (err) {
2511
+ const stderr = err?.stderr || err?.message || "unknown error";
2512
+ throw new Error(`gh pr view failed: ${stderr.trim()}`);
2513
+ }
2514
+ let diff = "";
2515
+ try {
2516
+ const { stdout } = await execFileAsync("gh", [
2517
+ "pr",
2518
+ "diff",
2519
+ String(resolved.pullNumber),
2520
+ ...args
2521
+ ], {
2522
+ encoding: "utf-8",
2523
+ maxBuffer: 50 * 1024 * 1024
2524
+ });
2525
+ diff = stdout;
2526
+ } catch (err) {
2527
+ const stderr = err?.stderr || err?.message || "unknown error";
2528
+ throw new Error(`gh pr diff failed: ${stderr.trim()}`);
2529
+ }
2530
+ const headOwner = metaJson.headRepositoryOwner?.login || metaJson.headRepository?.owner?.login || resolved.owner;
2531
+ const repoName = metaJson.headRepository?.name || resolved.repo;
2532
+ const author = metaJson.author ? {
2533
+ login: metaJson.author.login,
2534
+ avatarUrl: metaJson.author.avatarUrl
2535
+ } : null;
2536
+ const existingComments = await fetchExistingCommentsViaGh(resolved);
2537
+ return {
2538
+ number: metaJson.number,
2539
+ title: metaJson.title,
2540
+ url: metaJson.url,
2541
+ author,
2542
+ baseSha: metaJson.baseRefOid,
2543
+ headSha: metaJson.headRefOid,
2544
+ additions: metaJson.additions,
2545
+ deletions: metaJson.deletions,
2546
+ changedFiles: metaJson.changedFiles,
2547
+ owner: headOwner,
2548
+ repo: repoName,
2549
+ diff,
2550
+ existingComments
2551
+ };
2552
+ }
2553
+ async function fetchExistingCommentsViaGh(resolved) {
2554
+ `${resolved.owner}${resolved.repo}`;
2555
+ const endpoint = `repos/${resolved.owner}/${resolved.repo}/pulls/${resolved.pullNumber}/comments`;
2556
+ const reviewsEndpoint = `repos/${resolved.owner}/${resolved.repo}/pulls/${resolved.pullNumber}/reviews`;
2557
+ let reviews = [];
2558
+ try {
2559
+ const { stdout } = await execFileAsync("gh", [
2560
+ "api",
2561
+ reviewsEndpoint,
2562
+ "--paginate"
2563
+ ], {
2564
+ encoding: "utf-8",
2565
+ maxBuffer: 20 * 1024 * 1024
2566
+ });
2567
+ const all = JSON.parse(stdout);
2568
+ if (Array.isArray(all)) reviews = all;
2569
+ } catch {}
2570
+ reviews.sort((a, b) => a.submitted_at < b.submitted_at ? 1 : -1);
2571
+ const recentReviews = reviews.slice(0, 50);
2572
+ const reviewStateById = /* @__PURE__ */ new Map();
2573
+ for (const r of recentReviews) reviewStateById.set(r.id, r.state);
2574
+ let commentsRaw = [];
2575
+ try {
2576
+ const { stdout } = await execFileAsync("gh", [
2577
+ "api",
2578
+ `${endpoint}?per_page=100`,
2579
+ "--paginate"
2580
+ ], {
2581
+ encoding: "utf-8",
2582
+ maxBuffer: 20 * 1024 * 1024
2583
+ });
2584
+ const parsed = JSON.parse(stdout);
2585
+ if (Array.isArray(parsed)) commentsRaw = parsed;
2586
+ } catch {
2587
+ return [];
2588
+ }
2589
+ const byId = /* @__PURE__ */ new Map();
2590
+ for (const c of commentsRaw) byId.set(c.id, c);
2591
+ const replyByParent = /* @__PURE__ */ new Map();
2592
+ for (const c of commentsRaw) if (c.in_reply_to_id && byId.has(c.in_reply_to_id)) {
2593
+ const list = replyByParent.get(c.in_reply_to_id) ?? [];
2594
+ list.push(c);
2595
+ replyByParent.set(c.in_reply_to_id, list);
2596
+ }
2597
+ const tops = [];
2598
+ for (const c of commentsRaw) {
2599
+ if (c.in_reply_to_id) continue;
2600
+ const state = c.pull_request_review_id ? reviewStateById.get(c.pull_request_review_id) ?? null : null;
2601
+ tops.push({
2602
+ id: c.id,
2603
+ author: c.user ? {
2604
+ login: c.user.login,
2605
+ avatarUrl: c.user.avatar_url
2606
+ } : null,
2607
+ body: c.body ?? "",
2608
+ path: c.path,
2609
+ line: typeof c.line === "number" ? c.line : null,
2610
+ side: c.side === "LEFT" || c.side === "RIGHT" ? c.side : null,
2611
+ createdAt: c.created_at,
2612
+ updatedAt: c.updated_at,
2613
+ state,
2614
+ replies: (replyByParent.get(c.id) ?? []).map((r) => ({
2615
+ id: r.id,
2616
+ author: r.user ? {
2617
+ login: r.user.login,
2618
+ avatarUrl: r.user.avatar_url
2619
+ } : null,
2620
+ body: r.body ?? "",
2621
+ createdAt: r.created_at,
2622
+ updatedAt: r.updated_at
2623
+ })),
2624
+ isOutdated: typeof c.position === "number" && c.position === null ? false : false
2625
+ });
2626
+ }
2627
+ tops.sort((a, b) => {
2628
+ if (a.path !== b.path) return a.path.localeCompare(b.path);
2629
+ return (a.line ?? 0) - (b.line ?? 0);
2630
+ });
2631
+ return tops;
2632
+ }
2633
+ /**
2634
+ * POST the review to GitHub. Prefers `gh api` (uses the user's existing
2635
+ * `gh auth`); falls back to a direct HTTP call with `$GITHUB_TOKEN` when
2636
+ * `gh` is unavailable.
2637
+ */
2638
+ async function submitReview(input) {
2639
+ const gh = await detectGhCli();
2640
+ if (gh.available && gh.authenticated) return submitViaGh(input);
2641
+ const token = readGithubToken();
2642
+ if (token) return submitViaToken(input, token);
2643
+ return {
2644
+ ok: false,
2645
+ authSource: "none",
2646
+ error: "Cannot submit: no `gh` CLI on $PATH (or not authenticated) and no $GITHUB_TOKEN env var. Run `gh auth login` or set $GITHUB_TOKEN."
2647
+ };
2648
+ }
2649
+ /**
2650
+ * Map our `PrDecision` to the GitHub REST event string. Exported so the
2651
+ * test suite can pin the mapping (including the `rejected → REQUEST_CHANGES`
2652
+ * quirk, which exists because GitHub has no REJECT event).
2653
+ */
2654
+ function decisionToEvent(decision) {
2655
+ if (decision === "approve") return "APPROVE";
2656
+ if (decision === "request-changes") return "REQUEST_CHANGES";
2657
+ return "COMMENT";
2658
+ }
2659
+ /**
2660
+ * Expand multi-line `ReviewComment`s into N single-line `gh`-shaped entries
2661
+ * with `[part N/M]` prefixes. Exported for the test suite — the body of the
2662
+ * caller (`buildReviewPayload`) is otherwise private.
2663
+ *
2664
+ * Skips: non-`open` comments, file-level comments (`lineNumber === 0`).
2665
+ * Strips the `a/` / `b/` prefix from the file path (GitHub expects PR-relative
2666
+ * paths in the `path` field).
2667
+ */
2668
+ function expandMultiLineComments(comments) {
2669
+ const flat = [];
2670
+ for (const c of comments) {
2671
+ if (c.status !== "open") continue;
2672
+ if (c.lineNumber === 0) continue;
2673
+ const path = stripBPrefix(c.filePath);
2674
+ const start = c.startLineNumber && c.startLineNumber < c.lineNumber ? c.startLineNumber : c.lineNumber;
2675
+ const end = c.lineNumber;
2676
+ const span = end - start + 1;
2677
+ if (span > 1) for (let i = 0; i < span; i++) flat.push({
2678
+ path,
2679
+ line: start + i,
2680
+ side: "RIGHT",
2681
+ body: `[part ${i + 1}/${span}]\n${c.body}`
2682
+ });
2683
+ else flat.push({
2684
+ path,
2685
+ line: end,
2686
+ side: "RIGHT",
2687
+ body: c.body
2688
+ });
2689
+ }
2690
+ return flat;
2691
+ }
2692
+ function buildReviewPayload(input) {
2693
+ return {
2694
+ body: input.body,
2695
+ event: decisionToEvent(input.decision ?? "comment"),
2696
+ comments: expandMultiLineComments(input.comments ?? [])
2697
+ };
2698
+ }
2699
+ function stripBPrefix(path) {
2700
+ if (path.startsWith("b/")) return path.slice(2);
2701
+ if (path.startsWith("a/")) return path.slice(2);
2702
+ return path;
2703
+ }
2704
+ async function submitViaGh(input) {
2705
+ const payload = buildReviewPayload(input);
2706
+ `${input.resolved.owner}${input.resolved.repo}`;
2707
+ const args = [
2708
+ "api",
2709
+ "--method",
2710
+ "POST",
2711
+ `repos/${input.resolved.owner}/${input.resolved.repo}/pulls/${input.resolved.pullNumber}/reviews`,
2712
+ "-H",
2713
+ "Accept: application/vnd.github+json",
2714
+ "--input",
2715
+ "-"
2716
+ ];
2717
+ try {
2718
+ const { stdout } = await execFileAsync("gh", args, {
2719
+ encoding: "utf-8",
2720
+ maxBuffer: 20 * 1024 * 1024,
2721
+ input: JSON.stringify(payload)
2722
+ });
2723
+ const result = JSON.parse(stdout);
2724
+ return {
2725
+ ok: true,
2726
+ authSource: "gh",
2727
+ reviewId: result.id,
2728
+ reviewUrl: result.html_url
2729
+ };
2730
+ } catch (err) {
2731
+ const stdout = err?.stdout || "";
2732
+ const stderr = err?.stderr || err?.message || "unknown error";
2733
+ let parsed = null;
2734
+ try {
2735
+ parsed = JSON.parse(stdout);
2736
+ } catch {}
2737
+ return {
2738
+ ok: false,
2739
+ authSource: "gh",
2740
+ error: parsed?.message || stderr.trim()
2741
+ };
2742
+ }
2743
+ }
2744
+ async function submitViaToken(input, token) {
2745
+ const payload = buildReviewPayload(input);
2746
+ const url = `https://api.github.com/repos/${input.resolved.owner}/${input.resolved.repo}/pulls/${input.resolved.pullNumber}/reviews`;
2747
+ try {
2748
+ const res = await fetch(url, {
2749
+ method: "POST",
2750
+ headers: {
2751
+ Authorization: `Bearer ${token}`,
2752
+ Accept: "application/vnd.github+json",
2753
+ "X-GitHub-Api-Version": "2022-11-28",
2754
+ "Content-Type": "application/json",
2755
+ "User-Agent": "diffing-cli"
2756
+ },
2757
+ body: JSON.stringify(payload)
2758
+ });
2759
+ if (!res.ok) {
2760
+ const errBody = await res.text().catch(() => "");
2761
+ return {
2762
+ ok: false,
2763
+ authSource: "token",
2764
+ error: `HTTP ${res.status}: ${errBody.slice(0, 500)}`
2765
+ };
2766
+ }
2767
+ const result = await res.json();
2768
+ return {
2769
+ ok: true,
2770
+ authSource: "token",
2771
+ reviewId: result.id,
2772
+ reviewUrl: result.html_url
2773
+ };
2774
+ } catch (err) {
2775
+ return {
2776
+ ok: false,
2777
+ authSource: "token",
2778
+ error: err?.message || "Network error"
2779
+ };
2780
+ }
2781
+ }
2782
+ async function buildPrSession(ref) {
2783
+ const meta = await fetchPrMetadataViaGh(parsePrRef(ref, await detectCwdRepo() ?? void 0));
2784
+ return {
2785
+ ref,
2786
+ owner: meta.owner,
2787
+ repo: meta.repo,
2788
+ pullNumber: meta.number,
2789
+ baseSha: meta.baseSha,
2790
+ headSha: meta.headSha,
2791
+ title: meta.title,
2792
+ url: meta.url,
2793
+ author: meta.author,
2794
+ additions: meta.additions,
2795
+ deletions: meta.deletions,
2796
+ changedFiles: meta.changedFiles,
2797
+ diff: meta.diff,
2798
+ comments: [],
2799
+ existingComments: meta.existingComments
2800
+ };
2801
+ }
2802
+ /** Refresh `diff` + `existingComments` + head SHA in an existing session. */
2803
+ async function refreshPrSession(session) {
2804
+ const meta = await fetchPrMetadataViaGh({
2805
+ owner: session.owner,
2806
+ repo: session.repo,
2807
+ pullNumber: session.pullNumber,
2808
+ ref: session.ref
2809
+ });
2810
+ return {
2811
+ ...session,
2812
+ baseSha: meta.baseSha,
2813
+ headSha: meta.headSha,
2814
+ title: meta.title,
2815
+ url: meta.url,
2816
+ author: meta.author,
2817
+ additions: meta.additions,
2818
+ deletions: meta.deletions,
2819
+ changedFiles: meta.changedFiles,
2820
+ diff: meta.diff,
2821
+ existingComments: meta.existingComments
2822
+ };
2823
+ }
2824
+ //#endregion
2825
+ //#region src/server.ts
2826
+ const MIME_TYPES = {
2827
+ ".html": "text/html",
2828
+ ".js": "application/javascript",
2829
+ ".css": "text/css",
2830
+ ".json": "application/json",
2831
+ ".svg": "image/svg+xml",
2832
+ ".png": "image/png",
2833
+ ".ico": "image/x-icon",
2834
+ ".jpg": "image/jpeg",
2835
+ ".jpeg": "image/jpeg",
2836
+ ".gif": "image/gif",
2837
+ ".webp": "image/webp",
2838
+ ".bmp": "image/bmp",
2839
+ ".avif": "image/avif"
2840
+ };
2841
+ function isCustomMode(opts) {
2842
+ return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
2843
+ }
2844
+ function createApp(clientDir, diffOpts = DEFAULTS$1, commentStore, planStore, prSessionStore, prMode = false) {
2845
+ const app = new Hono();
2846
+ const customMode = isCustomMode(diffOpts);
2847
+ const store = commentStore ?? new FileCommentStore();
2848
+ const plans = planStore ?? new FilePlanStore();
2849
+ const prStore = prSessionStore ?? new FilePrSessionStore();
2850
+ const uiStateStore = new FileUiStateStore();
2851
+ const viewedFiles = /* @__PURE__ */ new Set();
2852
+ const activeClients = /* @__PURE__ */ new Set();
2853
+ const broadcast = (event, data) => {
2854
+ for (const send of activeClients) try {
2855
+ send(event, data);
2856
+ } catch {}
2857
+ };
2858
+ const reviewSession = new ReviewSession((snapshot) => broadcast("agent-status", JSON.stringify(snapshot)));
2859
+ const planReviewSession = new PlanReviewSession((snapshot) => broadcast("plan-review-status", JSON.stringify(snapshot)));
2860
+ let repoRoot;
2861
+ try {
2862
+ repoRoot = getRepoRoot();
2863
+ } catch {
2864
+ repoRoot = process.cwd();
2865
+ }
2866
+ if (!commentStore && !planStore) try {
2867
+ const storageDir = getProjectStorageDir();
2868
+ mkdirSync(storageDir, { recursive: true });
2869
+ let commentsDebounce = null;
2870
+ let plansDebounce = null;
2871
+ let prSessionDebounce = null;
2872
+ watch(storageDir, (_eventType, filename) => {
2873
+ if (!filename) return;
2874
+ if (filename.startsWith("comments.json")) {
2875
+ if (commentsDebounce) clearTimeout(commentsDebounce);
2876
+ commentsDebounce = setTimeout(() => broadcast("comments", Date.now().toString()), 120);
2877
+ } else if (filename.startsWith("plans.json")) {
2878
+ if (plansDebounce) clearTimeout(plansDebounce);
2879
+ plansDebounce = setTimeout(() => broadcast("plans", Date.now().toString()), 120);
2880
+ } else if (filename.startsWith("pr-session.json")) {
2881
+ if (prSessionDebounce) clearTimeout(prSessionDebounce);
2882
+ prSessionDebounce = setTimeout(() => broadcast("pr-session", Date.now().toString()), 120);
2883
+ }
2884
+ }).unref();
2885
+ } catch (err) {
2886
+ console.warn("Failed to initialize storage watcher:", err);
2887
+ }
2888
+ let debounceTimeout = null;
2889
+ try {
2890
+ watch(repoRoot, { recursive: true }, (eventType, filename) => {
2891
+ if (!filename) return;
2892
+ const parts = filename.split(/[/\\]/);
2893
+ const isGit = parts.includes(".git");
2894
+ const isNodeModules = parts.includes("node_modules");
2895
+ const isDist = parts.includes("dist");
2896
+ const isChangeset = parts.includes(".changeset");
2897
+ let shouldTrigger = false;
2898
+ if (isGit) {
2899
+ const isIndex = filename.endsWith("index");
2900
+ const isHead = filename.endsWith("HEAD");
2901
+ const isRefs = filename.includes("refs/") || filename.includes("refs\\");
2902
+ if (isIndex || isHead || isRefs) shouldTrigger = true;
2903
+ } else if (!isNodeModules && !isDist && !isChangeset) shouldTrigger = true;
2904
+ if (shouldTrigger) {
2905
+ if (debounceTimeout) clearTimeout(debounceTimeout);
2906
+ debounceTimeout = setTimeout(() => broadcast("change", Date.now().toString()), 200);
2907
+ }
2908
+ }).unref();
2909
+ } catch (err) {
2910
+ console.warn("Failed to initialize repository watcher:", err);
2911
+ }
2912
+ app.get("/api/live", async (c) => {
2913
+ return streamSSE(c, async (stream) => {
2914
+ const sendUpdate = (event, data) => {
2915
+ stream.writeSSE({
2916
+ event,
2917
+ data
2918
+ });
2919
+ };
2920
+ activeClients.add(sendUpdate);
2921
+ await stream.writeSSE({
2922
+ event: "heartbeat",
2923
+ data: Date.now().toString()
2924
+ });
2925
+ const heartbeatInterval = setInterval(() => {
2926
+ stream.writeSSE({
2927
+ event: "heartbeat",
2928
+ data: Date.now().toString()
2929
+ }).catch(() => {});
2930
+ }, 15e3);
2931
+ await new Promise((resolve) => {
2932
+ stream.onAbort(() => {
2933
+ clearInterval(heartbeatInterval);
2934
+ activeClients.delete(sendUpdate);
2935
+ resolve();
2936
+ });
2937
+ });
2938
+ });
2939
+ });
2940
+ app.get("/api/diff", async (c) => {
2941
+ const stagedQuery = c.req.query("staged");
2942
+ const untrackedQuery = c.req.query("untracked");
2943
+ const staged = stagedQuery === void 0 ? diffOpts.staged : stagedQuery === "true";
2944
+ const untracked = untrackedQuery === void 0 ? diffOpts.includeUntracked : untrackedQuery === "true";
2945
+ if (prMode) {
2946
+ const prSession = await prStore.get();
2947
+ if (prSession) {
2948
+ const binaryFiles = [];
2949
+ const filePaths = [];
2950
+ for (const line of prSession.diff.split("\n")) {
2951
+ const m = /^diff --git a\/.+ b\/(.+)$/.exec(line);
2952
+ if (m) filePaths.push(m[1]);
2953
+ }
2954
+ const prOverview = buildPrOverview({
2955
+ prNumber: prSession.pullNumber,
2956
+ prTitle: prSession.title,
2957
+ prAuthor: prSession.author?.login ?? null,
2958
+ additions: prSession.additions,
2959
+ deletions: prSession.deletions
2960
+ });
2961
+ return c.json({
2962
+ patch: prSession.diff,
2963
+ repoName: prSession.repo,
2964
+ branch: `#${prSession.pullNumber}`,
2965
+ customMode: true,
2966
+ binaryFiles,
2967
+ tabSizeMap: {},
2968
+ untrackedFiles: [],
2969
+ prMode: true,
2970
+ prRef: prSession.ref,
2971
+ prOwner: prSession.owner,
2972
+ prRepo: prSession.repo,
2973
+ prPullNumber: prSession.pullNumber,
2974
+ prUrl: prSession.url,
2975
+ prTitle: prSession.title,
2976
+ prAuthor: prSession.author,
2977
+ prHeadSha: prSession.headSha,
2978
+ prBaseSha: prSession.baseSha,
2979
+ overview: prOverview
2980
+ });
2981
+ }
2982
+ }
2983
+ const optsForDiff = customMode ? diffOpts : {
2984
+ ...diffOpts,
2985
+ staged,
2986
+ includeUntracked: untracked
2987
+ };
2988
+ const result = await executeDiffWithMeta(optsForDiff);
2989
+ return c.json({
2990
+ patch: result.patch,
2991
+ repoName: result.repoName,
2992
+ branch: result.branch,
2993
+ customMode,
2994
+ binaryFiles: result.binaryFiles,
2995
+ tabSizeMap: result.tabSizeMap,
2996
+ untrackedFiles: result.untrackedFiles,
2997
+ showMode: optsForDiff.showMode || void 0,
2998
+ commits: result.commits,
2999
+ truncated: result.truncated,
3000
+ overview: result.overview
3001
+ });
3002
+ });
3003
+ app.get("/api/file-content", (c) => {
3004
+ const path = c.req.query("path");
3005
+ const version = c.req.query("version");
3006
+ if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
3007
+ const content = getFileContent(path, version);
3008
+ if (!content) return c.json({ error: "File not found" }, 404);
3009
+ const contentType = MIME_TYPES[extname(path)] || "application/octet-stream";
3010
+ return new Response(new Uint8Array(content), { headers: { "Content-Type": contentType } });
3011
+ });
3012
+ app.get("/api/file-text", (c) => {
3013
+ const path = c.req.query("path");
3014
+ const version = c.req.query("version");
3015
+ if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
3016
+ const buffer = getFileContent(path, version);
3017
+ if (!buffer) return c.json({
3018
+ content: "",
3019
+ missing: true
3020
+ });
3021
+ const sample = buffer.subarray(0, Math.min(buffer.length, 8192));
3022
+ for (let i = 0; i < sample.length; i++) if (sample[i] === 0) return c.json({ error: "Binary file" }, 415);
3023
+ return c.json({
3024
+ content: buffer.toString("utf-8"),
3025
+ missing: false
3026
+ });
3027
+ });
3028
+ app.post("/api/open-file", async (c) => {
3029
+ const { filePath, editor } = await c.req.json();
3030
+ if (!filePath) return c.json({ error: "filePath is required" }, 400);
3031
+ try {
3032
+ const root = getRepoRoot();
3033
+ const relPath = toSafeRelativePath(filePath, root);
3034
+ if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
3035
+ const absolutePath = resolve(root, relPath);
3036
+ if (editor && editor !== "default") {
3037
+ const command = resolveEditorCommand(editor, absolutePath);
3038
+ if (command) {
3039
+ const { execFile } = await import("node:child_process");
3040
+ execFile(command.cmd, command.args, (err) => {
3041
+ if (err) console.error(`Failed to launch ${editor} for ${absolutePath}: ${err.message}`);
3042
+ });
3043
+ return c.json({ ok: true });
3044
+ }
3045
+ }
3046
+ await (await import("open")).default(absolutePath);
3047
+ return c.json({ ok: true });
3048
+ } catch (err) {
3049
+ return c.json({ error: `Failed to open file: ${err.message}` }, 500);
3050
+ }
3051
+ });
3052
+ app.get("/api/repo-files", (c) => {
3053
+ try {
3054
+ return c.json({ files: listRepoFiles() });
3055
+ } catch (err) {
3056
+ return c.json({ error: err.message }, 500);
3057
+ }
3058
+ });
3059
+ app.post("/api/search", async (c) => {
3060
+ const body = await c.req.json().catch(() => ({}));
3061
+ const scope = body.scope ?? "files";
3062
+ const query = typeof body.query === "string" ? body.query : "";
3063
+ const limit = typeof body.limit === "number" ? body.limit : void 0;
3064
+ const paths = Array.isArray(body.changedPaths) ? body.changedPaths : void 0;
3065
+ try {
3066
+ if (scope === "all") return c.json(await searchAll(query, {
3067
+ limit,
3068
+ regex: !!body.regex,
3069
+ paths
3070
+ }));
3071
+ if (scope === "text") return c.json(await searchContent(query, {
3072
+ limit,
3073
+ regex: !!body.regex,
3074
+ paths
3075
+ }));
3076
+ if (scope === "symbols") return c.json(await searchSymbols(query, {
3077
+ limit,
3078
+ paths
3079
+ }));
3080
+ return c.json(await searchFiles(query, {
3081
+ limit,
3082
+ paths
3083
+ }));
3084
+ } catch (err) {
3085
+ return c.json({
3086
+ scope,
3087
+ items: [],
3088
+ total: 0,
3089
+ indexing: false,
3090
+ error: err?.message ?? "Search failed"
3091
+ }, 500);
3092
+ }
3093
+ });
3094
+ app.get("/api/search/status", async (c) => {
3095
+ return c.json(await getSearchStatus());
3096
+ });
3097
+ app.post("/api/search/track", async (c) => {
3098
+ const { query, path } = await c.req.json().catch(() => ({}));
3099
+ if (path) await trackSelection(query ?? "", path);
3100
+ return c.json({ ok: true });
3101
+ });
3102
+ app.get("/api/merge-status", (c) => {
3103
+ try {
3104
+ const status = getMergeStatus();
3105
+ return c.json(status);
3106
+ } catch (err) {
3107
+ return c.json({ error: err.message }, 500);
3108
+ }
3109
+ });
3110
+ app.post("/api/revert-hunk", async (c) => {
3111
+ const { filePath, hunkIndex } = await c.req.json();
3112
+ if (!filePath || typeof hunkIndex !== "number") return c.json({ error: "Missing filePath or hunkIndex" }, 400);
3113
+ try {
3114
+ const relPath = toSafeRelativePath(filePath, getRepoRoot());
3115
+ if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
3116
+ revertHunk(relPath, hunkIndex);
3117
+ return c.json({ ok: true });
3118
+ } catch (err) {
3119
+ const stderr = typeof err?.stderr === "string" ? err.stderr : err?.stderr instanceof Buffer ? err.stderr.toString("utf-8") : "";
3120
+ return c.json({ error: stderr || err?.message || "Failed to revert hunk" }, 500);
3121
+ }
3122
+ });
3123
+ /**
3124
+ * Pick a single tree-ish suitable for `git blame` from a list of revisions
3125
+ * or show-revspecs. `git blame` does not accept range notation, so for
3126
+ * `A..B` or `A...B` we use the right endpoint (the side being compared
3127
+ * against), which matches the diff's "destination" side.
3128
+ */
3129
+ function extractBlameRevision(revisions, showRevspecs, showMode) {
3130
+ const list = showMode ? showRevspecs : revisions;
3131
+ if (list.length === 0) return "HEAD";
3132
+ const last = list[list.length - 1];
3133
+ const threeDot = last.lastIndexOf("...");
3134
+ if (threeDot >= 0) {
3135
+ const target = last.slice(threeDot + 3);
3136
+ if (target) return target;
3137
+ }
3138
+ const twoDot = last.lastIndexOf("..");
3139
+ if (twoDot >= 0) {
3140
+ const target = last.slice(twoDot + 2);
3141
+ if (target) return target;
3142
+ }
3143
+ return last;
3144
+ }
3145
+ app.get("/api/hunk-history", async (c) => {
3146
+ const filePath = c.req.query("filePath");
3147
+ const deletionStart = Number(c.req.query("deletionStart"));
3148
+ const deletionCount = Number(c.req.query("deletionCount"));
3149
+ if (!filePath || Number.isNaN(deletionStart) || Number.isNaN(deletionCount)) return c.json({ error: "Missing or invalid parameters" }, 400);
3150
+ try {
3151
+ const relPath = toSafeRelativePath(filePath, getRepoRoot());
3152
+ if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
3153
+ const history = getHunkHistory(relPath, deletionStart, deletionCount, extractBlameRevision(diffOpts.revisions, diffOpts.showRevspecs, diffOpts.showMode));
3154
+ return c.json(history);
3155
+ } catch (err) {
3156
+ return c.json({ error: err.message || "Failed to fetch hunk history" }, 500);
3157
+ }
3158
+ });
3159
+ app.post("/api/save-file", async (c) => {
3160
+ const { filePath, content, gitAdd } = await c.req.json();
3161
+ if (!filePath || typeof content !== "string") return c.json({ error: "Missing filePath or content" }, 400);
3162
+ try {
3163
+ const root = getRepoRoot();
3164
+ const relPath = toSafeRelativePath(filePath, root);
3165
+ if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
3166
+ await writeFile(resolve(root, relPath), content, "utf-8");
3167
+ if (gitAdd) try {
3168
+ gitAddFile(relPath);
3169
+ } catch (err) {
3170
+ return c.json({
3171
+ ok: true,
3172
+ gitAddError: err.message
3173
+ });
3174
+ }
3175
+ return c.json({ ok: true });
3176
+ } catch (err) {
3177
+ return c.json({ error: `Failed to save file: ${err.message}` }, 500);
3178
+ }
3179
+ });
3180
+ app.get("/api/settings", (c) => {
3181
+ return c.json(loadSettings());
3182
+ });
3183
+ app.put("/api/settings", async (c) => {
3184
+ const settings = saveSettings(await c.req.json());
3185
+ return c.json(settings);
3186
+ });
3187
+ app.get("/api/ui-state", async (c) => {
3188
+ return c.json(await uiStateStore.getAll());
3189
+ });
3190
+ app.put("/api/ui-state", async (c) => {
3191
+ const body = await c.req.json();
3192
+ const merged = {
3193
+ ...await uiStateStore.getAll(),
3194
+ ...body
3195
+ };
3196
+ for (const key of Object.keys(body)) if (body[key] === null || body[key] === void 0) delete merged[key];
3197
+ await uiStateStore.setAll(merged);
3198
+ return c.json(merged);
3199
+ });
3200
+ app.get("/api/viewed", (c) => {
3201
+ return c.json([...viewedFiles]);
3202
+ });
3203
+ app.put("/api/viewed", async (c) => {
3204
+ const { filePath, viewed } = await c.req.json();
3205
+ if (viewed) viewedFiles.add(filePath);
3206
+ else viewedFiles.delete(filePath);
3207
+ broadcast("viewed", JSON.stringify([...viewedFiles]));
3208
+ return c.json({ ok: true });
3209
+ });
3210
+ app.get("/api/comments", async (c) => {
3211
+ const comments = await store.getAll();
3212
+ return c.json(comments);
3213
+ });
3214
+ app.post("/api/comments/resolve-all", async (c) => {
3215
+ const resolved = await store.resolveAllOpen();
3216
+ return c.json({
3217
+ ok: true,
3218
+ resolved
3219
+ });
3220
+ });
3221
+ app.post("/api/comments", async (c) => {
3222
+ const body = await c.req.json();
3223
+ const comment = {
3224
+ id: crypto.randomUUID(),
3225
+ filePath: body.filePath,
3226
+ side: body.side,
3227
+ lineNumber: body.lineNumber,
3228
+ startLineNumber: body.startLineNumber,
3229
+ lineContent: body.lineContent,
3230
+ body: body.body,
3231
+ status: "open",
3232
+ createdAt: Date.now(),
3233
+ replies: []
3234
+ };
3235
+ const created = await store.add(comment);
3236
+ return c.json(created, 201);
3237
+ });
3238
+ app.put("/api/comments/:id", async (c) => {
3239
+ const id = c.req.param("id");
3240
+ const { body, status } = await c.req.json();
3241
+ const updated = await store.update(id, {
3242
+ body,
3243
+ status
3244
+ });
3245
+ if (!updated) return c.json({ error: "Comment not found" }, 404);
3246
+ return c.json(updated);
3247
+ });
3248
+ app.post("/api/comments/:id/replies", async (c) => {
3249
+ const commentId = c.req.param("id");
3250
+ const { body, role, model } = await c.req.json();
3251
+ const reply = {
3252
+ id: crypto.randomUUID(),
3253
+ body,
3254
+ createdAt: Date.now(),
3255
+ role: role || (model ? "agent" : "user"),
3256
+ model: model || void 0
3257
+ };
3258
+ const updated = await store.addReply(commentId, reply);
3259
+ if (!updated) return c.json({ error: "Comment not found" }, 404);
3260
+ return c.json(updated);
3261
+ });
3262
+ app.delete("/api/comments/:id/replies/:replyId", async (c) => {
3263
+ const commentId = c.req.param("id");
3264
+ const replyId = c.req.param("replyId");
3265
+ const updated = await store.removeReply(commentId, replyId);
3266
+ if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
3267
+ return c.json(updated);
3268
+ });
3269
+ app.put("/api/comments/:id/replies/:replyId", async (c) => {
3270
+ const commentId = c.req.param("id");
3271
+ const replyId = c.req.param("replyId");
3272
+ const { body } = await c.req.json();
3273
+ if (!body) return c.json({ error: "Body is required" }, 400);
3274
+ const updated = await store.updateReply(commentId, replyId, body);
3275
+ if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
3276
+ return c.json(updated);
3277
+ });
3278
+ app.post("/api/comments/:id/apply-suggestion", async (c) => {
3279
+ const id = c.req.param("id");
3280
+ const comment = (await store.getAll()).find((c) => c.id === id);
3281
+ if (!comment) return c.json({ error: "Comment not found" }, 404);
3282
+ if (comment.side !== "additions") return c.json({ error: "Suggestions can only be applied to added or modified lines" }, 400);
3283
+ const match = comment.body.match(/```suggestion\n([\s\S]*?)```/);
3284
+ if (!match) return c.json({ error: "No suggestion block found in comment body" }, 400);
3285
+ const suggestion = match[1];
3286
+ try {
3287
+ const root = getRepoRoot();
3288
+ const relPath = toSafeRelativePath(comment.filePath, root);
3289
+ if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
3290
+ const absolutePath = resolve(root, relPath);
3291
+ const lines = (await readFile(absolutePath, "utf-8")).split(/\r?\n/);
3292
+ const lineIdx = comment.lineNumber - 1;
3293
+ if (lineIdx < 0 || lineIdx >= lines.length) return c.json({ error: "Comment line number out of range" }, 400);
3294
+ lines[lineIdx] = suggestion.trimEnd();
3295
+ await writeFile(absolutePath, lines.join("\n"), "utf-8");
3296
+ await store.update(id, { status: "resolved" });
3297
+ return c.json({ ok: true });
3298
+ } catch (err) {
3299
+ return c.json({ error: `Failed to apply suggestion: ${err.message}` }, 500);
3300
+ }
3301
+ });
3302
+ app.delete("/api/comments/:id", async (c) => {
3303
+ const id = c.req.param("id");
3304
+ if (!await store.remove(id)) return c.json({ error: "Comment not found" }, 404);
3305
+ return c.json({ ok: true });
3306
+ });
3307
+ /** Shared helper: 404 with a stable shape so the client knows "not in PR mode". */
3308
+ const notInPrMode = (c) => c.json({
3309
+ error: "Not in PR review mode",
3310
+ prMode: false
3311
+ }, 404);
3312
+ app.get("/api/gh/session", async (c) => {
3313
+ if (!prMode) return notInPrMode(c);
3314
+ const session = await prStore.get();
3315
+ if (!session) return notInPrMode(c);
3316
+ return c.json({
3317
+ prMode: true,
3318
+ ref: session.ref,
3319
+ owner: session.owner,
3320
+ repo: session.repo,
3321
+ pullNumber: session.pullNumber,
3322
+ baseSha: session.baseSha,
3323
+ headSha: session.headSha,
3324
+ title: session.title,
3325
+ url: session.url,
3326
+ author: session.author,
3327
+ additions: session.additions,
3328
+ deletions: session.deletions,
3329
+ changedFiles: session.changedFiles,
3330
+ existingComments: session.existingComments,
3331
+ submittedAt: session.submittedAt,
3332
+ submittedReviewId: session.submittedReviewId,
3333
+ submittedReviewUrl: session.submittedReviewUrl,
3334
+ authSource: session.authSource
3335
+ });
3336
+ });
3337
+ /** Re-fetch PR metadata (head SHA, diff, existing comments) and persist. */
3338
+ app.post("/api/gh/pr/refresh", async (c) => {
3339
+ if (!prMode) return notInPrMode(c);
3340
+ const session = await prStore.get();
3341
+ if (!session) return notInPrMode(c);
3342
+ try {
3343
+ const refreshed = await refreshPrSession(session);
3344
+ await prStore.set(refreshed);
3345
+ return c.json({
3346
+ ok: true,
3347
+ headSha: refreshed.headSha
3348
+ });
3349
+ } catch (err) {
3350
+ return c.json({ error: err?.message ?? "Refresh failed" }, 500);
3351
+ }
3352
+ });
3353
+ /** Initialize a PR session from a ref like `1234`, `o/r#42`, or a GitHub URL. */
3354
+ app.post("/api/gh/pr/init", async (c) => {
3355
+ if (!prMode) return notInPrMode(c);
3356
+ const body = await c.req.json().catch(() => ({}));
3357
+ const ref = typeof body?.ref === "string" ? body.ref : "";
3358
+ if (!ref.trim()) return c.json({ error: "ref is required" }, 400);
3359
+ try {
3360
+ parsePrRef(ref, await detectCwdRepo() ?? void 0);
3361
+ const session = await buildPrSession(ref);
3362
+ await prStore.set(session);
3363
+ return c.json({
3364
+ ok: true,
3365
+ ref: session.ref,
3366
+ owner: session.owner,
3367
+ repo: session.repo,
3368
+ pullNumber: session.pullNumber,
3369
+ url: session.url
3370
+ });
3371
+ } catch (err) {
3372
+ return c.json({ error: err?.message ?? "Failed to initialise PR session" }, 500);
3373
+ }
3374
+ });
3375
+ app.get("/api/gh/pr-session/comments", async (c) => {
3376
+ if (!prMode) return notInPrMode(c);
3377
+ const session = await prStore.get();
3378
+ if (!session) return notInPrMode(c);
3379
+ return c.json(session.comments ?? []);
3380
+ });
3381
+ app.post("/api/gh/pr-session/comments", async (c) => {
3382
+ if (!prMode) return notInPrMode(c);
3383
+ const body = await c.req.json();
3384
+ const session = await prStore.get();
3385
+ if (!session) return notInPrMode(c);
3386
+ const comment = {
3387
+ id: crypto.randomUUID(),
3388
+ filePath: body.filePath,
3389
+ side: body.side,
3390
+ lineNumber: body.lineNumber,
3391
+ startLineNumber: body.startLineNumber,
3392
+ lineContent: body.lineContent,
3393
+ body: body.body,
3394
+ status: "open",
3395
+ createdAt: Date.now(),
3396
+ replies: []
3397
+ };
3398
+ const next = {
3399
+ ...session,
3400
+ comments: [...session.comments ?? [], comment]
3401
+ };
3402
+ await prStore.set(next);
3403
+ return c.json(comment, 201);
3404
+ });
3405
+ app.put("/api/gh/pr-session/comments/:id", async (c) => {
3406
+ if (!prMode) return notInPrMode(c);
3407
+ const id = c.req.param("id");
3408
+ const { body, status } = await c.req.json();
3409
+ const session = await prStore.get();
3410
+ if (!session) return notInPrMode(c);
3411
+ const comments = (session.comments ?? []).map((cm) => cm.id === id ? {
3412
+ ...cm,
3413
+ body: body ?? cm.body,
3414
+ status: status ?? cm.status
3415
+ } : cm);
3416
+ await prStore.set({
3417
+ ...session,
3418
+ comments
3419
+ });
3420
+ const updated = comments.find((cm) => cm.id === id) ?? null;
3421
+ if (!updated) return c.json({ error: "Comment not found" }, 404);
3422
+ return c.json(updated);
3423
+ });
3424
+ app.delete("/api/gh/pr-session/comments/:id", async (c) => {
3425
+ if (!prMode) return notInPrMode(c);
3426
+ const id = c.req.param("id");
3427
+ const session = await prStore.get();
3428
+ if (!session) return notInPrMode(c);
3429
+ const comments = (session.comments ?? []).filter((cm) => cm.id !== id);
3430
+ await prStore.set({
3431
+ ...session,
3432
+ comments
3433
+ });
3434
+ return c.json({ ok: true });
3435
+ });
3436
+ app.post("/api/gh/pr-session/comments/:id/replies", async (c) => {
3437
+ if (!prMode) return notInPrMode(c);
3438
+ const id = c.req.param("id");
3439
+ const { body, role, model } = await c.req.json();
3440
+ const session = await prStore.get();
3441
+ if (!session) return notInPrMode(c);
3442
+ const comments = (session.comments ?? []).map((cm) => {
3443
+ if (cm.id !== id) return cm;
3444
+ const reply = {
3445
+ id: crypto.randomUUID(),
3446
+ body,
3447
+ createdAt: Date.now(),
3448
+ role: role || (model ? "agent" : "user"),
3449
+ model: model || void 0
3450
+ };
3451
+ return {
3452
+ ...cm,
3453
+ replies: [...cm.replies ?? [], reply]
3454
+ };
3455
+ });
3456
+ await prStore.set({
3457
+ ...session,
3458
+ comments
3459
+ });
3460
+ return c.json(comments.find((cm) => cm.id === id));
3461
+ });
3462
+ /** Submit the current PR session's review (new comments + verdict + body) to GitHub. */
3463
+ app.post("/api/gh/submit", async (c) => {
3464
+ if (!prMode) return notInPrMode(c);
3465
+ const session = await prStore.get();
3466
+ if (!session) return notInPrMode(c);
3467
+ const body = await c.req.json().catch(() => ({}));
3468
+ const decision = body.decision;
3469
+ if (decision !== "approve" && decision !== "comment" && decision !== "request-changes") return c.json({ error: "decision must be one of: approve, comment, request-changes" }, 400);
3470
+ const generalBody = typeof body.body === "string" ? body.body : "";
3471
+ const dryRun = body.dryRun === true;
3472
+ const result = await submitReview({
3473
+ resolved: {
3474
+ owner: session.owner,
3475
+ repo: session.repo,
3476
+ pullNumber: session.pullNumber,
3477
+ ref: session.ref
3478
+ },
3479
+ decision,
3480
+ body: generalBody,
3481
+ comments: session.comments ?? []
3482
+ });
3483
+ if (result.ok && !dryRun) {
3484
+ const next = {
3485
+ ...session,
3486
+ submittedAt: Date.now(),
3487
+ submittedReviewId: result.reviewId,
3488
+ submittedReviewUrl: result.reviewUrl,
3489
+ authSource: result.authSource
3490
+ };
3491
+ await prStore.set(next);
3492
+ }
3493
+ return c.json({
3494
+ ok: result.ok,
3495
+ reviewId: result.reviewId,
3496
+ reviewUrl: result.reviewUrl,
3497
+ failedComments: result.failedComments ?? 0,
3498
+ authSource: result.authSource,
3499
+ error: result.error,
3500
+ dryRun
3501
+ });
3502
+ });
3503
+ app.post("/api/review/send", async (c) => {
3504
+ const body = await c.req.json().catch(() => ({}));
3505
+ const generalComment = typeof body?.generalComment === "string" ? body.generalComment : void 0;
3506
+ const decision = body?.decision === "approved" || body?.decision === "changes-requested" || body?.decision === "rejected" || body?.decision === "comment-only" ? body.decision : void 0;
3507
+ const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
3508
+ const force = body?.force === true;
3509
+ const all = await store.getAll();
3510
+ const findings = scanReviewForSecrets({
3511
+ generalComment,
3512
+ comments: all
3513
+ });
3514
+ if (findings.length > 0 && !force) return c.json({
3515
+ ok: false,
3516
+ error: "secrets-detected",
3517
+ findings
3518
+ }, 400);
3519
+ const openCount = all.filter((x) => x.status === "open").length;
3520
+ const payload = reviewSession.send({
3521
+ sentAt: Date.now(),
3522
+ commentXml: formatComments(all, generalComment, decision, mode),
3523
+ openCount,
3524
+ comments: all,
3525
+ decision,
3526
+ mode
3527
+ });
3528
+ return c.json({
3529
+ ok: true,
3530
+ round: payload.round,
3531
+ openCount: payload.openCount,
3532
+ decision: payload.decision,
3533
+ mode: payload.mode,
3534
+ waiters: reviewSession.snapshot().waiters,
3535
+ secretsBypassed: findings.length > 0 && force
3536
+ });
3537
+ });
3538
+ app.get("/api/review/await", async (c) => {
3539
+ const sinceRaw = c.req.query("sinceRound");
3540
+ const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
3541
+ const requested = Number(c.req.query("timeoutMs")) || 25e3;
3542
+ const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
3543
+ const result = await reviewSession.await({
3544
+ sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
3545
+ timeoutMs,
3546
+ signal: c.req.raw.signal
3547
+ });
3548
+ return c.json(result);
3549
+ });
3550
+ app.get("/api/review/status", (c) => {
3551
+ return c.json(reviewSession.snapshot());
3552
+ });
3553
+ app.get("/api/review/history", (c) => {
3554
+ return c.json({ rounds: reviewSession.getHistory() });
3555
+ });
3556
+ app.get("/api/plans", async (c) => {
3557
+ return c.json(await plans.getAll());
3558
+ });
3559
+ app.get("/api/plans/:id", async (c) => {
3560
+ const plan = await plans.get(c.req.param("id"));
3561
+ if (!plan) return c.json({ error: "Plan not found" }, 404);
3562
+ return c.json(plan);
3563
+ });
3564
+ app.get("/api/plans/:id/versions", async (c) => {
3565
+ const plan = await plans.get(c.req.param("id"));
3566
+ if (!plan) return c.json({ error: "Plan not found" }, 404);
3567
+ return c.json(plan.versions ?? []);
3568
+ });
3569
+ app.get("/api/plans/:id/versions/:n", async (c) => {
3570
+ const id = c.req.param("id");
3571
+ const n = Number(c.req.param("n"));
3572
+ if (!Number.isFinite(n) || n < 1) return c.json({ error: "version must be a positive integer" }, 400);
3573
+ const plan = await plans.get(id);
3574
+ if (!plan) return c.json({ error: "Plan not found" }, 404);
3575
+ const version = (plan.versions ?? []).find((v) => v.version === n);
3576
+ if (!version) return c.json({ error: `Version ${n} not found` }, 404);
3577
+ return c.json({
3578
+ version,
3579
+ plan: {
3580
+ id: plan.id,
3581
+ title: plan.title,
3582
+ decision: plan.decision,
3583
+ currentVersion: plan.version
3584
+ }
3585
+ });
3586
+ });
3587
+ app.post("/api/plans", async (c) => {
3588
+ const body = await c.req.json().catch(() => ({}));
3589
+ if (typeof body.body !== "string" || !body.body.trim()) return c.json({ error: "A plan body (markdown) is required" }, 400);
3590
+ const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "Untitled plan";
3591
+ const plan = await plans.upsert({
3592
+ id: typeof body.id === "string" && body.id ? body.id : void 0,
3593
+ title,
3594
+ body: body.body,
3595
+ source: typeof body.source === "string" ? body.source : void 0,
3596
+ model: typeof body.model === "string" ? body.model : void 0
3597
+ });
3598
+ return c.json(plan, 201);
3599
+ });
3600
+ app.put("/api/plans/:id", async (c) => {
3601
+ const id = c.req.param("id");
3602
+ const { title, body, source, model } = await c.req.json().catch(() => ({}));
3603
+ const updated = await plans.update(id, {
3604
+ title: typeof title === "string" ? title : void 0,
3605
+ body: typeof body === "string" ? body : void 0,
3606
+ source: typeof source === "string" ? source : void 0,
3607
+ model: typeof model === "string" ? model : void 0
3608
+ });
3609
+ if (!updated) return c.json({ error: "Plan not found" }, 404);
3610
+ return c.json(updated);
3611
+ });
3612
+ app.delete("/api/plans/:id", async (c) => {
3613
+ if (!await plans.remove(c.req.param("id"))) return c.json({ error: "Plan not found" }, 404);
3614
+ return c.json({ ok: true });
3615
+ });
3616
+ app.post("/api/plans/:id/comments", async (c) => {
3617
+ const planId = c.req.param("id");
3618
+ const plan = await plans.get(planId);
3619
+ if (!plan) return c.json({ error: "Plan not found" }, 404);
3620
+ const body = await c.req.json();
3621
+ const lineNumber = Number.isFinite(body.lineNumber) ? Number(body.lineNumber) : 0;
3622
+ const startLineNumber = Number.isFinite(body.startLineNumber) ? Number(body.startLineNumber) : void 0;
3623
+ const anchorStart = startLineNumber ?? lineNumber;
3624
+ const lineContent = typeof body.lineContent === "string" && body.lineContent ? body.lineContent : lineNumber > 0 ? extractPlanLines(plan.body, anchorStart, lineNumber) : "";
3625
+ const sectionTitle = typeof body.sectionTitle === "string" && body.sectionTitle ? body.sectionTitle : lineNumber > 0 ? sectionTitleForLine(plan.body, anchorStart) : void 0;
3626
+ const createdAtPlanVersion = Number.isFinite(body.createdAtPlanVersion) ? Number(body.createdAtPlanVersion) : plan.version;
3627
+ const comment = {
3628
+ id: crypto.randomUUID(),
3629
+ lineNumber,
3630
+ startLineNumber,
3631
+ lineContent,
3632
+ sectionTitle,
3633
+ body: body.body,
3634
+ status: "open",
3635
+ createdAt: Date.now(),
3636
+ createdAtPlanVersion,
3637
+ replies: []
3638
+ };
3639
+ const updated = await plans.addComment(planId, comment);
3640
+ if (!updated) return c.json({ error: "Plan not found" }, 404);
3641
+ return c.json(updated, 201);
3642
+ });
3643
+ app.put("/api/plans/:id/comments/:commentId", async (c) => {
3644
+ const { body, status } = await c.req.json();
3645
+ const updated = await plans.updateComment(c.req.param("id"), c.req.param("commentId"), {
3646
+ body,
3647
+ status
3648
+ });
3649
+ if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3650
+ return c.json(updated);
3651
+ });
3652
+ app.delete("/api/plans/:id/comments/:commentId", async (c) => {
3653
+ const updated = await plans.removeComment(c.req.param("id"), c.req.param("commentId"));
3654
+ if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3655
+ return c.json(updated);
3656
+ });
3657
+ app.post("/api/plans/:id/comments/:commentId/replies", async (c) => {
3658
+ const { body, role, model } = await c.req.json();
3659
+ const reply = {
3660
+ id: crypto.randomUUID(),
3661
+ body,
3662
+ createdAt: Date.now(),
3663
+ role: role || (model ? "agent" : "user"),
3664
+ model: model || void 0
3665
+ };
3666
+ const updated = await plans.addReply(c.req.param("id"), c.req.param("commentId"), reply);
3667
+ if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3668
+ return c.json(updated);
3669
+ });
3670
+ app.put("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3671
+ const { body } = await c.req.json();
3672
+ if (!body) return c.json({ error: "Body is required" }, 400);
3673
+ const updated = await plans.updateReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"), body);
3674
+ if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3675
+ return c.json(updated);
3676
+ });
3677
+ app.delete("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3678
+ const updated = await plans.removeReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"));
3679
+ if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3680
+ return c.json(updated);
3681
+ });
3682
+ app.post("/api/plans/:id/decision", async (c) => {
3683
+ const planId = c.req.param("id");
3684
+ const body = await c.req.json().catch(() => ({}));
3685
+ const decision = body.decision;
3686
+ if (decision !== "approved" && decision !== "rejected" && decision !== "changes-requested" && decision !== "comment-only") return c.json({ error: "decision must be one of: approved, rejected, changes-requested, comment-only" }, 400);
3687
+ const decisionComment = typeof body.decisionComment === "string" ? body.decisionComment : void 0;
3688
+ const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
3689
+ const plan = await plans.setDecision(planId, decision, decisionComment);
3690
+ if (!plan) return c.json({ error: "Plan not found" }, 404);
3691
+ const openCommentCount = (plan.comments ?? []).filter((x) => x.status === "open").length;
3692
+ const payload = planReviewSession.decide({
3693
+ sentAt: Date.now(),
3694
+ planId,
3695
+ decision,
3696
+ decisionComment: plan.decisionComment,
3697
+ reviewXml: formatPlanReview(plan, { mode }),
3698
+ openCommentCount,
3699
+ plan,
3700
+ mode
3701
+ });
3702
+ return c.json({
3703
+ ok: true,
3704
+ round: payload.round,
3705
+ decision,
3706
+ mode: payload.mode,
3707
+ openCommentCount,
3708
+ waiters: planReviewSession.snapshot().waiters
3709
+ });
3710
+ });
3711
+ app.get("/api/plan-review/await", async (c) => {
3712
+ const sinceRaw = c.req.query("sinceRound");
3713
+ const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
3714
+ const requested = Number(c.req.query("timeoutMs")) || 25e3;
3715
+ const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
3716
+ const result = await planReviewSession.await({
3717
+ sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
3718
+ timeoutMs,
3719
+ signal: c.req.raw.signal
3720
+ });
3721
+ return c.json(result);
3722
+ });
3723
+ app.get("/api/plan-review/status", (c) => {
3724
+ return c.json(planReviewSession.snapshot());
3725
+ });
3726
+ app.post("/api/attachments", async (c) => {
3727
+ const file = (await c.req.parseBody())["file"];
3728
+ if (!file || !(file instanceof File)) return c.json({ error: "No file uploaded" }, 400);
3729
+ try {
3730
+ const storageDir = getProjectStorageDir();
3731
+ const attachmentsDir = join(storageDir, "attachments");
3732
+ await mkdir(attachmentsDir, { recursive: true });
3733
+ const repoRoot = getRepoRoot();
3734
+ await writeFile(join(storageDir, "repo_path.txt"), repoRoot, "utf-8");
3735
+ const ext = extname(file.name) || ".png";
3736
+ const filename = `pasted_image_${crypto.randomUUID()}${ext}`;
3737
+ const absolutePath = join(attachmentsDir, filename);
3738
+ const arrayBuffer = await file.arrayBuffer();
3739
+ await writeFile(absolutePath, new Uint8Array(arrayBuffer));
3740
+ return c.json({ url: `/api/attachments/${filename}` });
3741
+ } catch (err) {
3742
+ return c.json({ error: `Failed to save attachment: ${err.message}` }, 500);
3743
+ }
3744
+ });
3745
+ app.get("/api/attachments/:filename", async (c) => {
3746
+ const filename = c.req.param("filename");
3747
+ const attachmentsDir = join(getProjectStorageDir(), "attachments");
3748
+ const absolutePath = resolve(attachmentsDir, filename);
3749
+ if (!absolutePath.startsWith(attachmentsDir)) return c.text("Forbidden", 403);
3750
+ try {
3751
+ const content = await readFile(absolutePath);
3752
+ const contentType = MIME_TYPES[extname(absolutePath)] || "application/octet-stream";
3753
+ return new Response(content, { headers: { "Content-Type": contentType } });
3754
+ } catch {
3755
+ return c.text("Attachment not found", 404);
3756
+ }
3757
+ });
3758
+ app.get("/*", async (c) => {
3759
+ let filePath = c.req.path;
3760
+ if (filePath === "/") filePath = "/index.html";
3761
+ const relativePath = filePath.slice(1);
3762
+ if (!isSafePath(relativePath, clientDir)) return c.text("Forbidden", 403);
3763
+ const fullPath = resolve(clientDir, relativePath);
3764
+ try {
3765
+ const content = await readFile(fullPath);
3766
+ const contentType = MIME_TYPES[extname(fullPath)] || "application/octet-stream";
3767
+ return new Response(content, { headers: { "Content-Type": contentType } });
3768
+ } catch {
3769
+ const indexContent = await readFile(join(clientDir, "index.html"));
3770
+ return new Response(indexContent, { headers: { "Content-Type": "text/html" } });
3771
+ }
3772
+ });
3773
+ return app;
3774
+ }
3775
+ /**
3776
+ * Newest mtime (epoch ms) across everything that counts as project activity:
3777
+ * comments.json, plans.json, and any attachment (media) file. Plans and media
3778
+ * extend a project's life exactly like comments do, so retention is uniform
3779
+ * across all three. Returns null when none of them exist yet.
3780
+ */
3781
+ async function newestActivityMs(projectDir) {
3782
+ const candidates = [];
3783
+ const safeStat = async (p) => {
3784
+ try {
3785
+ return (await stat(p)).mtimeMs;
3786
+ } catch {
3787
+ return null;
3788
+ }
3789
+ };
3790
+ for (const name of [
3791
+ "comments.json",
3792
+ "plans.json",
3793
+ "pr-session.json"
3794
+ ]) {
3795
+ const file = join(projectDir, name);
3796
+ if (!existsSync(file)) continue;
3797
+ const m = await safeStat(file);
3798
+ if (m !== null) candidates.push(m);
3799
+ }
3800
+ const attachmentsDir = join(projectDir, "attachments");
3801
+ if (existsSync(attachmentsDir)) {
3802
+ const dirM = await safeStat(attachmentsDir);
3803
+ if (dirM !== null) candidates.push(dirM);
3804
+ try {
3805
+ for (const file of await readdir(attachmentsDir)) {
3806
+ const m = await safeStat(join(attachmentsDir, file));
3807
+ if (m !== null) candidates.push(m);
3808
+ }
3809
+ } catch {}
3810
+ }
3811
+ return candidates.length ? Math.max(...candidates) : null;
3812
+ }
3813
+ async function cleanupStaleProjects() {
3814
+ const baseDir = join(homedir(), ".diffing");
3815
+ if (!existsSync(baseDir)) return;
3816
+ try {
3817
+ const entries = await readdir(baseDir, { withFileTypes: true });
3818
+ const now = Date.now();
3819
+ const STALE_TIME = 336 * 60 * 60 * 1e3;
3820
+ for (const entry of entries) if (entry.isDirectory()) {
3821
+ const projectDir = join(baseDir, entry.name);
3822
+ const repoPathFile = join(projectDir, "repo_path.txt");
3823
+ let shouldDelete = false;
3824
+ if (existsSync(repoPathFile)) try {
3825
+ const repoPath = (await readFile(repoPathFile, "utf-8")).trim();
3826
+ if (!repoPath || !existsSync(repoPath)) shouldDelete = true;
3827
+ } catch {}
3828
+ if (!shouldDelete) {
3829
+ const newest = await newestActivityMs(projectDir);
3830
+ if (newest !== null && now - newest > STALE_TIME) shouldDelete = true;
3831
+ }
3832
+ if (shouldDelete) await rm(projectDir, {
3833
+ recursive: true,
3834
+ force: true
3835
+ });
3836
+ }
3837
+ } catch (err) {
3838
+ console.error("Failed to cleanup stale projects:", err);
3839
+ }
3840
+ }
3841
+ async function startServer(options) {
3842
+ cleanupStaleProjects().catch((err) => {
3843
+ console.error("Failed to clean up stale projects:", err);
3844
+ });
3845
+ let prMode = false;
3846
+ if (options.prRef) {
3847
+ console.error(`Building PR session for ${options.prRef}...`);
3848
+ try {
3849
+ const store = new FilePrSessionStore();
3850
+ const existing = await store.get();
3851
+ if (!existing || existing.ref !== options.prRef) {
3852
+ const session = await buildPrSession(options.prRef);
3853
+ await store.set(session);
3854
+ }
3855
+ prMode = true;
3856
+ } catch (err) {
3857
+ console.error(`[pr-session] failed to build session for ${options.prRef}: ${err?.message ?? err}`);
3858
+ }
3859
+ }
3860
+ const app = createApp(options.clientDir, options.diffOpts, void 0, void 0, void 0, prMode);
3861
+ return new Promise((resolve) => {
3862
+ serve({
3863
+ fetch: app.fetch,
3864
+ port: options.port,
3865
+ hostname: options.host
3866
+ }, (info) => {
3867
+ resolve({
3868
+ port: info.port,
3869
+ prMode
3870
+ });
3871
+ });
3872
+ });
3873
+ }
3874
+ //#endregion
3875
+ export { buildGitDiffArgs as a, printHelp as c, validateEnvironment as i, loadSettings as n, intoShowMode as o, runTerminalDiff as r, parseDiffOptions as s, startServer as t };