diffing 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +41 -7
  2. package/dist/cli-agent-BatQgghr.mjs +499 -0
  3. package/dist/cli-agent-BwZE05CQ.mjs +499 -0
  4. package/dist/cli-agent-CKE1Cvor.mjs +513 -0
  5. package/dist/cli-agent-CLvCYpmH.mjs +499 -0
  6. package/dist/cli-agent-CX8Fa1Ph.mjs +499 -0
  7. package/dist/cli-agent-SILzesQP.mjs +513 -0
  8. package/dist/cli-agent-USzLoAit.mjs +499 -0
  9. package/dist/cli-gh-BV5az425.mjs +147 -0
  10. package/dist/cli-gh-Bo6fOHQR.mjs +147 -0
  11. package/dist/cli-gh-D1LoWJl-.mjs +147 -0
  12. package/dist/cli-gh-D1sIZ-jX.mjs +147 -0
  13. package/dist/cli-gh-DROAJlHi.mjs +147 -0
  14. package/dist/cli-gh-DiT8BWwu.mjs +147 -0
  15. package/dist/cli.mjs +97 -3381
  16. package/dist/client/assets/{angular-html-DIKVmS-w.js → angular-html-CDZ9SrQX.js} +1 -1
  17. package/dist/client/assets/{angular-ts-DK13mfBQ.js → angular-ts-CNMbVia5.js} +1 -1
  18. package/dist/client/assets/{apl-NVZUxqwo.js → apl-BqNxQgsm.js} +1 -1
  19. package/dist/client/assets/{arc-kijUuucY.js → arc-BrMp-_55.js} +1 -1
  20. package/dist/client/assets/{architectureDiagram-3BPJPVTR-Dup-CzBS.js → architectureDiagram-3BPJPVTR-BIZJkdXp.js} +1 -1
  21. package/dist/client/assets/{astro-RPdCumat.js → astro-r55-Uy0e.js} +1 -1
  22. package/dist/client/assets/{blade-_ubz_KMD.js → blade-F8SZw05t.js} +1 -1
  23. package/dist/client/assets/{blockDiagram-GPEHLZMM-Cl0-G1MY.js → blockDiagram-GPEHLZMM-DlzFca7z.js} +1 -1
  24. package/dist/client/assets/{c-IEKcSTtW.js → c-DMmuyoXv.js} +1 -1
  25. package/dist/client/assets/{c4Diagram-AAUBKEIU-C3T6FV-K.js → c4Diagram-AAUBKEIU-BqJFYdcn.js} +1 -1
  26. package/dist/client/assets/channel-DVxVbqCb.js +1 -0
  27. package/dist/client/assets/{chunk-2J33WTMH-B5MFxFjX.js → chunk-2J33WTMH-CRN3t_Zt.js} +1 -1
  28. package/dist/client/assets/{chunk-3OPIFGDE-DWxCOZgI.js → chunk-3OPIFGDE-Bb8pGWXE.js} +1 -1
  29. package/dist/client/assets/{chunk-4BX2VUAB-DWdovlBC.js → chunk-4BX2VUAB--s6olL4E.js} +1 -1
  30. package/dist/client/assets/{chunk-55IACEB6-CFSaZijP.js → chunk-55IACEB6-C-iaNYfB.js} +1 -1
  31. package/dist/client/assets/{chunk-5ZQYHXKU-BH_cLkIj.js → chunk-5ZQYHXKU-Bvzi1CUr.js} +1 -1
  32. package/dist/client/assets/{chunk-727SXJPM-BbsJC2PT.js → chunk-727SXJPM-CjoyjZeg.js} +1 -1
  33. package/dist/client/assets/{chunk-AQP2D5EJ-tFAP6fC1.js → chunk-AQP2D5EJ-BJJOqjwm.js} +1 -1
  34. package/dist/client/assets/{chunk-BSJP7CBP-BGuhsdwy.js → chunk-BSJP7CBP-A0UL_0xV.js} +1 -1
  35. package/dist/client/assets/{chunk-CSCIHK7Q-DXSJWhsY.js → chunk-CSCIHK7Q-DW570vKT.js} +1 -1
  36. package/dist/client/assets/{chunk-FMBD7UC4-6vBylg_I.js → chunk-FMBD7UC4-CzNJ-Iy-.js} +1 -1
  37. package/dist/client/assets/{chunk-KSCS5N6A-C7iBFsUg.js → chunk-KSCS5N6A-DCbYTAZg.js} +1 -1
  38. package/dist/client/assets/{chunk-L5ZTLDWV-CRU3nvaK.js → chunk-L5ZTLDWV-BMdyyjjc.js} +1 -1
  39. package/dist/client/assets/{chunk-LZXEDZCA-6ppA-_4h.js → chunk-LZXEDZCA-BENQV-I4.js} +2 -2
  40. package/dist/client/assets/{chunk-ND2GUHAM-D1cTmgHe.js → chunk-ND2GUHAM-C1y3WzOx.js} +1 -1
  41. package/dist/client/assets/{chunk-NZK2D7GU-CpUab6v7.js → chunk-NZK2D7GU-BkBT6O_M.js} +1 -1
  42. package/dist/client/assets/{chunk-O5CBEL6O-cDxBycWe.js → chunk-O5CBEL6O-jdz4J9aA.js} +1 -1
  43. package/dist/client/assets/chunk-QZHKN3VN-mumapnEV.js +1 -0
  44. package/dist/client/assets/chunk-WU5MYG2G-Bsqs8ZKl.js +1 -0
  45. package/dist/client/assets/{chunk-XPW4576I-CI9GEEdy.js → chunk-XPW4576I-Bf8OI8wY.js} +1 -1
  46. package/dist/client/assets/classDiagram-4FO5ZUOK-CKaaw3uU.js +1 -0
  47. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-BxwzeqDR.js +1 -0
  48. package/dist/client/assets/{cobol-BVhbHJgp.js → cobol-BanHX5pe.js} +1 -1
  49. package/dist/client/assets/{coffee-gY6asS_B.js → coffee-CACo0LEP.js} +1 -1
  50. package/dist/client/assets/{cose-bilkent-S5V4N54A-BOs7zxZa.js → cose-bilkent-S5V4N54A-7mNCsL0j.js} +1 -1
  51. package/dist/client/assets/{cpp-el3R6exS.js → cpp-4Kwtmkwn.js} +1 -1
  52. package/dist/client/assets/{crystal-D2_0btIo.js → crystal-D1kAaPsE.js} +1 -1
  53. package/dist/client/assets/{css-DtPe7dg4.js → css-CCMEBYEn.js} +1 -1
  54. package/dist/client/assets/{dagre-BM42HDAG-CR_0cBOz.js → dagre-BM42HDAG-BTEYZegB.js} +1 -1
  55. package/dist/client/assets/{diagram-2AECGRRQ-D9um0wp2.js → diagram-2AECGRRQ-Cj_XZNTN.js} +1 -1
  56. package/dist/client/assets/{diagram-5GNKFQAL-Dx0TEfBJ.js → diagram-5GNKFQAL-DVTFfYPd.js} +1 -1
  57. package/dist/client/assets/{diagram-KO2AKTUF-DjBHOuUD.js → diagram-KO2AKTUF-C7BU5Ncp.js} +1 -1
  58. package/dist/client/assets/{diagram-LMA3HP47-CK2MO5Gx.js → diagram-LMA3HP47-06rwT7mb.js} +1 -1
  59. package/dist/client/assets/{diagram-OG6HWLK6-CANQancN.js → diagram-OG6HWLK6-COEuKA9B.js} +1 -1
  60. package/dist/client/assets/{dist-DGlwcsQQ.js → dist-C-G1vI6B.js} +1 -1
  61. package/dist/client/assets/{edge-Ch_PYBsB.js → edge-BV-WbkC9.js} +1 -1
  62. package/dist/client/assets/{elixir-DEJrJATq.js → elixir-C6pMvu6H.js} +1 -1
  63. package/dist/client/assets/{elm-Brlko4-d.js → elm-D8LnUrCG.js} +1 -1
  64. package/dist/client/assets/{erDiagram-TEJ5UH35-Dnfrs6yk.js → erDiagram-TEJ5UH35-SPxPVg85.js} +1 -1
  65. package/dist/client/assets/{erb-DQPphNua.js → erb-C6ADBE0Q.js} +1 -1
  66. package/dist/client/assets/{flowDiagram-I6XJVG4X-BNMdFtjG.js → flowDiagram-I6XJVG4X-DyEhCtUv.js} +1 -1
  67. package/dist/client/assets/{ganttDiagram-6RSMTGT7-X-fPXz_A.js → ganttDiagram-6RSMTGT7-fj-zRHIk.js} +1 -1
  68. package/dist/client/assets/{git-rebase-BpS915SI.js → git-rebase-BhYZ4R3x.js} +1 -1
  69. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CRN_dRXM.js → gitGraphDiagram-PVQCEYII-CpUJh4CR.js} +1 -1
  70. package/dist/client/assets/{glimmer-js-DZDngVuD.js → glimmer-js-D2CVO-NF.js} +1 -1
  71. package/dist/client/assets/{glimmer-ts-DKNjJvyp.js → glimmer-ts-BjYisPeM.js} +1 -1
  72. package/dist/client/assets/{glsl-C-Y1tHoU.js → glsl-qP0lyfIY.js} +1 -1
  73. package/dist/client/assets/{graphql-DYVBNazO.js → graphql-BZE_lBur.js} +1 -1
  74. package/dist/client/assets/{hack-DewKAtLe.js → hack-C6KM9SLG.js} +1 -1
  75. package/dist/client/assets/{haml-CIA_AeXu.js → haml-BT3JKqL8.js} +1 -1
  76. package/dist/client/assets/{handlebars-Bade6JXX.js → handlebars-SHKYyRQ6.js} +1 -1
  77. package/dist/client/assets/{html-C4hhbuGp.js → html-CAc9HUGa.js} +1 -1
  78. package/dist/client/assets/{html-derivative-BXfztBtv.js → html-derivative-Cu6n_YRN.js} +1 -1
  79. package/dist/client/assets/{http-Cq90-CTl.js → http-o21PuOy8.js} +1 -1
  80. package/dist/client/assets/{hurl-DklQHYoa.js → hurl-ClrxMWQi.js} +1 -1
  81. package/dist/client/assets/{index-j9gqGQit.js → index-BPI8nJUS.js} +98 -98
  82. package/dist/client/assets/index-F_YfUisJ.css +1 -0
  83. package/dist/client/assets/{infoDiagram-5YYISTIA-Ht-AcvP4.js → infoDiagram-5YYISTIA-DDYGwUUs.js} +1 -1
  84. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-k_l70iFb.js → ishikawaDiagram-YF4QCWOH-Benmqbm6.js} +1 -1
  85. package/dist/client/assets/{java-BMUwLm1h.js → java-Bmlmy6B3.js} +1 -1
  86. package/dist/client/assets/{javascript-B8nPCUVp.js → javascript-Bdrc0lyI.js} +1 -1
  87. package/dist/client/assets/{jinja-CkxiRcB3.js → jinja-DBkct7nV.js} +1 -1
  88. package/dist/client/assets/{jison-CFnN5uQs.js → jison-Tb1xkShc.js} +1 -1
  89. package/dist/client/assets/{journeyDiagram-JHISSGLW-C98PUC9Y.js → journeyDiagram-JHISSGLW-CCkv1GnE.js} +1 -1
  90. package/dist/client/assets/{json-B7HNnjIx.js → json-DwLxGyui.js} +1 -1
  91. package/dist/client/assets/{jsx-BfVPuW3i.js → jsx-DWSSTqEB.js} +1 -1
  92. package/dist/client/assets/{julia-Bj0ETGjT.js → julia-LUN3XhcV.js} +1 -1
  93. package/dist/client/assets/{just-CqIe_c9k.js → just-C6LrD5tm.js} +1 -1
  94. package/dist/client/assets/{kanban-definition-UN3LZRKU-BE-uvH7w.js → kanban-definition-UN3LZRKU-CQSBf6Ys.js} +1 -1
  95. package/dist/client/assets/{latex-Cvy8E64e.js → latex-aaU-rirg.js} +1 -1
  96. package/dist/client/assets/{line-BpooNUgm.js → line-DG7hZYkR.js} +1 -1
  97. package/dist/client/assets/{linear-CM6ZoyCp.js → linear-A5s-ps1u.js} +1 -1
  98. package/dist/client/assets/{liquid-x09l8QqE.js → liquid-BhVOoUfG.js} +1 -1
  99. package/dist/client/assets/{lua-BSlDLjt5.js → lua-BTF9vmdD.js} +1 -1
  100. package/dist/client/assets/{marko-CoNMQlTn.js → marko-DlwBrpd_.js} +1 -1
  101. package/dist/client/assets/{mdc-BSzVESPu.js → mdc-H8mdhEag.js} +1 -1
  102. package/dist/client/assets/{mermaid-parser.core-BDXJMxHu.js → mermaid-parser.core-BKvEMhB3.js} +1 -1
  103. package/dist/client/assets/{mermaid.core-Dw-_vXTc.js → mermaid.core-BaDGp29W.js} +3 -3
  104. package/dist/client/assets/{mindmap-definition-RKZ34NQL-BTxGT8rM.js → mindmap-definition-RKZ34NQL-BCrf7cJv.js} +1 -1
  105. package/dist/client/assets/{nginx-CBhJTj0i.js → nginx-DoaqXoFJ.js} +1 -1
  106. package/dist/client/assets/{nim-CtHbOBlO.js → nim-DqoAP4Np.js} +1 -1
  107. package/dist/client/assets/{perl-DLMzG3tu.js → perl-D1ou0isN.js} +1 -1
  108. package/dist/client/assets/{php-KomVR3Hz.js → php-DL6kQj3i.js} +1 -1
  109. package/dist/client/assets/{pieDiagram-4H26LBE5-BBUObAJW.js → pieDiagram-4H26LBE5-CF0X4ECG.js} +1 -1
  110. package/dist/client/assets/{pug-T4SRLx8P.js → pug-Bn3xDPVT.js} +1 -1
  111. package/dist/client/assets/{qml-DJdSRUmU.js → qml-CaA5S6hT.js} +1 -1
  112. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-B7vvauZv.js → quadrantDiagram-W4KKPZXB-A76pK4Cy.js} +1 -1
  113. package/dist/client/assets/{r-CwuTg9lK.js → r-DuUvfJBZ.js} +1 -1
  114. package/dist/client/assets/{razor-Ch4dgsGY.js → razor-DOv4xAWl.js} +1 -1
  115. package/dist/client/assets/{regexp-D2GTwJE0.js → regexp-DXetztjB.js} +1 -1
  116. package/dist/client/assets/{requirementDiagram-4Y6WPE33-DpcNiR3Y.js → requirementDiagram-4Y6WPE33-Cju--fB8.js} +1 -1
  117. package/dist/client/assets/{rst-D78f0DyR.js → rst-CDn5EUee.js} +1 -1
  118. package/dist/client/assets/{ruby-BUcw6ITs.js → ruby-40qcnJX-.js} +1 -1
  119. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-ChzSQD2O.js → sankeyDiagram-5OEKKPKP-CvkQY1O-.js} +1 -1
  120. package/dist/client/assets/{sas-DoT2JDsj.js → sas-D3a9oRtu.js} +1 -1
  121. package/dist/client/assets/{scss-B6G_d-6b.js → scss-BJ8ZKq49.js} +1 -1
  122. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CzkdL8s7.js → sequenceDiagram-3UESZ5HK-DKU8lZlC.js} +1 -1
  123. package/dist/client/assets/{shellscript-DI252Bga.js → shellscript-yTgK8aYT.js} +1 -1
  124. package/dist/client/assets/{shellsession-BuO_s8FQ.js → shellsession-DrVaQSNg.js} +1 -1
  125. package/dist/client/assets/{soy-DZTZJTEE.js → soy-BasCadaZ.js} +1 -1
  126. package/dist/client/assets/{sql-C4isoJr_.js → sql-COJH6ALP.js} +1 -1
  127. package/dist/client/assets/{src-BMvz5HE8.js → src-BokBJ4oL.js} +1 -1
  128. package/dist/client/assets/{stata-Dhu6qITh.js → stata-Ble9lhMp.js} +1 -1
  129. package/dist/client/assets/{stateDiagram-AJRCARHV-DvYcrdap.js → stateDiagram-AJRCARHV-9IU9PT8A.js} +1 -1
  130. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-Ce46Lf8G.js +1 -0
  131. package/dist/client/assets/{surrealql-CSDpq5j3.js → surrealql-BZ5cQJLk.js} +1 -1
  132. package/dist/client/assets/{svelte-C4ITAvxr.js → svelte-CLa9l6VK.js} +1 -1
  133. package/dist/client/assets/{templ-BTgKA9-7.js → templ-DVKkE2Tb.js} +1 -1
  134. package/dist/client/assets/{tex-Dg4N9ndP.js → tex-BET3iISl.js} +1 -1
  135. package/dist/client/assets/{timeline-definition-PNZ67QCA-Djt5Lwk2.js → timeline-definition-PNZ67QCA-CkkYIhNz.js} +1 -1
  136. package/dist/client/assets/{ts-tags-BufYnYos.js → ts-tags-D5fPAs5W.js} +1 -1
  137. package/dist/client/assets/{tsx-DmkFP0sw.js → tsx-CfNzz9iB.js} +1 -1
  138. package/dist/client/assets/{twig-BJv_IWYK.js → twig-_Ml9CBGK.js} +1 -1
  139. package/dist/client/assets/{typescript-BKp05Qme.js → typescript-DMiV0dhX.js} +1 -1
  140. package/dist/client/assets/{vennDiagram-CIIHVFJN-DDVADTIa.js → vennDiagram-CIIHVFJN-HUv6L4Dt.js} +1 -1
  141. package/dist/client/assets/{vue-BsHXCXzh.js → vue-BcbmWIQt.js} +1 -1
  142. package/dist/client/assets/{vue-html-CCsH-lmo.js → vue-html-CcUgk6WA.js} +1 -1
  143. package/dist/client/assets/{vue-vine-B5P1JXxo.js → vue-vine-BbIBT3jy.js} +1 -1
  144. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-yeVKWvtX.js → wardleyDiagram-YWT4CUSO-avUfWkuC.js} +1 -1
  145. package/dist/client/assets/{xml-CFkhYff0.js → xml-9mtlBTUG.js} +1 -1
  146. package/dist/client/assets/{xsl-Dc5XRzm6.js → xsl-Dm8BN5j0.js} +1 -1
  147. package/dist/client/assets/{xychartDiagram-2RQKCTM6--8Ik-9v0.js → xychartDiagram-2RQKCTM6-BSZPOH7-.js} +1 -1
  148. package/dist/client/assets/{yaml-BTCCxCxi.js → yaml-Ccz1qKlL.js} +1 -1
  149. package/dist/client/index.html +2 -2
  150. package/dist/mcp-B6mCC7D3.mjs +1047 -0
  151. package/dist/mcp-BMTZLQuB.mjs +758 -0
  152. package/dist/mcp-BUF2nEL7.mjs +1036 -0
  153. package/dist/mcp-Bpx76OGU.mjs +945 -0
  154. package/dist/mcp-C1T7LI0H.mjs +1036 -0
  155. package/dist/mcp-C4Bjmf9m.mjs +1047 -0
  156. package/dist/mcp-CFxcdEcJ.mjs +733 -0
  157. package/dist/mcp-CwjThGi2.mjs +913 -0
  158. package/dist/mcp-D4OsB9lt.mjs +1047 -0
  159. package/dist/mcp-DJ2batvt.mjs +913 -0
  160. package/dist/mcp-D_LGvBTw.mjs +1047 -0
  161. package/dist/mcp-Ds_lPX_o.mjs +913 -0
  162. package/dist/plan-format-B6nbAw_c.mjs +132 -0
  163. package/dist/server-95UE5bgh.mjs +3367 -0
  164. package/dist/server-B0cS95Lf.mjs +3488 -0
  165. package/dist/server-Bj-6KlK5.mjs +3367 -0
  166. package/dist/server-Bpf84Il0.mjs +3367 -0
  167. package/dist/server-CYSpLbdA.mjs +3360 -0
  168. package/dist/server-ChT2DCaR.mjs +3701 -0
  169. package/dist/server-DJxysGxV.mjs +3701 -0
  170. package/dist/server-Dov7jbV3.mjs +3367 -0
  171. package/dist/server-eQ2E4Axo.mjs +3367 -0
  172. package/dist/server-lock-C_wPtEsH.mjs +909 -0
  173. package/dist/server-lock-Cbu3qHdu.mjs +924 -0
  174. package/dist/server-lock-D32inEn9.mjs +924 -0
  175. package/dist/server-lock-Ddcat0HF.mjs +851 -0
  176. package/dist/server-lock-Dq_1CJaF.mjs +1047 -0
  177. package/dist/server-lock-Ujbcgq28.mjs +954 -0
  178. package/dist/update-check-CXeSZANo.mjs +129 -0
  179. package/package.json +3 -2
  180. package/dist/client/assets/channel-CpWSvbvQ.js +0 -1
  181. package/dist/client/assets/chunk-QZHKN3VN-HhMIifwl.js +0 -1
  182. package/dist/client/assets/chunk-WU5MYG2G-CvIzXEms.js +0 -1
  183. package/dist/client/assets/classDiagram-4FO5ZUOK-DFu-dNVy.js +0 -1
  184. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-D7Xcgo6q.js +0 -1
  185. package/dist/client/assets/index-CMyunQt6.css +0 -1
  186. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-D5igY81I.js +0 -1
package/dist/cli.mjs CHANGED
@@ -1,3365 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { C as toSafeRelativePath, S as isSafePath, _ as getUntrackedFilePathsAsync, a as formatComments, b as listRepoFiles, c as getFileContent, d as getMergeStatus, f as getProjectStorageDir, g as getTabSizeForFiles, h as getShowDiff, i as writeServerLock, l as getGitDiffAsync, m as getRepoRoot, o as getBranchName, p as getRepoName, r as removeServerLock, s as getCustomGitDiffAsync, u as getHunkHistory, v as gitAddFile, x as revertHunk, y as isGitRepo } from "./server-lock-D73NKKbn.mjs";
3
- import { n as formatPlanReview, r as sectionTitleForLine, t as extractPlanLines } from "./plan-format-mSDtsPcC.mjs";
4
- import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import { c as printHelp, i as validateEnvironment, n as loadSettings, o as intoShowMode, r as runTerminalDiff, s as parseDiffOptions, t as startServer } from "./server-DJxysGxV.mjs";
3
+ import { i as readServerLock, n as diffScopeKey, o as removeServerLockIfOwned, r as isLockAlive, s as writeServerLock, t as acquireServerStartupLease, v as getRepoRoot } from "./server-lock-Dq_1CJaF.mjs";
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
5
6
  import { fileURLToPath } from "node:url";
6
- import { dirname, extname, isAbsolute, join, resolve } from "node:path";
7
- import { existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
7
+ import { dirname, isAbsolute, resolve } from "node:path";
8
+ import { existsSync, readFileSync } from "node:fs";
8
9
  import getPort from "get-port";
9
- import { parseArgs, promisify } from "node:util";
10
- import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
11
- import { homedir } from "node:os";
12
- import { Hono } from "hono";
13
- import { streamSSE } from "hono/streaming";
14
- import { serve } from "@hono/node-server";
15
10
  import { stdout } from "node:process";
16
- //#region src/lib/diff-options.ts
17
- const DEFAULTS$1 = {
18
- revisions: [],
19
- staged: false,
20
- merge: false,
21
- pathspecs: [],
22
- indentHeuristic: true,
23
- noIndentHeuristic: false,
24
- ignoreSpaceChange: false,
25
- ignoreAllSpace: false,
26
- ignoreBlankLines: false,
27
- ignoreCrAtEol: false,
28
- functionContext: false,
29
- patchWithRaw: false,
30
- patchWithStat: false,
31
- compactSummary: false,
32
- cumulative: false,
33
- pickaxeAll: false,
34
- exitCode: false,
35
- quiet: false,
36
- noPrefix: false,
37
- binary: false,
38
- fullIndex: false,
39
- text: false,
40
- textconv: false,
41
- noExtDiff: false,
42
- itaVisible: false,
43
- noRelative: false,
44
- findCopiesHarder: false,
45
- check: false,
46
- outputMode: "auto",
47
- host: "127.0.0.1",
48
- noOpen: false,
49
- help: false,
50
- version: false,
51
- includeUnstaged: true,
52
- includeUntracked: true,
53
- tui: false,
54
- gpu: false,
55
- showMode: false,
56
- showRevspecs: []
57
- };
58
- /**
59
- * All git-diff option definitions for `node:util.parseArgs`.
60
- * Categorised to match `git diff --help`.
61
- */
62
- const GIT_DIFF_OPTIONS = {
63
- staged: { type: "boolean" },
64
- cached: { type: "boolean" },
65
- merge: { type: "boolean" },
66
- "diff-algorithm": { type: "string" },
67
- "indent-heuristic": {
68
- type: "boolean",
69
- default: true
70
- },
71
- "no-indent-heuristic": { type: "boolean" },
72
- anchored: { type: "string" },
73
- "ignore-space-change": {
74
- type: "boolean",
75
- short: "b"
76
- },
77
- "ignore-all-space": {
78
- type: "boolean",
79
- short: "w"
80
- },
81
- "ignore-blank-lines": { type: "boolean" },
82
- "ignore-cr-at-eol": { type: "boolean" },
83
- "ws-error-highlight": { type: "string" },
84
- "unified": {
85
- type: "string",
86
- short: "U"
87
- },
88
- "inter-hunk-context": { type: "string" },
89
- "function-context": {
90
- type: "boolean",
91
- short: "W"
92
- },
93
- "word-diff": { type: "string" },
94
- "word-diff-regex": { type: "string" },
95
- "color-words": { type: "string" },
96
- "color-moved": { type: "string" },
97
- "color-moved-ws": { type: "string" },
98
- "find-copies": {
99
- type: "string",
100
- short: "C"
101
- },
102
- "find-copies-harder": { type: "boolean" },
103
- "find-renames": {
104
- type: "string",
105
- short: "M"
106
- },
107
- "break-rewrites": {
108
- type: "string",
109
- short: "B"
110
- },
111
- patch: {
112
- type: "boolean",
113
- short: "p"
114
- },
115
- "no-patch": {
116
- type: "boolean",
117
- short: "s"
118
- },
119
- raw: { type: "boolean" },
120
- "patch-with-raw": { type: "boolean" },
121
- "patch-with-stat": { type: "boolean" },
122
- numstat: { type: "boolean" },
123
- shortstat: { type: "boolean" },
124
- stat: { type: "string" },
125
- summary: { type: "boolean" },
126
- "name-only": { type: "boolean" },
127
- "name-status": { type: "boolean" },
128
- check: { type: "boolean" },
129
- "compact-summary": { type: "boolean" },
130
- dirstat: { type: "string" },
131
- "dirstat-by-file": { type: "string" },
132
- cumulative: { type: "boolean" },
133
- "diff-filter": { type: "string" },
134
- S: { type: "string" },
135
- G: { type: "string" },
136
- "pickaxe-all": { type: "boolean" },
137
- output: {
138
- type: "string",
139
- short: "o"
140
- },
141
- "exit-code": { type: "boolean" },
142
- quiet: { type: "boolean" },
143
- "src-prefix": { type: "string" },
144
- "dst-prefix": { type: "string" },
145
- "no-prefix": { type: "boolean" },
146
- "line-prefix": { type: "string" },
147
- submodule: { type: "string" },
148
- binary: { type: "boolean" },
149
- "no-binary": { type: "boolean" },
150
- "full-index": { type: "boolean" },
151
- text: {
152
- type: "boolean",
153
- short: "a"
154
- },
155
- textconv: { type: "boolean" },
156
- "no-textconv": { type: "boolean" },
157
- "no-ext-diff": { type: "boolean" },
158
- "ext-diff": { type: "string" },
159
- "ita-visible": { type: "boolean" },
160
- "ita-invisible-in-index": { type: "boolean" },
161
- relative: { type: "string" },
162
- "no-relative": { type: "boolean" },
163
- "ignore-submodules": { type: "string" }
164
- };
165
- /** Options that are diffing-specific, not git-diff options. */
166
- const DIFFING_OPTIONS = {
167
- port: { type: "string" },
168
- host: { type: "string" },
169
- "no-open": {
170
- type: "boolean",
171
- default: false
172
- },
173
- web: {
174
- type: "boolean",
175
- default: false
176
- },
177
- terminal: {
178
- type: "boolean",
179
- default: false
180
- },
181
- tui: {
182
- type: "boolean",
183
- default: false
184
- },
185
- gpu: {
186
- type: "boolean",
187
- default: false
188
- },
189
- "gh-pr": { type: "string" },
190
- help: {
191
- type: "boolean",
192
- short: "h"
193
- },
194
- version: { type: "boolean" }
195
- };
196
- function getVersion() {
197
- try {
198
- const __dirname = dirname(fileURLToPath(import.meta.url));
199
- return JSON.parse(readFileSync(resolve(__dirname, "..", "..", "package.json"), "utf-8")).version;
200
- } catch {
201
- return "unknown";
202
- }
203
- }
204
- function printHelp() {
205
- const version = getVersion();
206
- console.log(`diffing v${version} – Local code review tool for git diffs
207
-
208
- Usage: diffing [<git diff options>] [<revision>...] [-- <path>...]
209
- diffing --web [<git diff options>] [<revision>...] [-- <path>...]
210
- diffing [server options]
211
-
212
- Git Diff Options (drop-in replacement for git diff):`);
213
- printGitDiffHelp();
214
- console.log(`
215
- Diffing Server Options:
216
- --port <port> Port to run the server on (default: random available port)
217
- --host <host> Host address to bind to (default: 127.0.0.1). Pass
218
- 0.0.0.0 to expose the server to the local network.
219
- --no-open Don't open the browser automatically
220
-
221
- Output Modes:
222
- By default diffing auto-selects the best output mode:
223
- - Terminal mode: when output is a pipe, redirect, or non-TTY
224
- - Web mode: when output is a TTY (interactive terminal)
225
-
226
- Force a mode with --web, --terminal, or --tui flags.
227
- --tui is experimental and opt-in. It opens a native-Rust terminal
228
- interface that mirrors the web dashboard. Falls back to git diff
229
- output if the environment cannot support a TUI (piped stdin, CI,
230
- missing binary).
231
-
232
- Subcommands:
233
- show <revspec>... Drop-in for 'git show'. Renders commit metadata
234
- (subject, author, date, message body) above the
235
- diff in the web UI. Accepts single commits,
236
- ranges (a..b, a...b), tags, and multiple SHAs.
237
- Use '--' to separate revspecs from pathspecs.
238
-
239
- Examples:
240
- diffing Review uncommitted changes (web UI)
241
- diffing --staged Review staged changes
242
- diffing HEAD~3 Review last 3 commits
243
- diffing main..feature Compare branches
244
- diffing show HEAD Review a single commit's metadata + diff
245
- diffing show HEAD~3..HEAD Review the last 3 commits as a series
246
- diffing show HEAD -- src/ Limit a commit review to a directory
247
- diffing --diff-algorithm=patience src/ Diff with patience algorithm
248
- diffing -U10 Diff with 10 context lines
249
- diffing --word-diff=color Word-level diff in color
250
- diffing -b -w Ignore whitespace changes
251
- diffing --host 0.0.0.0 Allow other machines on the LAN to review
252
- diffing --tui Open the experimental TUI (native Rust)
253
-
254
- Note: 'diffing <sha>' runs 'git diff <sha>' (working tree vs <sha>); it
255
- is not the same as 'diffing show <sha>'. Use 'show' when you want to
256
- review a commit's changes.`);
257
- }
258
- function printGitDiffHelp() {
259
- console.log(`
260
- Revision / Range:
261
- --staged, --cached Show staged changes
262
- --merge Show merge conflicts
263
-
264
- Diff Algorithm:
265
- --diff-algorithm=<A> Choose diff algorithm (minimal, patience, histogram, myers)
266
- --indent-heuristic Enable indent heuristic (default: on)
267
- --no-indent-heuristic Disable indent heuristic
268
- --anchored=<TEXT> Anchor diff algorithm to <TEXT>
269
-
270
- Whitespace:
271
- -b, --ignore-space-change Ignore changes in amount of whitespace
272
- -w, --ignore-all-space Ignore whitespace when comparing lines
273
- --ignore-blank-lines Ignore blank lines
274
- --ignore-cr-at-eol Ignore carriage-return at EOL
275
- --ws-error-highlight=<KIND> Highlight whitespace errors (none, default, all)
276
-
277
- Context:
278
- -U<n>, --unified=<n> Generate diffs with <n> lines of context
279
- --inter-hunk-context=<n> Show <n> lines between diff hunks
280
- -W, --function-context Show whole function as context
281
-
282
- Word Diff:
283
- --word-diff=<MODE> Word diff (color, plain, porcelain, none)
284
- --word-diff-regex=<REGEX> Regex to determine a word
285
- --color-words[=<REGEX>] Word diff with color
286
-
287
- Moved / Copied Detection:
288
- --color-moved=<MODE> Color moved lines (no, default, plain, blocks, zebra, dimmed-zebra)
289
- --color-moved-ws=<MODE> How whitespace is treated in --color-moved
290
- -C[<n>], --find-copies[=<n>] Detect copies
291
- --find-copies-harder Spend extra cycles to find copies
292
- -M[<n>], --find-renames[=<n>] Detect renames
293
- -B[<n>], --break-rewrites[=<n>] Break complete rewrite changes into delete/add pairs
294
-
295
- Output Format:
296
- -p, --patch Generate patch (default)
297
- -s, --no-patch Suppress diff output
298
- --raw Generate raw diff
299
- --patch-with-raw Both patch and raw output
300
- --patch-with-stat Both patch and stat
301
- --numstat Machine-friendly stat: additions/deletions per file
302
- --shortstat Summary of additions/deletions
303
- --stat[=<width>] Diffstat with graph
304
- --summary Extended header summary
305
- --name-only Show only names of changed files
306
- --name-status Show only names and status of changed files
307
- --check Check if diff introduces whitespace errors
308
- --compact-summary Compact summary for submodule changes
309
- --dirstat[=<param>] Directory-level change stats
310
- --dirstat-by-file[=<param>] Per-file directory stats
311
- --cumulative Cumulative directory stats
312
-
313
- Filtering:
314
- --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]]
315
- -S<string> Look for differences that change number of occurrences of <string>
316
- -G<regex> Look for differences whose patch text contains <regex>
317
- --pickaxe-all Show all changes with -S or -G
318
-
319
- Output Control:
320
- -o, --output=<file> Write diff to <file>
321
- --exit-code Exit with 1 if differences, 0 if not
322
- --quiet Disable all output, imply --exit-code
323
-
324
- Prefixes:
325
- --src-prefix=<PREFIX> Source prefix (default: "a/")
326
- --dst-prefix=<PREFIX> Destination prefix (default: "b/")
327
- --no-prefix Do not show source/destination prefixes
328
- --line-prefix=<PREFIX> Prepend <PREFIX> to every line
329
-
330
- Submodule:
331
- --submodule=<FORMAT> Submodule diff format (diff, log, short)
332
-
333
- Miscellaneous:
334
- --binary Output binary diff (apply patch to binary files)
335
- --no-binary Don't output binary diff
336
- --full-index Show full blob object names
337
- -a, --text Treat all files as text
338
- --textconv Allow external text conversion filters
339
- --no-textconv Disallow external text conversion filters
340
- --no-ext-diff Disallow external diff drivers
341
- --ext-diff=<CMD> Allow external diff driver
342
- --ita-visible Include intent-to-add files
343
- --ignore-submodules=<WHEN> Ignore submodule changes
344
- --relative[=<path>] Show changes relative to <path>
345
- --no-relative Don't show relative paths`);
346
- }
347
- /**
348
- * Parse raw `process.argv` slice into typed DiffOptions.
349
- *
350
- * Strategy:
351
- * 1. Split argv into: [diffing options] [git revisions] [-- pathspecs]
352
- * 2. Parse known flags via node:util.parseArgs
353
- * 3. Anything unknown / positional becomes a revision or pathspec
354
- */
355
- function parseDiffOptions(rawArgs) {
356
- const { values, positionals } = parseArgs({
357
- options: {
358
- ...GIT_DIFF_OPTIONS,
359
- ...DIFFING_OPTIONS
360
- },
361
- allowPositionals: true,
362
- strict: false,
363
- args: rawArgs
364
- });
365
- const opts = { ...DEFAULTS$1 };
366
- if (values.help) opts.help = true;
367
- if (values.version) opts.version = true;
368
- if (values.port) opts.port = parseInt(values.port, 10);
369
- if (values.host) opts.host = values.host;
370
- if (values["no-open"]) opts.noOpen = true;
371
- if (values.staged || values.cached) opts.staged = true;
372
- if (values.merge) opts.merge = true;
373
- const algo = values["diff-algorithm"];
374
- if (algo && [
375
- "minimal",
376
- "patience",
377
- "histogram",
378
- "myers"
379
- ].includes(algo)) opts.algorithm = algo;
380
- if (values["no-indent-heuristic"]) {
381
- opts.noIndentHeuristic = true;
382
- opts.indentHeuristic = false;
383
- }
384
- if (values.anchored) opts.anchored = values.anchored;
385
- if (values["ignore-space-change"]) opts.ignoreSpaceChange = true;
386
- if (values["ignore-all-space"]) opts.ignoreAllSpace = true;
387
- if (values["ignore-blank-lines"]) opts.ignoreBlankLines = true;
388
- if (values["ignore-cr-at-eol"]) opts.ignoreCrAtEol = true;
389
- const wsh = values["ws-error-highlight"];
390
- if (wsh && [
391
- "none",
392
- "default",
393
- "all"
394
- ].includes(wsh)) opts.wsErrorHighlight = wsh;
395
- if (values.unified) opts.unifiedContext = parseInt(values.unified, 10);
396
- if (values["inter-hunk-context"]) opts.interHunkContext = parseInt(values["inter-hunk-context"], 10);
397
- if (values["function-context"]) opts.functionContext = true;
398
- const wd = values["word-diff"];
399
- if (wd && [
400
- "color",
401
- "plain",
402
- "porcelain",
403
- "none"
404
- ].includes(wd)) opts.wordDiff = wd;
405
- if (values["word-diff-regex"]) opts.wordDiffRegex = values["word-diff-regex"];
406
- if (values["color-words"]) {
407
- opts.wordDiff = "color";
408
- opts.wordDiffRegex = values["color-words"] || void 0;
409
- }
410
- const cm = values["color-moved"];
411
- if (cm && [
412
- "default",
413
- "plain",
414
- "blocks",
415
- "zebra",
416
- "dimmed-zebra",
417
- "no"
418
- ].includes(cm)) opts.colorMoved = cm;
419
- const cmw = values["color-moved-ws"];
420
- if (cmw && [
421
- "no",
422
- "ignore-space-at-eol",
423
- "ignore-space-change",
424
- "ignore-all-space",
425
- "allow-indentation-change"
426
- ].includes(cmw)) opts.colorMovedWs = cmw;
427
- if (values["find-copies"] !== void 0) {
428
- const v = values["find-copies"];
429
- opts.findCopies = v ? parseInt(v, 10) : 40;
430
- }
431
- if (values["find-copies-harder"]) opts.findCopiesHarder = true;
432
- if (values["find-renames"] !== void 0) {
433
- const v = values["find-renames"];
434
- opts.findRenames = v ? parseInt(v, 10) : 50;
435
- }
436
- if (values["break-rewrites"] !== void 0) opts.breakRewrites = values["break-rewrites"];
437
- if (values.raw) opts.outputFormat = "raw";
438
- if (values.numstat) opts.outputFormat = "numstat";
439
- if (values.shortstat) opts.outputFormat = "shortstat";
440
- if (values.stat !== void 0) opts.outputFormat = "stat";
441
- if (values.summary) opts.outputFormat = "summary";
442
- if (values["name-only"]) opts.outputFormat = "name-only";
443
- if (values["name-status"]) opts.outputFormat = "name-status";
444
- if (values["patch-with-raw"]) opts.patchWithRaw = true;
445
- if (values["patch-with-stat"]) opts.patchWithStat = true;
446
- if (values["compact-summary"]) opts.compactSummary = true;
447
- if (values.dirstat) opts.dirstat = values.dirstat;
448
- if (values["dirstat-by-file"]) opts.dirstatByFile = values["dirstat-by-file"];
449
- if (values.cumulative) opts.cumulative = true;
450
- if (values["no-patch"]) opts.outputFormat = void 0;
451
- if (values.check) opts.outputFormat = void 0;
452
- if (values["diff-filter"]) opts.diffFilter = values["diff-filter"];
453
- if (values.S) opts.pickaxeString = values.S;
454
- if (values.G) opts.pickaxeRegex = values.G;
455
- if (values["pickaxe-all"]) opts.pickaxeAll = true;
456
- if (values.output) opts.outputFile = values.output;
457
- if (values["exit-code"]) opts.exitCode = true;
458
- if (values.quiet) {
459
- opts.quiet = true;
460
- opts.exitCode = true;
461
- }
462
- if (values["src-prefix"]) opts.srcPrefix = values["src-prefix"];
463
- if (values["dst-prefix"]) opts.dstPrefix = values["dst-prefix"];
464
- if (values["no-prefix"]) opts.noPrefix = true;
465
- if (values["line-prefix"]) opts.linePrefix = values["line-prefix"];
466
- const sm = values.submodule;
467
- if (sm && [
468
- "diff",
469
- "log",
470
- "short"
471
- ].includes(sm)) opts.submodule = sm;
472
- if (values.binary) opts.binary = true;
473
- if (values["no-binary"]) opts.binary = false;
474
- if (values["full-index"]) opts.fullIndex = true;
475
- if (values.text) opts.text = true;
476
- if (values.textconv) opts.textconv = true;
477
- if (values["no-textconv"]) opts.textconv = false;
478
- if (values["no-ext-diff"]) opts.noExtDiff = true;
479
- if (values["ext-diff"]) opts.extDiff = values["ext-diff"];
480
- if (values["ita-visible"] || values["ita-invisible-in-index"]) opts.itaVisible = true;
481
- if (values.relative !== void 0) opts.relative = values.relative || void 0;
482
- if (values["no-relative"]) opts.noRelative = true;
483
- if (values["ignore-submodules"]) {
484
- const ig = values["ignore-submodules"];
485
- if ([
486
- "none",
487
- "untracked",
488
- "dirty",
489
- "all"
490
- ].includes(ig)) opts.ignoreSubmodules = ig;
491
- }
492
- const dashDashIdx = rawArgs.indexOf("--");
493
- if (dashDashIdx >= 0) {
494
- for (let i = 0; i < dashDashIdx; i++) {
495
- const arg = rawArgs[i];
496
- if (!arg.startsWith("-")) opts.revisions.push(arg);
497
- }
498
- for (let i = dashDashIdx + 1; i < rawArgs.length; i++) opts.pathspecs.push(rawArgs[i]);
499
- } else for (const p of positionals) opts.revisions.push(p);
500
- if (values.tui) opts.outputMode = "tui";
501
- else if (values.web) opts.outputMode = "web";
502
- else if (values.terminal) opts.outputMode = "terminal";
503
- if (process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "web";
504
- else if (!process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "terminal";
505
- if (opts.outputFormat || opts.patchWithRaw || opts.patchWithStat || opts.exitCode || opts.quiet || opts.outputFile) opts.outputMode = "terminal";
506
- return opts;
507
- }
508
- /**
509
- * Build the `git diff` argument array from parsed options.
510
- * Returns args that can be spread into `git diff <args>`.
511
- */
512
- function buildGitDiffArgs(opts) {
513
- const args = [];
514
- if (opts.algorithm) args.push(`--diff-algorithm=${opts.algorithm}`);
515
- if (opts.noIndentHeuristic) args.push("--no-indent-heuristic");
516
- if (opts.anchored) args.push(`--anchored=${opts.anchored}`);
517
- if (opts.staged) args.push("--staged");
518
- if (opts.merge) args.push("--merge");
519
- if (opts.ignoreSpaceChange) args.push("--ignore-space-change");
520
- if (opts.ignoreAllSpace) args.push("--ignore-all-space");
521
- if (opts.ignoreBlankLines) args.push("--ignore-blank-lines");
522
- if (opts.ignoreCrAtEol) args.push("--ignore-cr-at-eol");
523
- if (opts.wsErrorHighlight) args.push(`--ws-error-highlight=${opts.wsErrorHighlight}`);
524
- if (opts.unifiedContext !== void 0) args.push(`--unified=${opts.unifiedContext}`);
525
- if (opts.interHunkContext !== void 0) args.push(`--inter-hunk-context=${opts.interHunkContext}`);
526
- if (opts.functionContext) args.push("--function-context");
527
- if (opts.wordDiff) if (opts.wordDiff === "color" && opts.wordDiffRegex && !opts.colorWords) {
528
- args.push(`--word-diff=color`);
529
- args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
530
- } else if (opts.wordDiff === "color" && opts.colorWords) args.push(`--color-words=${opts.wordDiffRegex || "."}`);
531
- else args.push(`--word-diff=${opts.wordDiff}`);
532
- if (opts.wordDiffRegex && opts.wordDiff !== "color") args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
533
- if (opts.colorMoved) args.push(`--color-moved=${opts.colorMoved}`);
534
- if (opts.colorMovedWs) args.push(`--color-moved-ws=${opts.colorMovedWs}`);
535
- if (opts.findCopies !== void 0) args.push(opts.findCopies === 40 ? "-C" : `-C${opts.findCopies}`);
536
- if (opts.findCopiesHarder) args.push("--find-copies-harder");
537
- if (opts.findRenames !== void 0) args.push(opts.findRenames === 50 ? "-M" : `-M${opts.findRenames}`);
538
- if (opts.breakRewrites !== void 0) args.push(`-B${opts.breakRewrites}`);
539
- if (opts.outputFormat === "raw") args.push("--raw");
540
- if (opts.outputFormat === "numstat") args.push("--numstat");
541
- if (opts.outputFormat === "shortstat") args.push("--shortstat");
542
- if (opts.outputFormat === "stat") args.push("--stat");
543
- if (opts.outputFormat === "summary") args.push("--summary");
544
- if (opts.outputFormat === "name-only") args.push("--name-only");
545
- if (opts.outputFormat === "name-status") args.push("--name-status");
546
- if (opts.patchWithRaw) args.push("--patch-with-raw");
547
- if (opts.patchWithStat) args.push("--patch-with-stat");
548
- if (opts.compactSummary) args.push("--compact-summary");
549
- if (opts.dirstat) args.push(`--dirstat=${opts.dirstat}`);
550
- if (opts.dirstatByFile) args.push(`--dirstat-by-file=${opts.dirstatByFile}`);
551
- if (opts.cumulative) args.push("--cumulative");
552
- if (opts.check) args.push("--check");
553
- if (opts.diffFilter) args.push(`--diff-filter=${opts.diffFilter}`);
554
- if (opts.pickaxeString) args.push(`-S${opts.pickaxeString}`);
555
- if (opts.pickaxeRegex) args.push(`-G${opts.pickaxeRegex}`);
556
- if (opts.pickaxeAll) args.push("--pickaxe-all");
557
- if (opts.outputFile) args.push(`--output=${opts.outputFile}`);
558
- if (opts.exitCode) args.push("--exit-code");
559
- if (opts.quiet) args.push("--quiet");
560
- if (opts.srcPrefix) args.push(`--src-prefix=${opts.srcPrefix}`);
561
- if (opts.dstPrefix) args.push(`--dst-prefix=${opts.dstPrefix}`);
562
- if (opts.noPrefix) args.push("--no-prefix");
563
- if (opts.linePrefix) args.push(`--line-prefix=${opts.linePrefix}`);
564
- if (opts.submodule) args.push(`--submodule=${opts.submodule}`);
565
- if (opts.binary) args.push("--binary");
566
- if (opts.fullIndex) args.push("--full-index");
567
- if (opts.text) args.push("--text");
568
- if (opts.textconv) args.push("--textconv");
569
- if (opts.noExtDiff) args.push("--no-ext-diff");
570
- if (opts.extDiff) args.push(`--ext-diff=${opts.extDiff}`);
571
- if (opts.itaVisible) args.push("--ita-visible");
572
- if (opts.relative !== void 0) args.push(opts.relative ? `--relative=${opts.relative}` : "--relative");
573
- if (opts.noRelative) args.push("--no-relative");
574
- if (opts.ignoreSubmodules) args.push(`--ignore-submodules=${opts.ignoreSubmodules}`);
575
- for (const rev of opts.revisions) args.push(rev);
576
- if (opts.pathspecs.length > 0) {
577
- args.push("--");
578
- args.push(...opts.pathspecs);
579
- }
580
- return args;
581
- }
582
- /**
583
- * Transform a `parseDiffOptions(...)` result into a "show mode" variant:
584
- * moves any parsed revisions into `showRevspecs`, clears `revisions` (so the
585
- * existing diff-engine path does not try to `git diff` them), and sets the
586
- * `showMode` flag. Pathspecs and every other flag survive unchanged.
587
- *
588
- * Returns the same object for callsite ergonomics — the mutation is in-place
589
- * because `parseDiffOptions` always returns a fresh object.
590
- */
591
- function intoShowMode(opts) {
592
- opts.showRevspecs = opts.revisions;
593
- opts.revisions = [];
594
- opts.showMode = true;
595
- return opts;
596
- }
597
- //#endregion
598
- //#region src/lib/diff-engine.ts
599
- const MAX_BUFFER = 50 * 1024 * 1024;
600
- /**
601
- * Determine whether to use the "standard" web mode (unstaged+staged+untracked)
602
- * or a "custom" mode (specific revisions / pathspecs).
603
- *
604
- * Custom mode is used when the user provides explicit revisions or pathspecs
605
- * beyond just toggling staged/untracked. `showMode` is *also* a custom mode
606
- * — the "Show staged / Show untracked" toggles don't apply to a commit view.
607
- */
608
- function isCustomMode$1(opts) {
609
- return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
610
- }
611
- function parseFilePaths(patch) {
612
- const paths = /* @__PURE__ */ new Set();
613
- for (const line of patch.split("\n")) {
614
- const match = line.match(/^diff --git a\/.+ b\/(.+)$/);
615
- if (match) paths.add(match[1]);
616
- }
617
- return [...paths];
618
- }
619
- function parseBinaryFiles(patch, untrackedFiles) {
620
- const binaryFiles = [];
621
- const lines = patch.split("\n");
622
- for (let i = 0; i < lines.length; i++) {
623
- const line = lines[i];
624
- if (!line.startsWith("Binary files ") || !line.includes(" differ")) continue;
625
- let filePath = "";
626
- for (let j = i - 1; j >= 0; j--) {
627
- const match = lines[j].match(/^diff --git a\/.+ b\/(.+)$/);
628
- if (match) {
629
- filePath = match[1];
630
- break;
631
- }
632
- }
633
- if (!filePath) continue;
634
- let changeType = "changed";
635
- for (let j = i - 1; j >= 0; j--) {
636
- if (lines[j].startsWith("diff --git")) break;
637
- if (lines[j].startsWith("new file mode")) {
638
- changeType = "added";
639
- break;
640
- }
641
- if (lines[j].startsWith("deleted file mode")) {
642
- changeType = "deleted";
643
- break;
644
- }
645
- }
646
- if (changeType === "added" && untrackedFiles?.has(filePath)) changeType = "untracked";
647
- binaryFiles.push({
648
- path: filePath,
649
- type: changeType
650
- });
651
- }
652
- return binaryFiles;
653
- }
654
- /**
655
- * Execute a diff asynchronously — used by the server.
656
- *
657
- * Show mode bypasses the normal `git diff` path entirely: it resolves
658
- * revspecs to a commit list and fetches per-commit metadata + patches in
659
- * one `git log` call. The concatenated patch is returned in the same shape
660
- * the existing UI pipeline expects (so file tree, binary detection, and
661
- * tab-size detection all keep working unchanged); the per-commit data
662
- * rides along on `commits` for the metadata banners.
663
- */
664
- async function executeDiffAsync(opts) {
665
- if (opts.showMode) {
666
- const { commits, patch, truncated } = await getShowDiff(opts.showRevspecs, opts.pathspecs);
667
- return {
668
- patch,
669
- args: [],
670
- commits,
671
- truncated
672
- };
673
- }
674
- if (isCustomMode$1(opts)) {
675
- const args = buildGitDiffArgs(opts);
676
- return {
677
- patch: await getCustomGitDiffAsync(args),
678
- args
679
- };
680
- }
681
- return {
682
- patch: await getGitDiffAsync({
683
- staged: opts.staged,
684
- untracked: opts.includeUntracked
685
- }),
686
- args: []
687
- };
688
- }
689
- /**
690
- * Execute a diff and produce the full enriched result used by the web API.
691
- */
692
- async function executeDiffWithMeta(opts) {
693
- const { patch, commits, truncated } = await executeDiffAsync(opts);
694
- const repoName = getRepoName();
695
- const branch = getBranchName();
696
- const untrackedFiles = opts.includeUntracked && !opts.showMode ? await getUntrackedFilePathsAsync() : [];
697
- const binaryFiles = parseBinaryFiles(patch, new Set(untrackedFiles));
698
- const filePaths = parseFilePaths(patch);
699
- return {
700
- patch,
701
- binaryFiles,
702
- filePaths,
703
- tabSizeMap: getTabSizeForFiles(filePaths),
704
- untrackedFiles,
705
- repoName,
706
- branch,
707
- ...commits ? { commits } : {},
708
- ...truncated ? { truncated } : {}
709
- };
710
- }
711
- /**
712
- * Run the diff in terminal mode: forward to git diff with full flags,
713
- * output to stdout. Behaves identically to `git diff`. In show mode this
714
- * delegates to `git show` instead so `diffing show <rev>... --terminal`
715
- * is a drop-in for `git show <rev>...`.
716
- */
717
- function runTerminalDiff(opts) {
718
- if (opts.showMode) return runTerminalShow(opts);
719
- const args = buildGitDiffArgs(opts);
720
- const enforceDefaults = !opts.outputFormat && !opts.quiet;
721
- const finalArgs = [];
722
- if (enforceDefaults) {
723
- if (!args.includes("--no-ext-diff") && !opts.extDiff) finalArgs.push("--no-ext-diff");
724
- }
725
- finalArgs.push(...args);
726
- try {
727
- execFileSync("git", ["diff", ...finalArgs], {
728
- encoding: "utf-8",
729
- maxBuffer: MAX_BUFFER,
730
- stdio: "inherit"
731
- });
732
- return 0;
733
- } catch (err) {
734
- if (err.status === 1 && opts.exitCode) return 1;
735
- return err.status ?? 1;
736
- }
737
- }
738
- /**
739
- * Terminal mode for `diffing show`: spawn `git show` with the user's revspecs
740
- * and pathspecs, inherit stdio, propagate exit code. We pass `--no-ext-diff`
741
- * so the output is a clean unified diff regardless of the user's git config
742
- * (matches the web-mode pipeline), but otherwise hand everything to git.
743
- */
744
- function runTerminalShow(opts) {
745
- const args = [
746
- "show",
747
- "--no-ext-diff",
748
- ...opts.showRevspecs
749
- ];
750
- if (opts.pathspecs.length > 0) args.push("--", ...opts.pathspecs);
751
- try {
752
- execFileSync("git", args, {
753
- encoding: "utf-8",
754
- maxBuffer: MAX_BUFFER,
755
- stdio: "inherit"
756
- });
757
- return 0;
758
- } catch (err) {
759
- return err.status ?? 1;
760
- }
761
- }
762
- /**
763
- * Validate the environment: check that we're in a git repo.
764
- * Returns an error message or null.
765
- */
766
- function validateEnvironment() {
767
- if (!isGitRepo()) return "Error: not inside a git repository";
768
- return null;
769
- }
770
- //#endregion
771
- //#region src/lib/symbols.ts
772
- const SYMBOL_PATTERNS = [
773
- {
774
- pattern: /^\s*(?:export\s+)?(?:async\s+)?function\s+(\w[\w$]*)\s*[<(]/i,
775
- kind: "function",
776
- nameGroup: 1
777
- },
778
- {
779
- pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=\s*(?:async\s*)?\(/i,
780
- kind: "function",
781
- nameGroup: 1
782
- },
783
- {
784
- pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=\s*(?:async\s+)?function/i,
785
- kind: "function",
786
- nameGroup: 1
787
- },
788
- {
789
- pattern: /^\s*(?:export\s+)?class\s+(\w[\w$]*)/i,
790
- kind: "class",
791
- nameGroup: 1
792
- },
793
- {
794
- pattern: /^\s*(?:export\s+)?interface\s+(\w[\w$]*)/i,
795
- kind: "interface",
796
- nameGroup: 1
797
- },
798
- {
799
- pattern: /^\s*(?:export\s+)?type\s+(\w[\w$]*)\s*=/i,
800
- kind: "type",
801
- nameGroup: 1
802
- },
803
- {
804
- pattern: /^\s*(?:export\s+)?enum\s+(\w[\w$]*)/i,
805
- kind: "enum",
806
- nameGroup: 1
807
- },
808
- {
809
- pattern: /^\s*(?:export\s+)?(?:const|let|var)\s+(\w[\w$]*)\s*=/i,
810
- kind: "variable",
811
- nameGroup: 1
812
- },
813
- {
814
- pattern: /^\s*def\s+(\w[\w$]*)\s*\(/i,
815
- kind: "function",
816
- nameGroup: 1
817
- },
818
- {
819
- pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?fn\s+(\w[\w$]*)\s*[<(]/i,
820
- kind: "function",
821
- nameGroup: 1
822
- },
823
- {
824
- pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?struct\s+(\w[\w$]*)/i,
825
- kind: "struct",
826
- nameGroup: 1
827
- },
828
- {
829
- pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?enum\s+(\w[\w$]*)/i,
830
- kind: "enum",
831
- nameGroup: 1
832
- },
833
- {
834
- pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?impl\s+(\w[\w$]*)/i,
835
- kind: "impl",
836
- nameGroup: 1
837
- },
838
- {
839
- pattern: /^\s*(?:pub(?:\s*\(\w+\))?\s+)?trait\s+(\w[\w$]*)/i,
840
- kind: "trait",
841
- nameGroup: 1
842
- },
843
- {
844
- pattern: /^\s*func\s+(\w[\w$]*)\s*\(/i,
845
- kind: "function",
846
- nameGroup: 1
847
- },
848
- {
849
- pattern: /^\s*(?:func\s+)?\((\w[\w$]*)\s+\*?\w+\)\s+(\w[\w$]*)\s*\(/i,
850
- kind: "method",
851
- nameGroup: 2
852
- }
853
- ];
854
- /**
855
- * Returns the symbol defined on this line (name + kind), or null if the line
856
- * is not a recognizable definition. The first matching pattern wins.
857
- */
858
- function classifySymbolLine(line) {
859
- for (const { pattern, kind, nameGroup } of SYMBOL_PATTERNS) {
860
- const match = pattern.exec(line);
861
- if (match) {
862
- const name = match[nameGroup];
863
- if (name) return {
864
- name,
865
- kind
866
- };
867
- }
868
- }
869
- return null;
870
- }
871
- //#endregion
872
- //#region src/lib/search.ts
873
- /**
874
- * Server-side code search powered by `@ff-labs/fff-node` — a native (Rust)
875
- * fuzzy file finder + live grep. Because it is a native Node addon it cannot
876
- * run in the browser, so the React client calls the `/api/search` endpoint and
877
- * this module owns the single long-lived `FileFinder` instance for the repo.
878
- *
879
- * Design notes:
880
- * - The native binary is loaded lazily via dynamic import inside `init()` so a
881
- * missing/incompatible platform binary degrades gracefully (search returns
882
- * an error) instead of crashing the whole server at module load.
883
- * - One finder per process, keyed implicitly to the repo root. Its frecency /
884
- * history databases live under the project's `~/.diffing/<repo>` storage dir
885
- * so we never write stray files into the user's repository.
886
- * - fff runs its own file-system watcher, so the index stays fresh as the
887
- * working tree changes during a review.
888
- * - "Symbols" search is plain grep for the identifier, then each hit line is
889
- * classified with the shared {@link classifySymbolLine} patterns — fff 0.8.x
890
- * does not populate `isDefinition`, so we do the classification ourselves.
891
- */
892
- const DEFAULT_LIMIT = 60;
893
- const MAX_LIMIT = 200;
894
- /** Internal page size when no path filter — generous so diff-first client
895
- * ranking has enough to work with. */
896
- const SCAN_PAGE = 200;
897
- /** Larger page size when filtering to a path set, so the post-filter is
898
- * effectively complete for normal-sized diffs/repos. */
899
- const SCAN_PAGE_FILTERED = 1e3;
900
- let finder = null;
901
- let initPromise = null;
902
- let initError = null;
903
- let shutdownHooked = false;
904
- function clampLimit(limit) {
905
- if (!limit || limit < 1) return DEFAULT_LIMIT;
906
- return Math.min(limit, MAX_LIMIT);
907
- }
908
- async function init() {
909
- try {
910
- const { FileFinder } = await import("@ff-labs/fff-node");
911
- const root = getRepoRoot();
912
- const dbDir = join(getProjectStorageDir(root), "fff");
913
- mkdirSync(dbDir, { recursive: true });
914
- const created = FileFinder.create({
915
- basePath: root,
916
- frecencyDbPath: join(dbDir, "frecency.db"),
917
- historyDbPath: join(dbDir, "history.db"),
918
- logLevel: "error"
919
- });
920
- if (!created.ok) {
921
- initError = created.error;
922
- return null;
923
- }
924
- const f = created.value;
925
- if (!shutdownHooked) {
926
- shutdownHooked = true;
927
- process.once("exit", () => {
928
- try {
929
- f.destroy();
930
- } catch {}
931
- });
932
- }
933
- await f.waitForScan(8e3);
934
- finder = f;
935
- return f;
936
- } catch (err) {
937
- initError = err?.message ?? String(err);
938
- return null;
939
- }
940
- }
941
- async function getFinder() {
942
- if (finder) return finder;
943
- if (initError) return null;
944
- if (!initPromise) initPromise = init();
945
- return initPromise;
946
- }
947
- function isIndexing(f) {
948
- try {
949
- return f.isScanning();
950
- } catch {
951
- return false;
952
- }
953
- }
954
- async function searchFiles(query, opts = {}) {
955
- const f = await getFinder();
956
- if (!f) return {
957
- scope: "files",
958
- items: [],
959
- total: 0,
960
- indexing: false,
961
- error: initError ?? "Search unavailable"
962
- };
963
- const limit = clampLimit(opts.limit);
964
- const pathSet = opts.paths ? new Set(opts.paths) : null;
965
- const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE, limit);
966
- const res = f.fileSearch(query, { pageSize });
967
- if (!res.ok) return {
968
- scope: "files",
969
- items: [],
970
- total: 0,
971
- indexing: isIndexing(f),
972
- error: res.error
973
- };
974
- const items = [];
975
- const { items: raw, scores } = res.value;
976
- for (let i = 0; i < raw.length && items.length < limit; i++) {
977
- const it = raw[i];
978
- if (pathSet && !pathSet.has(it.relativePath)) continue;
979
- const score = scores[i];
980
- items.push({
981
- path: it.relativePath,
982
- fileName: it.fileName,
983
- gitStatus: it.gitStatus,
984
- matchType: score?.matchType ?? "",
985
- exact: !!score?.exactMatch
986
- });
987
- }
988
- return {
989
- scope: "files",
990
- items,
991
- total: res.value.totalMatched,
992
- indexing: isIndexing(f)
993
- };
994
- }
995
- async function searchContent(query, opts = {}) {
996
- const f = await getFinder();
997
- if (!f) return {
998
- scope: "text",
999
- items: [],
1000
- total: 0,
1001
- indexing: false,
1002
- error: initError ?? "Search unavailable"
1003
- };
1004
- if (!query) return {
1005
- scope: "text",
1006
- items: [],
1007
- total: 0,
1008
- indexing: isIndexing(f)
1009
- };
1010
- const limit = clampLimit(opts.limit);
1011
- const pathSet = opts.paths ? new Set(opts.paths) : null;
1012
- const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE, limit);
1013
- const res = f.grep(query, {
1014
- mode: opts.regex ? "regex" : "plain",
1015
- smartCase: true,
1016
- beforeContext: 0,
1017
- afterContext: 0,
1018
- pageSize
1019
- });
1020
- if (!res.ok) return {
1021
- scope: "text",
1022
- items: [],
1023
- total: 0,
1024
- indexing: isIndexing(f),
1025
- error: res.error
1026
- };
1027
- const items = [];
1028
- for (const m of res.value.items) {
1029
- if (items.length >= limit) break;
1030
- if (pathSet && !pathSet.has(m.relativePath)) continue;
1031
- items.push(toContentHit(m));
1032
- }
1033
- return {
1034
- scope: "text",
1035
- items,
1036
- total: res.value.totalMatched,
1037
- indexing: isIndexing(f),
1038
- regexError: res.value.regexFallbackError || void 0
1039
- };
1040
- }
1041
- function toContentHit(m) {
1042
- return {
1043
- path: m.relativePath,
1044
- fileName: m.fileName,
1045
- line: m.lineNumber,
1046
- col: m.col,
1047
- content: m.lineContent,
1048
- matchRanges: m.matchRanges ?? [],
1049
- gitStatus: m.gitStatus
1050
- };
1051
- }
1052
- async function searchSymbols(query, opts = {}) {
1053
- const f = await getFinder();
1054
- if (!f) return {
1055
- scope: "symbols",
1056
- items: [],
1057
- total: 0,
1058
- indexing: false,
1059
- error: initError ?? "Search unavailable"
1060
- };
1061
- if (!query) return {
1062
- scope: "symbols",
1063
- items: [],
1064
- total: 0,
1065
- indexing: isIndexing(f)
1066
- };
1067
- const limit = clampLimit(opts.limit);
1068
- const pathSet = opts.paths ? new Set(opts.paths) : null;
1069
- const pageSize = pathSet ? SCAN_PAGE_FILTERED : Math.max(SCAN_PAGE_FILTERED, limit * 8);
1070
- const res = f.grep(query, {
1071
- mode: "plain",
1072
- smartCase: true,
1073
- beforeContext: 0,
1074
- afterContext: 0,
1075
- pageSize
1076
- });
1077
- if (!res.ok) return {
1078
- scope: "symbols",
1079
- items: [],
1080
- total: 0,
1081
- indexing: isIndexing(f),
1082
- error: res.error
1083
- };
1084
- const items = [];
1085
- const ql = query.toLowerCase();
1086
- const seen = /* @__PURE__ */ new Set();
1087
- for (const m of res.value.items) {
1088
- if (items.length >= limit) break;
1089
- if (pathSet && !pathSet.has(m.relativePath)) continue;
1090
- const sym = classifySymbolLine(m.lineContent);
1091
- if (!sym) continue;
1092
- if (!sym.name.toLowerCase().includes(ql)) continue;
1093
- const key = `${m.relativePath}:${m.lineNumber}:${sym.name}`;
1094
- if (seen.has(key)) continue;
1095
- seen.add(key);
1096
- const nameIdx = m.lineContent.indexOf(sym.name);
1097
- const matchRanges = nameIdx >= 0 ? [[nameIdx, nameIdx + sym.name.length]] : m.matchRanges ?? [];
1098
- items.push({
1099
- name: sym.name,
1100
- kind: sym.kind,
1101
- path: m.relativePath,
1102
- fileName: m.fileName,
1103
- line: m.lineNumber,
1104
- content: m.lineContent,
1105
- matchRanges,
1106
- gitStatus: m.gitStatus
1107
- });
1108
- }
1109
- return {
1110
- scope: "symbols",
1111
- items,
1112
- total: items.length,
1113
- indexing: isIndexing(f)
1114
- };
1115
- }
1116
- async function searchAll(query, opts = {}) {
1117
- const limit = clampLimit(opts.limit);
1118
- const [filesRes, contentRes, symbolsRes] = await Promise.all([
1119
- searchFiles(query, {
1120
- ...opts,
1121
- limit
1122
- }),
1123
- searchContent(query, {
1124
- ...opts,
1125
- limit
1126
- }),
1127
- searchSymbols(query, {
1128
- ...opts,
1129
- limit
1130
- })
1131
- ]);
1132
- const items = [];
1133
- for (const hit of filesRes.items) items.push({
1134
- kind: "file",
1135
- hit
1136
- });
1137
- for (const hit of symbolsRes.items) items.push({
1138
- kind: "symbol",
1139
- hit
1140
- });
1141
- for (const hit of contentRes.items) items.push({
1142
- kind: "text",
1143
- hit
1144
- });
1145
- const total = (filesRes.total || 0) + (contentRes.total || 0) + (symbolsRes.total || 0);
1146
- const indexing = filesRes.indexing || contentRes.indexing || symbolsRes.indexing;
1147
- const error = filesRes.error || contentRes.error || symbolsRes.error;
1148
- const regexError = contentRes.regexError;
1149
- return {
1150
- scope: "all",
1151
- items: items.slice(0, limit),
1152
- total,
1153
- indexing,
1154
- error,
1155
- regexError
1156
- };
1157
- }
1158
- async function getSearchStatus() {
1159
- const f = await getFinder();
1160
- if (!f) return {
1161
- available: false,
1162
- indexing: false,
1163
- indexedFiles: 0,
1164
- error: initError ?? "Search unavailable"
1165
- };
1166
- let indexedFiles = 0;
1167
- let indexing = false;
1168
- try {
1169
- const prog = f.getScanProgress();
1170
- if (prog.ok) {
1171
- indexedFiles = prog.value.scannedFilesCount;
1172
- indexing = prog.value.isScanning;
1173
- }
1174
- } catch {}
1175
- return {
1176
- available: true,
1177
- indexing,
1178
- indexedFiles
1179
- };
1180
- }
1181
- /** Record that the user opened `path` from a query, improving fff's frecency
1182
- * ranking for future searches. Best-effort, never throws. */
1183
- async function trackSelection(query, path) {
1184
- const f = await getFinder();
1185
- if (!f) return;
1186
- try {
1187
- f.trackQuery(query, path);
1188
- } catch {}
1189
- }
1190
- //#endregion
1191
- //#region src/lib/settings.ts
1192
- const CONFIG_DIR = join(homedir(), ".config", "diffing");
1193
- const SETTINGS_FILE = join(CONFIG_DIR, "settings.json");
1194
- const DEFAULTS = {
1195
- staged: true,
1196
- untracked: true,
1197
- diffStyle: "split",
1198
- defaultTabSize: 4,
1199
- theme: "nord",
1200
- editorIDE: "default",
1201
- lineDiffType: "word",
1202
- lineWrap: false,
1203
- diffIndicators: "classic",
1204
- showLineNumbers: true,
1205
- hunkSeparators: "line-info",
1206
- lineHoverHighlight: "both",
1207
- fontSize: 13,
1208
- expandContextByDefault: false,
1209
- collapsedContextThreshold: 10,
1210
- expansionLineCount: 20,
1211
- haptics: true,
1212
- sounds: true,
1213
- uiFont: null,
1214
- monoFont: null
1215
- };
1216
- function loadSettings() {
1217
- try {
1218
- const data = readFileSync(SETTINGS_FILE, "utf-8");
1219
- return {
1220
- ...DEFAULTS,
1221
- ...JSON.parse(data)
1222
- };
1223
- } catch {
1224
- return { ...DEFAULTS };
1225
- }
1226
- }
1227
- function saveSettings(settings) {
1228
- const merged = {
1229
- ...loadSettings(),
1230
- ...settings
1231
- };
1232
- mkdirSync(CONFIG_DIR, { recursive: true });
1233
- writeFileSync(SETTINGS_FILE, JSON.stringify(merged, null, 2));
1234
- return merged;
1235
- }
1236
- //#endregion
1237
- //#region src/lib/comments.ts
1238
- var FileCommentStore = class {
1239
- dirPath;
1240
- filePath;
1241
- /**
1242
- * @param storageDir Absolute directory to persist `comments.json` in.
1243
- * Defaults to the per-repo storage dir under `~/.diffing` — comments are
1244
- * NEVER written inside the reviewed (consumer) repo, so a consumer project
1245
- * stays free of any diffing-specific artifacts. The override exists only so
1246
- * tests can point at a throwaway temp dir.
1247
- */
1248
- constructor(storageDir) {
1249
- this.dirPath = storageDir ?? getProjectStorageDir();
1250
- this.filePath = join(this.dirPath, "comments.json");
1251
- }
1252
- async getAll() {
1253
- try {
1254
- const data = await readFile(this.filePath, "utf-8");
1255
- return JSON.parse(data);
1256
- } catch {
1257
- return [];
1258
- }
1259
- }
1260
- async save(comments) {
1261
- try {
1262
- await mkdir(this.dirPath, { recursive: true });
1263
- try {
1264
- const repoRoot = getRepoRoot();
1265
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1266
- } catch {}
1267
- await writeFile(this.filePath, JSON.stringify(comments, null, 2), "utf-8");
1268
- } catch (err) {
1269
- console.error("Failed to save comments to file:", err);
1270
- }
1271
- }
1272
- async add(comment) {
1273
- const comments = await this.getAll();
1274
- comments.push(comment);
1275
- await this.save(comments);
1276
- return comment;
1277
- }
1278
- async update(id, fields) {
1279
- const comments = await this.getAll();
1280
- const index = comments.findIndex((c) => c.id === id);
1281
- if (index === -1) return null;
1282
- const comment = comments[index];
1283
- if (fields.body !== void 0) comment.body = fields.body;
1284
- if (fields.status !== void 0) comment.status = fields.status;
1285
- await this.save(comments);
1286
- return comment;
1287
- }
1288
- async remove(id) {
1289
- const comments = await this.getAll();
1290
- const index = comments.findIndex((c) => c.id === id);
1291
- if (index === -1) return false;
1292
- comments.splice(index, 1);
1293
- await this.save(comments);
1294
- return true;
1295
- }
1296
- async addReply(commentId, reply) {
1297
- const comments = await this.getAll();
1298
- const index = comments.findIndex((c) => c.id === commentId);
1299
- if (index === -1) return null;
1300
- const comment = comments[index];
1301
- if (!comment.replies) comment.replies = [];
1302
- comment.replies.push(reply);
1303
- await this.save(comments);
1304
- return comment;
1305
- }
1306
- async removeReply(commentId, replyId) {
1307
- const comments = await this.getAll();
1308
- const index = comments.findIndex((c) => c.id === commentId);
1309
- if (index === -1) return null;
1310
- const comment = comments[index];
1311
- const replyIndex = comment.replies.findIndex((r) => r.id === replyId);
1312
- if (replyIndex === -1) return null;
1313
- comment.replies.splice(replyIndex, 1);
1314
- await this.save(comments);
1315
- return comment;
1316
- }
1317
- async updateReply(commentId, replyId, body) {
1318
- const comments = await this.getAll();
1319
- const index = comments.findIndex((c) => c.id === commentId);
1320
- if (index === -1) return null;
1321
- const comment = comments[index];
1322
- const reply = comment.replies.find((r) => r.id === replyId);
1323
- if (!reply) return null;
1324
- reply.body = body;
1325
- await this.save(comments);
1326
- return comment;
1327
- }
1328
- };
1329
- //#endregion
1330
- //#region src/lib/plans.ts
1331
- function newId() {
1332
- return crypto.randomUUID();
1333
- }
1334
- /**
1335
- * Backfill / repair a plan loaded from disk so it matches the current schema.
1336
- * Older persisted plans may be missing `versions` and `createdAtPlanVersion`;
1337
- * we synthesize sensible values so callers can always rely on the new fields.
1338
- */
1339
- function backfillPlan(plan) {
1340
- const currentVersion = plan.version ?? 1;
1341
- const have = Array.isArray(plan.versions) ? plan.versions.length : 0;
1342
- if (!plan.versions || have === 0 || have < currentVersion) {
1343
- const createdAt = plan.updatedAt ?? plan.createdAt ?? Date.now();
1344
- const haveEntries = Array.isArray(plan.versions) ? plan.versions : [];
1345
- const present = new Set(haveEntries.map((v) => v.version));
1346
- const next = [];
1347
- for (let i = 1; i <= currentVersion; i++) {
1348
- const existing = haveEntries.find((v) => v.version === i);
1349
- if (existing) next.push(existing);
1350
- else next.push({
1351
- version: i,
1352
- body: plan.body,
1353
- title: plan.title,
1354
- source: plan.source,
1355
- model: plan.model,
1356
- createdAt
1357
- });
1358
- }
1359
- plan.versions = next.filter((v) => v.version >= 1 && v.version <= currentVersion);
1360
- if (have < currentVersion || !present.has(currentVersion)) markBackfilled(plan);
1361
- }
1362
- if (plan.comments) {
1363
- for (const c of plan.comments) if (typeof c.createdAtPlanVersion !== "number") c.createdAtPlanVersion = plan.version ?? 1;
1364
- }
1365
- if (!plan.comments) plan.comments = [];
1366
- }
1367
- function markBackfilled(plan) {
1368
- plan.__backfilledVersions = true;
1369
- }
1370
- /** Shared mutation helpers so both stores behave identically. */
1371
- function applyUpsert(plans, input, now) {
1372
- if (input.id) {
1373
- const existing = plans.find((p) => p.id === input.id);
1374
- if (existing) {
1375
- existing.title = input.title;
1376
- existing.body = input.body;
1377
- if (input.source !== void 0) existing.source = input.source;
1378
- if (input.model !== void 0) existing.model = input.model;
1379
- existing.version += 1;
1380
- existing.updatedAt = now;
1381
- if (!existing.versions) existing.versions = [];
1382
- existing.versions.push({
1383
- version: existing.version,
1384
- body: existing.body,
1385
- title: existing.title,
1386
- source: existing.source,
1387
- model: existing.model,
1388
- createdAt: now
1389
- });
1390
- existing.decision = "pending";
1391
- existing.decisionComment = void 0;
1392
- existing.decidedAt = void 0;
1393
- return existing;
1394
- }
1395
- }
1396
- const plan = {
1397
- id: input.id || newId(),
1398
- title: input.title,
1399
- body: input.body,
1400
- source: input.source,
1401
- model: input.model,
1402
- createdAt: now,
1403
- updatedAt: now,
1404
- version: 1,
1405
- decision: "pending",
1406
- comments: [],
1407
- versions: [{
1408
- version: 1,
1409
- body: input.body,
1410
- title: input.title,
1411
- source: input.source,
1412
- model: input.model,
1413
- createdAt: now
1414
- }]
1415
- };
1416
- plans.push(plan);
1417
- return plan;
1418
- }
1419
- /**
1420
- * Keep the most-recent `PlanVersion` snapshot in sync with the current `Plan`
1421
- * fields after a non-resubmit edit (PUT). Doesn't add a new entry — that only
1422
- * happens via `upsert` (the resubmit flow).
1423
- */
1424
- function syncCurrentVersion(plan) {
1425
- if (!plan.versions || plan.versions.length === 0) plan.versions = [];
1426
- if (plan.versions.length === 0) {
1427
- plan.versions.push({
1428
- version: plan.version,
1429
- body: plan.body,
1430
- title: plan.title,
1431
- source: plan.source,
1432
- model: plan.model,
1433
- createdAt: plan.updatedAt
1434
- });
1435
- return;
1436
- }
1437
- const last = plan.versions[plan.versions.length - 1];
1438
- last.body = plan.body;
1439
- last.title = plan.title;
1440
- last.source = plan.source;
1441
- last.model = plan.model;
1442
- }
1443
- var FilePlanStore = class {
1444
- dirPath;
1445
- filePath;
1446
- /**
1447
- * @param storageDir Absolute directory to persist `plans.json` in. Defaults
1448
- * to the per-repo storage dir under `~/.diffing`, the same place comments
1449
- * and media live — plans are NEVER written inside the reviewed (consumer)
1450
- * repo, so a consumer project stays free of any diffing-specific artifacts.
1451
- * The override exists only so tests can point at a throwaway temp dir.
1452
- */
1453
- constructor(storageDir) {
1454
- this.dirPath = storageDir ?? getProjectStorageDir();
1455
- this.filePath = join(this.dirPath, "plans.json");
1456
- }
1457
- async getAll() {
1458
- try {
1459
- const data = await readFile(this.filePath, "utf-8");
1460
- const plans = JSON.parse(data);
1461
- let anyBackfilled = false;
1462
- for (const p of plans) {
1463
- const before = Array.isArray(p.versions) ? p.versions.length : 0;
1464
- const beforeValid = Array.isArray(p.versions) && p.versions.length > 0;
1465
- backfillPlan(p);
1466
- const after = Array.isArray(p.versions) ? p.versions.length : 0;
1467
- if ((!beforeValid || before < (p.version ?? 1)) && after > before) anyBackfilled = true;
1468
- }
1469
- if (anyBackfilled) try {
1470
- await this.save(plans);
1471
- } catch {}
1472
- return plans;
1473
- } catch {
1474
- return [];
1475
- }
1476
- }
1477
- async get(id) {
1478
- return (await this.getAll()).find((p) => p.id === id) ?? null;
1479
- }
1480
- async getVersion(id, version) {
1481
- const plan = await this.get(id);
1482
- if (!plan) return null;
1483
- return plan.versions.find((v) => v.version === version) ?? null;
1484
- }
1485
- async save(plans) {
1486
- try {
1487
- await mkdir(this.dirPath, { recursive: true });
1488
- try {
1489
- const repoRoot = getRepoRoot();
1490
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1491
- } catch {}
1492
- const clean = plans.map((p) => {
1493
- const copy = { ...p };
1494
- delete copy.__backfilledVersions;
1495
- return copy;
1496
- });
1497
- await writeFile(this.filePath, JSON.stringify(clean, null, 2), "utf-8");
1498
- } catch (err) {
1499
- console.error("Failed to save plans to file:", err);
1500
- }
1501
- }
1502
- async upsert(input) {
1503
- const plans = await this.getAll();
1504
- const plan = applyUpsert(plans, input, Date.now());
1505
- backfillPlan(plan);
1506
- await this.save(plans);
1507
- return plan;
1508
- }
1509
- async update(id, fields) {
1510
- const plans = await this.getAll();
1511
- const plan = plans.find((p) => p.id === id);
1512
- if (!plan) return null;
1513
- if (fields.title !== void 0) plan.title = fields.title;
1514
- if (fields.body !== void 0) plan.body = fields.body;
1515
- if (fields.source !== void 0) plan.source = fields.source;
1516
- if (fields.model !== void 0) plan.model = fields.model;
1517
- plan.updatedAt = Date.now();
1518
- syncCurrentVersion(plan);
1519
- backfillPlan(plan);
1520
- await this.save(plans);
1521
- return plan;
1522
- }
1523
- async remove(id) {
1524
- const plans = await this.getAll();
1525
- const idx = plans.findIndex((p) => p.id === id);
1526
- if (idx === -1) return false;
1527
- plans.splice(idx, 1);
1528
- await this.save(plans);
1529
- return true;
1530
- }
1531
- async setDecision(id, decision, decisionComment) {
1532
- const plans = await this.getAll();
1533
- const plan = plans.find((p) => p.id === id);
1534
- if (!plan) return null;
1535
- plan.decision = decision;
1536
- plan.decisionComment = decisionComment?.trim() || void 0;
1537
- plan.decidedAt = Date.now();
1538
- plan.updatedAt = plan.decidedAt;
1539
- await this.save(plans);
1540
- return plan;
1541
- }
1542
- async mutate(planId, fn) {
1543
- const plans = await this.getAll();
1544
- const plan = plans.find((p) => p.id === planId);
1545
- if (!plan) return null;
1546
- if (!plan.comments) plan.comments = [];
1547
- if (!fn(plan)) return null;
1548
- backfillPlan(plan);
1549
- await this.save(plans);
1550
- return plan;
1551
- }
1552
- async addComment(planId, comment) {
1553
- return this.mutate(planId, (plan) => {
1554
- if (typeof comment.createdAtPlanVersion !== "number") comment.createdAtPlanVersion = plan.version ?? 1;
1555
- plan.comments.push(comment);
1556
- return true;
1557
- });
1558
- }
1559
- async updateComment(planId, commentId, fields) {
1560
- return this.mutate(planId, (plan) => {
1561
- const c = plan.comments.find((x) => x.id === commentId);
1562
- if (!c) return false;
1563
- if (fields.body !== void 0) c.body = fields.body;
1564
- if (fields.status !== void 0) c.status = fields.status;
1565
- return true;
1566
- });
1567
- }
1568
- async removeComment(planId, commentId) {
1569
- return this.mutate(planId, (plan) => {
1570
- const idx = plan.comments.findIndex((x) => x.id === commentId);
1571
- if (idx === -1) return false;
1572
- plan.comments.splice(idx, 1);
1573
- return true;
1574
- });
1575
- }
1576
- async addReply(planId, commentId, reply) {
1577
- return this.mutate(planId, (plan) => {
1578
- const c = plan.comments.find((x) => x.id === commentId);
1579
- if (!c) return false;
1580
- if (typeof c.createdAtPlanVersion === "number" && typeof reply.createdAtPlanVersion !== "number") reply.createdAtPlanVersion = c.createdAtPlanVersion;
1581
- if (!c.replies) c.replies = [];
1582
- c.replies.push(reply);
1583
- return true;
1584
- });
1585
- }
1586
- async removeReply(planId, commentId, replyId) {
1587
- return this.mutate(planId, (plan) => {
1588
- const c = plan.comments.find((x) => x.id === commentId);
1589
- if (!c) return false;
1590
- const idx = c.replies.findIndex((r) => r.id === replyId);
1591
- if (idx === -1) return false;
1592
- c.replies.splice(idx, 1);
1593
- return true;
1594
- });
1595
- }
1596
- async updateReply(planId, commentId, replyId, body) {
1597
- return this.mutate(planId, (plan) => {
1598
- const c = plan.comments.find((x) => x.id === commentId);
1599
- if (!c) return false;
1600
- const reply = c.replies.find((r) => r.id === replyId);
1601
- if (!reply) return false;
1602
- reply.body = body;
1603
- return true;
1604
- });
1605
- }
1606
- };
1607
- //#endregion
1608
- //#region src/lib/state.ts
1609
- var FileUiStateStore = class {
1610
- dirPath;
1611
- filePath;
1612
- constructor(storageDir) {
1613
- this.dirPath = storageDir ?? getProjectStorageDir();
1614
- this.filePath = join(this.dirPath, "ui-state.json");
1615
- }
1616
- async getAll() {
1617
- try {
1618
- const data = await readFile(this.filePath, "utf-8");
1619
- return JSON.parse(data);
1620
- } catch {
1621
- return {};
1622
- }
1623
- }
1624
- async setAll(state) {
1625
- await this.save(state);
1626
- }
1627
- async save(state) {
1628
- try {
1629
- await mkdir(this.dirPath, { recursive: true });
1630
- try {
1631
- const repoRoot = getRepoRoot();
1632
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1633
- } catch {}
1634
- await writeFile(this.filePath, JSON.stringify(state, null, 2), "utf-8");
1635
- } catch (err) {
1636
- console.error("Failed to save UI state to file:", err);
1637
- }
1638
- }
1639
- };
1640
- //#endregion
1641
- //#region src/lib/editor-launcher.ts
1642
- function resolveEditorCommand(editor, absolutePath, platform = process.platform, env = process.env) {
1643
- switch (editor) {
1644
- case "vscode": return guiEditorCommand("code", absolutePath, platform);
1645
- case "zed": return guiEditorCommand("zed", absolutePath, platform);
1646
- case "vim": return terminalEditorCommand("vim", absolutePath, platform, env);
1647
- case "neovim": return terminalEditorCommand("nvim", absolutePath, platform, env);
1648
- default: return null;
1649
- }
1650
- }
1651
- function guiEditorCommand(bin, absolutePath, platform) {
1652
- if (platform === "win32") return {
1653
- cmd: `${bin}.cmd`,
1654
- args: [absolutePath]
1655
- };
1656
- return {
1657
- cmd: bin,
1658
- args: [absolutePath]
1659
- };
1660
- }
1661
- function terminalEditorCommand(bin, absolutePath, platform, env) {
1662
- if (platform === "darwin") return {
1663
- cmd: "osascript",
1664
- args: ["-e", `tell application "Terminal" to do script "${bin} \\"${absolutePath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}\\""`]
1665
- };
1666
- if (platform === "win32") return {
1667
- cmd: "cmd.exe",
1668
- args: [
1669
- "/c",
1670
- "start",
1671
- "\"\"",
1672
- "cmd.exe",
1673
- "/k",
1674
- bin,
1675
- absolutePath
1676
- ]
1677
- };
1678
- const term = env.TERMINAL?.trim();
1679
- if (term) return {
1680
- cmd: term,
1681
- args: [
1682
- "-e",
1683
- bin,
1684
- absolutePath
1685
- ]
1686
- };
1687
- return {
1688
- cmd: "x-terminal-emulator",
1689
- args: [
1690
- "-e",
1691
- bin,
1692
- absolutePath
1693
- ]
1694
- };
1695
- }
1696
- //#endregion
1697
- //#region src/lib/review-session.ts
1698
- var ReviewSession = class {
1699
- round = 0;
1700
- lastSentAt = null;
1701
- lastPayload = null;
1702
- waiters = /* @__PURE__ */ new Set();
1703
- onStatusChange;
1704
- constructor(onStatusChange) {
1705
- this.onStatusChange = onStatusChange;
1706
- }
1707
- /**
1708
- * Block until the next `send()` or until `timeoutMs` elapses.
1709
- *
1710
- * If `sinceRound` is provided and is behind the current round, a send already
1711
- * happened since the client last checked → resolve immediately with the
1712
- * cached payload (the race guard). Otherwise register a waiter.
1713
- */
1714
- await(opts) {
1715
- const { sinceRound, timeoutMs, signal } = opts;
1716
- if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
1717
- status: "released",
1718
- payload: this.lastPayload
1719
- });
1720
- if (signal?.aborted) return Promise.resolve({
1721
- status: "keep-waiting",
1722
- round: this.round
1723
- });
1724
- return new Promise((resolve) => {
1725
- const waiter = {
1726
- resolve,
1727
- timer: setTimeout(() => {
1728
- this.removeWaiter(waiter);
1729
- resolve({
1730
- status: "keep-waiting",
1731
- round: this.round
1732
- });
1733
- }, timeoutMs),
1734
- cleanup: () => {}
1735
- };
1736
- if (signal) {
1737
- const onAbort = () => {
1738
- this.removeWaiter(waiter);
1739
- resolve({
1740
- status: "keep-waiting",
1741
- round: this.round
1742
- });
1743
- };
1744
- signal.addEventListener("abort", onAbort, { once: true });
1745
- waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
1746
- }
1747
- this.waiters.add(waiter);
1748
- this.emitStatus();
1749
- });
1750
- }
1751
- /** Capture a review batch and release every blocked waiter. */
1752
- send(input) {
1753
- this.round += 1;
1754
- this.lastSentAt = input.sentAt;
1755
- const payload = {
1756
- round: this.round,
1757
- sentAt: input.sentAt,
1758
- commentXml: input.commentXml,
1759
- openCount: input.openCount,
1760
- comments: input.comments,
1761
- decision: input.decision,
1762
- mode: input.mode ?? "standard"
1763
- };
1764
- this.lastPayload = payload;
1765
- const waiters = [...this.waiters];
1766
- this.waiters.clear();
1767
- for (const waiter of waiters) {
1768
- clearTimeout(waiter.timer);
1769
- waiter.cleanup();
1770
- waiter.resolve({
1771
- status: "released",
1772
- payload
1773
- });
1774
- }
1775
- this.emitStatus();
1776
- return payload;
1777
- }
1778
- snapshot() {
1779
- return {
1780
- round: this.round,
1781
- waiters: this.waiters.size,
1782
- lastSentAt: this.lastSentAt
1783
- };
1784
- }
1785
- removeWaiter(waiter) {
1786
- if (!this.waiters.delete(waiter)) return;
1787
- clearTimeout(waiter.timer);
1788
- waiter.cleanup();
1789
- this.emitStatus();
1790
- }
1791
- emitStatus() {
1792
- this.onStatusChange?.(this.snapshot());
1793
- }
1794
- };
1795
- //#endregion
1796
- //#region src/lib/plan-review-session.ts
1797
- var PlanReviewSession = class {
1798
- round = 0;
1799
- lastDecidedAt = null;
1800
- lastPayload = null;
1801
- waiters = /* @__PURE__ */ new Set();
1802
- onStatusChange;
1803
- constructor(onStatusChange) {
1804
- this.onStatusChange = onStatusChange;
1805
- }
1806
- /** Block until the next `decide()` or until `timeoutMs` elapses. */
1807
- await(opts) {
1808
- const { sinceRound, timeoutMs, signal } = opts;
1809
- if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
1810
- status: "released",
1811
- payload: this.lastPayload
1812
- });
1813
- if (signal?.aborted) return Promise.resolve({
1814
- status: "keep-waiting",
1815
- round: this.round
1816
- });
1817
- return new Promise((resolve) => {
1818
- const waiter = {
1819
- resolve,
1820
- timer: setTimeout(() => {
1821
- this.removeWaiter(waiter);
1822
- resolve({
1823
- status: "keep-waiting",
1824
- round: this.round
1825
- });
1826
- }, timeoutMs),
1827
- cleanup: () => {}
1828
- };
1829
- if (signal) {
1830
- const onAbort = () => {
1831
- this.removeWaiter(waiter);
1832
- resolve({
1833
- status: "keep-waiting",
1834
- round: this.round
1835
- });
1836
- };
1837
- signal.addEventListener("abort", onAbort, { once: true });
1838
- waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
1839
- }
1840
- this.waiters.add(waiter);
1841
- this.emitStatus();
1842
- });
1843
- }
1844
- /** Capture a decision and release every blocked waiter. */
1845
- decide(input) {
1846
- this.round += 1;
1847
- this.lastDecidedAt = input.sentAt;
1848
- const payload = {
1849
- round: this.round,
1850
- sentAt: input.sentAt,
1851
- planId: input.planId,
1852
- decision: input.decision,
1853
- decisionComment: input.decisionComment,
1854
- reviewXml: input.reviewXml,
1855
- openCommentCount: input.openCommentCount,
1856
- plan: input.plan,
1857
- mode: input.mode ?? "standard"
1858
- };
1859
- this.lastPayload = payload;
1860
- const waiters = [...this.waiters];
1861
- this.waiters.clear();
1862
- for (const waiter of waiters) {
1863
- clearTimeout(waiter.timer);
1864
- waiter.cleanup();
1865
- waiter.resolve({
1866
- status: "released",
1867
- payload
1868
- });
1869
- }
1870
- this.emitStatus();
1871
- return payload;
1872
- }
1873
- snapshot() {
1874
- return {
1875
- round: this.round,
1876
- waiters: this.waiters.size,
1877
- lastDecidedAt: this.lastDecidedAt
1878
- };
1879
- }
1880
- removeWaiter(waiter) {
1881
- if (!this.waiters.delete(waiter)) return;
1882
- clearTimeout(waiter.timer);
1883
- waiter.cleanup();
1884
- this.emitStatus();
1885
- }
1886
- emitStatus() {
1887
- this.onStatusChange?.(this.snapshot());
1888
- }
1889
- };
1890
- //#endregion
1891
- //#region src/lib/pr-session.ts
1892
- var FilePrSessionStore = class {
1893
- dirPath;
1894
- filePath;
1895
- constructor(storageDir) {
1896
- this.dirPath = storageDir ?? getProjectStorageDir();
1897
- this.filePath = join(this.dirPath, "pr-session.json");
1898
- }
1899
- async get() {
1900
- try {
1901
- const data = await readFile(this.filePath, "utf-8");
1902
- return JSON.parse(data);
1903
- } catch {
1904
- return null;
1905
- }
1906
- }
1907
- async save(session) {
1908
- try {
1909
- await mkdir(this.dirPath, { recursive: true });
1910
- await writeFile(this.filePath, JSON.stringify(session, null, 2), "utf-8");
1911
- } catch (err) {
1912
- console.error("Failed to save pr-session to file:", err);
1913
- }
1914
- }
1915
- async set(session) {
1916
- await this.save(session);
1917
- }
1918
- async update(fields) {
1919
- const current = await this.get();
1920
- if (!current) return null;
1921
- const next = {
1922
- ...current,
1923
- ...fields
1924
- };
1925
- await this.save(next);
1926
- return next;
1927
- }
1928
- async clear() {
1929
- try {
1930
- const { unlink } = await import("node:fs/promises");
1931
- await unlink(this.filePath);
1932
- } catch {}
1933
- }
1934
- };
1935
- //#endregion
1936
- //#region src/lib/github.ts
1937
- const execFileAsync = promisify(execFile);
1938
- /**
1939
- * Probe the `gh` CLI: is it on `$PATH`, and is the user authenticated?
1940
- * Never throws — returns a permissive `available: false` on any failure.
1941
- */
1942
- async function detectGhCli() {
1943
- try {
1944
- const { stdout } = await execFileAsync("gh", ["--version"], { encoding: "utf-8" });
1945
- const version = stdout.split("\n")[0]?.trim() || void 0;
1946
- try {
1947
- const result = await execFileAsync("gh", ["auth", "status"], { encoding: "utf-8" });
1948
- return {
1949
- available: true,
1950
- authenticated: true,
1951
- version,
1952
- user: parseGhAuthStatusUser(`${result.stdout ?? ""}\n${result.stderr ?? ""}`)
1953
- };
1954
- } catch {
1955
- return {
1956
- available: true,
1957
- authenticated: false,
1958
- version
1959
- };
1960
- }
1961
- } catch {
1962
- return {
1963
- available: false,
1964
- authenticated: false
1965
- };
1966
- }
1967
- }
1968
- /**
1969
- * Extract the GitHub username from `gh auth status` output. Exported for
1970
- * unit tests — see `__tests__/github-auth.test.ts`.
1971
- *
1972
- * Real-world samples:
1973
- * `✓ Logged in to github.com account octocat (keyring)` (gh 2.40+)
1974
- * `Logged in to github.com as octocat (oauth_token)` (older gh)
1975
- * ` ✓ Logged in to github.com as octocat (~/.config/gh/hosts.yml)`
1976
- */
1977
- function parseGhAuthStatusUser(output) {
1978
- const account = /Logged in to [^\s]+ account\s+([^\s(]+)/.exec(output);
1979
- if (account) return account[1];
1980
- return /Logged in to [^\s]+ as\s+([^\s(]+)/.exec(output)?.[1];
1981
- }
1982
- /** Read the most-preferred GitHub token from the env. */
1983
- function readGithubToken() {
1984
- const env = process.env;
1985
- return env.GH_TOKEN || env.GITHUB_TOKEN || env.GITHUB_API_TOKEN || null;
1986
- }
1987
- function parsePrRef(input, cwdRepo) {
1988
- const trimmed = input.trim();
1989
- const urlMatch = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/i.exec(trimmed);
1990
- if (urlMatch) return {
1991
- owner: urlMatch[1],
1992
- repo: urlMatch[2],
1993
- pullNumber: Number(urlMatch[3]),
1994
- ref: trimmed
1995
- };
1996
- const shorthand = /^([^/\s]+)\/([^#\s]+)#(\d+)$/.exec(trimmed);
1997
- if (shorthand) return {
1998
- owner: shorthand[1],
1999
- repo: shorthand[2],
2000
- pullNumber: Number(shorthand[3]),
2001
- ref: trimmed
2002
- };
2003
- const bare = /^#?(\d+)$/.exec(trimmed);
2004
- if (bare && cwdRepo) return {
2005
- owner: cwdRepo.owner,
2006
- repo: cwdRepo.repo,
2007
- pullNumber: Number(bare[1]),
2008
- ref: trimmed
2009
- };
2010
- 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\`.`);
2011
- throw new Error(`Unrecognised PR ref: ${trimmed}`);
2012
- }
2013
- /**
2014
- * Best-effort: derive `{ owner, repo }` for the current working directory
2015
- * from `git remote get-url origin`. Falls back to throwing.
2016
- */
2017
- async function detectCwdRepo() {
2018
- try {
2019
- const { stdout } = await execFileAsync("git", [
2020
- "remote",
2021
- "get-url",
2022
- "origin"
2023
- ], { encoding: "utf-8" });
2024
- const url = stdout.trim();
2025
- const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\s*$/.exec(url);
2026
- if (m) return {
2027
- owner: m[1],
2028
- repo: m[2]
2029
- };
2030
- } catch {}
2031
- return null;
2032
- }
2033
- /**
2034
- * Fetch PR metadata + diff + existing review comments using `gh`.
2035
- * Throws with a user-readable message on failure.
2036
- */
2037
- async function fetchPrMetadataViaGh(resolved) {
2038
- const args = ["-R", `${resolved.owner}/${resolved.repo}`];
2039
- let metaJson;
2040
- try {
2041
- const { stdout } = await execFileAsync("gh", [
2042
- "pr",
2043
- "view",
2044
- String(resolved.pullNumber),
2045
- ...args,
2046
- "--json",
2047
- "number,title,url,author,baseRefOid,headRefOid,additions,deletions,changedFiles,headRepositoryOwner,headRepository"
2048
- ], {
2049
- encoding: "utf-8",
2050
- maxBuffer: 20 * 1024 * 1024
2051
- });
2052
- metaJson = JSON.parse(stdout);
2053
- } catch (err) {
2054
- const stderr = err?.stderr || err?.message || "unknown error";
2055
- throw new Error(`gh pr view failed: ${stderr.trim()}`);
2056
- }
2057
- let diff = "";
2058
- try {
2059
- const { stdout } = await execFileAsync("gh", [
2060
- "pr",
2061
- "diff",
2062
- String(resolved.pullNumber),
2063
- ...args
2064
- ], {
2065
- encoding: "utf-8",
2066
- maxBuffer: 50 * 1024 * 1024
2067
- });
2068
- diff = stdout;
2069
- } catch (err) {
2070
- const stderr = err?.stderr || err?.message || "unknown error";
2071
- throw new Error(`gh pr diff failed: ${stderr.trim()}`);
2072
- }
2073
- const headOwner = metaJson.headRepositoryOwner?.login || metaJson.headRepository?.owner?.login || resolved.owner;
2074
- const repoName = metaJson.headRepository?.name || resolved.repo;
2075
- const author = metaJson.author ? {
2076
- login: metaJson.author.login,
2077
- avatarUrl: metaJson.author.avatarUrl
2078
- } : null;
2079
- const existingComments = await fetchExistingCommentsViaGh(resolved);
2080
- return {
2081
- number: metaJson.number,
2082
- title: metaJson.title,
2083
- url: metaJson.url,
2084
- author,
2085
- baseSha: metaJson.baseRefOid,
2086
- headSha: metaJson.headRefOid,
2087
- additions: metaJson.additions,
2088
- deletions: metaJson.deletions,
2089
- changedFiles: metaJson.changedFiles,
2090
- owner: headOwner,
2091
- repo: repoName,
2092
- diff,
2093
- existingComments
2094
- };
2095
- }
2096
- async function fetchExistingCommentsViaGh(resolved) {
2097
- `${resolved.owner}${resolved.repo}`;
2098
- const endpoint = `repos/${resolved.owner}/${resolved.repo}/pulls/${resolved.pullNumber}/comments`;
2099
- const reviewsEndpoint = `repos/${resolved.owner}/${resolved.repo}/pulls/${resolved.pullNumber}/reviews`;
2100
- let reviews = [];
2101
- try {
2102
- const { stdout } = await execFileAsync("gh", [
2103
- "api",
2104
- reviewsEndpoint,
2105
- "--paginate"
2106
- ], {
2107
- encoding: "utf-8",
2108
- maxBuffer: 20 * 1024 * 1024
2109
- });
2110
- const all = JSON.parse(stdout);
2111
- if (Array.isArray(all)) reviews = all;
2112
- } catch {}
2113
- reviews.sort((a, b) => a.submitted_at < b.submitted_at ? 1 : -1);
2114
- const recentReviews = reviews.slice(0, 50);
2115
- const reviewStateById = /* @__PURE__ */ new Map();
2116
- for (const r of recentReviews) reviewStateById.set(r.id, r.state);
2117
- let commentsRaw = [];
2118
- try {
2119
- const { stdout } = await execFileAsync("gh", [
2120
- "api",
2121
- `${endpoint}?per_page=100`,
2122
- "--paginate"
2123
- ], {
2124
- encoding: "utf-8",
2125
- maxBuffer: 20 * 1024 * 1024
2126
- });
2127
- const parsed = JSON.parse(stdout);
2128
- if (Array.isArray(parsed)) commentsRaw = parsed;
2129
- } catch {
2130
- return [];
2131
- }
2132
- const byId = /* @__PURE__ */ new Map();
2133
- for (const c of commentsRaw) byId.set(c.id, c);
2134
- const replyByParent = /* @__PURE__ */ new Map();
2135
- for (const c of commentsRaw) if (c.in_reply_to_id && byId.has(c.in_reply_to_id)) {
2136
- const list = replyByParent.get(c.in_reply_to_id) ?? [];
2137
- list.push(c);
2138
- replyByParent.set(c.in_reply_to_id, list);
2139
- }
2140
- const tops = [];
2141
- for (const c of commentsRaw) {
2142
- if (c.in_reply_to_id) continue;
2143
- const state = c.pull_request_review_id ? reviewStateById.get(c.pull_request_review_id) ?? null : null;
2144
- tops.push({
2145
- id: c.id,
2146
- author: c.user ? {
2147
- login: c.user.login,
2148
- avatarUrl: c.user.avatar_url
2149
- } : null,
2150
- body: c.body ?? "",
2151
- path: c.path,
2152
- line: typeof c.line === "number" ? c.line : null,
2153
- side: c.side === "LEFT" || c.side === "RIGHT" ? c.side : null,
2154
- createdAt: c.created_at,
2155
- updatedAt: c.updated_at,
2156
- state,
2157
- replies: (replyByParent.get(c.id) ?? []).map((r) => ({
2158
- id: r.id,
2159
- author: r.user ? {
2160
- login: r.user.login,
2161
- avatarUrl: r.user.avatar_url
2162
- } : null,
2163
- body: r.body ?? "",
2164
- createdAt: r.created_at,
2165
- updatedAt: r.updated_at
2166
- })),
2167
- isOutdated: typeof c.position === "number" && c.position === null ? false : false
2168
- });
2169
- }
2170
- tops.sort((a, b) => {
2171
- if (a.path !== b.path) return a.path.localeCompare(b.path);
2172
- return (a.line ?? 0) - (b.line ?? 0);
2173
- });
2174
- return tops;
2175
- }
2176
- /**
2177
- * POST the review to GitHub. Prefers `gh api` (uses the user's existing
2178
- * `gh auth`); falls back to a direct HTTP call with `$GITHUB_TOKEN` when
2179
- * `gh` is unavailable.
2180
- */
2181
- async function submitReview(input) {
2182
- const gh = await detectGhCli();
2183
- if (gh.available && gh.authenticated) return submitViaGh(input);
2184
- const token = readGithubToken();
2185
- if (token) return submitViaToken(input, token);
2186
- return {
2187
- ok: false,
2188
- authSource: "none",
2189
- 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."
2190
- };
2191
- }
2192
- /**
2193
- * Map our `PrDecision` to the GitHub REST event string. Exported so the
2194
- * test suite can pin the mapping (including the `rejected → REQUEST_CHANGES`
2195
- * quirk, which exists because GitHub has no REJECT event).
2196
- */
2197
- function decisionToEvent(decision) {
2198
- if (decision === "approve") return "APPROVE";
2199
- if (decision === "request-changes") return "REQUEST_CHANGES";
2200
- return "COMMENT";
2201
- }
2202
- /**
2203
- * Expand multi-line `ReviewComment`s into N single-line `gh`-shaped entries
2204
- * with `[part N/M]` prefixes. Exported for the test suite — the body of the
2205
- * caller (`buildReviewPayload`) is otherwise private.
2206
- *
2207
- * Skips: non-`open` comments, file-level comments (`lineNumber === 0`).
2208
- * Strips the `a/` / `b/` prefix from the file path (GitHub expects PR-relative
2209
- * paths in the `path` field).
2210
- */
2211
- function expandMultiLineComments(comments) {
2212
- const flat = [];
2213
- for (const c of comments) {
2214
- if (c.status !== "open") continue;
2215
- if (c.lineNumber === 0) continue;
2216
- const path = stripBPrefix(c.filePath);
2217
- const start = c.startLineNumber && c.startLineNumber < c.lineNumber ? c.startLineNumber : c.lineNumber;
2218
- const end = c.lineNumber;
2219
- const span = end - start + 1;
2220
- if (span > 1) for (let i = 0; i < span; i++) flat.push({
2221
- path,
2222
- line: start + i,
2223
- side: "RIGHT",
2224
- body: `[part ${i + 1}/${span}]\n${c.body}`
2225
- });
2226
- else flat.push({
2227
- path,
2228
- line: end,
2229
- side: "RIGHT",
2230
- body: c.body
2231
- });
2232
- }
2233
- return flat;
2234
- }
2235
- function buildReviewPayload(input) {
2236
- return {
2237
- body: input.body,
2238
- event: decisionToEvent(input.decision ?? "comment"),
2239
- comments: expandMultiLineComments(input.comments ?? [])
2240
- };
2241
- }
2242
- function stripBPrefix(path) {
2243
- if (path.startsWith("b/")) return path.slice(2);
2244
- if (path.startsWith("a/")) return path.slice(2);
2245
- return path;
2246
- }
2247
- async function submitViaGh(input) {
2248
- const payload = buildReviewPayload(input);
2249
- `${input.resolved.owner}${input.resolved.repo}`;
2250
- const args = [
2251
- "api",
2252
- "--method",
2253
- "POST",
2254
- `repos/${input.resolved.owner}/${input.resolved.repo}/pulls/${input.resolved.pullNumber}/reviews`,
2255
- "-H",
2256
- "Accept: application/vnd.github+json",
2257
- "--input",
2258
- "-"
2259
- ];
2260
- try {
2261
- const { stdout } = await execFileAsync("gh", args, {
2262
- encoding: "utf-8",
2263
- maxBuffer: 20 * 1024 * 1024,
2264
- input: JSON.stringify(payload)
2265
- });
2266
- const result = JSON.parse(stdout);
2267
- return {
2268
- ok: true,
2269
- authSource: "gh",
2270
- reviewId: result.id,
2271
- reviewUrl: result.html_url
2272
- };
2273
- } catch (err) {
2274
- const stdout = err?.stdout || "";
2275
- const stderr = err?.stderr || err?.message || "unknown error";
2276
- let parsed = null;
2277
- try {
2278
- parsed = JSON.parse(stdout);
2279
- } catch {}
2280
- return {
2281
- ok: false,
2282
- authSource: "gh",
2283
- error: parsed?.message || stderr.trim()
2284
- };
2285
- }
2286
- }
2287
- async function submitViaToken(input, token) {
2288
- const payload = buildReviewPayload(input);
2289
- const url = `https://api.github.com/repos/${input.resolved.owner}/${input.resolved.repo}/pulls/${input.resolved.pullNumber}/reviews`;
2290
- try {
2291
- const res = await fetch(url, {
2292
- method: "POST",
2293
- headers: {
2294
- Authorization: `Bearer ${token}`,
2295
- Accept: "application/vnd.github+json",
2296
- "X-GitHub-Api-Version": "2022-11-28",
2297
- "Content-Type": "application/json",
2298
- "User-Agent": "diffing-cli"
2299
- },
2300
- body: JSON.stringify(payload)
2301
- });
2302
- if (!res.ok) {
2303
- const errBody = await res.text().catch(() => "");
2304
- return {
2305
- ok: false,
2306
- authSource: "token",
2307
- error: `HTTP ${res.status}: ${errBody.slice(0, 500)}`
2308
- };
2309
- }
2310
- const result = await res.json();
2311
- return {
2312
- ok: true,
2313
- authSource: "token",
2314
- reviewId: result.id,
2315
- reviewUrl: result.html_url
2316
- };
2317
- } catch (err) {
2318
- return {
2319
- ok: false,
2320
- authSource: "token",
2321
- error: err?.message || "Network error"
2322
- };
2323
- }
2324
- }
2325
- async function buildPrSession(ref) {
2326
- const meta = await fetchPrMetadataViaGh(parsePrRef(ref, await detectCwdRepo() ?? void 0));
2327
- return {
2328
- ref,
2329
- owner: meta.owner,
2330
- repo: meta.repo,
2331
- pullNumber: meta.number,
2332
- baseSha: meta.baseSha,
2333
- headSha: meta.headSha,
2334
- title: meta.title,
2335
- url: meta.url,
2336
- author: meta.author,
2337
- additions: meta.additions,
2338
- deletions: meta.deletions,
2339
- changedFiles: meta.changedFiles,
2340
- diff: meta.diff,
2341
- comments: [],
2342
- existingComments: meta.existingComments
2343
- };
2344
- }
2345
- /** Refresh `diff` + `existingComments` + head SHA in an existing session. */
2346
- async function refreshPrSession(session) {
2347
- const meta = await fetchPrMetadataViaGh({
2348
- owner: session.owner,
2349
- repo: session.repo,
2350
- pullNumber: session.pullNumber,
2351
- ref: session.ref
2352
- });
2353
- return {
2354
- ...session,
2355
- baseSha: meta.baseSha,
2356
- headSha: meta.headSha,
2357
- title: meta.title,
2358
- url: meta.url,
2359
- author: meta.author,
2360
- additions: meta.additions,
2361
- deletions: meta.deletions,
2362
- changedFiles: meta.changedFiles,
2363
- diff: meta.diff,
2364
- existingComments: meta.existingComments
2365
- };
2366
- }
2367
- //#endregion
2368
- //#region src/server.ts
2369
- const MIME_TYPES = {
2370
- ".html": "text/html",
2371
- ".js": "application/javascript",
2372
- ".css": "text/css",
2373
- ".json": "application/json",
2374
- ".svg": "image/svg+xml",
2375
- ".png": "image/png",
2376
- ".ico": "image/x-icon",
2377
- ".jpg": "image/jpeg",
2378
- ".jpeg": "image/jpeg",
2379
- ".gif": "image/gif",
2380
- ".webp": "image/webp",
2381
- ".bmp": "image/bmp",
2382
- ".avif": "image/avif"
2383
- };
2384
- function isCustomMode(opts) {
2385
- return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
2386
- }
2387
- function createApp(clientDir, diffOpts = DEFAULTS$1, commentStore, planStore, prSessionStore, prMode = false) {
2388
- const app = new Hono();
2389
- const customMode = isCustomMode(diffOpts);
2390
- const store = commentStore ?? new FileCommentStore();
2391
- const plans = planStore ?? new FilePlanStore();
2392
- const prStore = prSessionStore ?? new FilePrSessionStore();
2393
- const uiStateStore = new FileUiStateStore();
2394
- const viewedFiles = /* @__PURE__ */ new Set();
2395
- const activeClients = /* @__PURE__ */ new Set();
2396
- const broadcast = (event, data) => {
2397
- for (const send of activeClients) try {
2398
- send(event, data);
2399
- } catch {}
2400
- };
2401
- const reviewSession = new ReviewSession((snapshot) => broadcast("agent-status", JSON.stringify(snapshot)));
2402
- const planReviewSession = new PlanReviewSession((snapshot) => broadcast("plan-review-status", JSON.stringify(snapshot)));
2403
- let repoRoot;
2404
- try {
2405
- repoRoot = getRepoRoot();
2406
- } catch {
2407
- repoRoot = process.cwd();
2408
- }
2409
- if (!commentStore && !planStore) try {
2410
- const storageDir = getProjectStorageDir();
2411
- mkdirSync(storageDir, { recursive: true });
2412
- let commentsDebounce = null;
2413
- let plansDebounce = null;
2414
- let prSessionDebounce = null;
2415
- watch(storageDir, (_eventType, filename) => {
2416
- if (!filename) return;
2417
- if (filename.startsWith("comments.json")) {
2418
- if (commentsDebounce) clearTimeout(commentsDebounce);
2419
- commentsDebounce = setTimeout(() => broadcast("comments", Date.now().toString()), 120);
2420
- } else if (filename.startsWith("plans.json")) {
2421
- if (plansDebounce) clearTimeout(plansDebounce);
2422
- plansDebounce = setTimeout(() => broadcast("plans", Date.now().toString()), 120);
2423
- } else if (filename.startsWith("pr-session.json")) {
2424
- if (prSessionDebounce) clearTimeout(prSessionDebounce);
2425
- prSessionDebounce = setTimeout(() => broadcast("pr-session", Date.now().toString()), 120);
2426
- }
2427
- }).unref();
2428
- } catch (err) {
2429
- console.warn("Failed to initialize storage watcher:", err);
2430
- }
2431
- let debounceTimeout = null;
2432
- try {
2433
- watch(repoRoot, { recursive: true }, (eventType, filename) => {
2434
- if (!filename) return;
2435
- const parts = filename.split(/[/\\]/);
2436
- const isGit = parts.includes(".git");
2437
- const isNodeModules = parts.includes("node_modules");
2438
- const isDist = parts.includes("dist");
2439
- const isChangeset = parts.includes(".changeset");
2440
- let shouldTrigger = false;
2441
- if (isGit) {
2442
- const isIndex = filename.endsWith("index");
2443
- const isHead = filename.endsWith("HEAD");
2444
- const isRefs = filename.includes("refs/") || filename.includes("refs\\");
2445
- if (isIndex || isHead || isRefs) shouldTrigger = true;
2446
- } else if (!isNodeModules && !isDist && !isChangeset) shouldTrigger = true;
2447
- if (shouldTrigger) {
2448
- if (debounceTimeout) clearTimeout(debounceTimeout);
2449
- debounceTimeout = setTimeout(() => broadcast("change", Date.now().toString()), 200);
2450
- }
2451
- }).unref();
2452
- } catch (err) {
2453
- console.warn("Failed to initialize repository watcher:", err);
2454
- }
2455
- app.get("/api/live", async (c) => {
2456
- return streamSSE(c, async (stream) => {
2457
- const sendUpdate = (event, data) => {
2458
- stream.writeSSE({
2459
- event,
2460
- data
2461
- });
2462
- };
2463
- activeClients.add(sendUpdate);
2464
- await stream.writeSSE({
2465
- event: "heartbeat",
2466
- data: Date.now().toString()
2467
- });
2468
- const heartbeatInterval = setInterval(() => {
2469
- stream.writeSSE({
2470
- event: "heartbeat",
2471
- data: Date.now().toString()
2472
- }).catch(() => {});
2473
- }, 15e3);
2474
- await new Promise((resolve) => {
2475
- stream.onAbort(() => {
2476
- clearInterval(heartbeatInterval);
2477
- activeClients.delete(sendUpdate);
2478
- resolve();
2479
- });
2480
- });
2481
- });
2482
- });
2483
- app.get("/api/diff", async (c) => {
2484
- const staged = c.req.query("staged") === "true";
2485
- const untracked = c.req.query("untracked") === "true";
2486
- if (prMode) {
2487
- const prSession = await prStore.get();
2488
- if (prSession) {
2489
- const binaryFiles = [];
2490
- const filePaths = [];
2491
- for (const line of prSession.diff.split("\n")) {
2492
- const m = /^diff --git a\/.+ b\/(.+)$/.exec(line);
2493
- if (m) filePaths.push(m[1]);
2494
- }
2495
- return c.json({
2496
- patch: prSession.diff,
2497
- repoName: prSession.repo,
2498
- branch: `#${prSession.pullNumber}`,
2499
- customMode: true,
2500
- binaryFiles,
2501
- tabSizeMap: {},
2502
- untrackedFiles: [],
2503
- prMode: true,
2504
- prRef: prSession.ref,
2505
- prOwner: prSession.owner,
2506
- prRepo: prSession.repo,
2507
- prPullNumber: prSession.pullNumber,
2508
- prUrl: prSession.url,
2509
- prTitle: prSession.title,
2510
- prAuthor: prSession.author,
2511
- prHeadSha: prSession.headSha,
2512
- prBaseSha: prSession.baseSha
2513
- });
2514
- }
2515
- }
2516
- const optsForDiff = customMode ? diffOpts : {
2517
- ...diffOpts,
2518
- staged,
2519
- includeUntracked: untracked
2520
- };
2521
- const result = await executeDiffWithMeta(optsForDiff);
2522
- return c.json({
2523
- patch: result.patch,
2524
- repoName: result.repoName,
2525
- branch: result.branch,
2526
- customMode,
2527
- binaryFiles: result.binaryFiles,
2528
- tabSizeMap: result.tabSizeMap,
2529
- untrackedFiles: result.untrackedFiles,
2530
- showMode: optsForDiff.showMode || void 0,
2531
- commits: result.commits,
2532
- truncated: result.truncated
2533
- });
2534
- });
2535
- app.get("/api/file-content", (c) => {
2536
- const path = c.req.query("path");
2537
- const version = c.req.query("version");
2538
- if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
2539
- const content = getFileContent(path, version);
2540
- if (!content) return c.json({ error: "File not found" }, 404);
2541
- const contentType = MIME_TYPES[extname(path)] || "application/octet-stream";
2542
- return new Response(new Uint8Array(content), { headers: { "Content-Type": contentType } });
2543
- });
2544
- app.get("/api/file-text", (c) => {
2545
- const path = c.req.query("path");
2546
- const version = c.req.query("version");
2547
- if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
2548
- const buffer = getFileContent(path, version);
2549
- if (!buffer) return c.json({
2550
- content: "",
2551
- missing: true
2552
- });
2553
- const sample = buffer.subarray(0, Math.min(buffer.length, 8192));
2554
- for (let i = 0; i < sample.length; i++) if (sample[i] === 0) return c.json({ error: "Binary file" }, 415);
2555
- return c.json({
2556
- content: buffer.toString("utf-8"),
2557
- missing: false
2558
- });
2559
- });
2560
- app.post("/api/open-file", async (c) => {
2561
- const { filePath, editor } = await c.req.json();
2562
- if (!filePath) return c.json({ error: "filePath is required" }, 400);
2563
- try {
2564
- const root = getRepoRoot();
2565
- const relPath = toSafeRelativePath(filePath, root);
2566
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2567
- const absolutePath = resolve(root, relPath);
2568
- if (editor && editor !== "default") {
2569
- const command = resolveEditorCommand(editor, absolutePath);
2570
- if (command) {
2571
- const { execFile } = await import("node:child_process");
2572
- execFile(command.cmd, command.args, (err) => {
2573
- if (err) console.error(`Failed to launch ${editor} for ${absolutePath}: ${err.message}`);
2574
- });
2575
- return c.json({ ok: true });
2576
- }
2577
- }
2578
- await (await import("open")).default(absolutePath);
2579
- return c.json({ ok: true });
2580
- } catch (err) {
2581
- return c.json({ error: `Failed to open file: ${err.message}` }, 500);
2582
- }
2583
- });
2584
- app.get("/api/repo-files", (c) => {
2585
- try {
2586
- return c.json({ files: listRepoFiles() });
2587
- } catch (err) {
2588
- return c.json({ error: err.message }, 500);
2589
- }
2590
- });
2591
- app.post("/api/search", async (c) => {
2592
- const body = await c.req.json().catch(() => ({}));
2593
- const scope = body.scope ?? "files";
2594
- const query = typeof body.query === "string" ? body.query : "";
2595
- const limit = typeof body.limit === "number" ? body.limit : void 0;
2596
- const paths = Array.isArray(body.changedPaths) ? body.changedPaths : void 0;
2597
- try {
2598
- if (scope === "all") return c.json(await searchAll(query, {
2599
- limit,
2600
- regex: !!body.regex,
2601
- paths
2602
- }));
2603
- if (scope === "text") return c.json(await searchContent(query, {
2604
- limit,
2605
- regex: !!body.regex,
2606
- paths
2607
- }));
2608
- if (scope === "symbols") return c.json(await searchSymbols(query, {
2609
- limit,
2610
- paths
2611
- }));
2612
- return c.json(await searchFiles(query, {
2613
- limit,
2614
- paths
2615
- }));
2616
- } catch (err) {
2617
- return c.json({
2618
- scope,
2619
- items: [],
2620
- total: 0,
2621
- indexing: false,
2622
- error: err?.message ?? "Search failed"
2623
- }, 500);
2624
- }
2625
- });
2626
- app.get("/api/search/status", async (c) => {
2627
- return c.json(await getSearchStatus());
2628
- });
2629
- app.post("/api/search/track", async (c) => {
2630
- const { query, path } = await c.req.json().catch(() => ({}));
2631
- if (path) await trackSelection(query ?? "", path);
2632
- return c.json({ ok: true });
2633
- });
2634
- app.get("/api/merge-status", (c) => {
2635
- try {
2636
- const status = getMergeStatus();
2637
- return c.json(status);
2638
- } catch (err) {
2639
- return c.json({ error: err.message }, 500);
2640
- }
2641
- });
2642
- app.post("/api/revert-hunk", async (c) => {
2643
- const { filePath, hunkIndex } = await c.req.json();
2644
- if (!filePath || typeof hunkIndex !== "number") return c.json({ error: "Missing filePath or hunkIndex" }, 400);
2645
- try {
2646
- const relPath = toSafeRelativePath(filePath, getRepoRoot());
2647
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2648
- revertHunk(relPath, hunkIndex);
2649
- return c.json({ ok: true });
2650
- } catch (err) {
2651
- const stderr = typeof err?.stderr === "string" ? err.stderr : err?.stderr instanceof Buffer ? err.stderr.toString("utf-8") : "";
2652
- return c.json({ error: stderr || err?.message || "Failed to revert hunk" }, 500);
2653
- }
2654
- });
2655
- app.get("/api/hunk-history", async (c) => {
2656
- const filePath = c.req.query("filePath");
2657
- const deletionStart = Number(c.req.query("deletionStart"));
2658
- const deletionCount = Number(c.req.query("deletionCount"));
2659
- if (!filePath || Number.isNaN(deletionStart) || Number.isNaN(deletionCount)) return c.json({ error: "Missing or invalid parameters" }, 400);
2660
- try {
2661
- const relPath = toSafeRelativePath(filePath, getRepoRoot());
2662
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2663
- const history = getHunkHistory(relPath, deletionStart, deletionCount, diffOpts.showMode ? diffOpts.showRevspecs[diffOpts.showRevspecs.length - 1] || "HEAD" : diffOpts.revisions[0] || "HEAD");
2664
- return c.json(history);
2665
- } catch (err) {
2666
- return c.json({ error: err.message || "Failed to fetch hunk history" }, 500);
2667
- }
2668
- });
2669
- app.post("/api/save-file", async (c) => {
2670
- const { filePath, content, gitAdd } = await c.req.json();
2671
- if (!filePath || typeof content !== "string") return c.json({ error: "Missing filePath or content" }, 400);
2672
- try {
2673
- const root = getRepoRoot();
2674
- const relPath = toSafeRelativePath(filePath, root);
2675
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2676
- await writeFile(resolve(root, relPath), content, "utf-8");
2677
- if (gitAdd) try {
2678
- gitAddFile(relPath);
2679
- } catch (err) {
2680
- return c.json({
2681
- ok: true,
2682
- gitAddError: err.message
2683
- });
2684
- }
2685
- return c.json({ ok: true });
2686
- } catch (err) {
2687
- return c.json({ error: `Failed to save file: ${err.message}` }, 500);
2688
- }
2689
- });
2690
- app.get("/api/settings", (c) => {
2691
- return c.json(loadSettings());
2692
- });
2693
- app.put("/api/settings", async (c) => {
2694
- const settings = saveSettings(await c.req.json());
2695
- return c.json(settings);
2696
- });
2697
- app.get("/api/ui-state", async (c) => {
2698
- return c.json(await uiStateStore.getAll());
2699
- });
2700
- app.put("/api/ui-state", async (c) => {
2701
- const body = await c.req.json();
2702
- const merged = {
2703
- ...await uiStateStore.getAll(),
2704
- ...body
2705
- };
2706
- for (const key of Object.keys(body)) if (body[key] === null || body[key] === void 0) delete merged[key];
2707
- await uiStateStore.setAll(merged);
2708
- return c.json(merged);
2709
- });
2710
- app.get("/api/viewed", (c) => {
2711
- return c.json([...viewedFiles]);
2712
- });
2713
- app.put("/api/viewed", async (c) => {
2714
- const { filePath, viewed } = await c.req.json();
2715
- if (viewed) viewedFiles.add(filePath);
2716
- else viewedFiles.delete(filePath);
2717
- return c.json({ ok: true });
2718
- });
2719
- app.get("/api/comments", async (c) => {
2720
- const comments = await store.getAll();
2721
- return c.json(comments);
2722
- });
2723
- app.post("/api/comments", async (c) => {
2724
- const body = await c.req.json();
2725
- const comment = {
2726
- id: crypto.randomUUID(),
2727
- filePath: body.filePath,
2728
- side: body.side,
2729
- lineNumber: body.lineNumber,
2730
- startLineNumber: body.startLineNumber,
2731
- lineContent: body.lineContent,
2732
- body: body.body,
2733
- status: "open",
2734
- createdAt: Date.now(),
2735
- replies: []
2736
- };
2737
- const created = await store.add(comment);
2738
- return c.json(created, 201);
2739
- });
2740
- app.put("/api/comments/:id", async (c) => {
2741
- const id = c.req.param("id");
2742
- const { body, status } = await c.req.json();
2743
- const updated = await store.update(id, {
2744
- body,
2745
- status
2746
- });
2747
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2748
- return c.json(updated);
2749
- });
2750
- app.post("/api/comments/:id/replies", async (c) => {
2751
- const commentId = c.req.param("id");
2752
- const { body, role, model } = await c.req.json();
2753
- const reply = {
2754
- id: crypto.randomUUID(),
2755
- body,
2756
- createdAt: Date.now(),
2757
- role: role || (model ? "agent" : "user"),
2758
- model: model || void 0
2759
- };
2760
- const updated = await store.addReply(commentId, reply);
2761
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2762
- return c.json(updated);
2763
- });
2764
- app.delete("/api/comments/:id/replies/:replyId", async (c) => {
2765
- const commentId = c.req.param("id");
2766
- const replyId = c.req.param("replyId");
2767
- const updated = await store.removeReply(commentId, replyId);
2768
- if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
2769
- return c.json(updated);
2770
- });
2771
- app.put("/api/comments/:id/replies/:replyId", async (c) => {
2772
- const commentId = c.req.param("id");
2773
- const replyId = c.req.param("replyId");
2774
- const { body } = await c.req.json();
2775
- if (!body) return c.json({ error: "Body is required" }, 400);
2776
- const updated = await store.updateReply(commentId, replyId, body);
2777
- if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
2778
- return c.json(updated);
2779
- });
2780
- app.post("/api/comments/:id/apply-suggestion", async (c) => {
2781
- const id = c.req.param("id");
2782
- const comment = (await store.getAll()).find((c) => c.id === id);
2783
- if (!comment) return c.json({ error: "Comment not found" }, 404);
2784
- if (comment.side !== "additions") return c.json({ error: "Suggestions can only be applied to added or modified lines" }, 400);
2785
- const match = comment.body.match(/```suggestion\n([\s\S]*?)```/);
2786
- if (!match) return c.json({ error: "No suggestion block found in comment body" }, 400);
2787
- const suggestion = match[1];
2788
- try {
2789
- const root = getRepoRoot();
2790
- const relPath = toSafeRelativePath(comment.filePath, root);
2791
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2792
- const absolutePath = resolve(root, relPath);
2793
- const lines = (await readFile(absolutePath, "utf-8")).split(/\r?\n/);
2794
- const lineIdx = comment.lineNumber - 1;
2795
- if (lineIdx < 0 || lineIdx >= lines.length) return c.json({ error: "Comment line number out of range" }, 400);
2796
- lines[lineIdx] = suggestion.trimEnd();
2797
- await writeFile(absolutePath, lines.join("\n"), "utf-8");
2798
- await store.update(id, { status: "resolved" });
2799
- return c.json({ ok: true });
2800
- } catch (err) {
2801
- return c.json({ error: `Failed to apply suggestion: ${err.message}` }, 500);
2802
- }
2803
- });
2804
- app.delete("/api/comments/:id", async (c) => {
2805
- const id = c.req.param("id");
2806
- if (!await store.remove(id)) return c.json({ error: "Comment not found" }, 404);
2807
- return c.json({ ok: true });
2808
- });
2809
- /** Shared helper: 404 with a stable shape so the client knows "not in PR mode". */
2810
- const notInPrMode = (c) => c.json({
2811
- error: "Not in PR review mode",
2812
- prMode: false
2813
- }, 404);
2814
- app.get("/api/gh/session", async (c) => {
2815
- if (!prMode) return notInPrMode(c);
2816
- const session = await prStore.get();
2817
- if (!session) return notInPrMode(c);
2818
- return c.json({
2819
- prMode: true,
2820
- ref: session.ref,
2821
- owner: session.owner,
2822
- repo: session.repo,
2823
- pullNumber: session.pullNumber,
2824
- baseSha: session.baseSha,
2825
- headSha: session.headSha,
2826
- title: session.title,
2827
- url: session.url,
2828
- author: session.author,
2829
- additions: session.additions,
2830
- deletions: session.deletions,
2831
- changedFiles: session.changedFiles,
2832
- existingComments: session.existingComments,
2833
- submittedAt: session.submittedAt,
2834
- submittedReviewId: session.submittedReviewId,
2835
- submittedReviewUrl: session.submittedReviewUrl,
2836
- authSource: session.authSource
2837
- });
2838
- });
2839
- /** Re-fetch PR metadata (head SHA, diff, existing comments) and persist. */
2840
- app.post("/api/gh/pr/refresh", async (c) => {
2841
- if (!prMode) return notInPrMode(c);
2842
- const session = await prStore.get();
2843
- if (!session) return notInPrMode(c);
2844
- try {
2845
- const refreshed = await refreshPrSession(session);
2846
- await prStore.set(refreshed);
2847
- return c.json({
2848
- ok: true,
2849
- headSha: refreshed.headSha
2850
- });
2851
- } catch (err) {
2852
- return c.json({ error: err?.message ?? "Refresh failed" }, 500);
2853
- }
2854
- });
2855
- /** Initialize a PR session from a ref like `1234`, `o/r#42`, or a GitHub URL. */
2856
- app.post("/api/gh/pr/init", async (c) => {
2857
- if (!prMode) return notInPrMode(c);
2858
- const body = await c.req.json().catch(() => ({}));
2859
- const ref = typeof body?.ref === "string" ? body.ref : "";
2860
- if (!ref.trim()) return c.json({ error: "ref is required" }, 400);
2861
- try {
2862
- parsePrRef(ref, await detectCwdRepo() ?? void 0);
2863
- const session = await buildPrSession(ref);
2864
- await prStore.set(session);
2865
- return c.json({
2866
- ok: true,
2867
- ref: session.ref,
2868
- owner: session.owner,
2869
- repo: session.repo,
2870
- pullNumber: session.pullNumber,
2871
- url: session.url
2872
- });
2873
- } catch (err) {
2874
- return c.json({ error: err?.message ?? "Failed to initialise PR session" }, 500);
2875
- }
2876
- });
2877
- app.get("/api/gh/pr-session/comments", async (c) => {
2878
- if (!prMode) return notInPrMode(c);
2879
- const session = await prStore.get();
2880
- if (!session) return notInPrMode(c);
2881
- return c.json(session.comments ?? []);
2882
- });
2883
- app.post("/api/gh/pr-session/comments", async (c) => {
2884
- if (!prMode) return notInPrMode(c);
2885
- const body = await c.req.json();
2886
- const session = await prStore.get();
2887
- if (!session) return notInPrMode(c);
2888
- const comment = {
2889
- id: crypto.randomUUID(),
2890
- filePath: body.filePath,
2891
- side: body.side,
2892
- lineNumber: body.lineNumber,
2893
- startLineNumber: body.startLineNumber,
2894
- lineContent: body.lineContent,
2895
- body: body.body,
2896
- status: "open",
2897
- createdAt: Date.now(),
2898
- replies: []
2899
- };
2900
- const next = {
2901
- ...session,
2902
- comments: [...session.comments ?? [], comment]
2903
- };
2904
- await prStore.set(next);
2905
- return c.json(comment, 201);
2906
- });
2907
- app.put("/api/gh/pr-session/comments/:id", async (c) => {
2908
- if (!prMode) return notInPrMode(c);
2909
- const id = c.req.param("id");
2910
- const { body, status } = await c.req.json();
2911
- const session = await prStore.get();
2912
- if (!session) return notInPrMode(c);
2913
- const comments = (session.comments ?? []).map((cm) => cm.id === id ? {
2914
- ...cm,
2915
- body: body ?? cm.body,
2916
- status: status ?? cm.status
2917
- } : cm);
2918
- await prStore.set({
2919
- ...session,
2920
- comments
2921
- });
2922
- const updated = comments.find((cm) => cm.id === id) ?? null;
2923
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2924
- return c.json(updated);
2925
- });
2926
- app.delete("/api/gh/pr-session/comments/:id", async (c) => {
2927
- if (!prMode) return notInPrMode(c);
2928
- const id = c.req.param("id");
2929
- const session = await prStore.get();
2930
- if (!session) return notInPrMode(c);
2931
- const comments = (session.comments ?? []).filter((cm) => cm.id !== id);
2932
- await prStore.set({
2933
- ...session,
2934
- comments
2935
- });
2936
- return c.json({ ok: true });
2937
- });
2938
- app.post("/api/gh/pr-session/comments/:id/replies", async (c) => {
2939
- if (!prMode) return notInPrMode(c);
2940
- const id = c.req.param("id");
2941
- const { body, role, model } = await c.req.json();
2942
- const session = await prStore.get();
2943
- if (!session) return notInPrMode(c);
2944
- const comments = (session.comments ?? []).map((cm) => {
2945
- if (cm.id !== id) return cm;
2946
- const reply = {
2947
- id: crypto.randomUUID(),
2948
- body,
2949
- createdAt: Date.now(),
2950
- role: role || (model ? "agent" : "user"),
2951
- model: model || void 0
2952
- };
2953
- return {
2954
- ...cm,
2955
- replies: [...cm.replies ?? [], reply]
2956
- };
2957
- });
2958
- await prStore.set({
2959
- ...session,
2960
- comments
2961
- });
2962
- return c.json(comments.find((cm) => cm.id === id));
2963
- });
2964
- /** Submit the current PR session's review (new comments + verdict + body) to GitHub. */
2965
- app.post("/api/gh/submit", async (c) => {
2966
- if (!prMode) return notInPrMode(c);
2967
- const session = await prStore.get();
2968
- if (!session) return notInPrMode(c);
2969
- const body = await c.req.json().catch(() => ({}));
2970
- const decision = body.decision;
2971
- if (decision !== "approve" && decision !== "comment" && decision !== "request-changes") return c.json({ error: "decision must be one of: approve, comment, request-changes" }, 400);
2972
- const generalBody = typeof body.body === "string" ? body.body : "";
2973
- const dryRun = body.dryRun === true;
2974
- const result = await submitReview({
2975
- resolved: {
2976
- owner: session.owner,
2977
- repo: session.repo,
2978
- pullNumber: session.pullNumber,
2979
- ref: session.ref
2980
- },
2981
- decision,
2982
- body: generalBody,
2983
- comments: session.comments ?? []
2984
- });
2985
- if (result.ok && !dryRun) {
2986
- const next = {
2987
- ...session,
2988
- submittedAt: Date.now(),
2989
- submittedReviewId: result.reviewId,
2990
- submittedReviewUrl: result.reviewUrl,
2991
- authSource: result.authSource
2992
- };
2993
- await prStore.set(next);
2994
- }
2995
- return c.json({
2996
- ok: result.ok,
2997
- reviewId: result.reviewId,
2998
- reviewUrl: result.reviewUrl,
2999
- failedComments: result.failedComments ?? 0,
3000
- authSource: result.authSource,
3001
- error: result.error,
3002
- dryRun
3003
- });
3004
- });
3005
- app.post("/api/review/send", async (c) => {
3006
- const body = await c.req.json().catch(() => ({}));
3007
- const generalComment = typeof body?.generalComment === "string" ? body.generalComment : void 0;
3008
- const decision = body?.decision === "approved" || body?.decision === "changes-requested" || body?.decision === "rejected" || body?.decision === "comment-only" ? body.decision : void 0;
3009
- const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
3010
- const all = await store.getAll();
3011
- const openCount = all.filter((x) => x.status === "open").length;
3012
- const payload = reviewSession.send({
3013
- sentAt: Date.now(),
3014
- commentXml: formatComments(all, generalComment, decision, mode),
3015
- openCount,
3016
- comments: all,
3017
- decision,
3018
- mode
3019
- });
3020
- return c.json({
3021
- ok: true,
3022
- round: payload.round,
3023
- openCount: payload.openCount,
3024
- decision: payload.decision,
3025
- mode: payload.mode,
3026
- waiters: reviewSession.snapshot().waiters
3027
- });
3028
- });
3029
- app.get("/api/review/await", async (c) => {
3030
- const sinceRaw = c.req.query("sinceRound");
3031
- const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
3032
- const requested = Number(c.req.query("timeoutMs")) || 25e3;
3033
- const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
3034
- const result = await reviewSession.await({
3035
- sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
3036
- timeoutMs,
3037
- signal: c.req.raw.signal
3038
- });
3039
- return c.json(result);
3040
- });
3041
- app.get("/api/review/status", (c) => {
3042
- return c.json(reviewSession.snapshot());
3043
- });
3044
- app.get("/api/plans", async (c) => {
3045
- return c.json(await plans.getAll());
3046
- });
3047
- app.get("/api/plans/:id", async (c) => {
3048
- const plan = await plans.get(c.req.param("id"));
3049
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3050
- return c.json(plan);
3051
- });
3052
- app.get("/api/plans/:id/versions", async (c) => {
3053
- const plan = await plans.get(c.req.param("id"));
3054
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3055
- return c.json(plan.versions ?? []);
3056
- });
3057
- app.get("/api/plans/:id/versions/:n", async (c) => {
3058
- const id = c.req.param("id");
3059
- const n = Number(c.req.param("n"));
3060
- if (!Number.isFinite(n) || n < 1) return c.json({ error: "version must be a positive integer" }, 400);
3061
- const plan = await plans.get(id);
3062
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3063
- const version = (plan.versions ?? []).find((v) => v.version === n);
3064
- if (!version) return c.json({ error: `Version ${n} not found` }, 404);
3065
- return c.json({
3066
- version,
3067
- plan: {
3068
- id: plan.id,
3069
- title: plan.title,
3070
- decision: plan.decision,
3071
- currentVersion: plan.version
3072
- }
3073
- });
3074
- });
3075
- app.post("/api/plans", async (c) => {
3076
- const body = await c.req.json().catch(() => ({}));
3077
- if (typeof body.body !== "string" || !body.body.trim()) return c.json({ error: "A plan body (markdown) is required" }, 400);
3078
- const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "Untitled plan";
3079
- const plan = await plans.upsert({
3080
- id: typeof body.id === "string" && body.id ? body.id : void 0,
3081
- title,
3082
- body: body.body,
3083
- source: typeof body.source === "string" ? body.source : void 0,
3084
- model: typeof body.model === "string" ? body.model : void 0
3085
- });
3086
- return c.json(plan, 201);
3087
- });
3088
- app.put("/api/plans/:id", async (c) => {
3089
- const id = c.req.param("id");
3090
- const { title, body, source, model } = await c.req.json().catch(() => ({}));
3091
- const updated = await plans.update(id, {
3092
- title: typeof title === "string" ? title : void 0,
3093
- body: typeof body === "string" ? body : void 0,
3094
- source: typeof source === "string" ? source : void 0,
3095
- model: typeof model === "string" ? model : void 0
3096
- });
3097
- if (!updated) return c.json({ error: "Plan not found" }, 404);
3098
- return c.json(updated);
3099
- });
3100
- app.delete("/api/plans/:id", async (c) => {
3101
- if (!await plans.remove(c.req.param("id"))) return c.json({ error: "Plan not found" }, 404);
3102
- return c.json({ ok: true });
3103
- });
3104
- app.post("/api/plans/:id/comments", async (c) => {
3105
- const planId = c.req.param("id");
3106
- const plan = await plans.get(planId);
3107
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3108
- const body = await c.req.json();
3109
- const lineNumber = Number.isFinite(body.lineNumber) ? Number(body.lineNumber) : 0;
3110
- const startLineNumber = Number.isFinite(body.startLineNumber) ? Number(body.startLineNumber) : void 0;
3111
- const anchorStart = startLineNumber ?? lineNumber;
3112
- const lineContent = typeof body.lineContent === "string" && body.lineContent ? body.lineContent : lineNumber > 0 ? extractPlanLines(plan.body, anchorStart, lineNumber) : "";
3113
- const sectionTitle = typeof body.sectionTitle === "string" && body.sectionTitle ? body.sectionTitle : lineNumber > 0 ? sectionTitleForLine(plan.body, anchorStart) : void 0;
3114
- const createdAtPlanVersion = Number.isFinite(body.createdAtPlanVersion) ? Number(body.createdAtPlanVersion) : plan.version;
3115
- const comment = {
3116
- id: crypto.randomUUID(),
3117
- lineNumber,
3118
- startLineNumber,
3119
- lineContent,
3120
- sectionTitle,
3121
- body: body.body,
3122
- status: "open",
3123
- createdAt: Date.now(),
3124
- createdAtPlanVersion,
3125
- replies: []
3126
- };
3127
- const updated = await plans.addComment(planId, comment);
3128
- if (!updated) return c.json({ error: "Plan not found" }, 404);
3129
- return c.json(updated, 201);
3130
- });
3131
- app.put("/api/plans/:id/comments/:commentId", async (c) => {
3132
- const { body, status } = await c.req.json();
3133
- const updated = await plans.updateComment(c.req.param("id"), c.req.param("commentId"), {
3134
- body,
3135
- status
3136
- });
3137
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3138
- return c.json(updated);
3139
- });
3140
- app.delete("/api/plans/:id/comments/:commentId", async (c) => {
3141
- const updated = await plans.removeComment(c.req.param("id"), c.req.param("commentId"));
3142
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3143
- return c.json(updated);
3144
- });
3145
- app.post("/api/plans/:id/comments/:commentId/replies", async (c) => {
3146
- const { body, role, model } = await c.req.json();
3147
- const reply = {
3148
- id: crypto.randomUUID(),
3149
- body,
3150
- createdAt: Date.now(),
3151
- role: role || (model ? "agent" : "user"),
3152
- model: model || void 0
3153
- };
3154
- const updated = await plans.addReply(c.req.param("id"), c.req.param("commentId"), reply);
3155
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3156
- return c.json(updated);
3157
- });
3158
- app.put("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3159
- const { body } = await c.req.json();
3160
- if (!body) return c.json({ error: "Body is required" }, 400);
3161
- const updated = await plans.updateReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"), body);
3162
- if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3163
- return c.json(updated);
3164
- });
3165
- app.delete("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3166
- const updated = await plans.removeReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"));
3167
- if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3168
- return c.json(updated);
3169
- });
3170
- app.post("/api/plans/:id/decision", async (c) => {
3171
- const planId = c.req.param("id");
3172
- const body = await c.req.json().catch(() => ({}));
3173
- const decision = body.decision;
3174
- 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);
3175
- const decisionComment = typeof body.decisionComment === "string" ? body.decisionComment : void 0;
3176
- const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
3177
- const plan = await plans.setDecision(planId, decision, decisionComment);
3178
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3179
- const openCommentCount = (plan.comments ?? []).filter((x) => x.status === "open").length;
3180
- const payload = planReviewSession.decide({
3181
- sentAt: Date.now(),
3182
- planId,
3183
- decision,
3184
- decisionComment: plan.decisionComment,
3185
- reviewXml: formatPlanReview(plan, { mode }),
3186
- openCommentCount,
3187
- plan,
3188
- mode
3189
- });
3190
- return c.json({
3191
- ok: true,
3192
- round: payload.round,
3193
- decision,
3194
- mode: payload.mode,
3195
- openCommentCount,
3196
- waiters: planReviewSession.snapshot().waiters
3197
- });
3198
- });
3199
- app.get("/api/plan-review/await", async (c) => {
3200
- const sinceRaw = c.req.query("sinceRound");
3201
- const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
3202
- const requested = Number(c.req.query("timeoutMs")) || 25e3;
3203
- const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
3204
- const result = await planReviewSession.await({
3205
- sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
3206
- timeoutMs,
3207
- signal: c.req.raw.signal
3208
- });
3209
- return c.json(result);
3210
- });
3211
- app.get("/api/plan-review/status", (c) => {
3212
- return c.json(planReviewSession.snapshot());
3213
- });
3214
- app.post("/api/attachments", async (c) => {
3215
- const file = (await c.req.parseBody())["file"];
3216
- if (!file || !(file instanceof File)) return c.json({ error: "No file uploaded" }, 400);
3217
- try {
3218
- const storageDir = getProjectStorageDir();
3219
- const attachmentsDir = join(storageDir, "attachments");
3220
- await mkdir(attachmentsDir, { recursive: true });
3221
- const repoRoot = getRepoRoot();
3222
- await writeFile(join(storageDir, "repo_path.txt"), repoRoot, "utf-8");
3223
- const ext = extname(file.name) || ".png";
3224
- const filename = `pasted_image_${crypto.randomUUID()}${ext}`;
3225
- const absolutePath = join(attachmentsDir, filename);
3226
- const arrayBuffer = await file.arrayBuffer();
3227
- await writeFile(absolutePath, new Uint8Array(arrayBuffer));
3228
- return c.json({ url: `/api/attachments/${filename}` });
3229
- } catch (err) {
3230
- return c.json({ error: `Failed to save attachment: ${err.message}` }, 500);
3231
- }
3232
- });
3233
- app.get("/api/attachments/:filename", async (c) => {
3234
- const filename = c.req.param("filename");
3235
- const attachmentsDir = join(getProjectStorageDir(), "attachments");
3236
- const absolutePath = resolve(attachmentsDir, filename);
3237
- if (!absolutePath.startsWith(attachmentsDir)) return c.text("Forbidden", 403);
3238
- try {
3239
- const content = await readFile(absolutePath);
3240
- const contentType = MIME_TYPES[extname(absolutePath)] || "application/octet-stream";
3241
- return new Response(content, { headers: { "Content-Type": contentType } });
3242
- } catch {
3243
- return c.text("Attachment not found", 404);
3244
- }
3245
- });
3246
- app.get("/*", async (c) => {
3247
- let filePath = c.req.path;
3248
- if (filePath === "/") filePath = "/index.html";
3249
- const relativePath = filePath.slice(1);
3250
- if (!isSafePath(relativePath, clientDir)) return c.text("Forbidden", 403);
3251
- const fullPath = resolve(clientDir, relativePath);
3252
- try {
3253
- const content = await readFile(fullPath);
3254
- const contentType = MIME_TYPES[extname(fullPath)] || "application/octet-stream";
3255
- return new Response(content, { headers: { "Content-Type": contentType } });
3256
- } catch {
3257
- const indexContent = await readFile(join(clientDir, "index.html"));
3258
- return new Response(indexContent, { headers: { "Content-Type": "text/html" } });
3259
- }
3260
- });
3261
- return app;
3262
- }
3263
- /**
3264
- * Newest mtime (epoch ms) across everything that counts as project activity:
3265
- * comments.json, plans.json, and any attachment (media) file. Plans and media
3266
- * extend a project's life exactly like comments do, so retention is uniform
3267
- * across all three. Returns null when none of them exist yet.
3268
- */
3269
- async function newestActivityMs(projectDir) {
3270
- const candidates = [];
3271
- const safeStat = async (p) => {
3272
- try {
3273
- return (await stat(p)).mtimeMs;
3274
- } catch {
3275
- return null;
3276
- }
3277
- };
3278
- for (const name of [
3279
- "comments.json",
3280
- "plans.json",
3281
- "pr-session.json"
3282
- ]) {
3283
- const file = join(projectDir, name);
3284
- if (!existsSync(file)) continue;
3285
- const m = await safeStat(file);
3286
- if (m !== null) candidates.push(m);
3287
- }
3288
- const attachmentsDir = join(projectDir, "attachments");
3289
- if (existsSync(attachmentsDir)) {
3290
- const dirM = await safeStat(attachmentsDir);
3291
- if (dirM !== null) candidates.push(dirM);
3292
- try {
3293
- for (const file of await readdir(attachmentsDir)) {
3294
- const m = await safeStat(join(attachmentsDir, file));
3295
- if (m !== null) candidates.push(m);
3296
- }
3297
- } catch {}
3298
- }
3299
- return candidates.length ? Math.max(...candidates) : null;
3300
- }
3301
- async function cleanupStaleProjects() {
3302
- const baseDir = join(homedir(), ".diffing");
3303
- if (!existsSync(baseDir)) return;
3304
- try {
3305
- const entries = await readdir(baseDir, { withFileTypes: true });
3306
- const now = Date.now();
3307
- const STALE_TIME = 336 * 60 * 60 * 1e3;
3308
- for (const entry of entries) if (entry.isDirectory()) {
3309
- const projectDir = join(baseDir, entry.name);
3310
- const repoPathFile = join(projectDir, "repo_path.txt");
3311
- let shouldDelete = false;
3312
- if (existsSync(repoPathFile)) try {
3313
- const repoPath = (await readFile(repoPathFile, "utf-8")).trim();
3314
- if (!repoPath || !existsSync(repoPath)) shouldDelete = true;
3315
- } catch {}
3316
- if (!shouldDelete) {
3317
- const newest = await newestActivityMs(projectDir);
3318
- if (newest !== null && now - newest > STALE_TIME) shouldDelete = true;
3319
- }
3320
- if (shouldDelete) await rm(projectDir, {
3321
- recursive: true,
3322
- force: true
3323
- });
3324
- }
3325
- } catch (err) {
3326
- console.error("Failed to cleanup stale projects:", err);
3327
- }
3328
- }
3329
- async function startServer(options) {
3330
- cleanupStaleProjects().catch((err) => {
3331
- console.error("Failed to clean up stale projects:", err);
3332
- });
3333
- let prMode = false;
3334
- if (options.prRef) {
3335
- console.error(`Building PR session for ${options.prRef}...`);
3336
- try {
3337
- const store = new FilePrSessionStore();
3338
- const existing = await store.get();
3339
- if (!existing || existing.ref !== options.prRef) {
3340
- const session = await buildPrSession(options.prRef);
3341
- await store.set(session);
3342
- }
3343
- prMode = true;
3344
- } catch (err) {
3345
- console.error(`[pr-session] failed to build session for ${options.prRef}: ${err?.message ?? err}`);
3346
- }
3347
- }
3348
- const app = createApp(options.clientDir, options.diffOpts, void 0, void 0, void 0, prMode);
3349
- return new Promise((resolve) => {
3350
- serve({
3351
- fetch: app.fetch,
3352
- port: options.port,
3353
- hostname: options.host
3354
- }, (info) => {
3355
- resolve({
3356
- port: info.port,
3357
- prMode
3358
- });
3359
- });
3360
- });
3361
- }
3362
- //#endregion
3363
11
  //#region src/lib/startup-display.ts
3364
12
  const R = "\x1B[0m";
3365
13
  const B = "\x1B[1m";
@@ -3817,11 +465,53 @@ if (new Set([
3817
465
  "gh"
3818
466
  ]).has(args[0])) {
3819
467
  if (args[0] === "mcp") {
3820
- const { startMcpServer } = await import("./mcp-DNZQvKKF.mjs");
3821
- await startMcpServer();
468
+ const mcpArgs = args.slice(1);
469
+ if (mcpArgs.includes("--help") || mcpArgs.includes("-h")) {
470
+ console.log(`Usage: diffing mcp [--repo <absolute-path>]
471
+
472
+ Run diffing as a local stdio MCP server bound to one Git repository.
473
+
474
+ Options:
475
+ --repo <path> Bind to this absolute Git repository path.
476
+ If omitted, the Git repository containing the current directory is used.
477
+ -h, --help Show this help.`);
478
+ process.exit(0);
479
+ }
480
+ let repoPath;
481
+ for (let index = 0; index < mcpArgs.length; index += 1) {
482
+ const arg = mcpArgs[index];
483
+ if (arg === "--repo") {
484
+ const value = mcpArgs[index + 1];
485
+ if (!value || value.startsWith("-")) {
486
+ console.error("diffing mcp: --repo requires an absolute path");
487
+ process.exit(5);
488
+ }
489
+ if (repoPath !== void 0) {
490
+ console.error("diffing mcp: --repo may be specified only once");
491
+ process.exit(5);
492
+ }
493
+ repoPath = value;
494
+ index += 1;
495
+ } else if (arg.startsWith("--repo=")) {
496
+ if (repoPath !== void 0) {
497
+ console.error("diffing mcp: --repo may be specified only once");
498
+ process.exit(5);
499
+ }
500
+ repoPath = arg.slice(7);
501
+ } else {
502
+ console.error(`diffing mcp: unknown option ${arg}`);
503
+ process.exit(5);
504
+ }
505
+ }
506
+ if (repoPath !== void 0 && !isAbsolute(repoPath)) {
507
+ console.error("diffing mcp: --repo must be an absolute path");
508
+ process.exit(5);
509
+ }
510
+ const { startMcpServer } = await import("./mcp-B6mCC7D3.mjs");
511
+ await startMcpServer({ repoPath });
3822
512
  await new Promise(() => {});
3823
513
  }
3824
- const { runSubcommand } = await import("./cli-agent-B4hU6Xay.mjs");
514
+ const { runSubcommand } = await import("./cli-agent-CKE1Cvor.mjs");
3825
515
  process.exit(await runSubcommand(args[0], args.slice(1)));
3826
516
  }
3827
517
  let showSubcommand = false;
@@ -3864,7 +554,7 @@ const __pkgDir = dirname(fileURLToPath(import.meta.url));
3864
554
  const currentVersion = JSON.parse(readFileSync(resolve(__pkgDir, "..", "package.json"), "utf-8")).version;
3865
555
  const updateCheckPromise = (async () => {
3866
556
  try {
3867
- const { checkForUpdates } = await import("./update-check-DAPFCqpF.mjs");
557
+ const { checkForUpdates } = await import("./update-check-CXeSZANo.mjs");
3868
558
  return await checkForUpdates(currentVersion);
3869
559
  } catch {
3870
560
  return null;
@@ -3873,21 +563,38 @@ const updateCheckPromise = (async () => {
3873
563
  const port = await getPort(opts.port ? { port: opts.port } : void 0);
3874
564
  const host = opts.host;
3875
565
  const clientDir = resolve(__pkgDir, "client");
3876
- const { port: actualPort, prMode } = await startServer({
3877
- port,
3878
- host,
3879
- clientDir: existsSync(clientDir) ? clientDir : resolve(process.cwd(), "dist/client"),
3880
- diffOpts: opts,
3881
- prRef: prRef ?? void 0
3882
- });
3883
- const localUrl = `http://${host}:${actualPort}`;
566
+ const resolvedClientDir = existsSync(clientDir) ? clientDir : resolve(process.cwd(), "dist/client");
567
+ let repoRoot;
3884
568
  try {
3885
- let repoRoot;
3886
- try {
3887
- repoRoot = getRepoRoot();
3888
- } catch {
3889
- repoRoot = process.cwd();
3890
- }
569
+ repoRoot = getRepoRoot();
570
+ } catch {
571
+ repoRoot = process.cwd();
572
+ }
573
+ const sessionOwnerId = randomUUID();
574
+ const startupLease = acquireServerStartupLease(repoRoot, sessionOwnerId);
575
+ if (!startupLease) {
576
+ console.error("Another diffing process is starting a review for this repository. Retry in a moment.");
577
+ process.exit(3);
578
+ }
579
+ const existingLock = readServerLock(repoRoot);
580
+ if (existingLock && isLockAlive(existingLock, repoRoot)) {
581
+ startupLease.release();
582
+ const existingUrl = existingLock.port > 0 ? `http://${existingLock.host}:${existingLock.port}` : "a TUI session";
583
+ console.error(`A diffing review is already running for this repository at ${existingUrl}. End it before starting another scope.`);
584
+ process.exit(3);
585
+ }
586
+ let actualPort;
587
+ let prMode;
588
+ try {
589
+ const started = await startServer({
590
+ port,
591
+ host,
592
+ clientDir: resolvedClientDir,
593
+ diffOpts: opts,
594
+ prRef: prRef ?? void 0
595
+ });
596
+ actualPort = started.port;
597
+ prMode = started.prMode;
3891
598
  writeServerLock({
3892
599
  port: actualPort,
3893
600
  host,
@@ -3896,15 +603,24 @@ try {
3896
603
  startedAt: Date.now(),
3897
604
  version: currentVersion,
3898
605
  mode: prMode ? "gh-pr" : "web",
3899
- prRef: prMode ? prRef ?? void 0 : void 0
3900
- });
3901
- } catch {}
606
+ prRef: prMode ? prRef ?? void 0 : void 0,
607
+ scope: diffScopeKey(opts),
608
+ ownerId: sessionOwnerId
609
+ });
610
+ } catch (error) {
611
+ startupLease.release();
612
+ const detail = error instanceof Error ? error.message : String(error);
613
+ console.error(`Failed to start diffing review safely: ${detail}`);
614
+ process.exit(1);
615
+ }
616
+ startupLease.release();
617
+ const localUrl = `http://${host}:${actualPort}`;
3902
618
  console.log(`diffing server running at ${localUrl}`);
3903
619
  await playStartupDisplay();
3904
620
  try {
3905
621
  const updateInfo = await updateCheckPromise;
3906
622
  if (updateInfo?.hasUpdate) {
3907
- const { printUpdateDisclaimer } = await import("./update-check-DAPFCqpF.mjs");
623
+ const { printUpdateDisclaimer } = await import("./update-check-CXeSZANo.mjs");
3908
624
  printUpdateDisclaimer(currentVersion, updateInfo.latestVersion);
3909
625
  }
3910
626
  } catch {}
@@ -3919,7 +635,7 @@ if (!opts.noOpen) {
3919
635
  }
3920
636
  const shutdown = () => {
3921
637
  console.log("\nShutting down...");
3922
- removeServerLock();
638
+ removeServerLockIfOwned(repoRoot, process.pid, sessionOwnerId);
3923
639
  process.exit(0);
3924
640
  };
3925
641
  process.on("SIGINT", shutdown);