diffing 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/README.md +52 -18
  2. package/dist/{cli-agent-D71pq2ep.mjs → cli-agent-CLrK54k2.mjs} +2 -2
  3. package/dist/{cli-gh-D5OCnjNe.mjs → cli-gh-8YC1NzyM.mjs} +6 -1
  4. package/dist/cli.mjs +3 -3
  5. package/dist/client/assets/{angular-html-Dh86jUvr.js → angular-html-DdAR2u-k.js} +1 -1
  6. package/dist/client/assets/{angular-ts-Bh4wRJtT.js → angular-ts-Dz_vWKSu.js} +1 -1
  7. package/dist/client/assets/{apl-BSXBHduT.js → apl-BJ5QXrIk.js} +1 -1
  8. package/dist/client/assets/{arc-CRQlhBrV.js → arc-D9erSW6x.js} +1 -1
  9. package/dist/client/assets/{architectureDiagram-3BPJPVTR-BXq3UvEv.js → architectureDiagram-3BPJPVTR-CCQWZLXR.js} +1 -1
  10. package/dist/client/assets/{astro-Bh00klUw.js → astro-BQAej5a5.js} +1 -1
  11. package/dist/client/assets/{blade-CisA3zhm.js → blade-DkAmuwDx.js} +1 -1
  12. package/dist/client/assets/{blockDiagram-GPEHLZMM-Bw-PTAJr.js → blockDiagram-GPEHLZMM-vwjxNybI.js} +1 -1
  13. package/dist/client/assets/{c-D-pHVWrf.js → c-DG5p-ChJ.js} +1 -1
  14. package/dist/client/assets/{c4Diagram-AAUBKEIU-C0XyiqC_.js → c4Diagram-AAUBKEIU-DJ_hVlh4.js} +1 -1
  15. package/dist/client/assets/channel-DmZgR6r0.js +1 -0
  16. package/dist/client/assets/{chunk-2J33WTMH-DekjZXNj.js → chunk-2J33WTMH-CiLowxCo.js} +1 -1
  17. package/dist/client/assets/{chunk-3OPIFGDE-BtROpcL8.js → chunk-3OPIFGDE-H3jjMR5Y.js} +1 -1
  18. package/dist/client/assets/{chunk-4BX2VUAB-C92XLTlx.js → chunk-4BX2VUAB-Dk0dk4n5.js} +1 -1
  19. package/dist/client/assets/{chunk-55IACEB6-CceUgh8N.js → chunk-55IACEB6-nbLiUMJS.js} +1 -1
  20. package/dist/client/assets/{chunk-5ZQYHXKU-DSbYPAe7.js → chunk-5ZQYHXKU-DZ8RgHg8.js} +1 -1
  21. package/dist/client/assets/{chunk-727SXJPM-DVzUJa-9.js → chunk-727SXJPM-DDe5dqJV.js} +1 -1
  22. package/dist/client/assets/{chunk-AQP2D5EJ-6n3Z_IFa.js → chunk-AQP2D5EJ-DmpNclOr.js} +1 -1
  23. package/dist/client/assets/{chunk-BSJP7CBP-BgVLnkxr.js → chunk-BSJP7CBP-BKQKvtIj.js} +1 -1
  24. package/dist/client/assets/{chunk-CSCIHK7Q-CkGMXntp.js → chunk-CSCIHK7Q-D27t4cyv.js} +1 -1
  25. package/dist/client/assets/{chunk-FMBD7UC4-BM8lrLBo.js → chunk-FMBD7UC4-Bu3LA663.js} +1 -1
  26. package/dist/client/assets/{chunk-KSCS5N6A-Bm2pjMQg.js → chunk-KSCS5N6A-Ed5HNXRW.js} +1 -1
  27. package/dist/client/assets/{chunk-L5ZTLDWV-VL17ikXM.js → chunk-L5ZTLDWV-DLjJZgf8.js} +1 -1
  28. package/dist/client/assets/{chunk-LZXEDZCA-B629g67M.js → chunk-LZXEDZCA-B-cs89SM.js} +2 -2
  29. package/dist/client/assets/{chunk-ND2GUHAM-CjZGwhKA.js → chunk-ND2GUHAM-D_kPSuUA.js} +1 -1
  30. package/dist/client/assets/{chunk-NZK2D7GU-DGsLjESY.js → chunk-NZK2D7GU-D1u3pjq-.js} +1 -1
  31. package/dist/client/assets/{chunk-O5CBEL6O-EyUrGY3l.js → chunk-O5CBEL6O-Mt0cnPSf.js} +1 -1
  32. package/dist/client/assets/chunk-QZHKN3VN-BrYnBs7h.js +1 -0
  33. package/dist/client/assets/chunk-WU5MYG2G-CdBcsQs_.js +1 -0
  34. package/dist/client/assets/{chunk-XPW4576I-C2TeAQmQ.js → chunk-XPW4576I-Bt8a8x28.js} +1 -1
  35. package/dist/client/assets/classDiagram-4FO5ZUOK-CCpp3t5M.js +1 -0
  36. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-B1aV1sYb.js +1 -0
  37. package/dist/client/assets/{cobol-DsRZMP16.js → cobol-Daidj_5Y.js} +1 -1
  38. package/dist/client/assets/{coffee-DP0-MMsE.js → coffee-DUMdB2Cr.js} +1 -1
  39. package/dist/client/assets/{cose-bilkent-S5V4N54A-DMmK0b0W.js → cose-bilkent-S5V4N54A-DVUDLXie.js} +1 -1
  40. package/dist/client/assets/{cpp-B6XYbbze.js → cpp-C2FeX1Mc.js} +1 -1
  41. package/dist/client/assets/{crystal-dBLPFLMp.js → crystal-D4yb9blJ.js} +1 -1
  42. package/dist/client/assets/{css-tgwuSZL0.js → css-B5cr0U9F.js} +1 -1
  43. package/dist/client/assets/{dagre-BM42HDAG-CgNkf0TR.js → dagre-BM42HDAG-DdZWb-Ee.js} +1 -1
  44. package/dist/client/assets/{diagram-2AECGRRQ-ocAqn0LV.js → diagram-2AECGRRQ-C9DOZt92.js} +1 -1
  45. package/dist/client/assets/{diagram-5GNKFQAL-CB1Yo4Gc.js → diagram-5GNKFQAL-Bbc07UKr.js} +1 -1
  46. package/dist/client/assets/{diagram-KO2AKTUF-B2vpMBRT.js → diagram-KO2AKTUF-C-lUzY3m.js} +1 -1
  47. package/dist/client/assets/{diagram-LMA3HP47-DuxZOaQS.js → diagram-LMA3HP47-D-OjEFhp.js} +1 -1
  48. package/dist/client/assets/{diagram-OG6HWLK6-CkShDmcv.js → diagram-OG6HWLK6-BjtWGvrf.js} +1 -1
  49. package/dist/client/assets/{dist-BgZIvk5w.js → dist-BXZygPdX.js} +1 -1
  50. package/dist/client/assets/{edge-Bokubn8E.js → edge-RCQWcWNp.js} +1 -1
  51. package/dist/client/assets/{elixir-BEzcf3Xg.js → elixir-DwKyVg2X.js} +1 -1
  52. package/dist/client/assets/{elm-vJyLTAER.js → elm-DjR33IVs.js} +1 -1
  53. package/dist/client/assets/{erDiagram-TEJ5UH35-BFV1NQAH.js → erDiagram-TEJ5UH35-C5T4ywLG.js} +1 -1
  54. package/dist/client/assets/{erb-DDkAmjBS.js → erb-BnhUH1Hk.js} +1 -1
  55. package/dist/client/assets/{flowDiagram-I6XJVG4X-DU8xbFdO.js → flowDiagram-I6XJVG4X-BJmjm7Kx.js} +1 -1
  56. package/dist/client/assets/{ganttDiagram-6RSMTGT7-DCb7Qh0c.js → ganttDiagram-6RSMTGT7-DREPnzu5.js} +1 -1
  57. package/dist/client/assets/{git-rebase-DWcifAdK.js → git-rebase-DzXoSDXA.js} +1 -1
  58. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-C_Tw-piE.js → gitGraphDiagram-PVQCEYII-DIR4G_-_.js} +1 -1
  59. package/dist/client/assets/{glimmer-js--HDru5ys.js → glimmer-js-HKnZpCn_.js} +1 -1
  60. package/dist/client/assets/{glimmer-ts-DAdXisHh.js → glimmer-ts-DedV7rWs.js} +1 -1
  61. package/dist/client/assets/{glsl-CmIRlJht.js → glsl-Bz-0Alp2.js} +1 -1
  62. package/dist/client/assets/{graphql-tx4-7I3U.js → graphql-DSKkDYCD.js} +1 -1
  63. package/dist/client/assets/{hack-yA0XjhF7.js → hack-CnaHZm8k.js} +1 -1
  64. package/dist/client/assets/{haml-BR5MUE1b.js → haml-huGFYKlj.js} +1 -1
  65. package/dist/client/assets/{handlebars-BPOF7iOf.js → handlebars-CKmgzfWY.js} +1 -1
  66. package/dist/client/assets/{html-BbteRk96.js → html-B9Ih_dUU.js} +1 -1
  67. package/dist/client/assets/{html-derivative-59NNrcMm.js → html-derivative-YabD-M5d.js} +1 -1
  68. package/dist/client/assets/{http-D3odGQI4.js → http-Bdu12JYX.js} +1 -1
  69. package/dist/client/assets/{hurl-BLTj8fPj.js → hurl-twZzDTNs.js} +1 -1
  70. package/dist/client/assets/{index-DHXpO7eS.js → index-BktdZRWB.js} +122 -118
  71. package/dist/client/assets/{index-BZcKS8Sb.css → index-YlwaPTSG.css} +1 -1
  72. package/dist/client/assets/{infoDiagram-5YYISTIA-CI6hJyRl.js → infoDiagram-5YYISTIA-D2ty2R-i.js} +1 -1
  73. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-gMS1P1LQ.js → ishikawaDiagram-YF4QCWOH-Ccnc9xlE.js} +1 -1
  74. package/dist/client/assets/{java-CsViuzs_.js → java-_5trO-p9.js} +1 -1
  75. package/dist/client/assets/{javascript-DQgsl2Dh.js → javascript-BOQn0ikE.js} +1 -1
  76. package/dist/client/assets/{jinja-DQNp2NUA.js → jinja-BgY-0IBz.js} +1 -1
  77. package/dist/client/assets/{jison-CDDOZQdc.js → jison-BLNTmT1_.js} +1 -1
  78. package/dist/client/assets/{journeyDiagram-JHISSGLW-BTQ_Ws_h.js → journeyDiagram-JHISSGLW-W7eWXlw0.js} +1 -1
  79. package/dist/client/assets/{json-DP4TqCuE.js → json-BLbH8rZf.js} +1 -1
  80. package/dist/client/assets/{jsx-Df5hn0Tf.js → jsx-CxteptsJ.js} +1 -1
  81. package/dist/client/assets/{julia--u33yGLi.js → julia-B__Ncp_z.js} +1 -1
  82. package/dist/client/assets/{just-BCpMmSOD.js → just-DBsHUGW1.js} +1 -1
  83. package/dist/client/assets/{kanban-definition-UN3LZRKU-CvqGbLR_.js → kanban-definition-UN3LZRKU-Z_AFL-rd.js} +1 -1
  84. package/dist/client/assets/{latex-D8D4jZGw.js → latex-DFF_0wxo.js} +1 -1
  85. package/dist/client/assets/{line-DBgaS_RW.js → line-aAv8TyOs.js} +1 -1
  86. package/dist/client/assets/{linear-RQVzKNVU.js → linear-BOvEZKH8.js} +1 -1
  87. package/dist/client/assets/{liquid-CkH85f12.js → liquid-kDWCO6d7.js} +1 -1
  88. package/dist/client/assets/{lua-iKoV7WE3.js → lua-CYTFayq-.js} +1 -1
  89. package/dist/client/assets/{marko-N8ScQSqT.js → marko-Dpmz3Pdx.js} +1 -1
  90. package/dist/client/assets/{mdc-BvHTOxsp.js → mdc-BsxHyM1i.js} +1 -1
  91. package/dist/client/assets/{mermaid-parser.core-CwDRwMR7.js → mermaid-parser.core-D8z_CWL1.js} +1 -1
  92. package/dist/client/assets/{mermaid.core-D2LDJgXO.js → mermaid.core-DNKchnly.js} +3 -3
  93. package/dist/client/assets/{mindmap-definition-RKZ34NQL-FRnPh642.js → mindmap-definition-RKZ34NQL-xQKMV4Kw.js} +1 -1
  94. package/dist/client/assets/{nginx-DGgvASuI.js → nginx-CcdTDme-.js} +1 -1
  95. package/dist/client/assets/{nim-D-v9hzvR.js → nim-B5wWDskL.js} +1 -1
  96. package/dist/client/assets/{perl-CG8leJ8K.js → perl-Ce2_iKLz.js} +1 -1
  97. package/dist/client/assets/{php-DvkeSP10.js → php-DuLCFERd.js} +1 -1
  98. package/dist/client/assets/{pieDiagram-4H26LBE5-CepOg38Y.js → pieDiagram-4H26LBE5-CBSCJnUr.js} +1 -1
  99. package/dist/client/assets/{pug-B4T7-xaL.js → pug-BfQJoQj1.js} +1 -1
  100. package/dist/client/assets/{qml-BE6D5Bxn.js → qml-DYeovlVl.js} +1 -1
  101. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-DOFAsP60.js → quadrantDiagram-W4KKPZXB-uEcgb0Rm.js} +1 -1
  102. package/dist/client/assets/{r-BKZg9Mcq.js → r-DgHSP56L.js} +1 -1
  103. package/dist/client/assets/{razor-D-02oaxL.js → razor-B00x7W-i.js} +1 -1
  104. package/dist/client/assets/{regexp-BDFvAR1k.js → regexp-CmWVupmd.js} +1 -1
  105. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BBVNH-2W.js → requirementDiagram-4Y6WPE33-Q4yY_ALe.js} +1 -1
  106. package/dist/client/assets/{review-export-D5iIl46_.js → review-export-pcqDKNqx.js} +1 -1
  107. package/dist/client/assets/{rst-BcT26OSj.js → rst-B3VARbTX.js} +1 -1
  108. package/dist/client/assets/{ruby-Cq_YQvFT.js → ruby-CaxKSSbT.js} +1 -1
  109. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-BQfCTbBX.js → sankeyDiagram-5OEKKPKP-B-GLzFGa.js} +1 -1
  110. package/dist/client/assets/{sas-DN9oTxKY.js → sas-Ue0rHUIk.js} +1 -1
  111. package/dist/client/assets/{scss-BK_sp3z2.js → scss-BJJ7_L6c.js} +1 -1
  112. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CKAW2eyx.js → sequenceDiagram-3UESZ5HK-DW0em0D_.js} +1 -1
  113. package/dist/client/assets/{shellscript-CvNpOu0J.js → shellscript-C6LkZs1u.js} +1 -1
  114. package/dist/client/assets/{shellsession-8-yj2cJj.js → shellsession-CkZu1e84.js} +1 -1
  115. package/dist/client/assets/{soy-C6Q9atPF.js → soy-CDaZV57J.js} +1 -1
  116. package/dist/client/assets/{sql-CBL3BuHb.js → sql-CLfMGH4x.js} +1 -1
  117. package/dist/client/assets/{src-D-VUWIK5.js → src-C27zxuNO.js} +1 -1
  118. package/dist/client/assets/{stata-B2Q7Vqzu.js → stata-B0kNMHc9.js} +1 -1
  119. package/dist/client/assets/{stateDiagram-AJRCARHV-BGJiv0qO.js → stateDiagram-AJRCARHV-CrO_D3m4.js} +1 -1
  120. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-C9KDGD7R.js +1 -0
  121. package/dist/client/assets/{surrealql-C-A2N8vk.js → surrealql-D9os_yZO.js} +1 -1
  122. package/dist/client/assets/{svelte-VAut_-uy.js → svelte-2SxVToeO.js} +1 -1
  123. package/dist/client/assets/{templ-mUetM--K.js → templ-DzmZB67T.js} +1 -1
  124. package/dist/client/assets/{tex-BT53mWGp.js → tex-BMPk3nHk.js} +1 -1
  125. package/dist/client/assets/{timeline-definition-PNZ67QCA-lVwMt1rk.js → timeline-definition-PNZ67QCA-C9FBevHv.js} +1 -1
  126. package/dist/client/assets/{ts-tags-VkIOkgLN.js → ts-tags-CG14Bplc.js} +1 -1
  127. package/dist/client/assets/{tsx-D_aaGHTf.js → tsx-D6NK461A.js} +1 -1
  128. package/dist/client/assets/{twig-CufwqKkk.js → twig-Agh0j5sD.js} +1 -1
  129. package/dist/client/assets/{typescript-osFD2CEV.js → typescript-_AkeziZ2.js} +1 -1
  130. package/dist/client/assets/{vennDiagram-CIIHVFJN-_K9NtpA5.js → vennDiagram-CIIHVFJN-2H9HfhhR.js} +1 -1
  131. package/dist/client/assets/{vue-Bub1rXmL.js → vue-C1z3QGG9.js} +1 -1
  132. package/dist/client/assets/{vue-html-CN3x2pYg.js → vue-html-C1RMzLZk.js} +1 -1
  133. package/dist/client/assets/{vue-vine-C0csYkGm.js → vue-vine-oOixA6ge.js} +1 -1
  134. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-B2jTMfra.js → wardleyDiagram-YWT4CUSO-BJxrQhTf.js} +1 -1
  135. package/dist/client/assets/{xml-my6OjeGb.js → xml-okuDZ7vq.js} +1 -1
  136. package/dist/client/assets/{xsl-Bx0YVn26.js → xsl-S_n3XrKb.js} +1 -1
  137. package/dist/client/assets/{xychartDiagram-2RQKCTM6-DfZ4YYXU.js → xychartDiagram-2RQKCTM6-BGdee7KG.js} +1 -1
  138. package/dist/client/assets/{yaml-DanwOypk.js → yaml-BoX-kqX1.js} +1 -1
  139. package/dist/client/index.html +2 -2
  140. package/dist/{doctor-q6oA64hm.mjs → doctor-CmP0u7-d.mjs} +1 -1
  141. package/dist/github-BjZZcSKV.mjs +2 -0
  142. package/dist/{github-HfIlIS-J.mjs → github-oCZx5aim.mjs} +270 -29
  143. package/dist/{mcp-eor39qmD.mjs → mcp-CqxXILYL.mjs} +1 -1
  144. package/dist/{server-C105rwQw.mjs → server-CczuXSWo.mjs} +164 -11
  145. package/package.json +3 -3
  146. package/dist/cli-agent-B4hU6Xay.mjs +0 -499
  147. package/dist/cli-agent-B_PHd635.mjs +0 -499
  148. package/dist/cli-agent-BatQgghr.mjs +0 -499
  149. package/dist/cli-agent-BkkRbKqq.mjs +0 -513
  150. package/dist/cli-agent-BlMtx1Tx.mjs +0 -736
  151. package/dist/cli-agent-BwZE05CQ.mjs +0 -499
  152. package/dist/cli-agent-C4Fb90GL.mjs +0 -728
  153. package/dist/cli-agent-CKE1Cvor.mjs +0 -513
  154. package/dist/cli-agent-CLvCYpmH.mjs +0 -499
  155. package/dist/cli-agent-CX8Fa1Ph.mjs +0 -499
  156. package/dist/cli-agent-ChALuNbw.mjs +0 -841
  157. package/dist/cli-agent-KxNAFIPf.mjs +0 -450
  158. package/dist/cli-agent-SILzesQP.mjs +0 -513
  159. package/dist/cli-agent-USzLoAit.mjs +0 -499
  160. package/dist/cli-agent-qBT8clNM.mjs +0 -841
  161. package/dist/cli-gh-6qiblgj7.mjs +0 -150
  162. package/dist/cli-gh-BV5az425.mjs +0 -147
  163. package/dist/cli-gh-Bo6fOHQR.mjs +0 -147
  164. package/dist/cli-gh-CDGSpndZ.mjs +0 -147
  165. package/dist/cli-gh-D1LoWJl-.mjs +0 -147
  166. package/dist/cli-gh-D1sIZ-jX.mjs +0 -147
  167. package/dist/cli-gh-DROAJlHi.mjs +0 -147
  168. package/dist/cli-gh-DgqscIkg.mjs +0 -147
  169. package/dist/cli-gh-DiT8BWwu.mjs +0 -147
  170. package/dist/cli-gh-KjPnyST6.mjs +0 -150
  171. package/dist/cli-gh-abs-IJrz.mjs +0 -147
  172. package/dist/client/assets/channel-CDxgOu-3.js +0 -1
  173. package/dist/client/assets/chunk-QZHKN3VN-DJCeMpP8.js +0 -1
  174. package/dist/client/assets/chunk-WU5MYG2G-BbuOkMaH.js +0 -1
  175. package/dist/client/assets/classDiagram-4FO5ZUOK-D5oJbiED.js +0 -1
  176. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-5MJt5ZxQ.js +0 -1
  177. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-CdUgMghp.js +0 -1
  178. package/dist/comment-format-CKTt0fzi.mjs +0 -113
  179. package/dist/comment-format-DG_PAehC.mjs +0 -117
  180. package/dist/github-C9GLNak7.mjs +0 -2
  181. package/dist/mcp-7eXATtez.mjs +0 -1334
  182. package/dist/mcp-B6mCC7D3.mjs +0 -1047
  183. package/dist/mcp-BBk8AIO4.mjs +0 -1334
  184. package/dist/mcp-BJxrW9dS.mjs +0 -1334
  185. package/dist/mcp-BMTZLQuB.mjs +0 -758
  186. package/dist/mcp-BUF2nEL7.mjs +0 -1036
  187. package/dist/mcp-BWeWR4yd.mjs +0 -255
  188. package/dist/mcp-BgZO-iXI.mjs +0 -1047
  189. package/dist/mcp-BhT5GgYF.mjs +0 -1334
  190. package/dist/mcp-Bpx76OGU.mjs +0 -945
  191. package/dist/mcp-BsGdNA88.mjs +0 -1334
  192. package/dist/mcp-BxBm3d5l.mjs +0 -1047
  193. package/dist/mcp-C1T7LI0H.mjs +0 -1036
  194. package/dist/mcp-C4Bjmf9m.mjs +0 -1047
  195. package/dist/mcp-CFxcdEcJ.mjs +0 -733
  196. package/dist/mcp-Ca9QAlJ0.mjs +0 -1334
  197. package/dist/mcp-CphIUJUg.mjs +0 -1047
  198. package/dist/mcp-CtKRXQRC.mjs +0 -1047
  199. package/dist/mcp-CwjThGi2.mjs +0 -913
  200. package/dist/mcp-D4OsB9lt.mjs +0 -1047
  201. package/dist/mcp-DJ2batvt.mjs +0 -913
  202. package/dist/mcp-DNZQvKKF.mjs +0 -298
  203. package/dist/mcp-DO4zfNZX.mjs +0 -298
  204. package/dist/mcp-D_LGvBTw.mjs +0 -1047
  205. package/dist/mcp-Ds_lPX_o.mjs +0 -913
  206. package/dist/plan-format-B6nbAw_c.mjs +0 -132
  207. package/dist/plan-format-Bi46QS0m.mjs +0 -132
  208. package/dist/plan-format-DVnF8xrq.mjs +0 -126
  209. package/dist/plan-format-f62JWFI-.mjs +0 -117
  210. package/dist/plan-format-mSDtsPcC.mjs +0 -132
  211. package/dist/review-export-BoV0884M.mjs +0 -66
  212. package/dist/review-export-CKTI5Od_.mjs +0 -66
  213. package/dist/server-95UE5bgh.mjs +0 -3367
  214. package/dist/server-AisDKkpW.mjs +0 -3227
  215. package/dist/server-B0cS95Lf.mjs +0 -3488
  216. package/dist/server-BUsRhL1B.mjs +0 -3283
  217. package/dist/server-BZBFquG8.mjs +0 -3875
  218. package/dist/server-Bc2m9R5-.mjs +0 -3263
  219. package/dist/server-Bj-6KlK5.mjs +0 -3367
  220. package/dist/server-Bmt57wV5.mjs +0 -3875
  221. package/dist/server-Bpf84Il0.mjs +0 -3367
  222. package/dist/server-C15WRRnS.mjs +0 -3740
  223. package/dist/server-CYSpLbdA.mjs +0 -3360
  224. package/dist/server-ChT2DCaR.mjs +0 -3701
  225. package/dist/server-D0Ni8PKP.mjs +0 -3252
  226. package/dist/server-D2xEbakj.mjs +0 -3874
  227. package/dist/server-DJxysGxV.mjs +0 -3701
  228. package/dist/server-Dov7jbV3.mjs +0 -3367
  229. package/dist/server-TOElOuNP.mjs +0 -3258
  230. package/dist/server-eQ2E4Axo.mjs +0 -3367
  231. package/dist/server-lock-C_wPtEsH.mjs +0 -909
  232. package/dist/server-lock-Cbu3qHdu.mjs +0 -924
  233. package/dist/server-lock-D32inEn9.mjs +0 -924
  234. package/dist/server-lock-D73NKKbn.mjs +0 -842
  235. package/dist/server-lock-DaSx7DjW.mjs +0 -1049
  236. package/dist/server-lock-Ddcat0HF.mjs +0 -851
  237. package/dist/server-lock-Dj9fG9md.mjs +0 -838
  238. package/dist/server-lock-Dq_1CJaF.mjs +0 -1047
  239. package/dist/server-lock-Ujbcgq28.mjs +0 -954
  240. package/dist/update-check-CXeSZANo.mjs +0 -129
  241. package/dist/update-check-DAPFCqpF.mjs +0 -129
@@ -1,3258 +0,0 @@
1
- import { C as isSafePath, S as revertHunk, _ as getUntrackedFilePathsAsync, a as getCustomGitDiffAsync, b as listRepoFiles, c as getGitDiffAsync, d as getProjectStorageDir, f as getRepoName, g as getTabSizeForFiles, h as getShowDiff, i as getCommitSeriesSummary, l as getHunkHistory, o as getFileContent, p as getRepoRoot, r as getBranchName, u as getMergeStatus, v as gitAddFile, w as toSafeRelativePath, y as isGitRepo } from "./git-Czo96ymM.mjs";
2
- import { a as searchContent, c as trackSelection, i as searchAll, n as saveSettings, o as searchFiles, r as getSearchStatus, s as searchSymbols, t as loadSettings } from "./settings-BVnzGFL7.mjs";
3
- import { t as formatComments } from "./comment-format-CKTt0fzi.mjs";
4
- import { n as formatPlanReview, r as sectionTitleForLine, t as extractPlanLines } from "./plan-format-Bi46QS0m.mjs";
5
- import { f as refreshPrSession, i as detectCwdRepo, m as submitReview, t as buildPrSession, u as parsePrRef } from "./github-HfIlIS-J.mjs";
6
- import { execFileSync } from "node:child_process";
7
- import { fileURLToPath } from "node:url";
8
- import { dirname, extname, join, resolve } from "node:path";
9
- import { existsSync, mkdirSync, readFileSync, watch } from "node:fs";
10
- import { parseArgs } from "node:util";
11
- import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
12
- import { homedir } from "node:os";
13
- import { Hono } from "hono";
14
- import { streamSSE } from "hono/streaming";
15
- import { serve } from "@hono/node-server";
16
- //#region src/lib/diff-options.ts
17
- const DEFAULTS = {
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
- noRenames: false,
46
- base: false,
47
- ours: false,
48
- theirs: false,
49
- check: false,
50
- outputMode: "auto",
51
- host: "127.0.0.1",
52
- noOpen: false,
53
- help: false,
54
- version: false,
55
- includeUnstaged: true,
56
- includeUntracked: true,
57
- tui: false,
58
- gpu: false,
59
- showMode: false,
60
- showRevspecs: []
61
- };
62
- /**
63
- * All git-diff option definitions for `node:util.parseArgs`.
64
- * Categorised to match `git diff --help`.
65
- */
66
- const GIT_DIFF_OPTIONS = {
67
- staged: { type: "boolean" },
68
- cached: { type: "boolean" },
69
- merge: { type: "boolean" },
70
- "diff-algorithm": { type: "string" },
71
- "indent-heuristic": {
72
- type: "boolean",
73
- default: true
74
- },
75
- "no-indent-heuristic": { type: "boolean" },
76
- anchored: { type: "string" },
77
- "ignore-space-change": {
78
- type: "boolean",
79
- short: "b"
80
- },
81
- "ignore-all-space": {
82
- type: "boolean",
83
- short: "w"
84
- },
85
- "ignore-blank-lines": { type: "boolean" },
86
- "ignore-cr-at-eol": { type: "boolean" },
87
- "ws-error-highlight": { type: "string" },
88
- "unified": {
89
- type: "string",
90
- short: "U"
91
- },
92
- "inter-hunk-context": { type: "string" },
93
- "function-context": {
94
- type: "boolean",
95
- short: "W"
96
- },
97
- "word-diff": { type: "string" },
98
- "word-diff-regex": { type: "string" },
99
- "color-words": { type: "string" },
100
- "color-moved": { type: "string" },
101
- "color-moved-ws": { type: "string" },
102
- "find-copies": {
103
- type: "string",
104
- short: "C"
105
- },
106
- "find-copies-harder": { type: "boolean" },
107
- "find-renames": {
108
- type: "string",
109
- short: "M"
110
- },
111
- "break-rewrites": {
112
- type: "string",
113
- short: "B"
114
- },
115
- "no-renames": { type: "boolean" },
116
- patch: {
117
- type: "boolean",
118
- short: "p"
119
- },
120
- "no-patch": {
121
- type: "boolean",
122
- short: "s"
123
- },
124
- raw: { type: "boolean" },
125
- "patch-with-raw": { type: "boolean" },
126
- "patch-with-stat": { type: "boolean" },
127
- numstat: { type: "boolean" },
128
- shortstat: { type: "boolean" },
129
- stat: { type: "string" },
130
- summary: { type: "boolean" },
131
- "name-only": { type: "boolean" },
132
- "name-status": { type: "boolean" },
133
- check: { type: "boolean" },
134
- "compact-summary": { type: "boolean" },
135
- dirstat: { type: "string" },
136
- "dirstat-by-file": { type: "string" },
137
- cumulative: { type: "boolean" },
138
- "diff-filter": { type: "string" },
139
- S: { type: "string" },
140
- G: { type: "string" },
141
- "pickaxe-all": { type: "boolean" },
142
- output: {
143
- type: "string",
144
- short: "o"
145
- },
146
- "exit-code": { type: "boolean" },
147
- quiet: { type: "boolean" },
148
- "src-prefix": { type: "string" },
149
- "dst-prefix": { type: "string" },
150
- "no-prefix": { type: "boolean" },
151
- "line-prefix": { type: "string" },
152
- submodule: { type: "string" },
153
- binary: { type: "boolean" },
154
- "no-binary": { type: "boolean" },
155
- "full-index": { type: "boolean" },
156
- text: {
157
- type: "boolean",
158
- short: "a"
159
- },
160
- textconv: { type: "boolean" },
161
- "no-textconv": { type: "boolean" },
162
- "no-ext-diff": { type: "boolean" },
163
- "ext-diff": { type: "string" },
164
- "ita-visible": { type: "boolean" },
165
- "ita-invisible-in-index": { type: "boolean" },
166
- relative: { type: "string" },
167
- "no-relative": { type: "boolean" },
168
- "ignore-submodules": { type: "string" },
169
- base: { type: "boolean" },
170
- ours: { type: "boolean" },
171
- theirs: { type: "boolean" }
172
- };
173
- /** Options that are diffing-specific, not git-diff options. */
174
- const DIFFING_OPTIONS = {
175
- port: { type: "string" },
176
- host: { type: "string" },
177
- "no-open": {
178
- type: "boolean",
179
- default: false
180
- },
181
- web: {
182
- type: "boolean",
183
- default: false
184
- },
185
- terminal: {
186
- type: "boolean",
187
- default: false
188
- },
189
- tui: {
190
- type: "boolean",
191
- default: false
192
- },
193
- gpu: {
194
- type: "boolean",
195
- default: false
196
- },
197
- "gh-pr": { type: "string" },
198
- help: {
199
- type: "boolean",
200
- short: "h"
201
- },
202
- version: { type: "boolean" }
203
- };
204
- function getVersion() {
205
- try {
206
- const __dirname = dirname(fileURLToPath(import.meta.url));
207
- return JSON.parse(readFileSync(resolve(__dirname, "..", "..", "package.json"), "utf-8")).version;
208
- } catch {
209
- return "unknown";
210
- }
211
- }
212
- function printHelp() {
213
- const version = getVersion();
214
- console.log(`diffing v${version} – Local code review tool for git diffs
215
-
216
- Usage: diffing [<git diff options>] [<revision>...] [-- <path>...]
217
- diffing --web [<git diff options>] [<revision>...] [-- <path>...]
218
- diffing [server options]
219
-
220
- Git Diff Options (drop-in replacement for git diff):`);
221
- printGitDiffHelp();
222
- console.log(`
223
- Diffing Server Options:
224
- --port <port> Port to run the server on (default: random available port)
225
- --host <host> Host address to bind to (default: 127.0.0.1). Pass
226
- 0.0.0.0 to expose the server to the local network.
227
- --no-open Don't open the browser automatically
228
-
229
- Output Modes:
230
- By default diffing auto-selects the best output mode:
231
- - Terminal mode: when output is a pipe, redirect, or non-TTY
232
- - Web mode: when output is a TTY (interactive terminal)
233
-
234
- Force a mode with --web, --terminal, or --tui flags.
235
- --tui is experimental and opt-in. It opens a native-Rust terminal
236
- interface that mirrors the web dashboard. Falls back to git diff
237
- output if the environment cannot support a TUI (piped stdin, CI,
238
- missing binary).
239
-
240
- Subcommands:
241
- show <revspec>... Drop-in for 'git show'. Renders commit metadata
242
- (subject, author, date, message body) above the
243
- diff in the web UI. Accepts single commits,
244
- ranges (a..b, a...b), tags, and multiple SHAs.
245
- Use '--' to separate revspecs from pathspecs.
246
-
247
- Custom ranges (e.g. main..feature) and 'gh pr' sessions also display a
248
- "what is this diff" banner in the web UI summarising the diff source.
249
-
250
- Examples:
251
- diffing Review uncommitted changes (web UI)
252
- diffing --staged Review staged changes
253
- diffing HEAD~3 Review last 3 commits
254
- diffing main..feature Compare branches
255
- diffing show HEAD Review a single commit's metadata + diff
256
- diffing show HEAD~3..HEAD Review the last 3 commits as a series
257
- diffing show HEAD -- src/ Limit a commit review to a directory
258
- diffing --diff-algorithm=patience src/ Diff with patience algorithm
259
- diffing -U10 Diff with 10 context lines
260
- diffing --word-diff=color Word-level diff in color
261
- diffing -b -w Ignore whitespace changes
262
- diffing --host 0.0.0.0 Allow other machines on the LAN to review
263
- diffing --tui Open the experimental TUI (native Rust)
264
-
265
- Note: 'diffing <sha>' runs 'git diff <sha>' (working tree vs <sha>); it
266
- is not the same as 'diffing show <sha>'. Use 'show' when you want to
267
- review a commit's changes.`);
268
- }
269
- function printGitDiffHelp() {
270
- console.log(`
271
- Revision / Range:
272
- --staged, --cached Show staged changes
273
- --merge Show merge conflicts
274
-
275
- Diff Algorithm:
276
- --diff-algorithm=<A> Choose diff algorithm (minimal, patience, histogram, myers)
277
- --indent-heuristic Enable indent heuristic (default: on)
278
- --no-indent-heuristic Disable indent heuristic
279
- --anchored=<TEXT> Anchor diff algorithm to <TEXT>
280
-
281
- Whitespace:
282
- -b, --ignore-space-change Ignore changes in amount of whitespace
283
- -w, --ignore-all-space Ignore whitespace when comparing lines
284
- --ignore-blank-lines Ignore blank lines
285
- --ignore-cr-at-eol Ignore carriage-return at EOL
286
- --ws-error-highlight=<KIND> Highlight whitespace errors (none, default, all)
287
-
288
- Context:
289
- -U<n>, --unified=<n> Generate diffs with <n> lines of context
290
- --inter-hunk-context=<n> Show <n> lines between diff hunks
291
- -W, --function-context Show whole function as context
292
-
293
- Word Diff:
294
- --word-diff=<MODE> Word diff (color, plain, porcelain, none)
295
- --word-diff-regex=<REGEX> Regex to determine a word
296
- --color-words[=<REGEX>] Word diff with color
297
-
298
- Moved / Copied Detection:
299
- --color-moved=<MODE> Color moved lines (no, default, plain, blocks, zebra, dimmed-zebra)
300
- --color-moved-ws=<MODE> How whitespace is treated in --color-moved
301
- -C[<n>], --find-copies[=<n>] Detect copies
302
- --find-copies-harder Spend extra cycles to find copies
303
- -M[<n>], --find-renames[=<n>] Detect renames
304
- -B[<n>], --break-rewrites[=<n>] Break complete rewrite changes into delete/add pairs
305
- --no-renames Turn off rename detection
306
-
307
- Merge / Conflict:
308
- --base Compare with merge base (stage 1)
309
- --ours Compare with our branch (stage 2)
310
- --theirs Compare with their branch (stage 3)
311
-
312
- Output Format:
313
- -p, --patch Generate patch (default)
314
- -s, --no-patch Suppress diff output
315
- --raw Generate raw diff
316
- --patch-with-raw Both patch and raw output
317
- --patch-with-stat Both patch and stat
318
- --numstat Machine-friendly stat: additions/deletions per file
319
- --shortstat Summary of additions/deletions
320
- --stat[=<width>] Diffstat with graph
321
- --summary Extended header summary
322
- --name-only Show only names of changed files
323
- --name-status Show only names and status of changed files
324
- --check Check if diff introduces whitespace errors
325
- --compact-summary Compact summary for submodule changes
326
- --dirstat[=<param>] Directory-level change stats
327
- --dirstat-by-file[=<param>] Per-file directory stats
328
- --cumulative Cumulative directory stats
329
-
330
- Filtering:
331
- --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]]
332
- -S<string> Look for differences that change number of occurrences of <string>
333
- -G<regex> Look for differences whose patch text contains <regex>
334
- --pickaxe-all Show all changes with -S or -G
335
-
336
- Output Control:
337
- -o, --output=<file> Write diff to <file>
338
- --exit-code Exit with 1 if differences, 0 if not
339
- --quiet Disable all output, imply --exit-code
340
-
341
- Prefixes:
342
- --src-prefix=<PREFIX> Source prefix (default: "a/")
343
- --dst-prefix=<PREFIX> Destination prefix (default: "b/")
344
- --no-prefix Do not show source/destination prefixes
345
- --line-prefix=<PREFIX> Prepend <PREFIX> to every line
346
-
347
- Submodule:
348
- --submodule=<FORMAT> Submodule diff format (diff, log, short)
349
-
350
- Miscellaneous:
351
- --binary Output binary diff (apply patch to binary files)
352
- --no-binary Don't output binary diff
353
- --full-index Show full blob object names
354
- -a, --text Treat all files as text
355
- --textconv Allow external text conversion filters
356
- --no-textconv Disallow external text conversion filters
357
- --no-ext-diff Disallow external diff drivers
358
- --ext-diff=<CMD> Allow external diff driver
359
- --ita-visible Include intent-to-add files
360
- --ignore-submodules=<WHEN> Ignore submodule changes
361
- --relative[=<path>] Show changes relative to <path>
362
- --no-relative Don't show relative paths`);
363
- }
364
- /**
365
- * Pre-process argv to handle git's optional-value flags.
366
- *
367
- * `-C`, `-M`, `-B` and their long forms (`--find-copies`, `--find-renames`,
368
- * `--break-rewrites`) take an **optional** numeric argument in git — when the
369
- * value is omitted, git uses the default similarity threshold (40%, 50%, 50%
370
- * respectively for `-B`'s percentage component, 60% for the `x` part of
371
- * `Bx/y`). `node:util.parseArgs` always consumes the next token as the value
372
- * for `type: 'string'`, which means `diffing -C main..feature` would
373
- * swallow `main..feature` as the `-C` value instead of treating it as a
374
- * revision.
375
- *
376
- * This function rewrites the input argv so that:
377
- * - `-C` (no attached value) followed by a non-digit → `--find-copies=40`
378
- * - `-C` (no attached value) followed by a digit → left as-is so
379
- * parseArgs consumes
380
- * the numeric value
381
- * - `-C40` (attached value) → left as-is
382
- * - `--find-copies` (no value) followed by a digit → `--find-copies=<n>`
383
- * - `--find-copies=40` (attached value) → left as-is
384
- *
385
- * The defaults mirror git's own behaviour: 40, 50, 50/60.
386
- */
387
- function preprocessOptionalValueArgs(rawArgs) {
388
- const SHORTS = {
389
- C: {
390
- long: "find-copies",
391
- def: "40"
392
- },
393
- M: {
394
- long: "find-renames",
395
- def: "50"
396
- },
397
- B: {
398
- long: "break-rewrites",
399
- def: "50/60"
400
- }
401
- };
402
- const LONGS = new Set([
403
- "find-copies",
404
- "find-renames",
405
- "break-rewrites"
406
- ]);
407
- const startsWithDigit = (s) => typeof s === "string" && /^[0-9]/.test(s);
408
- const out = [];
409
- for (let i = 0; i < rawArgs.length; i++) {
410
- const arg = rawArgs[i];
411
- if (arg.length === 2 && arg[0] === "-" && SHORTS[arg[1]]) {
412
- const cfg = SHORTS[arg[1]];
413
- const next = rawArgs[i + 1];
414
- if (startsWithDigit(next)) out.push(arg);
415
- else out.push(`--${cfg.long}=${cfg.def}`);
416
- continue;
417
- }
418
- const longMatch = /^--(find-copies|find-renames|break-rewrites)$/.exec(arg);
419
- if (longMatch) {
420
- const name = longMatch[1];
421
- if (!LONGS.has(name)) {
422
- out.push(arg);
423
- continue;
424
- }
425
- const next = rawArgs[i + 1];
426
- if (startsWithDigit(next)) {
427
- out.push(`--${name}=${next}`);
428
- i++;
429
- } else {
430
- const def = name === "find-copies" ? "40" : name === "find-renames" ? "50" : "50/60";
431
- out.push(`--${name}=${def}`);
432
- }
433
- continue;
434
- }
435
- out.push(arg);
436
- }
437
- return out;
438
- }
439
- /**
440
- * Parse raw `process.argv` slice into typed DiffOptions.
441
- *
442
- * Strategy:
443
- * 1. Pre-process optional-value args (`-C`, `-M`, `-B`, long forms) so they
444
- * don't swallow following revisions like `main..feature`.
445
- * 2. Split argv into: [diffing options] [git revisions] [-- pathspecs]
446
- * 3. Parse known flags via node:util.parseArgs
447
- * 4. Anything unknown / positional becomes a revision or pathspec
448
- */
449
- function parseDiffOptions(rawArgs) {
450
- const { values, positionals } = parseArgs({
451
- options: {
452
- ...GIT_DIFF_OPTIONS,
453
- ...DIFFING_OPTIONS
454
- },
455
- allowPositionals: true,
456
- strict: false,
457
- args: preprocessOptionalValueArgs(rawArgs)
458
- });
459
- const opts = {
460
- ...DEFAULTS,
461
- revisions: [],
462
- pathspecs: [],
463
- showRevspecs: []
464
- };
465
- if (values.help) opts.help = true;
466
- if (values.version) opts.version = true;
467
- if (values.port) opts.port = parseInt(values.port, 10);
468
- if (values.host) opts.host = values.host;
469
- if (values["no-open"]) opts.noOpen = true;
470
- if (values["gh-pr"]) opts.ghPr = String(values["gh-pr"]);
471
- if (values.staged || values.cached) opts.staged = true;
472
- if (values.merge) opts.merge = true;
473
- const algo = values["diff-algorithm"];
474
- if (algo && [
475
- "minimal",
476
- "patience",
477
- "histogram",
478
- "myers"
479
- ].includes(algo)) opts.algorithm = algo;
480
- if (values["no-indent-heuristic"]) {
481
- opts.noIndentHeuristic = true;
482
- opts.indentHeuristic = false;
483
- }
484
- if (values.anchored) opts.anchored = values.anchored;
485
- if (values["ignore-space-change"]) opts.ignoreSpaceChange = true;
486
- if (values["ignore-all-space"]) opts.ignoreAllSpace = true;
487
- if (values["ignore-blank-lines"]) opts.ignoreBlankLines = true;
488
- if (values["ignore-cr-at-eol"]) opts.ignoreCrAtEol = true;
489
- const wsh = values["ws-error-highlight"];
490
- if (wsh && [
491
- "none",
492
- "default",
493
- "all"
494
- ].includes(wsh)) opts.wsErrorHighlight = wsh;
495
- if (values.unified) opts.unifiedContext = parseInt(values.unified, 10);
496
- if (values["inter-hunk-context"]) opts.interHunkContext = parseInt(values["inter-hunk-context"], 10);
497
- if (values["function-context"]) opts.functionContext = true;
498
- const wd = values["word-diff"];
499
- if (wd && [
500
- "color",
501
- "plain",
502
- "porcelain",
503
- "none"
504
- ].includes(wd)) opts.wordDiff = wd;
505
- if (values["word-diff-regex"]) opts.wordDiffRegex = values["word-diff-regex"];
506
- if (values["color-words"]) {
507
- opts.wordDiff = "color";
508
- opts.wordDiffRegex = values["color-words"] || void 0;
509
- }
510
- const cm = values["color-moved"];
511
- if (cm && [
512
- "default",
513
- "plain",
514
- "blocks",
515
- "zebra",
516
- "dimmed-zebra",
517
- "no"
518
- ].includes(cm)) opts.colorMoved = cm;
519
- const cmw = values["color-moved-ws"];
520
- if (cmw && [
521
- "no",
522
- "ignore-space-at-eol",
523
- "ignore-space-change",
524
- "ignore-all-space",
525
- "allow-indentation-change"
526
- ].includes(cmw)) opts.colorMovedWs = cmw;
527
- if (values["find-copies"] !== void 0) {
528
- const v = values["find-copies"];
529
- opts.findCopies = v ? parseInt(v, 10) : 40;
530
- }
531
- if (values["find-copies-harder"]) opts.findCopiesHarder = true;
532
- if (values["find-renames"] !== void 0) {
533
- const v = values["find-renames"];
534
- opts.findRenames = v ? parseInt(v, 10) : 50;
535
- }
536
- if (values["break-rewrites"] !== void 0) opts.breakRewrites = values["break-rewrites"];
537
- if (values["no-renames"]) opts.noRenames = true;
538
- if (values.base) opts.base = true;
539
- if (values.ours) opts.ours = true;
540
- if (values.theirs) opts.theirs = true;
541
- if (values.raw) opts.outputFormat = "raw";
542
- if (values.numstat) opts.outputFormat = "numstat";
543
- if (values.shortstat) opts.outputFormat = "shortstat";
544
- if (values.stat !== void 0) opts.outputFormat = "stat";
545
- if (values.summary) opts.outputFormat = "summary";
546
- if (values["name-only"]) opts.outputFormat = "name-only";
547
- if (values["name-status"]) opts.outputFormat = "name-status";
548
- if (values["patch-with-raw"]) opts.patchWithRaw = true;
549
- if (values["patch-with-stat"]) opts.patchWithStat = true;
550
- if (values["compact-summary"]) opts.compactSummary = true;
551
- if (values.dirstat) opts.dirstat = values.dirstat;
552
- if (values["dirstat-by-file"]) opts.dirstatByFile = values["dirstat-by-file"];
553
- if (values.cumulative) opts.cumulative = true;
554
- if (values["no-patch"]) opts.outputFormat = void 0;
555
- if (values.check) opts.outputFormat = void 0;
556
- if (values["diff-filter"]) opts.diffFilter = values["diff-filter"];
557
- if (values.S) opts.pickaxeString = values.S;
558
- if (values.G) opts.pickaxeRegex = values.G;
559
- if (values["pickaxe-all"]) opts.pickaxeAll = true;
560
- if (values.output) opts.outputFile = values.output;
561
- if (values["exit-code"]) opts.exitCode = true;
562
- if (values.quiet) {
563
- opts.quiet = true;
564
- opts.exitCode = true;
565
- }
566
- if (values["src-prefix"]) opts.srcPrefix = values["src-prefix"];
567
- if (values["dst-prefix"]) opts.dstPrefix = values["dst-prefix"];
568
- if (values["no-prefix"]) opts.noPrefix = true;
569
- if (values["line-prefix"]) opts.linePrefix = values["line-prefix"];
570
- const sm = values.submodule;
571
- if (sm && [
572
- "diff",
573
- "log",
574
- "short"
575
- ].includes(sm)) opts.submodule = sm;
576
- if (values.binary) opts.binary = true;
577
- if (values["no-binary"]) opts.binary = false;
578
- if (values["full-index"]) opts.fullIndex = true;
579
- if (values.text) opts.text = true;
580
- if (values.textconv) opts.textconv = true;
581
- if (values["no-textconv"]) opts.textconv = false;
582
- if (values["no-ext-diff"]) opts.noExtDiff = true;
583
- if (values["ext-diff"]) opts.extDiff = values["ext-diff"];
584
- if (values["ita-visible"] || values["ita-invisible-in-index"]) opts.itaVisible = true;
585
- if (values.relative !== void 0) opts.relative = values.relative || void 0;
586
- if (values["no-relative"]) opts.noRelative = true;
587
- if (values["ignore-submodules"]) {
588
- const ig = values["ignore-submodules"];
589
- if ([
590
- "none",
591
- "untracked",
592
- "dirty",
593
- "all"
594
- ].includes(ig)) opts.ignoreSubmodules = ig;
595
- }
596
- const dashDashIdx = rawArgs.indexOf("--");
597
- if (dashDashIdx >= 0) {
598
- for (let i = 0; i < dashDashIdx; i++) {
599
- const arg = rawArgs[i];
600
- if (!arg.startsWith("-")) opts.revisions.push(arg);
601
- }
602
- for (let i = dashDashIdx + 1; i < rawArgs.length; i++) opts.pathspecs.push(rawArgs[i]);
603
- } else for (const p of positionals) opts.revisions.push(p);
604
- if (values.tui) opts.outputMode = "tui";
605
- else if (values.web) opts.outputMode = "web";
606
- else if (values.terminal) opts.outputMode = "terminal";
607
- if (process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "web";
608
- else if (!process.stdout.isTTY && opts.outputMode === "auto") opts.outputMode = "terminal";
609
- if (opts.outputFormat || opts.patchWithRaw || opts.patchWithStat || opts.exitCode || opts.quiet || opts.outputFile) opts.outputMode = "terminal";
610
- return opts;
611
- }
612
- /**
613
- * Build the `git diff` argument array from parsed options.
614
- * Returns args that can be spread into `git diff <args>`.
615
- */
616
- function buildGitDiffArgs(opts) {
617
- const args = [];
618
- if (opts.algorithm) args.push(`--diff-algorithm=${opts.algorithm}`);
619
- if (opts.noIndentHeuristic) args.push("--no-indent-heuristic");
620
- if (opts.anchored) args.push(`--anchored=${opts.anchored}`);
621
- if (opts.staged) args.push("--staged");
622
- if (opts.merge) args.push("--merge");
623
- if (opts.base) args.push("--base");
624
- if (opts.ours) args.push("--ours");
625
- if (opts.theirs) args.push("--theirs");
626
- if (opts.ignoreSpaceChange) args.push("--ignore-space-change");
627
- if (opts.ignoreAllSpace) args.push("--ignore-all-space");
628
- if (opts.ignoreBlankLines) args.push("--ignore-blank-lines");
629
- if (opts.ignoreCrAtEol) args.push("--ignore-cr-at-eol");
630
- if (opts.wsErrorHighlight) args.push(`--ws-error-highlight=${opts.wsErrorHighlight}`);
631
- if (opts.unifiedContext !== void 0) args.push(`--unified=${opts.unifiedContext}`);
632
- if (opts.interHunkContext !== void 0) args.push(`--inter-hunk-context=${opts.interHunkContext}`);
633
- if (opts.functionContext) args.push("--function-context");
634
- if (opts.wordDiff) if (opts.wordDiff === "color" && opts.wordDiffRegex && !opts.colorWords) {
635
- args.push(`--word-diff=color`);
636
- args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
637
- } else if (opts.wordDiff === "color" && opts.colorWords) args.push(`--color-words=${opts.wordDiffRegex || "."}`);
638
- else args.push(`--word-diff=${opts.wordDiff}`);
639
- if (opts.wordDiffRegex && opts.wordDiff !== "color") args.push(`--word-diff-regex=${opts.wordDiffRegex}`);
640
- if (opts.colorMoved) args.push(`--color-moved=${opts.colorMoved}`);
641
- if (opts.colorMovedWs) args.push(`--color-moved-ws=${opts.colorMovedWs}`);
642
- if (opts.findCopies !== void 0) args.push(opts.findCopies === 40 ? "-C" : `-C${opts.findCopies}`);
643
- if (opts.findCopiesHarder) args.push("--find-copies-harder");
644
- if (opts.findRenames !== void 0) args.push(opts.findRenames === 50 ? "-M" : `-M${opts.findRenames}`);
645
- if (opts.breakRewrites !== void 0) args.push(`-B${opts.breakRewrites}`);
646
- if (opts.noRenames) args.push("--no-renames");
647
- if (opts.outputFormat === "raw") args.push("--raw");
648
- if (opts.outputFormat === "numstat") args.push("--numstat");
649
- if (opts.outputFormat === "shortstat") args.push("--shortstat");
650
- if (opts.outputFormat === "stat") args.push("--stat");
651
- if (opts.outputFormat === "summary") args.push("--summary");
652
- if (opts.outputFormat === "name-only") args.push("--name-only");
653
- if (opts.outputFormat === "name-status") args.push("--name-status");
654
- if (opts.patchWithRaw) args.push("--patch-with-raw");
655
- if (opts.patchWithStat) args.push("--patch-with-stat");
656
- if (opts.compactSummary) args.push("--compact-summary");
657
- if (opts.dirstat) args.push(`--dirstat=${opts.dirstat}`);
658
- if (opts.dirstatByFile) args.push(`--dirstat-by-file=${opts.dirstatByFile}`);
659
- if (opts.cumulative) args.push("--cumulative");
660
- if (opts.check) args.push("--check");
661
- if (opts.diffFilter) args.push(`--diff-filter=${opts.diffFilter}`);
662
- if (opts.pickaxeString) args.push(`-S${opts.pickaxeString}`);
663
- if (opts.pickaxeRegex) args.push(`-G${opts.pickaxeRegex}`);
664
- if (opts.pickaxeAll) args.push("--pickaxe-all");
665
- if (opts.outputFile) args.push(`--output=${opts.outputFile}`);
666
- if (opts.exitCode) args.push("--exit-code");
667
- if (opts.quiet) args.push("--quiet");
668
- if (opts.srcPrefix) args.push(`--src-prefix=${opts.srcPrefix}`);
669
- if (opts.dstPrefix) args.push(`--dst-prefix=${opts.dstPrefix}`);
670
- if (opts.noPrefix) args.push("--no-prefix");
671
- if (opts.linePrefix) args.push(`--line-prefix=${opts.linePrefix}`);
672
- if (opts.submodule) args.push(`--submodule=${opts.submodule}`);
673
- if (opts.binary) args.push("--binary");
674
- if (opts.fullIndex) args.push("--full-index");
675
- if (opts.text) args.push("--text");
676
- if (opts.textconv) args.push("--textconv");
677
- if (opts.noExtDiff) args.push("--no-ext-diff");
678
- if (opts.extDiff) args.push(`--ext-diff=${opts.extDiff}`);
679
- if (opts.itaVisible) args.push("--ita-visible");
680
- if (opts.relative !== void 0) args.push(opts.relative ? `--relative=${opts.relative}` : "--relative");
681
- if (opts.noRelative) args.push("--no-relative");
682
- if (opts.ignoreSubmodules) args.push(`--ignore-submodules=${opts.ignoreSubmodules}`);
683
- for (const rev of opts.revisions) args.push(rev);
684
- if (opts.pathspecs.length > 0) {
685
- args.push("--");
686
- args.push(...opts.pathspecs);
687
- }
688
- return args;
689
- }
690
- /**
691
- * Transform a `parseDiffOptions(...)` result into a "show mode" variant:
692
- * moves any parsed revisions into `showRevspecs`, clears `revisions` (so the
693
- * existing diff-engine path does not try to `git diff` them), and sets the
694
- * `showMode` flag. Pathspecs and every other flag survive unchanged.
695
- *
696
- * Returns the same object for callsite ergonomics — the mutation is in-place
697
- * because `parseDiffOptions` always returns a fresh object.
698
- */
699
- function intoShowMode(opts) {
700
- opts.showRevspecs = opts.revisions;
701
- opts.revisions = [];
702
- opts.showMode = true;
703
- return opts;
704
- }
705
- //#endregion
706
- //#region src/lib/diff-overview.ts
707
- /**
708
- * Compose the working-tree banner. Used by the default `git diff` (unstaged +
709
- * optionally staged + optionally untracked) flow.
710
- */
711
- function buildWorkingTreeOverview(input) {
712
- const { branch, staged, untracked, untrackedCount, fileCount } = input;
713
- const fileLabel = fileCount === 1 ? "file" : "files";
714
- const headline = `Working-tree changes${branch ? ` on ${branch}` : ""}`;
715
- const parts = [`${fileCount} ${fileLabel} changed`];
716
- if (staged) parts.push("staged included");
717
- if (untracked) {
718
- const u = untrackedCount === 1 ? "1 untracked file" : `${untrackedCount} untracked files`;
719
- parts.push(u);
720
- }
721
- return {
722
- kind: "working-tree",
723
- headline,
724
- subtitle: parts.join(" · "),
725
- commitSubjects: [],
726
- commitCount: 0,
727
- truncated: 0,
728
- authors: []
729
- };
730
- }
731
- /**
732
- * Staged-only banner: only `--staged` is on, no untracked, no revisions.
733
- * Shown when the user reviews a clean staging area.
734
- */
735
- function buildStagedOnlyOverview(input) {
736
- const { branch, fileCount } = input;
737
- const fileLabel = fileCount === 1 ? "file" : "files";
738
- return {
739
- kind: "staged-only",
740
- headline: `Staged changes${branch ? ` on ${branch}` : ""}`,
741
- subtitle: `${fileCount} ${fileLabel} staged for commit`,
742
- commitSubjects: [],
743
- commitCount: 0,
744
- truncated: 0,
745
- authors: []
746
- };
747
- }
748
- /**
749
- * Range banner: user-supplied revisions like `main..feature`, `HEAD~3..HEAD`,
750
- * or multiple SHAs/tags. `revspecs` are joined into the `rangeLabel` verbatim
751
- * (preserving `..` / `...` form the user typed).
752
- */
753
- function buildRangeOverview(input) {
754
- const { revspecs, branch, commitSeries } = input;
755
- const rangeLabel = revspecs.join(" ");
756
- const { commitCount, truncated, subjects, authors, fromDate, toDate } = summariseCommitSeries(commitSeries);
757
- const plural = commitCount === 1 ? "commit" : "commits";
758
- return {
759
- kind: "range",
760
- headline: `Comparing ${rangeLabel}${branch ? ` (current: ${branch})` : ""}`,
761
- subtitle: truncated > 0 ? `${commitCount} of ${commitCount + truncated} ${plural} shown` : `${commitCount} ${plural}`,
762
- commitSubjects: subjects,
763
- commitCount,
764
- truncated,
765
- fromDate,
766
- toDate,
767
- authors,
768
- rangeLabel
769
- };
770
- }
771
- /**
772
- * Commit banner: invoked by `diffing show <rev>` — single SHA or series. The
773
- * kind branches on `commits.length` so a single-commit review gets a tighter
774
- * headline than a series.
775
- */
776
- function buildCommitOverview(input) {
777
- const { commits, truncated, rangeLabel } = input;
778
- const { commitCount, subjects, authors, fromDate, toDate } = summariseCommitRows(commits);
779
- const isSingle = commitCount === 1;
780
- const kind = isSingle ? "commit-single" : "commit-series";
781
- let headline;
782
- let subtitle;
783
- if (isSingle) {
784
- headline = subjects[0] ? `Commit: ${subjects[0]}` : "Single commit";
785
- const subParts = [];
786
- if (rangeLabel) subParts.push(rangeLabel);
787
- if (authors[0]) subParts.push(authors[0]);
788
- if (fromDate) subParts.push(formatDateShort(fromDate));
789
- if (truncated > 0) subParts.push(`${commitCount} of ${commitCount + truncated} commits shown`);
790
- subtitle = subParts.length > 0 ? subParts.join(" · ") : void 0;
791
- } else {
792
- const plural = "commits";
793
- headline = `Reviewing ${commitCount} ${plural}`;
794
- const subParts = [];
795
- if (rangeLabel) subParts.push(rangeLabel);
796
- if (authors.length > 0) subParts.push(authors.join(", "));
797
- if (fromDate && toDate) subParts.push(`${formatDateShort(fromDate)} – ${formatDateShort(toDate)}`);
798
- if (truncated > 0) subParts.push(`${commitCount} of ${commitCount + truncated} ${plural} shown`);
799
- subtitle = subParts.length > 0 ? subParts.join(" · ") : void 0;
800
- }
801
- return {
802
- kind,
803
- headline,
804
- subtitle,
805
- commitSubjects: subjects,
806
- commitCount,
807
- truncated,
808
- fromDate,
809
- toDate,
810
- authors,
811
- rangeLabel
812
- };
813
- }
814
- function formatDateShort(iso) {
815
- try {
816
- const d = new Date(iso);
817
- if (Number.isNaN(d.getTime())) return iso;
818
- return d.toLocaleDateString(void 0, {
819
- year: "numeric",
820
- month: "short",
821
- day: "numeric"
822
- });
823
- } catch {
824
- return iso;
825
- }
826
- }
827
- /**
828
- * PR banner: built from fields already in `pr-session.json`. No extra git or
829
- * GitHub calls — the server's PR-mode branch hands us the headline shape and
830
- * we keep the field set minimal so the banner never lies about counts.
831
- */
832
- function buildPrOverview(input) {
833
- const { prNumber, prTitle, prAuthor, additions, deletions } = input;
834
- const subParts = [];
835
- if (prAuthor) subParts.push(`by ${prAuthor}`);
836
- if (additions || deletions) subParts.push(`+${additions} / -${deletions}`);
837
- return {
838
- kind: "pr",
839
- headline: `PR #${prNumber}: ${prTitle}`,
840
- subtitle: subParts.length > 0 ? subParts.join(" · ") : void 0,
841
- commitSubjects: [],
842
- commitCount: 0,
843
- truncated: 0,
844
- authors: prAuthor ? [prAuthor] : [],
845
- prNumber,
846
- prTitle
847
- };
848
- }
849
- /**
850
- * Normalise a list of commit rows for the banner. Aggregates author + date
851
- * ranges and trims subjects past the cap (so the banner never tries to render
852
- * thousands of rows). The caller is responsible for passing the *visible*
853
- * slice; `truncated` is preserved as-is.
854
- */
855
- function summariseCommitRows(rows) {
856
- return summariseCommitSeries({
857
- subjects: rows.map((r) => r.subject),
858
- authors: [],
859
- commitCount: rows.length,
860
- truncated: 0
861
- }, rows);
862
- }
863
- /**
864
- * Internal helper used by both the row-list and the pre-aggregated series
865
- * shape. When the caller already has aggregated metadata, it passes that
866
- * directly; the rows are only used to recover authors + dates if the caller
867
- * didn't supply them.
868
- */
869
- function summariseCommitSeries(series, rows) {
870
- const subjects = series.subjects.filter((s) => s.length > 0);
871
- let authors = series.authors;
872
- let fromDate = series.fromDate;
873
- let toDate = series.toDate;
874
- if (rows && (authors.length === 0 || !fromDate || !toDate)) {
875
- const seen = new Set(authors);
876
- for (const r of rows) {
877
- if (r.author && !seen.has(r.author)) {
878
- seen.add(r.author);
879
- authors = [...authors, r.author];
880
- }
881
- if (r.date) {
882
- if (!fromDate || r.date < fromDate) fromDate = r.date;
883
- if (!toDate || r.date > toDate) toDate = r.date;
884
- }
885
- }
886
- }
887
- return {
888
- commitCount: series.commitCount,
889
- subjects,
890
- authors,
891
- fromDate,
892
- toDate,
893
- truncated: series.truncated
894
- };
895
- }
896
- //#endregion
897
- //#region src/lib/diff-engine.ts
898
- const MAX_BUFFER = 50 * 1024 * 1024;
899
- /**
900
- * Determine whether to use the "standard" web mode (unstaged+staged+untracked)
901
- * or a "custom" mode (specific revisions / pathspecs).
902
- *
903
- * Custom mode is used when the user provides explicit revisions or pathspecs
904
- * beyond just toggling staged/untracked. `showMode` is *also* a custom mode
905
- * — the "Show staged / Show untracked" toggles don't apply to a commit view.
906
- */
907
- function isCustomMode$1(opts) {
908
- return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
909
- }
910
- function parseFilePaths(patch) {
911
- const paths = /* @__PURE__ */ new Set();
912
- for (const line of patch.split("\n")) {
913
- const match = line.match(/^diff --git a\/.+ b\/(.+)$/);
914
- if (match) paths.add(match[1]);
915
- }
916
- return [...paths];
917
- }
918
- function parseBinaryFiles(patch, untrackedFiles) {
919
- const binaryFiles = [];
920
- const lines = patch.split("\n");
921
- for (let i = 0; i < lines.length; i++) {
922
- const line = lines[i];
923
- if (!line.startsWith("Binary files ") || !line.includes(" differ")) continue;
924
- let filePath = "";
925
- for (let j = i - 1; j >= 0; j--) {
926
- const match = lines[j].match(/^diff --git a\/.+ b\/(.+)$/);
927
- if (match) {
928
- filePath = match[1];
929
- break;
930
- }
931
- }
932
- if (!filePath) continue;
933
- let changeType = "changed";
934
- for (let j = i - 1; j >= 0; j--) {
935
- if (lines[j].startsWith("diff --git")) break;
936
- if (lines[j].startsWith("new file mode")) {
937
- changeType = "added";
938
- break;
939
- }
940
- if (lines[j].startsWith("deleted file mode")) {
941
- changeType = "deleted";
942
- break;
943
- }
944
- }
945
- if (changeType === "added" && untrackedFiles?.has(filePath)) changeType = "untracked";
946
- binaryFiles.push({
947
- path: filePath,
948
- type: changeType
949
- });
950
- }
951
- return binaryFiles;
952
- }
953
- /**
954
- * Execute a diff asynchronously — used by the server.
955
- *
956
- * Show mode bypasses the normal `git diff` path entirely: it resolves
957
- * revspecs to a commit list and fetches per-commit metadata + patches in
958
- * one `git log` call. The concatenated patch is returned in the same shape
959
- * the existing UI pipeline expects (so file tree, binary detection, and
960
- * tab-size detection all keep working unchanged); the per-commit data
961
- * rides along on `commits` for the metadata banners.
962
- */
963
- async function executeDiffAsync(opts) {
964
- if (opts.showMode) {
965
- const { commits, patch, truncated } = await getShowDiff(opts.showRevspecs, opts.pathspecs);
966
- return {
967
- patch,
968
- args: [],
969
- commits,
970
- truncated
971
- };
972
- }
973
- if (isCustomMode$1(opts)) {
974
- const args = buildGitDiffArgs(opts);
975
- return {
976
- patch: await getCustomGitDiffAsync(args),
977
- args
978
- };
979
- }
980
- return {
981
- patch: await getGitDiffAsync({
982
- staged: opts.staged,
983
- untracked: opts.includeUntracked
984
- }),
985
- args: []
986
- };
987
- }
988
- /**
989
- * Execute a diff and produce the full enriched result used by the web API.
990
- */
991
- async function executeDiffWithMeta(opts) {
992
- const { patch, commits, truncated } = await executeDiffAsync(opts);
993
- const repoName = getRepoName();
994
- const branch = getBranchName();
995
- const untrackedFiles = opts.includeUntracked && !opts.showMode ? await getUntrackedFilePathsAsync() : [];
996
- const binaryFiles = parseBinaryFiles(patch, new Set(untrackedFiles));
997
- const filePaths = parseFilePaths(patch);
998
- const tabSizeMap = getTabSizeForFiles(filePaths);
999
- let overview;
1000
- if (opts.showMode && commits && commits.length > 0) overview = buildCommitOverview({
1001
- commits: commits.map((c) => ({
1002
- subject: c.subject,
1003
- author: c.authorName,
1004
- date: c.authorDate
1005
- })),
1006
- truncated: truncated ?? 0,
1007
- rangeLabel: deriveShowRangeLabel(opts.showRevspecs)
1008
- });
1009
- else if (!opts.showMode && opts.revisions.length > 0) {
1010
- const series = await getCommitSeriesSummary(opts.revisions, opts.pathspecs);
1011
- overview = buildRangeOverview({
1012
- revspecs: opts.revisions,
1013
- branch,
1014
- commitSeries: {
1015
- subjects: series.subjects,
1016
- authors: series.authors,
1017
- fromDate: series.fromDate,
1018
- toDate: series.toDate,
1019
- commitCount: series.commitCount,
1020
- truncated: series.truncated
1021
- }
1022
- });
1023
- } else if (!opts.showMode && opts.staged && !opts.includeUntracked && opts.revisions.length === 0) overview = buildStagedOnlyOverview({
1024
- branch,
1025
- fileCount: filePaths.length
1026
- });
1027
- else if (!opts.showMode) overview = buildWorkingTreeOverview({
1028
- branch,
1029
- staged: opts.staged,
1030
- untracked: opts.includeUntracked,
1031
- untrackedCount: untrackedFiles.length,
1032
- fileCount: filePaths.length
1033
- });
1034
- return {
1035
- patch,
1036
- binaryFiles,
1037
- filePaths,
1038
- tabSizeMap,
1039
- untrackedFiles,
1040
- repoName,
1041
- branch,
1042
- ...commits ? { commits } : {},
1043
- ...truncated ? { truncated } : {},
1044
- ...overview ? { overview } : {}
1045
- };
1046
- }
1047
- /**
1048
- * Derive a display label for `diffing show` revspecs. Multi-revspecs and
1049
- * range-like expressions (`A..B`, `A...B`) keep their raw form so the banner
1050
- * subtitle tells the reviewer exactly what range is being shown. A plain
1051
- * single SHA/tag is omitted because the headline already names the commit.
1052
- */
1053
- function deriveShowRangeLabel(revspecs) {
1054
- if (revspecs.length === 0) return void 0;
1055
- if (revspecs.length > 1) return revspecs.join(" ");
1056
- const single = revspecs[0];
1057
- if (single && (single.includes("..") || single.includes("..."))) return single;
1058
- }
1059
- /**
1060
- * Run the diff in terminal mode: forward to git diff with full flags,
1061
- * output to stdout. Behaves identically to `git diff`. In show mode this
1062
- * delegates to `git show` instead so `diffing show <rev>... --terminal`
1063
- * is a drop-in for `git show <rev>...`.
1064
- */
1065
- function runTerminalDiff(opts) {
1066
- if (opts.showMode) return runTerminalShow(opts);
1067
- const args = buildGitDiffArgs(opts);
1068
- const enforceDefaults = !opts.outputFormat && !opts.quiet;
1069
- const finalArgs = [];
1070
- if (enforceDefaults) {
1071
- if (!args.includes("--no-ext-diff") && !opts.extDiff) finalArgs.push("--no-ext-diff");
1072
- }
1073
- finalArgs.push(...args);
1074
- try {
1075
- execFileSync("git", ["diff", ...finalArgs], {
1076
- encoding: "utf-8",
1077
- maxBuffer: MAX_BUFFER,
1078
- stdio: "inherit"
1079
- });
1080
- return 0;
1081
- } catch (err) {
1082
- if (err.status === 1 && opts.exitCode) return 1;
1083
- return err.status ?? 1;
1084
- }
1085
- }
1086
- /**
1087
- * Terminal mode for `diffing show`: spawn `git show` with the user's revspecs
1088
- * and pathspecs, inherit stdio, propagate exit code. We pass `--no-ext-diff`
1089
- * so the output is a clean unified diff regardless of the user's git config
1090
- * (matches the web-mode pipeline), but otherwise hand everything to git.
1091
- */
1092
- function runTerminalShow(opts) {
1093
- const args = [
1094
- "show",
1095
- "--no-ext-diff",
1096
- ...opts.showRevspecs
1097
- ];
1098
- if (opts.pathspecs.length > 0) args.push("--", ...opts.pathspecs);
1099
- try {
1100
- execFileSync("git", args, {
1101
- encoding: "utf-8",
1102
- maxBuffer: MAX_BUFFER,
1103
- stdio: "inherit"
1104
- });
1105
- return 0;
1106
- } catch (err) {
1107
- return err.status ?? 1;
1108
- }
1109
- }
1110
- /**
1111
- * Validate the environment: check that we're in a git repo.
1112
- * Returns an error message or null.
1113
- */
1114
- function validateEnvironment() {
1115
- if (!isGitRepo()) return "Error: not inside a git repository";
1116
- return null;
1117
- }
1118
- //#endregion
1119
- //#region src/lib/comments.ts
1120
- var FileCommentStore = class {
1121
- dirPath;
1122
- filePath;
1123
- /**
1124
- * @param storageDir Absolute directory to persist `comments.json` in.
1125
- * Defaults to the per-repo storage dir under `~/.diffing` — comments are
1126
- * NEVER written inside the reviewed (consumer) repo, so a consumer project
1127
- * stays free of any diffing-specific artifacts. The override exists only so
1128
- * tests can point at a throwaway temp dir.
1129
- */
1130
- constructor(storageDir) {
1131
- this.dirPath = storageDir ?? getProjectStorageDir();
1132
- this.filePath = join(this.dirPath, "comments.json");
1133
- }
1134
- async getAll() {
1135
- try {
1136
- const data = await readFile(this.filePath, "utf-8");
1137
- return JSON.parse(data);
1138
- } catch {
1139
- return [];
1140
- }
1141
- }
1142
- async save(comments) {
1143
- try {
1144
- await mkdir(this.dirPath, { recursive: true });
1145
- try {
1146
- const repoRoot = getRepoRoot();
1147
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1148
- } catch {}
1149
- await writeFile(this.filePath, JSON.stringify(comments, null, 2), "utf-8");
1150
- } catch (err) {
1151
- console.error("Failed to save comments to file:", err);
1152
- }
1153
- }
1154
- async add(comment) {
1155
- const comments = await this.getAll();
1156
- comments.push(comment);
1157
- await this.save(comments);
1158
- return comment;
1159
- }
1160
- async update(id, fields) {
1161
- const comments = await this.getAll();
1162
- const index = comments.findIndex((c) => c.id === id);
1163
- if (index === -1) return null;
1164
- const comment = comments[index];
1165
- if (fields.body !== void 0) comment.body = fields.body;
1166
- if (fields.status !== void 0) comment.status = fields.status;
1167
- await this.save(comments);
1168
- return comment;
1169
- }
1170
- async resolveAllOpen() {
1171
- const comments = await this.getAll();
1172
- let n = 0;
1173
- for (const c of comments) if (c.status === "open") {
1174
- c.status = "resolved";
1175
- n++;
1176
- }
1177
- if (n > 0) await this.save(comments);
1178
- return n;
1179
- }
1180
- async remove(id) {
1181
- const comments = await this.getAll();
1182
- const index = comments.findIndex((c) => c.id === id);
1183
- if (index === -1) return false;
1184
- comments.splice(index, 1);
1185
- await this.save(comments);
1186
- return true;
1187
- }
1188
- async addReply(commentId, reply) {
1189
- const comments = await this.getAll();
1190
- const index = comments.findIndex((c) => c.id === commentId);
1191
- if (index === -1) return null;
1192
- const comment = comments[index];
1193
- if (!comment.replies) comment.replies = [];
1194
- comment.replies.push(reply);
1195
- await this.save(comments);
1196
- return comment;
1197
- }
1198
- async removeReply(commentId, replyId) {
1199
- const comments = await this.getAll();
1200
- const index = comments.findIndex((c) => c.id === commentId);
1201
- if (index === -1) return null;
1202
- const comment = comments[index];
1203
- const replyIndex = comment.replies.findIndex((r) => r.id === replyId);
1204
- if (replyIndex === -1) return null;
1205
- comment.replies.splice(replyIndex, 1);
1206
- await this.save(comments);
1207
- return comment;
1208
- }
1209
- async updateReply(commentId, replyId, body) {
1210
- const comments = await this.getAll();
1211
- const index = comments.findIndex((c) => c.id === commentId);
1212
- if (index === -1) return null;
1213
- const comment = comments[index];
1214
- const reply = comment.replies.find((r) => r.id === replyId);
1215
- if (!reply) return null;
1216
- reply.body = body;
1217
- await this.save(comments);
1218
- return comment;
1219
- }
1220
- };
1221
- //#endregion
1222
- //#region src/lib/plans.ts
1223
- /** Absolute path of the persisted markdown mirror for a plan id. */
1224
- function planSourceFilePath(storageDir, planId) {
1225
- return join(storageDir, "plan-sources", `${planId}.md`);
1226
- }
1227
- function newId() {
1228
- return crypto.randomUUID();
1229
- }
1230
- /**
1231
- * Backfill / repair a plan loaded from disk so it matches the current schema.
1232
- * Older persisted plans may be missing `versions` and `createdAtPlanVersion`;
1233
- * we synthesize sensible values so callers can always rely on the new fields.
1234
- */
1235
- function backfillPlan(plan) {
1236
- const currentVersion = plan.version ?? 1;
1237
- const have = Array.isArray(plan.versions) ? plan.versions.length : 0;
1238
- if (!plan.versions || have === 0 || have < currentVersion) {
1239
- const createdAt = plan.updatedAt ?? plan.createdAt ?? Date.now();
1240
- const haveEntries = Array.isArray(plan.versions) ? plan.versions : [];
1241
- const present = new Set(haveEntries.map((v) => v.version));
1242
- const next = [];
1243
- for (let i = 1; i <= currentVersion; i++) {
1244
- const existing = haveEntries.find((v) => v.version === i);
1245
- if (existing) next.push(existing);
1246
- else next.push({
1247
- version: i,
1248
- body: plan.body,
1249
- title: plan.title,
1250
- source: plan.source,
1251
- model: plan.model,
1252
- createdAt
1253
- });
1254
- }
1255
- plan.versions = next.filter((v) => v.version >= 1 && v.version <= currentVersion);
1256
- if (have < currentVersion || !present.has(currentVersion)) markBackfilled(plan);
1257
- }
1258
- if (plan.comments) {
1259
- for (const c of plan.comments) if (typeof c.createdAtPlanVersion !== "number") c.createdAtPlanVersion = plan.version ?? 1;
1260
- }
1261
- if (!plan.comments) plan.comments = [];
1262
- }
1263
- function markBackfilled(plan) {
1264
- plan.__backfilledVersions = true;
1265
- }
1266
- /** Shared mutation helpers so both stores behave identically. */
1267
- function applyUpsert(plans, input, now) {
1268
- if (input.id) {
1269
- const existing = plans.find((p) => p.id === input.id);
1270
- if (existing) {
1271
- existing.title = input.title;
1272
- existing.body = input.body;
1273
- if (input.source !== void 0) existing.source = input.source;
1274
- if (input.model !== void 0) existing.model = input.model;
1275
- existing.version += 1;
1276
- existing.updatedAt = now;
1277
- if (!existing.versions) existing.versions = [];
1278
- existing.versions.push({
1279
- version: existing.version,
1280
- body: existing.body,
1281
- title: existing.title,
1282
- source: existing.source,
1283
- model: existing.model,
1284
- createdAt: now
1285
- });
1286
- existing.decision = "pending";
1287
- existing.decisionComment = void 0;
1288
- existing.decidedAt = void 0;
1289
- return existing;
1290
- }
1291
- }
1292
- const plan = {
1293
- id: input.id || newId(),
1294
- title: input.title,
1295
- body: input.body,
1296
- source: input.source,
1297
- model: input.model,
1298
- createdAt: now,
1299
- updatedAt: now,
1300
- version: 1,
1301
- decision: "pending",
1302
- comments: [],
1303
- versions: [{
1304
- version: 1,
1305
- body: input.body,
1306
- title: input.title,
1307
- source: input.source,
1308
- model: input.model,
1309
- createdAt: now
1310
- }]
1311
- };
1312
- plans.push(plan);
1313
- return plan;
1314
- }
1315
- /**
1316
- * Keep the most-recent `PlanVersion` snapshot in sync with the current `Plan`
1317
- * fields after a non-resubmit edit (PUT). Doesn't add a new entry — that only
1318
- * happens via `upsert` (the resubmit flow).
1319
- */
1320
- function syncCurrentVersion(plan) {
1321
- if (!plan.versions || plan.versions.length === 0) plan.versions = [];
1322
- if (plan.versions.length === 0) {
1323
- plan.versions.push({
1324
- version: plan.version,
1325
- body: plan.body,
1326
- title: plan.title,
1327
- source: plan.source,
1328
- model: plan.model,
1329
- createdAt: plan.updatedAt
1330
- });
1331
- return;
1332
- }
1333
- const last = plan.versions[plan.versions.length - 1];
1334
- last.body = plan.body;
1335
- last.title = plan.title;
1336
- last.source = plan.source;
1337
- last.model = plan.model;
1338
- }
1339
- var FilePlanStore = class {
1340
- dirPath;
1341
- filePath;
1342
- /**
1343
- * @param storageDir Absolute directory to persist `plans.json` in. Defaults
1344
- * to the per-repo storage dir under `~/.diffing`, the same place comments
1345
- * and media live — plans are NEVER written inside the reviewed (consumer)
1346
- * repo, so a consumer project stays free of any diffing-specific artifacts.
1347
- * The override exists only so tests can point at a throwaway temp dir.
1348
- */
1349
- constructor(storageDir) {
1350
- this.dirPath = storageDir ?? getProjectStorageDir();
1351
- this.filePath = join(this.dirPath, "plans.json");
1352
- }
1353
- async getAll() {
1354
- try {
1355
- const data = await readFile(this.filePath, "utf-8");
1356
- const plans = JSON.parse(data);
1357
- let anyBackfilled = false;
1358
- for (const p of plans) {
1359
- const before = Array.isArray(p.versions) ? p.versions.length : 0;
1360
- const beforeValid = Array.isArray(p.versions) && p.versions.length > 0;
1361
- backfillPlan(p);
1362
- if (!p.sourcePath) {
1363
- p.sourcePath = planSourceFilePath(this.dirPath, p.id);
1364
- anyBackfilled = true;
1365
- }
1366
- const after = Array.isArray(p.versions) ? p.versions.length : 0;
1367
- if ((!beforeValid || before < (p.version ?? 1)) && after > before) anyBackfilled = true;
1368
- }
1369
- if (anyBackfilled) try {
1370
- await this.save(plans);
1371
- } catch {}
1372
- return plans;
1373
- } catch {
1374
- return [];
1375
- }
1376
- }
1377
- async get(id) {
1378
- return (await this.getAll()).find((p) => p.id === id) ?? null;
1379
- }
1380
- async getVersion(id, version) {
1381
- const plan = await this.get(id);
1382
- if (!plan) return null;
1383
- return plan.versions.find((v) => v.version === version) ?? null;
1384
- }
1385
- async save(plans) {
1386
- try {
1387
- await mkdir(this.dirPath, { recursive: true });
1388
- try {
1389
- const repoRoot = getRepoRoot();
1390
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1391
- } catch {}
1392
- const clean = plans.map((p) => {
1393
- const copy = { ...p };
1394
- delete copy.__backfilledVersions;
1395
- return copy;
1396
- });
1397
- await writeFile(this.filePath, JSON.stringify(clean, null, 2), "utf-8");
1398
- } catch (err) {
1399
- console.error("Failed to save plans to file:", err);
1400
- }
1401
- }
1402
- /**
1403
- * Mirror the plan body to `plan-sources/<id>.md` and stamp `sourcePath` so
1404
- * the UI / agents can always copy a stable absolute path (even when the
1405
- * submitter only piped stdin and never set `--source`).
1406
- */
1407
- async writeSourceMirror(plan) {
1408
- try {
1409
- await mkdir(join(this.dirPath, "plan-sources"), { recursive: true });
1410
- const path = planSourceFilePath(this.dirPath, plan.id);
1411
- await writeFile(path, plan.body, "utf-8");
1412
- plan.sourcePath = path;
1413
- } catch (err) {
1414
- console.error("Failed to write plan source mirror:", err);
1415
- }
1416
- }
1417
- async upsert(input) {
1418
- const plans = await this.getAll();
1419
- const plan = applyUpsert(plans, input, Date.now());
1420
- backfillPlan(plan);
1421
- await this.writeSourceMirror(plan);
1422
- await this.save(plans);
1423
- return plan;
1424
- }
1425
- async update(id, fields) {
1426
- const plans = await this.getAll();
1427
- const plan = plans.find((p) => p.id === id);
1428
- if (!plan) return null;
1429
- if (fields.title !== void 0) plan.title = fields.title;
1430
- if (fields.body !== void 0) plan.body = fields.body;
1431
- if (fields.source !== void 0) plan.source = fields.source;
1432
- if (fields.model !== void 0) plan.model = fields.model;
1433
- plan.updatedAt = Date.now();
1434
- syncCurrentVersion(plan);
1435
- backfillPlan(plan);
1436
- if (fields.body !== void 0) await this.writeSourceMirror(plan);
1437
- await this.save(plans);
1438
- return plan;
1439
- }
1440
- async remove(id) {
1441
- const plans = await this.getAll();
1442
- const idx = plans.findIndex((p) => p.id === id);
1443
- if (idx === -1) return false;
1444
- plans.splice(idx, 1);
1445
- await this.save(plans);
1446
- return true;
1447
- }
1448
- async setDecision(id, decision, decisionComment) {
1449
- const plans = await this.getAll();
1450
- const plan = plans.find((p) => p.id === id);
1451
- if (!plan) return null;
1452
- plan.decision = decision;
1453
- plan.decisionComment = decisionComment?.trim() || void 0;
1454
- plan.decidedAt = Date.now();
1455
- plan.updatedAt = plan.decidedAt;
1456
- await this.save(plans);
1457
- return plan;
1458
- }
1459
- async mutate(planId, fn) {
1460
- const plans = await this.getAll();
1461
- const plan = plans.find((p) => p.id === planId);
1462
- if (!plan) return null;
1463
- if (!plan.comments) plan.comments = [];
1464
- if (!fn(plan)) return null;
1465
- backfillPlan(plan);
1466
- await this.save(plans);
1467
- return plan;
1468
- }
1469
- async addComment(planId, comment) {
1470
- return this.mutate(planId, (plan) => {
1471
- if (typeof comment.createdAtPlanVersion !== "number") comment.createdAtPlanVersion = plan.version ?? 1;
1472
- plan.comments.push(comment);
1473
- return true;
1474
- });
1475
- }
1476
- async updateComment(planId, commentId, fields) {
1477
- return this.mutate(planId, (plan) => {
1478
- const c = plan.comments.find((x) => x.id === commentId);
1479
- if (!c) return false;
1480
- if (fields.body !== void 0) c.body = fields.body;
1481
- if (fields.status !== void 0) c.status = fields.status;
1482
- return true;
1483
- });
1484
- }
1485
- async removeComment(planId, commentId) {
1486
- return this.mutate(planId, (plan) => {
1487
- const idx = plan.comments.findIndex((x) => x.id === commentId);
1488
- if (idx === -1) return false;
1489
- plan.comments.splice(idx, 1);
1490
- return true;
1491
- });
1492
- }
1493
- async addReply(planId, commentId, reply) {
1494
- return this.mutate(planId, (plan) => {
1495
- const c = plan.comments.find((x) => x.id === commentId);
1496
- if (!c) return false;
1497
- if (typeof c.createdAtPlanVersion === "number" && typeof reply.createdAtPlanVersion !== "number") reply.createdAtPlanVersion = c.createdAtPlanVersion;
1498
- if (!c.replies) c.replies = [];
1499
- c.replies.push(reply);
1500
- return true;
1501
- });
1502
- }
1503
- async removeReply(planId, commentId, replyId) {
1504
- return this.mutate(planId, (plan) => {
1505
- const c = plan.comments.find((x) => x.id === commentId);
1506
- if (!c) return false;
1507
- const idx = c.replies.findIndex((r) => r.id === replyId);
1508
- if (idx === -1) return false;
1509
- c.replies.splice(idx, 1);
1510
- return true;
1511
- });
1512
- }
1513
- async updateReply(planId, commentId, replyId, body) {
1514
- return this.mutate(planId, (plan) => {
1515
- const c = plan.comments.find((x) => x.id === commentId);
1516
- if (!c) return false;
1517
- const reply = c.replies.find((r) => r.id === replyId);
1518
- if (!reply) return false;
1519
- reply.body = body;
1520
- return true;
1521
- });
1522
- }
1523
- };
1524
- //#endregion
1525
- //#region src/lib/state.ts
1526
- var FileUiStateStore = class {
1527
- dirPath;
1528
- filePath;
1529
- constructor(storageDir) {
1530
- this.dirPath = storageDir ?? getProjectStorageDir();
1531
- this.filePath = join(this.dirPath, "ui-state.json");
1532
- }
1533
- async getAll() {
1534
- try {
1535
- const data = await readFile(this.filePath, "utf-8");
1536
- return JSON.parse(data);
1537
- } catch {
1538
- return {};
1539
- }
1540
- }
1541
- async setAll(state) {
1542
- await this.save(state);
1543
- }
1544
- async save(state) {
1545
- try {
1546
- await mkdir(this.dirPath, { recursive: true });
1547
- try {
1548
- const repoRoot = getRepoRoot();
1549
- await writeFile(join(this.dirPath, "repo_path.txt"), repoRoot, "utf-8");
1550
- } catch {}
1551
- await writeFile(this.filePath, JSON.stringify(state, null, 2), "utf-8");
1552
- } catch (err) {
1553
- console.error("Failed to save UI state to file:", err);
1554
- }
1555
- }
1556
- };
1557
- //#endregion
1558
- //#region src/lib/editor-launcher.ts
1559
- function resolveEditorCommand(editor, absolutePath, platform = process.platform, env = process.env) {
1560
- switch (editor) {
1561
- case "vscode": return guiEditorCommand("code", absolutePath, platform);
1562
- case "zed": return guiEditorCommand("zed", absolutePath, platform);
1563
- case "vim": return terminalEditorCommand("vim", absolutePath, platform, env);
1564
- case "neovim": return terminalEditorCommand("nvim", absolutePath, platform, env);
1565
- default: return null;
1566
- }
1567
- }
1568
- function guiEditorCommand(bin, absolutePath, platform) {
1569
- if (platform === "win32") return {
1570
- cmd: `${bin}.cmd`,
1571
- args: [absolutePath]
1572
- };
1573
- return {
1574
- cmd: bin,
1575
- args: [absolutePath]
1576
- };
1577
- }
1578
- function terminalEditorCommand(bin, absolutePath, platform, env) {
1579
- if (platform === "darwin") return {
1580
- cmd: "osascript",
1581
- args: ["-e", `tell application "Terminal" to do script "${bin} \\"${absolutePath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}\\""`]
1582
- };
1583
- if (platform === "win32") return {
1584
- cmd: "cmd.exe",
1585
- args: [
1586
- "/c",
1587
- "start",
1588
- "\"\"",
1589
- "cmd.exe",
1590
- "/k",
1591
- bin,
1592
- absolutePath
1593
- ]
1594
- };
1595
- const term = env.TERMINAL?.trim();
1596
- if (term) return {
1597
- cmd: term,
1598
- args: [
1599
- "-e",
1600
- bin,
1601
- absolutePath
1602
- ]
1603
- };
1604
- return {
1605
- cmd: "x-terminal-emulator",
1606
- args: [
1607
- "-e",
1608
- bin,
1609
- absolutePath
1610
- ]
1611
- };
1612
- }
1613
- //#endregion
1614
- //#region src/lib/review-session.ts
1615
- const MAX_ROUND_HISTORY = 20;
1616
- var ReviewSession = class {
1617
- round = 0;
1618
- lastSentAt = null;
1619
- lastPayload = null;
1620
- history = [];
1621
- waiters = /* @__PURE__ */ new Set();
1622
- onStatusChange;
1623
- constructor(onStatusChange) {
1624
- this.onStatusChange = onStatusChange;
1625
- }
1626
- /**
1627
- * Block until the next `send()` or until `timeoutMs` elapses.
1628
- *
1629
- * If `sinceRound` is provided and is behind the current round, a send already
1630
- * happened since the client last checked → resolve immediately with the
1631
- * cached payload (the race guard). Otherwise register a waiter.
1632
- */
1633
- await(opts) {
1634
- const { sinceRound, timeoutMs, signal } = opts;
1635
- if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
1636
- status: "released",
1637
- payload: this.lastPayload
1638
- });
1639
- if (signal?.aborted) return Promise.resolve({
1640
- status: "keep-waiting",
1641
- round: this.round
1642
- });
1643
- return new Promise((resolve) => {
1644
- const waiter = {
1645
- resolve,
1646
- timer: setTimeout(() => {
1647
- this.removeWaiter(waiter);
1648
- resolve({
1649
- status: "keep-waiting",
1650
- round: this.round
1651
- });
1652
- }, timeoutMs),
1653
- cleanup: () => {}
1654
- };
1655
- if (signal) {
1656
- const onAbort = () => {
1657
- this.removeWaiter(waiter);
1658
- resolve({
1659
- status: "keep-waiting",
1660
- round: this.round
1661
- });
1662
- };
1663
- signal.addEventListener("abort", onAbort, { once: true });
1664
- waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
1665
- }
1666
- this.waiters.add(waiter);
1667
- this.emitStatus();
1668
- });
1669
- }
1670
- /** Capture a review batch and release every blocked waiter. */
1671
- send(input) {
1672
- this.round += 1;
1673
- this.lastSentAt = input.sentAt;
1674
- const mode = input.mode ?? "standard";
1675
- const payload = {
1676
- round: this.round,
1677
- sentAt: input.sentAt,
1678
- commentXml: input.commentXml,
1679
- openCount: input.openCount,
1680
- comments: input.comments,
1681
- decision: input.decision,
1682
- mode
1683
- };
1684
- this.lastPayload = payload;
1685
- const filePaths = [...new Set(input.comments.map((c) => c.filePath))].sort();
1686
- this.history.push({
1687
- round: this.round,
1688
- sentAt: input.sentAt,
1689
- openCount: input.openCount,
1690
- decision: input.decision,
1691
- mode,
1692
- filePaths,
1693
- diffFingerprints: input.diffFingerprints ? { ...input.diffFingerprints } : void 0
1694
- });
1695
- if (this.history.length > MAX_ROUND_HISTORY) this.history.splice(0, this.history.length - MAX_ROUND_HISTORY);
1696
- const waiters = [...this.waiters];
1697
- this.waiters.clear();
1698
- for (const waiter of waiters) {
1699
- clearTimeout(waiter.timer);
1700
- waiter.cleanup();
1701
- waiter.resolve({
1702
- status: "released",
1703
- payload
1704
- });
1705
- }
1706
- this.emitStatus();
1707
- return payload;
1708
- }
1709
- snapshot() {
1710
- const last = this.history[this.history.length - 1];
1711
- return {
1712
- round: this.round,
1713
- waiters: this.waiters.size,
1714
- lastSentAt: this.lastSentAt,
1715
- lastDecision: last?.decision,
1716
- lastOpenCount: last?.openCount,
1717
- hasSinceLastBaseline: Boolean(last?.diffFingerprints && Object.keys(last.diffFingerprints).length > 0)
1718
- };
1719
- }
1720
- /** Newest-first round summaries for the UI timeline. */
1721
- getHistory() {
1722
- return [...this.history].reverse();
1723
- }
1724
- /** Fingerprints captured at the most recent send, if any. */
1725
- getLastDiffFingerprints() {
1726
- const last = this.history[this.history.length - 1];
1727
- if (!last?.diffFingerprints) return null;
1728
- return { ...last.diffFingerprints };
1729
- }
1730
- removeWaiter(waiter) {
1731
- if (!this.waiters.delete(waiter)) return;
1732
- clearTimeout(waiter.timer);
1733
- waiter.cleanup();
1734
- this.emitStatus();
1735
- }
1736
- emitStatus() {
1737
- this.onStatusChange?.(this.snapshot());
1738
- }
1739
- };
1740
- //#endregion
1741
- //#region src/lib/plan-review-session.ts
1742
- var PlanReviewSession = class {
1743
- round = 0;
1744
- lastDecidedAt = null;
1745
- lastPayload = null;
1746
- waiters = /* @__PURE__ */ new Set();
1747
- onStatusChange;
1748
- constructor(onStatusChange) {
1749
- this.onStatusChange = onStatusChange;
1750
- }
1751
- /** Block until the next `decide()` or until `timeoutMs` elapses. */
1752
- await(opts) {
1753
- const { sinceRound, timeoutMs, signal } = opts;
1754
- if (sinceRound !== void 0 && sinceRound < this.round && this.lastPayload) return Promise.resolve({
1755
- status: "released",
1756
- payload: this.lastPayload
1757
- });
1758
- if (signal?.aborted) return Promise.resolve({
1759
- status: "keep-waiting",
1760
- round: this.round
1761
- });
1762
- return new Promise((resolve) => {
1763
- const waiter = {
1764
- resolve,
1765
- timer: setTimeout(() => {
1766
- this.removeWaiter(waiter);
1767
- resolve({
1768
- status: "keep-waiting",
1769
- round: this.round
1770
- });
1771
- }, timeoutMs),
1772
- cleanup: () => {}
1773
- };
1774
- if (signal) {
1775
- const onAbort = () => {
1776
- this.removeWaiter(waiter);
1777
- resolve({
1778
- status: "keep-waiting",
1779
- round: this.round
1780
- });
1781
- };
1782
- signal.addEventListener("abort", onAbort, { once: true });
1783
- waiter.cleanup = () => signal.removeEventListener("abort", onAbort);
1784
- }
1785
- this.waiters.add(waiter);
1786
- this.emitStatus();
1787
- });
1788
- }
1789
- /** Capture a decision and release every blocked waiter. */
1790
- decide(input) {
1791
- this.round += 1;
1792
- this.lastDecidedAt = input.sentAt;
1793
- const payload = {
1794
- round: this.round,
1795
- sentAt: input.sentAt,
1796
- planId: input.planId,
1797
- decision: input.decision,
1798
- decisionComment: input.decisionComment,
1799
- reviewXml: input.reviewXml,
1800
- openCommentCount: input.openCommentCount,
1801
- plan: input.plan,
1802
- mode: input.mode ?? "standard"
1803
- };
1804
- this.lastPayload = payload;
1805
- const waiters = [...this.waiters];
1806
- this.waiters.clear();
1807
- for (const waiter of waiters) {
1808
- clearTimeout(waiter.timer);
1809
- waiter.cleanup();
1810
- waiter.resolve({
1811
- status: "released",
1812
- payload
1813
- });
1814
- }
1815
- this.emitStatus();
1816
- return payload;
1817
- }
1818
- snapshot() {
1819
- return {
1820
- round: this.round,
1821
- waiters: this.waiters.size,
1822
- lastDecidedAt: this.lastDecidedAt
1823
- };
1824
- }
1825
- removeWaiter(waiter) {
1826
- if (!this.waiters.delete(waiter)) return;
1827
- clearTimeout(waiter.timer);
1828
- waiter.cleanup();
1829
- this.emitStatus();
1830
- }
1831
- emitStatus() {
1832
- this.onStatusChange?.(this.snapshot());
1833
- }
1834
- };
1835
- //#endregion
1836
- //#region src/lib/secrets-scan.ts
1837
- const RULES = [
1838
- {
1839
- id: "aws-access-key",
1840
- re: /\b(AKIA[0-9A-Z]{16})\b/g,
1841
- redact: (m) => `${m[0].slice(0, 4)}…${m[0].slice(-4)}`
1842
- },
1843
- {
1844
- id: "github-token",
1845
- re: /\b(gh[pousr]_[A-Za-z0-9_]{20,})\b/g,
1846
- redact: (m) => `${m[0].slice(0, 7)}…`
1847
- },
1848
- {
1849
- id: "slack-token",
1850
- re: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/g,
1851
- redact: (m) => `${m[0].slice(0, 8)}…`
1852
- },
1853
- {
1854
- id: "private-key",
1855
- re: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,
1856
- redact: () => "-----BEGIN PRIVATE KEY-----"
1857
- },
1858
- {
1859
- id: "generic-api-key",
1860
- re: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token)\s*[:=]\s*['"]?([A-Za-z0-9_\-]{16,})['"]?/gi,
1861
- redact: (m) => `…${(m[1] ?? "").slice(-4)}`
1862
- },
1863
- {
1864
- id: "jwt",
1865
- re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
1866
- redact: (m) => `${m[0].slice(0, 12)}…`
1867
- },
1868
- {
1869
- id: "connection-string",
1870
- re: /\b(?:postgres|mysql|mongodb(?:\+srv)?|redis):\/\/[^\s'"]+/gi,
1871
- redact: (m) => {
1872
- try {
1873
- const u = new URL(m[0]);
1874
- if (u.password) u.password = "***";
1875
- return u.toString();
1876
- } catch {
1877
- return m[0].replace(/:([^:@/]+)@/, ":***@");
1878
- }
1879
- }
1880
- }
1881
- ];
1882
- function scanTextForSecrets(text, source) {
1883
- if (!text) return [];
1884
- const findings = [];
1885
- for (const rule of RULES) {
1886
- rule.re.lastIndex = 0;
1887
- let match;
1888
- while ((match = rule.re.exec(text)) !== null) {
1889
- findings.push({
1890
- rule: rule.id,
1891
- snippet: rule.redact(match),
1892
- source
1893
- });
1894
- if (match.index === rule.re.lastIndex) rule.re.lastIndex++;
1895
- }
1896
- }
1897
- return findings;
1898
- }
1899
- function scanReviewForSecrets(input) {
1900
- const out = [];
1901
- if (input.generalComment) out.push(...scanTextForSecrets(input.generalComment, "overall comment"));
1902
- for (const c of input.comments) {
1903
- out.push(...scanTextForSecrets(c.body, `comment ${c.id} (${c.filePath})`));
1904
- if (c.lineContent) out.push(...scanTextForSecrets(c.lineContent, `code at ${c.filePath}`));
1905
- }
1906
- const seen = /* @__PURE__ */ new Set();
1907
- return out.filter((f) => {
1908
- const k = `${f.rule}|${f.snippet}|${f.source}`;
1909
- if (seen.has(k)) return false;
1910
- seen.add(k);
1911
- return true;
1912
- });
1913
- }
1914
- //#endregion
1915
- //#region src/lib/pr-session.ts
1916
- var FilePrSessionStore = class {
1917
- dirPath;
1918
- filePath;
1919
- constructor(storageDir) {
1920
- this.dirPath = storageDir ?? getProjectStorageDir();
1921
- this.filePath = join(this.dirPath, "pr-session.json");
1922
- }
1923
- async get() {
1924
- try {
1925
- const data = await readFile(this.filePath, "utf-8");
1926
- return JSON.parse(data);
1927
- } catch {
1928
- return null;
1929
- }
1930
- }
1931
- async save(session) {
1932
- try {
1933
- await mkdir(this.dirPath, { recursive: true });
1934
- await writeFile(this.filePath, JSON.stringify(session, null, 2), "utf-8");
1935
- } catch (err) {
1936
- console.error("Failed to save pr-session to file:", err);
1937
- }
1938
- }
1939
- async set(session) {
1940
- await this.save(session);
1941
- }
1942
- async update(fields) {
1943
- const current = await this.get();
1944
- if (!current) return null;
1945
- const next = {
1946
- ...current,
1947
- ...fields
1948
- };
1949
- await this.save(next);
1950
- return next;
1951
- }
1952
- async clear() {
1953
- try {
1954
- const { unlink } = await import("node:fs/promises");
1955
- await unlink(this.filePath);
1956
- } catch {}
1957
- }
1958
- };
1959
- //#endregion
1960
- //#region src/server.ts
1961
- const MIME_TYPES = {
1962
- ".html": "text/html",
1963
- ".js": "application/javascript",
1964
- ".css": "text/css",
1965
- ".json": "application/json",
1966
- ".svg": "image/svg+xml",
1967
- ".png": "image/png",
1968
- ".ico": "image/x-icon",
1969
- ".jpg": "image/jpeg",
1970
- ".jpeg": "image/jpeg",
1971
- ".gif": "image/gif",
1972
- ".webp": "image/webp",
1973
- ".bmp": "image/bmp",
1974
- ".avif": "image/avif"
1975
- };
1976
- function isCustomMode(opts) {
1977
- return opts.revisions.length > 0 || opts.pathspecs.length > 0 || opts.showMode;
1978
- }
1979
- function createApp(clientDir, diffOptsInput = DEFAULTS, commentStore, planStore, prSessionStore, prMode = false) {
1980
- const app = new Hono();
1981
- let diffOpts = { ...diffOptsInput };
1982
- const customMode = isCustomMode(diffOpts);
1983
- const store = commentStore ?? new FileCommentStore();
1984
- const plans = planStore ?? new FilePlanStore();
1985
- const prStore = prSessionStore ?? new FilePrSessionStore();
1986
- const uiStateStore = new FileUiStateStore();
1987
- const viewedFiles = /* @__PURE__ */ new Set();
1988
- /** Agent-reported progress events for the human UI (SSE `agent-progress`). */
1989
- let lastAgentProgress = null;
1990
- /** Waiters registered with optional identity for multi-agent display. */
1991
- const agentWaiters = /* @__PURE__ */ new Map();
1992
- const activeClients = /* @__PURE__ */ new Set();
1993
- const broadcast = (event, data) => {
1994
- for (const send of activeClients) try {
1995
- send(event, data);
1996
- } catch {}
1997
- };
1998
- const agentsSnapshot = () => [...agentWaiters.entries()].map(([id, a]) => ({
1999
- id,
2000
- ...a
2001
- }));
2002
- const reviewSession = new ReviewSession((snapshot) => broadcast("agent-status", JSON.stringify({
2003
- ...snapshot,
2004
- agents: agentsSnapshot()
2005
- })));
2006
- const planReviewSession = new PlanReviewSession((snapshot) => broadcast("plan-review-status", JSON.stringify(snapshot)));
2007
- let repoRoot;
2008
- try {
2009
- repoRoot = getRepoRoot();
2010
- } catch {
2011
- repoRoot = process.cwd();
2012
- }
2013
- if (!commentStore && !planStore) try {
2014
- const storageDir = getProjectStorageDir();
2015
- mkdirSync(storageDir, { recursive: true });
2016
- let commentsDebounce = null;
2017
- let plansDebounce = null;
2018
- let prSessionDebounce = null;
2019
- watch(storageDir, (_eventType, filename) => {
2020
- if (!filename) return;
2021
- if (filename.startsWith("comments.json")) {
2022
- if (commentsDebounce) clearTimeout(commentsDebounce);
2023
- commentsDebounce = setTimeout(() => broadcast("comments", Date.now().toString()), 120);
2024
- } else if (filename.startsWith("plans.json")) {
2025
- if (plansDebounce) clearTimeout(plansDebounce);
2026
- plansDebounce = setTimeout(() => broadcast("plans", Date.now().toString()), 120);
2027
- } else if (filename.startsWith("pr-session.json")) {
2028
- if (prSessionDebounce) clearTimeout(prSessionDebounce);
2029
- prSessionDebounce = setTimeout(() => broadcast("pr-session", Date.now().toString()), 120);
2030
- }
2031
- }).unref();
2032
- } catch (err) {
2033
- console.warn("Failed to initialize storage watcher:", err);
2034
- }
2035
- let debounceTimeout = null;
2036
- try {
2037
- watch(repoRoot, { recursive: true }, (eventType, filename) => {
2038
- if (!filename) return;
2039
- const parts = filename.split(/[/\\]/);
2040
- const isGit = parts.includes(".git");
2041
- const isNodeModules = parts.includes("node_modules");
2042
- const isDist = parts.includes("dist");
2043
- const isChangeset = parts.includes(".changeset");
2044
- let shouldTrigger = false;
2045
- if (isGit) {
2046
- const isIndex = filename.endsWith("index");
2047
- const isHead = filename.endsWith("HEAD");
2048
- const isRefs = filename.includes("refs/") || filename.includes("refs\\");
2049
- if (isIndex || isHead || isRefs) shouldTrigger = true;
2050
- } else if (!isNodeModules && !isDist && !isChangeset) shouldTrigger = true;
2051
- if (shouldTrigger) {
2052
- if (debounceTimeout) clearTimeout(debounceTimeout);
2053
- debounceTimeout = setTimeout(() => broadcast("change", Date.now().toString()), 200);
2054
- }
2055
- }).unref();
2056
- } catch (err) {
2057
- console.warn("Failed to initialize repository watcher:", err);
2058
- }
2059
- app.get("/api/live", async (c) => {
2060
- return streamSSE(c, async (stream) => {
2061
- const sendUpdate = (event, data) => {
2062
- stream.writeSSE({
2063
- event,
2064
- data
2065
- });
2066
- };
2067
- activeClients.add(sendUpdate);
2068
- await stream.writeSSE({
2069
- event: "heartbeat",
2070
- data: Date.now().toString()
2071
- });
2072
- const heartbeatInterval = setInterval(() => {
2073
- stream.writeSSE({
2074
- event: "heartbeat",
2075
- data: Date.now().toString()
2076
- }).catch(() => {});
2077
- }, 15e3);
2078
- await new Promise((resolve) => {
2079
- stream.onAbort(() => {
2080
- clearInterval(heartbeatInterval);
2081
- activeClients.delete(sendUpdate);
2082
- resolve();
2083
- });
2084
- });
2085
- });
2086
- });
2087
- app.get("/api/diff", async (c) => {
2088
- const stagedQuery = c.req.query("staged");
2089
- const untrackedQuery = c.req.query("untracked");
2090
- const staged = stagedQuery === void 0 ? diffOpts.staged : stagedQuery === "true";
2091
- const untracked = untrackedQuery === void 0 ? diffOpts.includeUntracked : untrackedQuery === "true";
2092
- if (prMode) {
2093
- const prSession = await prStore.get();
2094
- if (prSession) {
2095
- const binaryFiles = [];
2096
- const filePaths = [];
2097
- for (const line of prSession.diff.split("\n")) {
2098
- const m = /^diff --git a\/.+ b\/(.+)$/.exec(line);
2099
- if (m) filePaths.push(m[1]);
2100
- }
2101
- const prOverview = buildPrOverview({
2102
- prNumber: prSession.pullNumber,
2103
- prTitle: prSession.title,
2104
- prAuthor: prSession.author?.login ?? null,
2105
- additions: prSession.additions,
2106
- deletions: prSession.deletions
2107
- });
2108
- return c.json({
2109
- patch: prSession.diff,
2110
- repoName: prSession.repo,
2111
- branch: `#${prSession.pullNumber}`,
2112
- customMode: true,
2113
- binaryFiles,
2114
- tabSizeMap: {},
2115
- untrackedFiles: [],
2116
- prMode: true,
2117
- prRef: prSession.ref,
2118
- prOwner: prSession.owner,
2119
- prRepo: prSession.repo,
2120
- prPullNumber: prSession.pullNumber,
2121
- prUrl: prSession.url,
2122
- prTitle: prSession.title,
2123
- prAuthor: prSession.author,
2124
- prHeadSha: prSession.headSha,
2125
- prBaseSha: prSession.baseSha,
2126
- overview: prOverview
2127
- });
2128
- }
2129
- }
2130
- const optsForDiff = customMode ? diffOpts : {
2131
- ...diffOpts,
2132
- staged,
2133
- includeUntracked: untracked
2134
- };
2135
- const result = await executeDiffWithMeta(optsForDiff);
2136
- return c.json({
2137
- patch: result.patch,
2138
- repoName: result.repoName,
2139
- branch: result.branch,
2140
- customMode,
2141
- binaryFiles: result.binaryFiles,
2142
- tabSizeMap: result.tabSizeMap,
2143
- untrackedFiles: result.untrackedFiles,
2144
- showMode: optsForDiff.showMode || void 0,
2145
- commits: result.commits,
2146
- truncated: result.truncated,
2147
- overview: result.overview
2148
- });
2149
- });
2150
- app.get("/api/file-content", (c) => {
2151
- const path = c.req.query("path");
2152
- const version = c.req.query("version");
2153
- if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
2154
- const content = getFileContent(path, version);
2155
- if (!content) return c.json({ error: "File not found" }, 404);
2156
- const contentType = MIME_TYPES[extname(path)] || "application/octet-stream";
2157
- return new Response(new Uint8Array(content), { headers: { "Content-Type": contentType } });
2158
- });
2159
- app.get("/api/file-text", (c) => {
2160
- const path = c.req.query("path");
2161
- const version = c.req.query("version");
2162
- if (!path || !version) return c.json({ error: "Missing path or version" }, 400);
2163
- const buffer = getFileContent(path, version);
2164
- if (!buffer) return c.json({
2165
- content: "",
2166
- missing: true
2167
- });
2168
- const sample = buffer.subarray(0, Math.min(buffer.length, 8192));
2169
- for (let i = 0; i < sample.length; i++) if (sample[i] === 0) return c.json({ error: "Binary file" }, 415);
2170
- return c.json({
2171
- content: buffer.toString("utf-8"),
2172
- missing: false
2173
- });
2174
- });
2175
- app.post("/api/open-file", async (c) => {
2176
- const { filePath, editor } = await c.req.json();
2177
- if (!filePath) return c.json({ error: "filePath is required" }, 400);
2178
- try {
2179
- const root = getRepoRoot();
2180
- let absolutePath = null;
2181
- const relPath = toSafeRelativePath(filePath, root);
2182
- if (relPath) absolutePath = resolve(root, relPath);
2183
- else {
2184
- const resolved = resolve(filePath);
2185
- const diffingHome = resolve(homedir(), ".diffing");
2186
- if ((resolved === diffingHome || resolved.startsWith(diffingHome + "/") || resolved.startsWith(diffingHome + "\\")) && existsSync(resolved)) absolutePath = resolved;
2187
- }
2188
- if (!absolutePath) return c.json({ error: "Forbidden file path" }, 403);
2189
- if (editor && editor !== "default") {
2190
- const command = resolveEditorCommand(editor, absolutePath);
2191
- if (command) {
2192
- const { execFile } = await import("node:child_process");
2193
- execFile(command.cmd, command.args, (err) => {
2194
- if (err) console.error(`Failed to launch ${editor} for ${absolutePath}: ${err.message}`);
2195
- });
2196
- return c.json({ ok: true });
2197
- }
2198
- }
2199
- await (await import("open")).default(absolutePath);
2200
- return c.json({ ok: true });
2201
- } catch (err) {
2202
- return c.json({ error: `Failed to open file: ${err.message}` }, 500);
2203
- }
2204
- });
2205
- app.get("/api/repo-files", (c) => {
2206
- try {
2207
- return c.json({ files: listRepoFiles() });
2208
- } catch (err) {
2209
- return c.json({ error: err.message }, 500);
2210
- }
2211
- });
2212
- app.post("/api/search", async (c) => {
2213
- const body = await c.req.json().catch(() => ({}));
2214
- const scope = body.scope ?? "files";
2215
- const query = typeof body.query === "string" ? body.query : "";
2216
- const limit = typeof body.limit === "number" ? body.limit : void 0;
2217
- const paths = Array.isArray(body.changedPaths) ? body.changedPaths : void 0;
2218
- try {
2219
- if (scope === "all") return c.json(await searchAll(query, {
2220
- limit,
2221
- regex: !!body.regex,
2222
- paths
2223
- }));
2224
- if (scope === "text") return c.json(await searchContent(query, {
2225
- limit,
2226
- regex: !!body.regex,
2227
- paths
2228
- }));
2229
- if (scope === "symbols") return c.json(await searchSymbols(query, {
2230
- limit,
2231
- paths
2232
- }));
2233
- return c.json(await searchFiles(query, {
2234
- limit,
2235
- paths
2236
- }));
2237
- } catch (err) {
2238
- return c.json({
2239
- scope,
2240
- items: [],
2241
- total: 0,
2242
- indexing: false,
2243
- error: err?.message ?? "Search failed"
2244
- }, 500);
2245
- }
2246
- });
2247
- app.get("/api/search/status", async (c) => {
2248
- return c.json(await getSearchStatus());
2249
- });
2250
- app.post("/api/search/track", async (c) => {
2251
- const { query, path } = await c.req.json().catch(() => ({}));
2252
- if (path) await trackSelection(query ?? "", path);
2253
- return c.json({ ok: true });
2254
- });
2255
- app.get("/api/merge-status", (c) => {
2256
- try {
2257
- const status = getMergeStatus();
2258
- return c.json(status);
2259
- } catch (err) {
2260
- return c.json({ error: err.message }, 500);
2261
- }
2262
- });
2263
- app.post("/api/revert-hunk", async (c) => {
2264
- const { filePath, hunkIndex } = await c.req.json();
2265
- if (!filePath || typeof hunkIndex !== "number") return c.json({ error: "Missing filePath or hunkIndex" }, 400);
2266
- try {
2267
- const relPath = toSafeRelativePath(filePath, getRepoRoot());
2268
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2269
- revertHunk(relPath, hunkIndex);
2270
- return c.json({ ok: true });
2271
- } catch (err) {
2272
- const stderr = typeof err?.stderr === "string" ? err.stderr : err?.stderr instanceof Buffer ? err.stderr.toString("utf-8") : "";
2273
- return c.json({ error: stderr || err?.message || "Failed to revert hunk" }, 500);
2274
- }
2275
- });
2276
- /**
2277
- * Pick a single tree-ish suitable for `git blame` from a list of revisions
2278
- * or show-revspecs. `git blame` does not accept range notation, so for
2279
- * `A..B` or `A...B` we use the right endpoint (the side being compared
2280
- * against), which matches the diff's "destination" side.
2281
- */
2282
- function extractBlameRevision(revisions, showRevspecs, showMode) {
2283
- const list = showMode ? showRevspecs : revisions;
2284
- if (list.length === 0) return "HEAD";
2285
- const last = list[list.length - 1];
2286
- const threeDot = last.lastIndexOf("...");
2287
- if (threeDot >= 0) {
2288
- const target = last.slice(threeDot + 3);
2289
- if (target) return target;
2290
- }
2291
- const twoDot = last.lastIndexOf("..");
2292
- if (twoDot >= 0) {
2293
- const target = last.slice(twoDot + 2);
2294
- if (target) return target;
2295
- }
2296
- return last;
2297
- }
2298
- app.get("/api/hunk-history", async (c) => {
2299
- const filePath = c.req.query("filePath");
2300
- const deletionStart = Number(c.req.query("deletionStart"));
2301
- const deletionCount = Number(c.req.query("deletionCount"));
2302
- if (!filePath || Number.isNaN(deletionStart) || Number.isNaN(deletionCount)) return c.json({ error: "Missing or invalid parameters" }, 400);
2303
- try {
2304
- const relPath = toSafeRelativePath(filePath, getRepoRoot());
2305
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2306
- const history = getHunkHistory(relPath, deletionStart, deletionCount, extractBlameRevision(diffOpts.revisions, diffOpts.showRevspecs, diffOpts.showMode));
2307
- return c.json(history);
2308
- } catch (err) {
2309
- return c.json({ error: err.message || "Failed to fetch hunk history" }, 500);
2310
- }
2311
- });
2312
- app.post("/api/save-file", async (c) => {
2313
- const { filePath, content, gitAdd } = await c.req.json();
2314
- if (!filePath || typeof content !== "string") return c.json({ error: "Missing filePath or content" }, 400);
2315
- try {
2316
- const root = getRepoRoot();
2317
- const relPath = toSafeRelativePath(filePath, root);
2318
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2319
- await writeFile(resolve(root, relPath), content, "utf-8");
2320
- if (gitAdd) try {
2321
- gitAddFile(relPath);
2322
- } catch (err) {
2323
- return c.json({
2324
- ok: true,
2325
- gitAddError: err.message
2326
- });
2327
- }
2328
- return c.json({ ok: true });
2329
- } catch (err) {
2330
- return c.json({ error: `Failed to save file: ${err.message}` }, 500);
2331
- }
2332
- });
2333
- app.get("/api/settings", (c) => {
2334
- return c.json(loadSettings());
2335
- });
2336
- app.put("/api/settings", async (c) => {
2337
- const body = await c.req.json();
2338
- const settings = saveSettings(body);
2339
- let whitespaceChanged = false;
2340
- if (typeof body.ignoreSpaceChange === "boolean" && body.ignoreSpaceChange !== diffOpts.ignoreSpaceChange) {
2341
- diffOpts = {
2342
- ...diffOpts,
2343
- ignoreSpaceChange: body.ignoreSpaceChange
2344
- };
2345
- whitespaceChanged = true;
2346
- }
2347
- if (typeof body.ignoreAllSpace === "boolean" && body.ignoreAllSpace !== diffOpts.ignoreAllSpace) {
2348
- diffOpts = {
2349
- ...diffOpts,
2350
- ignoreAllSpace: body.ignoreAllSpace
2351
- };
2352
- whitespaceChanged = true;
2353
- }
2354
- if (whitespaceChanged) broadcast("change", Date.now().toString());
2355
- return c.json(settings);
2356
- });
2357
- /** Patch live diff options (subset). Broadcasts `change` so clients refetch. */
2358
- app.put("/api/diff-options", async (c) => {
2359
- const body = await c.req.json().catch(() => ({}));
2360
- const next = { ...diffOpts };
2361
- if (typeof body.ignoreSpaceChange === "boolean") next.ignoreSpaceChange = body.ignoreSpaceChange;
2362
- if (typeof body.ignoreAllSpace === "boolean") next.ignoreAllSpace = body.ignoreAllSpace;
2363
- if (typeof body.ignoreBlankLines === "boolean") next.ignoreBlankLines = body.ignoreBlankLines;
2364
- diffOpts = next;
2365
- const settingsPatch = {};
2366
- if (typeof body.ignoreSpaceChange === "boolean") settingsPatch.ignoreSpaceChange = body.ignoreSpaceChange;
2367
- if (typeof body.ignoreAllSpace === "boolean") settingsPatch.ignoreAllSpace = body.ignoreAllSpace;
2368
- if (Object.keys(settingsPatch).length) saveSettings(settingsPatch);
2369
- broadcast("change", Date.now().toString());
2370
- return c.json({
2371
- ignoreSpaceChange: diffOpts.ignoreSpaceChange,
2372
- ignoreAllSpace: diffOpts.ignoreAllSpace,
2373
- ignoreBlankLines: diffOpts.ignoreBlankLines
2374
- });
2375
- });
2376
- app.get("/api/diff-options", (c) => {
2377
- return c.json({
2378
- ignoreSpaceChange: diffOpts.ignoreSpaceChange,
2379
- ignoreAllSpace: diffOpts.ignoreAllSpace,
2380
- ignoreBlankLines: diffOpts.ignoreBlankLines
2381
- });
2382
- });
2383
- app.post("/api/agent/progress", async (c) => {
2384
- const body = await c.req.json().catch(() => ({}));
2385
- const message = typeof body.message === "string" ? body.message.trim() : "";
2386
- if (!message) return c.json({ error: "message is required" }, 400);
2387
- const payload = {
2388
- at: Date.now(),
2389
- message,
2390
- model: typeof body.model === "string" ? body.model : void 0,
2391
- agentId: typeof body.agentId === "string" ? body.agentId : void 0,
2392
- commentId: typeof body.commentId === "string" ? body.commentId : void 0,
2393
- pct: typeof body.pct === "number" && body.pct >= 0 && body.pct <= 100 ? body.pct : void 0
2394
- };
2395
- lastAgentProgress = payload;
2396
- broadcast("agent-progress", JSON.stringify(payload));
2397
- return c.json({
2398
- ok: true,
2399
- ...payload
2400
- });
2401
- });
2402
- app.get("/api/agent/progress", (c) => {
2403
- return c.json({ progress: lastAgentProgress });
2404
- });
2405
- app.post("/api/agent/register", async (c) => {
2406
- const body = await c.req.json().catch(() => ({}));
2407
- const agentId = typeof body.agentId === "string" && body.agentId || crypto.randomUUID();
2408
- const model = typeof body.model === "string" ? body.model : void 0;
2409
- const label = typeof body.label === "string" ? body.label : void 0;
2410
- agentWaiters.set(agentId, {
2411
- model,
2412
- label,
2413
- connectedAt: Date.now()
2414
- });
2415
- broadcast("agent-status", JSON.stringify({
2416
- ...reviewSession.snapshot(),
2417
- agents: [...agentWaiters.entries()].map(([id, a]) => ({
2418
- id,
2419
- ...a
2420
- }))
2421
- }));
2422
- return c.json({
2423
- ok: true,
2424
- agentId
2425
- });
2426
- });
2427
- app.delete("/api/agent/register/:id", async (c) => {
2428
- const id = c.req.param("id");
2429
- agentWaiters.delete(id);
2430
- broadcast("agent-status", JSON.stringify({
2431
- ...reviewSession.snapshot(),
2432
- agents: [...agentWaiters.entries()].map(([aid, a]) => ({
2433
- id: aid,
2434
- ...a
2435
- }))
2436
- }));
2437
- return c.json({ ok: true });
2438
- });
2439
- app.get("/api/ui-state", async (c) => {
2440
- return c.json(await uiStateStore.getAll());
2441
- });
2442
- app.put("/api/ui-state", async (c) => {
2443
- const body = await c.req.json();
2444
- const merged = {
2445
- ...await uiStateStore.getAll(),
2446
- ...body
2447
- };
2448
- for (const key of Object.keys(body)) if (body[key] === null || body[key] === void 0) delete merged[key];
2449
- await uiStateStore.setAll(merged);
2450
- return c.json(merged);
2451
- });
2452
- app.get("/api/viewed", (c) => {
2453
- return c.json([...viewedFiles]);
2454
- });
2455
- app.put("/api/viewed", async (c) => {
2456
- const { filePath, viewed } = await c.req.json();
2457
- if (viewed) viewedFiles.add(filePath);
2458
- else viewedFiles.delete(filePath);
2459
- broadcast("viewed", JSON.stringify([...viewedFiles]));
2460
- return c.json({ ok: true });
2461
- });
2462
- app.get("/api/comments", async (c) => {
2463
- const comments = await store.getAll();
2464
- return c.json(comments);
2465
- });
2466
- app.post("/api/comments/resolve-all", async (c) => {
2467
- const resolved = await store.resolveAllOpen();
2468
- return c.json({
2469
- ok: true,
2470
- resolved
2471
- });
2472
- });
2473
- app.post("/api/comments", async (c) => {
2474
- const body = await c.req.json();
2475
- const severityRaw = body.severity;
2476
- const severity = severityRaw === "blocking" || severityRaw === "nit" || severityRaw === "question" || severityRaw === "praise" || severityRaw === "none" ? severityRaw : void 0;
2477
- const comment = {
2478
- id: crypto.randomUUID(),
2479
- filePath: body.filePath,
2480
- side: body.side,
2481
- lineNumber: body.lineNumber,
2482
- startLineNumber: body.startLineNumber,
2483
- lineContent: body.lineContent,
2484
- body: body.body,
2485
- status: "open",
2486
- createdAt: Date.now(),
2487
- replies: [],
2488
- ...severity ? { severity } : {}
2489
- };
2490
- const created = await store.add(comment);
2491
- return c.json(created, 201);
2492
- });
2493
- app.put("/api/comments/:id", async (c) => {
2494
- const id = c.req.param("id");
2495
- const { body, status } = await c.req.json();
2496
- const updated = await store.update(id, {
2497
- body,
2498
- status
2499
- });
2500
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2501
- return c.json(updated);
2502
- });
2503
- app.post("/api/comments/:id/replies", async (c) => {
2504
- const commentId = c.req.param("id");
2505
- const { body, role, model } = await c.req.json();
2506
- const reply = {
2507
- id: crypto.randomUUID(),
2508
- body,
2509
- createdAt: Date.now(),
2510
- role: role || (model ? "agent" : "user"),
2511
- model: model || void 0
2512
- };
2513
- const updated = await store.addReply(commentId, reply);
2514
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2515
- return c.json(updated);
2516
- });
2517
- app.delete("/api/comments/:id/replies/:replyId", async (c) => {
2518
- const commentId = c.req.param("id");
2519
- const replyId = c.req.param("replyId");
2520
- const updated = await store.removeReply(commentId, replyId);
2521
- if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
2522
- return c.json(updated);
2523
- });
2524
- app.put("/api/comments/:id/replies/:replyId", async (c) => {
2525
- const commentId = c.req.param("id");
2526
- const replyId = c.req.param("replyId");
2527
- const { body } = await c.req.json();
2528
- if (!body) return c.json({ error: "Body is required" }, 400);
2529
- const updated = await store.updateReply(commentId, replyId, body);
2530
- if (!updated) return c.json({ error: "Comment or reply not found" }, 404);
2531
- return c.json(updated);
2532
- });
2533
- app.post("/api/comments/:id/apply-suggestion", async (c) => {
2534
- const id = c.req.param("id");
2535
- const comment = (await store.getAll()).find((c) => c.id === id);
2536
- if (!comment) return c.json({ error: "Comment not found" }, 404);
2537
- try {
2538
- const root = getRepoRoot();
2539
- const relPath = toSafeRelativePath(comment.filePath, root);
2540
- if (!relPath) return c.json({ error: "Forbidden file path" }, 403);
2541
- const absolutePath = resolve(root, relPath);
2542
- const content = await readFile(absolutePath, "utf-8");
2543
- const { applySuggestionToContent } = await import("./apply-suggestion-BAuyCYk6.mjs");
2544
- const result = applySuggestionToContent({
2545
- content,
2546
- lineNumber: comment.lineNumber,
2547
- startLineNumber: comment.startLineNumber,
2548
- body: comment.body,
2549
- side: comment.side
2550
- });
2551
- if (!result.ok) return c.json({ error: result.error }, 400);
2552
- await writeFile(absolutePath, result.content, "utf-8");
2553
- await store.update(id, { status: "resolved" });
2554
- return c.json({
2555
- ok: true,
2556
- replacedLines: result.replacedLines
2557
- });
2558
- } catch (err) {
2559
- return c.json({ error: `Failed to apply suggestion: ${err.message}` }, 500);
2560
- }
2561
- });
2562
- app.delete("/api/comments/:id", async (c) => {
2563
- const id = c.req.param("id");
2564
- if (!await store.remove(id)) return c.json({ error: "Comment not found" }, 404);
2565
- return c.json({ ok: true });
2566
- });
2567
- /** Shared helper: 404 with a stable shape so the client knows "not in PR mode". */
2568
- const notInPrMode = (c) => c.json({
2569
- error: "Not in PR review mode",
2570
- prMode: false
2571
- }, 404);
2572
- app.get("/api/gh/session", async (c) => {
2573
- if (!prMode) return c.json({ prMode: false });
2574
- const session = await prStore.get();
2575
- if (!session) return c.json({ prMode: false });
2576
- return c.json({
2577
- prMode: true,
2578
- ref: session.ref,
2579
- owner: session.owner,
2580
- repo: session.repo,
2581
- pullNumber: session.pullNumber,
2582
- baseSha: session.baseSha,
2583
- headSha: session.headSha,
2584
- title: session.title,
2585
- url: session.url,
2586
- author: session.author,
2587
- additions: session.additions,
2588
- deletions: session.deletions,
2589
- changedFiles: session.changedFiles,
2590
- existingComments: session.existingComments,
2591
- submittedAt: session.submittedAt,
2592
- submittedReviewId: session.submittedReviewId,
2593
- submittedReviewUrl: session.submittedReviewUrl,
2594
- authSource: session.authSource
2595
- });
2596
- });
2597
- /** Re-fetch PR metadata (head SHA, diff, existing comments) and persist. */
2598
- app.post("/api/gh/pr/refresh", async (c) => {
2599
- if (!prMode) return notInPrMode(c);
2600
- const session = await prStore.get();
2601
- if (!session) return notInPrMode(c);
2602
- try {
2603
- const refreshed = await refreshPrSession(session);
2604
- await prStore.set(refreshed);
2605
- return c.json({
2606
- ok: true,
2607
- headSha: refreshed.headSha
2608
- });
2609
- } catch (err) {
2610
- return c.json({ error: err?.message ?? "Refresh failed" }, 500);
2611
- }
2612
- });
2613
- /** CI / check-runs status for the PR head. */
2614
- app.get("/api/gh/checks", async (c) => {
2615
- if (!prMode) return notInPrMode(c);
2616
- const session = await prStore.get();
2617
- if (!session) return notInPrMode(c);
2618
- try {
2619
- const { fetchPrChecks } = await import("./github-C9GLNak7.mjs");
2620
- const checks = await fetchPrChecks({
2621
- owner: session.owner,
2622
- repo: session.repo,
2623
- pullNumber: session.pullNumber,
2624
- ref: session.ref
2625
- }, session.headSha);
2626
- const summary = {
2627
- total: checks.length,
2628
- success: checks.filter((x) => x.state === "success").length,
2629
- failure: checks.filter((x) => x.state === "failure" || x.state === "error").length,
2630
- pending: checks.filter((x) => x.state === "pending").length
2631
- };
2632
- return c.json({
2633
- checks,
2634
- summary,
2635
- headSha: session.headSha
2636
- });
2637
- } catch (err) {
2638
- return c.json({
2639
- error: err?.message ?? "Failed to fetch checks",
2640
- checks: [],
2641
- summary: null
2642
- }, 500);
2643
- }
2644
- });
2645
- /** Reply to an existing GitHub review comment thread. */
2646
- app.post("/api/gh/existing-comments/:id/replies", async (c) => {
2647
- if (!prMode) return notInPrMode(c);
2648
- const session = await prStore.get();
2649
- if (!session) return notInPrMode(c);
2650
- const id = Number(c.req.param("id"));
2651
- if (!Number.isFinite(id)) return c.json({ error: "Invalid comment id" }, 400);
2652
- const body = await c.req.json().catch(() => ({}));
2653
- const text = typeof body.body === "string" ? body.body.trim() : "";
2654
- if (!text) return c.json({ error: "body is required" }, 400);
2655
- try {
2656
- const { replyToPrComment } = await import("./github-C9GLNak7.mjs");
2657
- const result = await replyToPrComment({
2658
- resolved: {
2659
- owner: session.owner,
2660
- repo: session.repo,
2661
- pullNumber: session.pullNumber,
2662
- ref: session.ref
2663
- },
2664
- inReplyTo: id,
2665
- body: text
2666
- });
2667
- if (!result.ok) return c.json({ error: result.error ?? "Reply failed" }, 500);
2668
- const refreshed = await refreshPrSession(session);
2669
- await prStore.set(refreshed);
2670
- return c.json({
2671
- ok: true,
2672
- id: result.id
2673
- });
2674
- } catch (err) {
2675
- return c.json({ error: err?.message ?? "Reply failed" }, 500);
2676
- }
2677
- });
2678
- /** Initialize a PR session from a ref like `1234`, `o/r#42`, or a GitHub URL. */
2679
- app.post("/api/gh/pr/init", async (c) => {
2680
- if (!prMode) return notInPrMode(c);
2681
- const body = await c.req.json().catch(() => ({}));
2682
- const ref = typeof body?.ref === "string" ? body.ref : "";
2683
- if (!ref.trim()) return c.json({ error: "ref is required" }, 400);
2684
- try {
2685
- parsePrRef(ref, await detectCwdRepo() ?? void 0);
2686
- const session = await buildPrSession(ref);
2687
- await prStore.set(session);
2688
- return c.json({
2689
- ok: true,
2690
- ref: session.ref,
2691
- owner: session.owner,
2692
- repo: session.repo,
2693
- pullNumber: session.pullNumber,
2694
- url: session.url
2695
- });
2696
- } catch (err) {
2697
- return c.json({ error: err?.message ?? "Failed to initialise PR session" }, 500);
2698
- }
2699
- });
2700
- app.get("/api/gh/pr-session/comments", async (c) => {
2701
- if (!prMode) return notInPrMode(c);
2702
- const session = await prStore.get();
2703
- if (!session) return notInPrMode(c);
2704
- return c.json(session.comments ?? []);
2705
- });
2706
- app.post("/api/gh/pr-session/comments", async (c) => {
2707
- if (!prMode) return notInPrMode(c);
2708
- const body = await c.req.json();
2709
- const session = await prStore.get();
2710
- if (!session) return notInPrMode(c);
2711
- const comment = {
2712
- id: crypto.randomUUID(),
2713
- filePath: body.filePath,
2714
- side: body.side,
2715
- lineNumber: body.lineNumber,
2716
- startLineNumber: body.startLineNumber,
2717
- lineContent: body.lineContent,
2718
- body: body.body,
2719
- status: "open",
2720
- createdAt: Date.now(),
2721
- replies: []
2722
- };
2723
- const next = {
2724
- ...session,
2725
- comments: [...session.comments ?? [], comment]
2726
- };
2727
- await prStore.set(next);
2728
- return c.json(comment, 201);
2729
- });
2730
- app.put("/api/gh/pr-session/comments/:id", async (c) => {
2731
- if (!prMode) return notInPrMode(c);
2732
- const id = c.req.param("id");
2733
- const { body, status } = await c.req.json();
2734
- const session = await prStore.get();
2735
- if (!session) return notInPrMode(c);
2736
- const comments = (session.comments ?? []).map((cm) => cm.id === id ? {
2737
- ...cm,
2738
- body: body ?? cm.body,
2739
- status: status ?? cm.status
2740
- } : cm);
2741
- await prStore.set({
2742
- ...session,
2743
- comments
2744
- });
2745
- const updated = comments.find((cm) => cm.id === id) ?? null;
2746
- if (!updated) return c.json({ error: "Comment not found" }, 404);
2747
- return c.json(updated);
2748
- });
2749
- app.delete("/api/gh/pr-session/comments/:id", async (c) => {
2750
- if (!prMode) return notInPrMode(c);
2751
- const id = c.req.param("id");
2752
- const session = await prStore.get();
2753
- if (!session) return notInPrMode(c);
2754
- const comments = (session.comments ?? []).filter((cm) => cm.id !== id);
2755
- await prStore.set({
2756
- ...session,
2757
- comments
2758
- });
2759
- return c.json({ ok: true });
2760
- });
2761
- app.post("/api/gh/pr-session/comments/:id/replies", async (c) => {
2762
- if (!prMode) return notInPrMode(c);
2763
- const id = c.req.param("id");
2764
- const { body, role, model } = await c.req.json();
2765
- const session = await prStore.get();
2766
- if (!session) return notInPrMode(c);
2767
- const comments = (session.comments ?? []).map((cm) => {
2768
- if (cm.id !== id) return cm;
2769
- const reply = {
2770
- id: crypto.randomUUID(),
2771
- body,
2772
- createdAt: Date.now(),
2773
- role: role || (model ? "agent" : "user"),
2774
- model: model || void 0
2775
- };
2776
- return {
2777
- ...cm,
2778
- replies: [...cm.replies ?? [], reply]
2779
- };
2780
- });
2781
- await prStore.set({
2782
- ...session,
2783
- comments
2784
- });
2785
- return c.json(comments.find((cm) => cm.id === id));
2786
- });
2787
- /** Submit the current PR session's review (new comments + verdict + body) to GitHub. */
2788
- app.post("/api/gh/submit", async (c) => {
2789
- if (!prMode) return notInPrMode(c);
2790
- const session = await prStore.get();
2791
- if (!session) return notInPrMode(c);
2792
- const body = await c.req.json().catch(() => ({}));
2793
- const decision = body.decision;
2794
- if (decision !== "approve" && decision !== "comment" && decision !== "request-changes" && decision !== "draft") return c.json({ error: "decision must be one of: approve, comment, request-changes, draft" }, 400);
2795
- const generalBody = typeof body.body === "string" ? body.body : "";
2796
- if (body.dryRun === true) {
2797
- const { buildReviewPayload } = await import("./github-C9GLNak7.mjs");
2798
- const payload = buildReviewPayload({
2799
- decision,
2800
- body: generalBody,
2801
- comments: session.comments ?? []
2802
- });
2803
- return c.json({
2804
- ok: true,
2805
- dryRun: true,
2806
- authSource: session.authSource ?? "none",
2807
- failedComments: 0,
2808
- payload
2809
- });
2810
- }
2811
- const result = await submitReview({
2812
- resolved: {
2813
- owner: session.owner,
2814
- repo: session.repo,
2815
- pullNumber: session.pullNumber,
2816
- ref: session.ref
2817
- },
2818
- decision,
2819
- body: generalBody,
2820
- comments: session.comments ?? []
2821
- });
2822
- if (result.ok) {
2823
- const next = {
2824
- ...session,
2825
- submittedAt: Date.now(),
2826
- submittedReviewId: result.reviewId,
2827
- submittedReviewUrl: result.reviewUrl,
2828
- authSource: result.authSource
2829
- };
2830
- await prStore.set(next);
2831
- }
2832
- return c.json({
2833
- ok: result.ok,
2834
- reviewId: result.reviewId,
2835
- reviewUrl: result.reviewUrl,
2836
- failedComments: result.failedComments ?? 0,
2837
- authSource: result.authSource,
2838
- error: result.error,
2839
- dryRun: false
2840
- });
2841
- });
2842
- app.post("/api/review/send", async (c) => {
2843
- const body = await c.req.json().catch(() => ({}));
2844
- const generalComment = typeof body?.generalComment === "string" ? body.generalComment : void 0;
2845
- const decision = body?.decision === "approved" || body?.decision === "changes-requested" || body?.decision === "rejected" || body?.decision === "comment-only" ? body.decision : void 0;
2846
- const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
2847
- const force = body?.force === true;
2848
- const all = await store.getAll();
2849
- const findings = scanReviewForSecrets({
2850
- generalComment,
2851
- comments: all
2852
- });
2853
- if (findings.length > 0 && !force) return c.json({
2854
- ok: false,
2855
- error: "secrets-detected",
2856
- findings
2857
- }, 400);
2858
- const openCount = all.filter((x) => x.status === "open").length;
2859
- let diffFingerprints;
2860
- try {
2861
- const { fingerprintDiffFiles } = await import("./diff-fingerprint-CWa-soYD.mjs");
2862
- if (prMode) {
2863
- const prSession = await prStore.get();
2864
- if (prSession?.diff) diffFingerprints = fingerprintDiffFiles(prSession.diff);
2865
- } else {
2866
- const live = await executeDiffWithMeta(diffOpts);
2867
- if (live.patch) diffFingerprints = fingerprintDiffFiles(live.patch);
2868
- }
2869
- } catch {}
2870
- const payload = reviewSession.send({
2871
- sentAt: Date.now(),
2872
- commentXml: formatComments(all, generalComment, decision, mode),
2873
- openCount,
2874
- comments: all,
2875
- decision,
2876
- mode,
2877
- diffFingerprints
2878
- });
2879
- return c.json({
2880
- ok: true,
2881
- round: payload.round,
2882
- openCount: payload.openCount,
2883
- decision: payload.decision,
2884
- mode: payload.mode,
2885
- waiters: reviewSession.snapshot().waiters,
2886
- secretsBypassed: findings.length > 0 && force,
2887
- hasSinceLastBaseline: Boolean(diffFingerprints && Object.keys(diffFingerprints).length > 0)
2888
- });
2889
- });
2890
- app.get("/api/review/await", async (c) => {
2891
- const sinceRaw = c.req.query("sinceRound");
2892
- const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
2893
- const requested = Number(c.req.query("timeoutMs")) || 25e3;
2894
- const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
2895
- const result = await reviewSession.await({
2896
- sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
2897
- timeoutMs,
2898
- signal: c.req.raw.signal
2899
- });
2900
- return c.json(result);
2901
- });
2902
- app.get("/api/review/status", (c) => {
2903
- return c.json(reviewSession.snapshot());
2904
- });
2905
- app.get("/api/review/history", (c) => {
2906
- return c.json({ rounds: reviewSession.getHistory() });
2907
- });
2908
- /**
2909
- * Files that differ from the last handoff baseline (content changed or new
2910
- * in the live diff). Used by the "Since last" file-tree chip.
2911
- */
2912
- app.get("/api/review/since-last", async (c) => {
2913
- const previous = reviewSession.getLastDiffFingerprints();
2914
- if (!previous) return c.json({
2915
- hasBaseline: false,
2916
- round: reviewSession.snapshot().round,
2917
- changed: [],
2918
- added: [],
2919
- removed: [],
2920
- reviewFiles: []
2921
- });
2922
- let currentPatch = "";
2923
- try {
2924
- if (prMode) currentPatch = (await prStore.get())?.diff ?? "";
2925
- else currentPatch = (await executeDiffWithMeta(diffOpts)).patch ?? "";
2926
- } catch (err) {
2927
- return c.json({ error: err?.message ?? "Failed to compute current diff" }, 500);
2928
- }
2929
- const { fingerprintDiffFiles, diffSinceLast, filesToReviewSinceLast } = await import("./diff-fingerprint-CWa-soYD.mjs");
2930
- const delta = diffSinceLast(previous, fingerprintDiffFiles(currentPatch));
2931
- return c.json({
2932
- hasBaseline: true,
2933
- round: reviewSession.snapshot().round,
2934
- ...delta,
2935
- reviewFiles: filesToReviewSinceLast(delta)
2936
- });
2937
- });
2938
- app.get("/api/plans", async (c) => {
2939
- return c.json(await plans.getAll());
2940
- });
2941
- app.get("/api/plans/:id", async (c) => {
2942
- const plan = await plans.get(c.req.param("id"));
2943
- if (!plan) return c.json({ error: "Plan not found" }, 404);
2944
- return c.json(plan);
2945
- });
2946
- app.get("/api/plans/:id/versions", async (c) => {
2947
- const plan = await plans.get(c.req.param("id"));
2948
- if (!plan) return c.json({ error: "Plan not found" }, 404);
2949
- return c.json(plan.versions ?? []);
2950
- });
2951
- app.get("/api/plans/:id/versions/:n", async (c) => {
2952
- const id = c.req.param("id");
2953
- const n = Number(c.req.param("n"));
2954
- if (!Number.isFinite(n) || n < 1) return c.json({ error: "version must be a positive integer" }, 400);
2955
- const plan = await plans.get(id);
2956
- if (!plan) return c.json({ error: "Plan not found" }, 404);
2957
- const version = (plan.versions ?? []).find((v) => v.version === n);
2958
- if (!version) return c.json({ error: `Version ${n} not found` }, 404);
2959
- return c.json({
2960
- version,
2961
- plan: {
2962
- id: plan.id,
2963
- title: plan.title,
2964
- decision: plan.decision,
2965
- currentVersion: plan.version
2966
- }
2967
- });
2968
- });
2969
- app.post("/api/plans", async (c) => {
2970
- const body = await c.req.json().catch(() => ({}));
2971
- if (typeof body.body !== "string" || !body.body.trim()) return c.json({ error: "A plan body (markdown) is required" }, 400);
2972
- const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "Untitled plan";
2973
- const plan = await plans.upsert({
2974
- id: typeof body.id === "string" && body.id ? body.id : void 0,
2975
- title,
2976
- body: body.body,
2977
- source: typeof body.source === "string" ? body.source : void 0,
2978
- model: typeof body.model === "string" ? body.model : void 0
2979
- });
2980
- return c.json(plan, 201);
2981
- });
2982
- app.put("/api/plans/:id", async (c) => {
2983
- const id = c.req.param("id");
2984
- const { title, body, source, model } = await c.req.json().catch(() => ({}));
2985
- const updated = await plans.update(id, {
2986
- title: typeof title === "string" ? title : void 0,
2987
- body: typeof body === "string" ? body : void 0,
2988
- source: typeof source === "string" ? source : void 0,
2989
- model: typeof model === "string" ? model : void 0
2990
- });
2991
- if (!updated) return c.json({ error: "Plan not found" }, 404);
2992
- return c.json(updated);
2993
- });
2994
- app.delete("/api/plans/:id", async (c) => {
2995
- if (!await plans.remove(c.req.param("id"))) return c.json({ error: "Plan not found" }, 404);
2996
- return c.json({ ok: true });
2997
- });
2998
- app.post("/api/plans/:id/comments", async (c) => {
2999
- const planId = c.req.param("id");
3000
- const plan = await plans.get(planId);
3001
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3002
- const body = await c.req.json();
3003
- const lineNumber = Number.isFinite(body.lineNumber) ? Number(body.lineNumber) : 0;
3004
- const startLineNumber = Number.isFinite(body.startLineNumber) ? Number(body.startLineNumber) : void 0;
3005
- const anchorStart = startLineNumber ?? lineNumber;
3006
- const lineContent = typeof body.lineContent === "string" && body.lineContent ? body.lineContent : lineNumber > 0 ? extractPlanLines(plan.body, anchorStart, lineNumber) : "";
3007
- const sectionTitle = typeof body.sectionTitle === "string" && body.sectionTitle ? body.sectionTitle : lineNumber > 0 ? sectionTitleForLine(plan.body, anchorStart) : void 0;
3008
- const createdAtPlanVersion = Number.isFinite(body.createdAtPlanVersion) ? Number(body.createdAtPlanVersion) : plan.version;
3009
- const comment = {
3010
- id: crypto.randomUUID(),
3011
- lineNumber,
3012
- startLineNumber,
3013
- lineContent,
3014
- sectionTitle,
3015
- body: body.body,
3016
- status: "open",
3017
- createdAt: Date.now(),
3018
- createdAtPlanVersion,
3019
- replies: []
3020
- };
3021
- const updated = await plans.addComment(planId, comment);
3022
- if (!updated) return c.json({ error: "Plan not found" }, 404);
3023
- return c.json(updated, 201);
3024
- });
3025
- app.put("/api/plans/:id/comments/:commentId", async (c) => {
3026
- const { body, status } = await c.req.json();
3027
- const updated = await plans.updateComment(c.req.param("id"), c.req.param("commentId"), {
3028
- body,
3029
- status
3030
- });
3031
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3032
- return c.json(updated);
3033
- });
3034
- app.delete("/api/plans/:id/comments/:commentId", async (c) => {
3035
- const updated = await plans.removeComment(c.req.param("id"), c.req.param("commentId"));
3036
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3037
- return c.json(updated);
3038
- });
3039
- app.post("/api/plans/:id/comments/:commentId/replies", async (c) => {
3040
- const { body, role, model } = await c.req.json();
3041
- const reply = {
3042
- id: crypto.randomUUID(),
3043
- body,
3044
- createdAt: Date.now(),
3045
- role: role || (model ? "agent" : "user"),
3046
- model: model || void 0
3047
- };
3048
- const updated = await plans.addReply(c.req.param("id"), c.req.param("commentId"), reply);
3049
- if (!updated) return c.json({ error: "Plan or comment not found" }, 404);
3050
- return c.json(updated);
3051
- });
3052
- app.put("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3053
- const { body } = await c.req.json();
3054
- if (!body) return c.json({ error: "Body is required" }, 400);
3055
- const updated = await plans.updateReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"), body);
3056
- if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3057
- return c.json(updated);
3058
- });
3059
- app.delete("/api/plans/:id/comments/:commentId/replies/:replyId", async (c) => {
3060
- const updated = await plans.removeReply(c.req.param("id"), c.req.param("commentId"), c.req.param("replyId"));
3061
- if (!updated) return c.json({ error: "Plan, comment, or reply not found" }, 404);
3062
- return c.json(updated);
3063
- });
3064
- app.post("/api/plans/:id/decision", async (c) => {
3065
- const planId = c.req.param("id");
3066
- const body = await c.req.json().catch(() => ({}));
3067
- const decision = body.decision;
3068
- 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);
3069
- const decisionComment = typeof body.decisionComment === "string" ? body.decisionComment : void 0;
3070
- const mode = body?.mode === "comment-only" || body?.mode === "standard" ? body.mode : "standard";
3071
- const plan = await plans.setDecision(planId, decision, decisionComment);
3072
- if (!plan) return c.json({ error: "Plan not found" }, 404);
3073
- const openCommentCount = (plan.comments ?? []).filter((x) => x.status === "open").length;
3074
- const payload = planReviewSession.decide({
3075
- sentAt: Date.now(),
3076
- planId,
3077
- decision,
3078
- decisionComment: plan.decisionComment,
3079
- reviewXml: formatPlanReview(plan, { mode }),
3080
- openCommentCount,
3081
- plan,
3082
- mode
3083
- });
3084
- return c.json({
3085
- ok: true,
3086
- round: payload.round,
3087
- decision,
3088
- mode: payload.mode,
3089
- openCommentCount,
3090
- waiters: planReviewSession.snapshot().waiters
3091
- });
3092
- });
3093
- app.get("/api/plan-review/await", async (c) => {
3094
- const sinceRaw = c.req.query("sinceRound");
3095
- const sinceRound = sinceRaw !== void 0 && sinceRaw !== "" ? Number(sinceRaw) : void 0;
3096
- const requested = Number(c.req.query("timeoutMs")) || 25e3;
3097
- const timeoutMs = Math.min(Math.max(requested, 1e3), 5e4);
3098
- const result = await planReviewSession.await({
3099
- sinceRound: Number.isNaN(sinceRound) ? void 0 : sinceRound,
3100
- timeoutMs,
3101
- signal: c.req.raw.signal
3102
- });
3103
- return c.json(result);
3104
- });
3105
- app.get("/api/plan-review/status", (c) => {
3106
- return c.json(planReviewSession.snapshot());
3107
- });
3108
- app.post("/api/attachments", async (c) => {
3109
- const file = (await c.req.parseBody())["file"];
3110
- if (!file || !(file instanceof File)) return c.json({ error: "No file uploaded" }, 400);
3111
- try {
3112
- const storageDir = getProjectStorageDir();
3113
- const attachmentsDir = join(storageDir, "attachments");
3114
- await mkdir(attachmentsDir, { recursive: true });
3115
- const repoRoot = getRepoRoot();
3116
- await writeFile(join(storageDir, "repo_path.txt"), repoRoot, "utf-8");
3117
- const ext = extname(file.name) || ".png";
3118
- const filename = `pasted_image_${crypto.randomUUID()}${ext}`;
3119
- const absolutePath = join(attachmentsDir, filename);
3120
- const arrayBuffer = await file.arrayBuffer();
3121
- await writeFile(absolutePath, new Uint8Array(arrayBuffer));
3122
- return c.json({ url: `/api/attachments/${filename}` });
3123
- } catch (err) {
3124
- return c.json({ error: `Failed to save attachment: ${err.message}` }, 500);
3125
- }
3126
- });
3127
- app.get("/api/attachments/:filename", async (c) => {
3128
- const filename = c.req.param("filename");
3129
- const attachmentsDir = join(getProjectStorageDir(), "attachments");
3130
- const absolutePath = resolve(attachmentsDir, filename);
3131
- if (!absolutePath.startsWith(attachmentsDir)) return c.text("Forbidden", 403);
3132
- try {
3133
- const content = await readFile(absolutePath);
3134
- const contentType = MIME_TYPES[extname(absolutePath)] || "application/octet-stream";
3135
- return new Response(content, { headers: { "Content-Type": contentType } });
3136
- } catch {
3137
- return c.text("Attachment not found", 404);
3138
- }
3139
- });
3140
- app.get("/*", async (c) => {
3141
- let filePath = c.req.path;
3142
- if (filePath === "/") filePath = "/index.html";
3143
- const relativePath = filePath.slice(1);
3144
- if (!isSafePath(relativePath, clientDir)) return c.text("Forbidden", 403);
3145
- const fullPath = resolve(clientDir, relativePath);
3146
- try {
3147
- const content = await readFile(fullPath);
3148
- const contentType = MIME_TYPES[extname(fullPath)] || "application/octet-stream";
3149
- return new Response(content, { headers: { "Content-Type": contentType } });
3150
- } catch {
3151
- const indexContent = await readFile(join(clientDir, "index.html"));
3152
- return new Response(indexContent, { headers: { "Content-Type": "text/html" } });
3153
- }
3154
- });
3155
- return app;
3156
- }
3157
- /**
3158
- * Newest mtime (epoch ms) across everything that counts as project activity:
3159
- * comments.json, plans.json, and any attachment (media) file. Plans and media
3160
- * extend a project's life exactly like comments do, so retention is uniform
3161
- * across all three. Returns null when none of them exist yet.
3162
- */
3163
- async function newestActivityMs(projectDir) {
3164
- const candidates = [];
3165
- const safeStat = async (p) => {
3166
- try {
3167
- return (await stat(p)).mtimeMs;
3168
- } catch {
3169
- return null;
3170
- }
3171
- };
3172
- for (const name of [
3173
- "comments.json",
3174
- "plans.json",
3175
- "pr-session.json"
3176
- ]) {
3177
- const file = join(projectDir, name);
3178
- if (!existsSync(file)) continue;
3179
- const m = await safeStat(file);
3180
- if (m !== null) candidates.push(m);
3181
- }
3182
- const attachmentsDir = join(projectDir, "attachments");
3183
- if (existsSync(attachmentsDir)) {
3184
- const dirM = await safeStat(attachmentsDir);
3185
- if (dirM !== null) candidates.push(dirM);
3186
- try {
3187
- for (const file of await readdir(attachmentsDir)) {
3188
- const m = await safeStat(join(attachmentsDir, file));
3189
- if (m !== null) candidates.push(m);
3190
- }
3191
- } catch {}
3192
- }
3193
- return candidates.length ? Math.max(...candidates) : null;
3194
- }
3195
- async function cleanupStaleProjects() {
3196
- const baseDir = join(homedir(), ".diffing");
3197
- if (!existsSync(baseDir)) return;
3198
- try {
3199
- const entries = await readdir(baseDir, { withFileTypes: true });
3200
- const now = Date.now();
3201
- const STALE_TIME = 336 * 60 * 60 * 1e3;
3202
- for (const entry of entries) if (entry.isDirectory()) {
3203
- const projectDir = join(baseDir, entry.name);
3204
- const repoPathFile = join(projectDir, "repo_path.txt");
3205
- let shouldDelete = false;
3206
- if (existsSync(repoPathFile)) try {
3207
- const repoPath = (await readFile(repoPathFile, "utf-8")).trim();
3208
- if (!repoPath || !existsSync(repoPath)) shouldDelete = true;
3209
- } catch {}
3210
- if (!shouldDelete) {
3211
- const newest = await newestActivityMs(projectDir);
3212
- if (newest !== null && now - newest > STALE_TIME) shouldDelete = true;
3213
- }
3214
- if (shouldDelete) await rm(projectDir, {
3215
- recursive: true,
3216
- force: true
3217
- });
3218
- }
3219
- } catch (err) {
3220
- console.error("Failed to cleanup stale projects:", err);
3221
- }
3222
- }
3223
- async function startServer(options) {
3224
- cleanupStaleProjects().catch((err) => {
3225
- console.error("Failed to clean up stale projects:", err);
3226
- });
3227
- let prMode = false;
3228
- if (options.prRef) {
3229
- console.error(`Building PR session for ${options.prRef}...`);
3230
- try {
3231
- const store = new FilePrSessionStore();
3232
- const existing = await store.get();
3233
- if (!existing || existing.ref !== options.prRef) {
3234
- const session = await buildPrSession(options.prRef);
3235
- await store.set(session);
3236
- }
3237
- prMode = true;
3238
- } catch (err) {
3239
- const detail = err?.message ?? String(err);
3240
- throw new Error(`Failed to build PR session for ${options.prRef}: ${detail}`);
3241
- }
3242
- }
3243
- const app = createApp(options.clientDir, options.diffOpts, void 0, void 0, void 0, prMode);
3244
- return new Promise((resolve) => {
3245
- serve({
3246
- fetch: app.fetch,
3247
- port: options.port,
3248
- hostname: options.host
3249
- }, (info) => {
3250
- resolve({
3251
- port: info.port,
3252
- prMode
3253
- });
3254
- });
3255
- });
3256
- }
3257
- //#endregion
3258
- export { intoShowMode as a, buildGitDiffArgs as i, runTerminalDiff as n, parseDiffOptions as o, validateEnvironment as r, printHelp as s, startServer as t };