@evandu/super-pi-server 0.0.0-stage → 0.1.260

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 (370) hide show
  1. package/README.md +250 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +396 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +450 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,903 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { promisify } from "node:util";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { existsSync } from "node:fs";
6
+ import { mkdir, readFile, realpath, stat } from "node:fs/promises";
7
+ import { MAX_FILE_BYTES } from "./files.js";
8
+ const exec = promisify(execFile);
9
+ async function git(cwd, args, options) { return exec("git", ["--literal-pathspecs", "-c", "core.quotepath=false", ...args], { cwd, windowsHide: true, maxBuffer: options?.maxBuffer ?? 8 * 1024 * 1024, timeout: options?.timeout }); }
10
+ function files(raw, cwd = "") {
11
+ const staged = [], unstaged = [], untracked = [];
12
+ const records = raw.split("\0");
13
+ for (let index = 0; index < records.length; index++) {
14
+ const line = records[index];
15
+ if (!line || line.length < 4)
16
+ continue;
17
+ const xy = line.slice(0, 2), repoPath = line.slice(3).replaceAll("\\", "/");
18
+ // Porcelain -z emits a second path for renames/copies; it is not a status record.
19
+ if (/[RC]/.test(xy))
20
+ index++;
21
+ const path = cwd && repoPath.startsWith(cwd + "/") ? repoPath.slice(cwd.length + 1) : repoPath;
22
+ const item = { path, name: basename(path), xy };
23
+ if (xy === "??")
24
+ untracked.push(item);
25
+ else {
26
+ if (xy[0] !== " ")
27
+ staged.push(item);
28
+ if (xy[1] !== " ")
29
+ unstaged.push(item);
30
+ }
31
+ }
32
+ return { staged, unstaged, untracked };
33
+ }
34
+ export async function gitStatus(root, cwd = "") {
35
+ const repoRoot = await worktreeRoot(root);
36
+ const scope = relative(repoRoot, resolve(root, cwd)).split(sep).join("/");
37
+ const [status, branch, hasHead, counts] = await Promise.all([
38
+ git(root, ["status", "--porcelain=v1", "-z", ...(scope ? ["--", cwd || "."] : [])]),
39
+ git(root, ["symbolic-ref", "--short", "-q", "HEAD"]).then(result => result.stdout.trim() || null).catch(() => null),
40
+ git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false),
41
+ git(root, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])
42
+ .then(result => result.stdout.trim().split(/\s+/).map(Number)).catch(() => []),
43
+ ]);
44
+ const [ahead, behind] = counts;
45
+ return { branch, detached: !branch, unborn: !hasHead, ahead: ahead ?? null, behind: behind ?? null, ...files(status.stdout, scope) };
46
+ }
47
+ function pageNumber(value, fallback, min, max) {
48
+ return Number.isSafeInteger(value) ? Math.min(max, Math.max(min, value)) : fallback;
49
+ }
50
+ function gitFailure(message, code) {
51
+ return Object.assign(new Error(message), { code });
52
+ }
53
+ export async function gitLog(root, limit, cwd = "", query = "", offset = 0) {
54
+ const entireRepo = await canChangeWorktree(root, cwd);
55
+ const hasHead = await git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false);
56
+ if (!hasHead)
57
+ return { commits: [], truncated: false };
58
+ const size = pageNumber(limit, 20, 1, 50);
59
+ const start = pageNumber(offset, 0, 0, 1_000_000);
60
+ const filter = query.trim().slice(0, 160);
61
+ const names = filter ? ["--fixed-strings", "--regexp-ignore-case", `--grep=${filter}`] : [];
62
+ const hash = /^[a-f0-9]{4,64}$/i.test(filter)
63
+ ? await git(root, ["rev-parse", "--verify", `${filter}^{commit}`]).then(result => result.stdout.trim()).catch(() => "")
64
+ : "";
65
+ const format = "--format=%H%x00%h%x00%s%x00%an%x00%aI";
66
+ const args = hash && start === 0
67
+ ? ["log", "-z", "-1", "--no-walk", format, hash, "--"]
68
+ : ["log", "-z", `-${size + 1}`, `--skip=${start}`, format, ...names, "--", ...(!entireRepo ? [cwd || "."] : [])];
69
+ // In a scoped history, a named commit must also have changed something in the selected directory.
70
+ if (hash && start === 0 && !entireRepo) {
71
+ const matchingPaths = await git(root, ["diff-tree", "--root", "-m", "--no-commit-id", "--name-only", "-r", hash, "--", cwd || "."]);
72
+ if (!matchingPaths.stdout)
73
+ return { commits: [], truncated: false };
74
+ }
75
+ const commits = parseGitCommits((await git(root, args)).stdout);
76
+ return { commits: commits.slice(0, size), truncated: commits.length > size };
77
+ }
78
+ function parseGitCommits(raw) {
79
+ const parts = raw.split("\0");
80
+ const commits = [];
81
+ for (let i = 0; i + 4 < parts.length; i += 5) {
82
+ commits.push({ hash: parts[i], short: parts[i + 1], subject: parts[i + 2], author: parts[i + 3], date: new Date(parts[i + 4]).toISOString() });
83
+ }
84
+ return commits;
85
+ }
86
+ const COMMIT_HASH = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
87
+ export async function gitGraph(root, limit, offset, snapshot, after, knownSnapshot = "") {
88
+ const size = pageNumber(limit, 50, 1, 100);
89
+ const start = pageNumber(offset, 0, 0, 2_147_483_647);
90
+ const repo = await worktreeRoot(root);
91
+ const [refs, checkout] = await Promise.all([
92
+ git(repo, ["for-each-ref", "--format=%(refname)%00%(objectname)%00%(*objectname)%00%(symref)"], { maxBuffer: 32 * 1024 * 1024, timeout: 12_000 }),
93
+ gitWorktrees(repo),
94
+ ]);
95
+ const worktrees = checkout.worktrees.filter(entry => !entry.missing && COMMIT_HASH.test(entry.head) && !/^0+$/.test(entry.head));
96
+ const heads = worktrees.map(({ id, branch, head, current, name }) => ({ id, branch, head, current, name }));
97
+ const version = createHash("sha256").update(refs.stdout).update(JSON.stringify(heads)).digest("hex");
98
+ const changed = () => gitFailure("提交图已变化,请刷新后继续查看。", "graph_changed");
99
+ if (start && snapshot !== version)
100
+ throw changed();
101
+ if (!start && knownSnapshot === version)
102
+ return { unchanged: true, snapshot: version };
103
+ const labels = new Map();
104
+ const mark = (hash, label) => {
105
+ const list = labels.get(hash) ?? [];
106
+ list.push(label);
107
+ labels.set(hash, list);
108
+ };
109
+ for (const entry of worktrees) {
110
+ if (entry.current)
111
+ mark(entry.head, { kind: "head", name: entry.branch ? `HEAD → ${entry.branch}` : "HEAD" });
112
+ else {
113
+ const repeatedName = worktrees.some(other => other.id !== entry.id && other.name === entry.name);
114
+ const name = entry.branch ?? (repeatedName ? `${basename(dirname(entry.path))}/${entry.name}` : entry.name);
115
+ mark(entry.head, { kind: "worktree", name, checkoutId: entry.id });
116
+ }
117
+ }
118
+ for (const line of refs.stdout.split(/\r?\n/)) {
119
+ const [ref, hash, peeled, symbolic] = line.split("\0");
120
+ if (!ref || symbolic)
121
+ continue;
122
+ if (ref.startsWith("refs/heads/"))
123
+ mark(hash, { kind: "branch", name: ref.slice("refs/heads/".length) });
124
+ else if (ref.startsWith("refs/remotes/"))
125
+ mark(hash, { kind: "remote", name: ref.slice("refs/remotes/".length) });
126
+ else if (ref.startsWith("refs/tags/"))
127
+ mark(peeled || hash, { kind: "tag", name: ref.slice("refs/tags/".length) });
128
+ else if (ref === "refs/stash")
129
+ mark(hash, { kind: "stash", name: "Stash" });
130
+ }
131
+ const overlap = start ? 1 : 0;
132
+ const detached = worktrees.filter(entry => !entry.branch).map(entry => entry.head);
133
+ const format = "--format=%H%x00%h%x00%P%x00%s%x00%an%x00%aI";
134
+ const { stdout } = await git(repo, ["-c", "log.showSignature=false", "log", "--all", "--topo-order", "--no-notes", "--no-decorate",
135
+ "--no-patch", "--encoding=UTF-8", "-z", `--skip=${start - overlap}`, `-${size + 1 + overlap}`, format, ...detached, "--"], { timeout: 12_000 });
136
+ const parts = stdout.split("\0");
137
+ const commits = [];
138
+ for (let index = 0; index + 5 < parts.length; index += 6) {
139
+ const [hash, short, parents, subject, author, date] = parts.slice(index, index + 6);
140
+ commits.push({ hash, short, parents: parents ? parents.split(" ") : [], subject, author, date, refs: labels.get(hash) ?? [] });
141
+ }
142
+ if (overlap && commits.shift()?.hash !== after)
143
+ throw changed();
144
+ return { commits: commits.slice(0, size), snapshot: version, hasMore: commits.length > size };
145
+ }
146
+ const PATCH_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--submodule=short", "--full-index"];
147
+ const HISTORY_DIFF_OPTIONS = [...PATCH_OPTIONS, "--find-renames"];
148
+ const FULL_DIFF_MAX_BYTES = 2 * 1024 * 1024;
149
+ const FULL_DIFF_MAX_LINES = 12_000;
150
+ function patchContext(fullContext) {
151
+ // Any file that fits the full view limits fits within this unified context.
152
+ return fullContext ? "--unified=1000000" : "--unified=3";
153
+ }
154
+ async function readGitDiff(repo, args, fullContext = false) {
155
+ const tooLarge = () => fullContext
156
+ ? gitFailure("文件太大,无法一次展开全文。仍可查看改动。", "diff_context_too_large")
157
+ : gitFailure("差异或文件列表超过了查看上限。", "commit_diff_too_large");
158
+ let stdout;
159
+ try {
160
+ ({ stdout } = await git(repo, args, { timeout: 12_000, maxBuffer: fullContext ? FULL_DIFF_MAX_BYTES : undefined }));
161
+ }
162
+ catch (error) {
163
+ if (error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
164
+ throw tooLarge();
165
+ }
166
+ throw error;
167
+ }
168
+ if (fullContext) {
169
+ let offset = -1;
170
+ for (let line = 0; line < FULL_DIFF_MAX_LINES; line++) {
171
+ offset = stdout.indexOf("\n", offset + 1);
172
+ if (offset < 0)
173
+ return stdout;
174
+ }
175
+ if (offset < stdout.length - 1)
176
+ throw tooLarge();
177
+ }
178
+ return stdout;
179
+ }
180
+ async function commitSnapshot(root, cwd, revision) {
181
+ if (!COMMIT_HASH.test(revision))
182
+ throw gitFailure("请选择有效的提交哈希。", "bad_revision");
183
+ const hash = revision.toLowerCase();
184
+ const [repo, session] = await Promise.all([worktreeRoot(root).then(path => realpath(path)), realpath(resolve(root, cwd))]);
185
+ const scope = relative(repo, session).split(sep).join("/");
186
+ if (scope === ".." || scope.startsWith("../") || isAbsolute(scope)) {
187
+ throw gitFailure("会话目录位于 Git 仓库之外。", "outside_scope");
188
+ }
189
+ const type = await git(repo, ["cat-file", "-t", hash], { timeout: 12_000 }).then(result => result.stdout.trim()).catch(() => "");
190
+ if (type !== "commit")
191
+ throw gitFailure("找不到这个 Git 提交。", "not_found");
192
+ const raw = await readGitDiff(repo, ["cat-file", "commit", hash]);
193
+ const messageOffset = raw.indexOf("\n\n");
194
+ const message = messageOffset < 0 ? "" : raw.slice(messageOffset + 2).trimEnd();
195
+ const parents = (messageOffset < 0 ? raw : raw.slice(0, messageOffset)).split("\n")
196
+ .filter(line => line.startsWith("parent ")).map(line => line.slice(7));
197
+ if (parents.some(parent => !COMMIT_HASH.test(parent)))
198
+ throw gitFailure("这个提交的父版本记录无效。", "bad_revision");
199
+ const firstParent = parents[0];
200
+ const diff = (options, paths, exact = false, fullContext = false) => {
201
+ const flags = [...HISTORY_DIFF_OPTIONS, scope ? `--relative=${scope}` : "--no-relative", ...options];
202
+ // An escaped glob matches the file itself, even when that path was a directory in one tree.
203
+ const specs = exact ? paths.map(path => `:(top,glob)${path.replace(/[^/]/gu, "\\$&")}`) : paths;
204
+ const args = firstParent
205
+ ? ["diff", ...flags, firstParent, hash, "--", ...specs]
206
+ : ["diff-tree", "--root", "--no-commit-id", "-r", ...flags, hash, "--", ...specs];
207
+ return readGitDiff(repo, exact ? ["--no-literal-pathspecs", ...args] : args, fullContext);
208
+ };
209
+ // Read the parent from the stored commit. A shallow boundary is not a root commit.
210
+ if (firstParent && !await git(repo, ["cat-file", "-e", firstParent], { timeout: 12_000 }).then(() => true, () => false)) {
211
+ throw gitFailure("这个提交的父版本不在本地仓库中。", "not_found");
212
+ }
213
+ const records = (await diff(["--name-status", "-z"], scope ? [scope] : [])).split("\0");
214
+ const files = [];
215
+ for (let index = 0; index + 1 < records.length;) {
216
+ const status = records[index++];
217
+ const firstPath = records[index++];
218
+ if (status.startsWith("R") || status.startsWith("C")) {
219
+ files.push({ status, previousPath: firstPath, path: records[index++] });
220
+ }
221
+ else {
222
+ files.push({ status, path: firstPath });
223
+ }
224
+ }
225
+ return { detail: { hash, parents, message, files }, scope, diff };
226
+ }
227
+ export async function gitCommit(root, cwd, hash) {
228
+ return (await commitSnapshot(root, cwd, hash)).detail;
229
+ }
230
+ export async function gitCommitDiff(root, cwd, hash, path, fullContext = false) {
231
+ if (!path || path.includes("\0"))
232
+ throw gitFailure("请选择提交中的变更文件。", "path");
233
+ const { detail, scope, diff } = await commitSnapshot(root, cwd, hash);
234
+ // Match exact Git paths from the scoped tree diff. No live filesystem lookup is needed.
235
+ const file = detail.files.find(entry => entry.path === path);
236
+ if (!file)
237
+ throw gitFailure("这个提交在当前目录内没有该文件的差异。", "not_found");
238
+ const paths = (file.previousPath === undefined ? [file.path] : [file.previousPath, file.path])
239
+ .map(name => scope ? `${scope}/${name}` : name);
240
+ const patch = await diff(["--patch", patchContext(fullContext)], paths, true, fullContext);
241
+ const binary = /^Binary files .* differ$/m.test(patch);
242
+ return { path, staged: false, kind: binary ? "binary" : "text", diff: binary ? null : patch };
243
+ }
244
+ const normalizedPath = (path) => process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path);
245
+ async function worktreeRoot(root) {
246
+ return (await git(root, ["rev-parse", "--show-toplevel"])).stdout.replace(/\r?\n$/, "");
247
+ }
248
+ async function canChangeWorktree(root, cwd) {
249
+ return normalizedPath(resolve(root, cwd)) === normalizedPath(await worktreeRoot(root));
250
+ }
251
+ async function gitCommonDir(root) {
252
+ const { stdout } = await git(root, ["rev-parse", "--git-common-dir"]);
253
+ return realpath(resolve(root, stdout.replace(/\r?\n$/, "")));
254
+ }
255
+ let supportsNulWorktrees;
256
+ async function gitWorktreeList(root) {
257
+ const args = ["worktree", "list", "--porcelain"];
258
+ if (supportsNulWorktrees === false)
259
+ return { raw: (await git(root, args)).stdout, nul: false };
260
+ try {
261
+ const { stdout } = await git(root, [...args, "-z"]);
262
+ supportsNulWorktrees = true;
263
+ return { raw: stdout, nul: true };
264
+ }
265
+ catch (error) {
266
+ if (error?.code !== 129)
267
+ throw error;
268
+ const { stdout } = await git(root, args);
269
+ supportsNulWorktrees = false;
270
+ return { raw: stdout, nul: false };
271
+ }
272
+ }
273
+ const gitEscapes = {
274
+ a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", '"': '"',
275
+ };
276
+ function unquoteWorktreePath(field) {
277
+ if (!field.startsWith('"') || !field.endsWith('"'))
278
+ return field;
279
+ const quoted = field.slice(1, -1);
280
+ const chunks = [];
281
+ let from = 0;
282
+ for (const escape of quoted.matchAll(/\\([0-7]{1,3}|.)/gs)) {
283
+ chunks.push(Buffer.from(quoted.slice(from, escape.index)));
284
+ const code = escape[1];
285
+ chunks.push(/^[0-7]/.test(code) ? Buffer.from([parseInt(code, 8)]) : Buffer.from(gitEscapes[code] ?? code));
286
+ from = escape.index + escape[0].length;
287
+ }
288
+ chunks.push(Buffer.from(quoted.slice(from)));
289
+ return Buffer.concat(chunks).toString("utf8");
290
+ }
291
+ export function parseWorktreePorcelain(raw, nul) {
292
+ return raw.split(nul ? "\0\0" : /\r?\n\r?\n/).flatMap((record, index) => {
293
+ const fields = new Map();
294
+ let ambiguous = false;
295
+ for (const field of record.split(nul ? "\0" : /\r?\n/).filter(Boolean)) {
296
+ const separator = field.indexOf(" ");
297
+ const key = separator < 0 ? field : field.slice(0, separator);
298
+ if (fields.has(key))
299
+ ambiguous = true;
300
+ fields.set(key, separator < 0 ? "" : field.slice(separator + 1));
301
+ }
302
+ const path = fields.get("worktree");
303
+ const head = fields.get("HEAD");
304
+ if (ambiguous || !path || !head || !/^[a-f0-9]{40}([a-f0-9]{24})?$/.test(head) || fields.has("bare"))
305
+ return [];
306
+ return [{
307
+ path: nul ? path : unquoteWorktreePath(path), head, index,
308
+ branch: fields.get("branch")?.replace(/^refs\/heads\//, "") ?? null,
309
+ locked: fields.has("locked"), prunable: fields.has("prunable"),
310
+ }];
311
+ });
312
+ }
313
+ export async function gitWorktrees(root) {
314
+ const rootPath = await realpath(root);
315
+ const actualTop = await realpath(await worktreeRoot(root));
316
+ if (normalizedPath(rootPath) !== normalizedPath(actualTop)) {
317
+ throw gitFailure("在仓库根目录工作区中查看工作树", "outside_scope");
318
+ }
319
+ const [commonDir, result] = await Promise.all([
320
+ gitCommonDir(rootPath), gitWorktreeList(rootPath),
321
+ ]);
322
+ const worktrees = [];
323
+ for (const { path, head, index, branch, locked, prunable } of parseWorktreePorcelain(result.raw, result.nul)) {
324
+ const pathKey = normalizedPath(path);
325
+ const id = createHash("sha256").update(normalizedPath(commonDir)).update("\0").update(pathKey).digest("hex");
326
+ worktrees.push({
327
+ id, path, name: basename(path), branch, head, primary: index === 0, current: pathKey === normalizedPath(rootPath),
328
+ locked, missing: prunable || !existsSync(path),
329
+ });
330
+ }
331
+ return { worktrees, commonDir };
332
+ }
333
+ export async function resolveGitWorktree(root, id) {
334
+ const { worktrees, commonDir } = await gitWorktrees(root);
335
+ const entry = worktrees.find(worktree => worktree.id === id);
336
+ if (!entry || entry.missing)
337
+ throw gitFailure("此工作树已不存在,请刷新工作树列表", "not_found");
338
+ const checked = await Promise.all([realpath(entry.path), worktreeRoot(entry.path).then(path => realpath(path)), gitCommonDir(entry.path)]).catch(() => null);
339
+ if (!checked || normalizedPath(checked[0]) !== normalizedPath(checked[1]) || normalizedPath(checked[2]) !== normalizedPath(commonDir)) {
340
+ throw gitFailure("该目录已失效或不属于当前仓库", "not_found");
341
+ }
342
+ return { path: checked[0], entry, base: worktrees.find(item => item.primary && !item.missing) ?? worktrees.find(item => item.current) };
343
+ }
344
+ export async function createGitWorktree(root, storage, requestKey, options) {
345
+ const { worktrees, commonDir } = await gitWorktrees(root);
346
+ const project = createHash("sha256").update(normalizedPath(commonDir)).digest("hex").slice(0, 18);
347
+ const slot = createHash("sha256").update(requestKey).digest("hex").slice(0, 18);
348
+ const directory = join(storage, project, slot);
349
+ const path = join(directory, basename(root));
350
+ const known = worktrees.find(item => normalizedPath(item.path) === normalizedPath(path));
351
+ if (known) {
352
+ if (options.branch && known.branch !== options.branch)
353
+ throw gitFailure("该创建请求已绑定到另一分支", "bad_message");
354
+ return (await resolveGitWorktree(root, known.id)).entry;
355
+ }
356
+ if (options.branch) {
357
+ const valid = await git(root, ["check-ref-format", `refs/heads/${options.branch}`]).then(() => true).catch(() => false);
358
+ if (!valid || options.branch.startsWith("-"))
359
+ throw gitFailure("分支名不符合 Git 规范", "bad_message");
360
+ }
361
+ if (options.base && !await git(root, ["check-ref-format", `refs/heads/${options.base}`]).then(() => true).catch(() => false)) {
362
+ throw gitFailure("工作树起点须为本地分支名", "bad_revision");
363
+ }
364
+ const startRef = options.base ? `refs/heads/${options.base}` : "HEAD";
365
+ const { stdout } = await git(root, ["rev-parse", "--verify", `${startRef}^{commit}`]).catch(() => {
366
+ throw gitFailure("找不到工作树的起点,请选择已有提交的本地分支", "bad_revision");
367
+ });
368
+ await mkdir(directory, { recursive: true });
369
+ const checkout = options.branch ? ["-b", options.branch] : ["--detach"];
370
+ await git(root, ["worktree", "add", ...checkout, "--", path, stdout.trim()], { timeout: 60_000 });
371
+ const created = (await gitWorktrees(root)).worktrees.find(item => normalizedPath(item.path) === normalizedPath(path));
372
+ if (!created)
373
+ throw gitFailure("Git 未登记新工作树", "not_found");
374
+ return (await resolveGitWorktree(root, created.id)).entry;
375
+ }
376
+ const WORKTREE_COMMIT_LIMIT = 20;
377
+ async function worktreeComparisonBase(path, base) {
378
+ if (!base || !/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(base.head))
379
+ return null;
380
+ const target = await git(path, ["rev-parse", "--verify", "HEAD"]).then(result => result.stdout.trim()).catch(() => "");
381
+ if (!target)
382
+ return null;
383
+ const mergeBase = await git(path, ["merge-base", base.head, target]).then(result => result.stdout.trim()).catch(() => "");
384
+ return mergeBase ? { label: base.branch ?? base.head.slice(0, 8), head: base.head, target, mergeBase } : null;
385
+ }
386
+ export async function inspectGitWorktree(path, base) {
387
+ const [status, reference] = await Promise.all([gitStatus(path), worktreeComparisonBase(path, base)]);
388
+ if (!reference)
389
+ return { status, comparison: null };
390
+ const [counts, history, changes] = await Promise.all([
391
+ git(path, ["rev-list", "--left-right", "--count", `${reference.head}...${reference.target}`]),
392
+ git(path, ["log", "-z", `-${WORKTREE_COMMIT_LIMIT + 1}`, "--format=%H%x00%h%x00%s%x00%an%x00%aI", `${reference.head}..${reference.target}`, "--"]),
393
+ git(path, ["diff", "--name-status", "--no-renames", "-z", reference.mergeBase, reference.target, "--"]),
394
+ ]);
395
+ const [behind, ahead] = counts.stdout.trim().split(/\s+/).map(Number);
396
+ const commits = parseGitCommits(history.stdout);
397
+ const records = changes.stdout.split("\0");
398
+ const files = [];
399
+ for (let index = 0; index + 1 < records.length; index += 2) {
400
+ const [xy, file] = records.slice(index, index + 2);
401
+ files.push({ xy, path: file, name: basename(file) });
402
+ }
403
+ return { status, comparison: { base: reference.label, ahead, behind, commits: commits.slice(0, WORKTREE_COMMIT_LIMIT), truncated: commits.length > WORKTREE_COMMIT_LIMIT, files } };
404
+ }
405
+ export async function gitWorktreeCommittedDiff(root, base, path, fullContext = false) {
406
+ safePath(root, path);
407
+ const reference = await worktreeComparisonBase(root, base);
408
+ if (!reference)
409
+ return { path, staged: false, kind: "text", diff: "" };
410
+ const stdout = await readGitDiff(root, ["diff", ...PATCH_OPTIONS, patchContext(fullContext), reference.mergeBase, reference.target, "--", path], fullContext);
411
+ if (/^Binary files .* differ$/m.test(stdout))
412
+ return { path, staged: false, kind: "binary", diff: null };
413
+ return { path, staged: false, kind: "text", diff: stdout };
414
+ }
415
+ export async function gitBranches(root, cwd, query, offset) {
416
+ const canWrite = await canChangeWorktree(root, cwd);
417
+ const filter = query.trim().slice(0, 160).toLowerCase();
418
+ const start = pageNumber(offset, 0, 0, 1_000_000);
419
+ const format = "--format=%(refname)%00%(symref)%00%(HEAD)";
420
+ const { stdout } = await git(root, ["for-each-ref", "--sort=refname", format, "refs/heads", "refs/remotes"], { maxBuffer: 32 * 1024 * 1024 });
421
+ let total = 0, matches = 0;
422
+ const branches = [];
423
+ for (const line of stdout.split(/\r?\n/)) {
424
+ const [ref, target, head] = line.split("\0");
425
+ if (!ref || target)
426
+ continue;
427
+ total++;
428
+ const local = ref.startsWith("refs/heads/");
429
+ const name = ref.slice(local ? "refs/heads/".length : "refs/remotes/".length);
430
+ if (!name.toLowerCase().includes(filter))
431
+ continue;
432
+ const position = matches++;
433
+ if (position >= start && position < start + 50)
434
+ branches.push({ name, local, current: head === "*" });
435
+ }
436
+ return { branches, total, matches, canWrite };
437
+ }
438
+ export async function gitStashes(root, cwd, query = "", offset = 0) {
439
+ const canWrite = await canChangeWorktree(root, cwd);
440
+ const start = pageNumber(offset, 0, 0, 1_000_000);
441
+ const filter = query.trim().slice(0, 160).toLowerCase();
442
+ const { stdout } = await git(root, ["stash", "list", "-z", "--format=%H%x00%gd%x00%gs%x00%cI"]);
443
+ const fields = stdout.split("\0");
444
+ let total = 0, matches = 0;
445
+ const stashes = [];
446
+ for (let i = 0; i + 3 < fields.length; i += 4) {
447
+ const [hash, ref, subject, date] = fields.slice(i, i + 4);
448
+ total++;
449
+ if (!`${ref} ${subject} ${hash}`.toLowerCase().includes(filter))
450
+ continue;
451
+ const position = matches++;
452
+ if (position >= start && position < start + 50)
453
+ stashes.push({ hash, ref, subject, date });
454
+ }
455
+ return { stashes, total, matches, canWrite };
456
+ }
457
+ export async function gitStagedDraftInput(root, cwd) {
458
+ const maxBytes = 24 * 1024;
459
+ const child = spawn("git", ["--literal-pathspecs", "--no-pager", "diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color", "--", cwd || "."], {
460
+ cwd: root, stdio: ["ignore", "pipe", "ignore"], windowsHide: true,
461
+ });
462
+ const chunks = [];
463
+ let bytes = 0, truncated = false;
464
+ child.stdout.on("data", (chunk) => {
465
+ const remaining = maxBytes - bytes;
466
+ if (remaining > 0) {
467
+ const piece = chunk.subarray(0, remaining);
468
+ chunks.push(piece);
469
+ bytes += piece.length;
470
+ }
471
+ if (chunk.length > remaining && !truncated) {
472
+ truncated = true;
473
+ child.kill();
474
+ }
475
+ });
476
+ await new Promise((done, fail) => {
477
+ child.once("error", fail);
478
+ child.once("close", code => {
479
+ if (code === 0 || truncated)
480
+ done();
481
+ else
482
+ fail(gitFailure("无法读取暂存差异", "git_error"));
483
+ });
484
+ });
485
+ if (!bytes)
486
+ throw gitFailure("没有已暂存的更改", "empty_index");
487
+ return { patch: Buffer.concat(chunks).toString("utf8"), truncated };
488
+ }
489
+ export async function gitDiff(root, path, staged, fullContext = false) {
490
+ const safe = resolve(root, path);
491
+ if (!safe.startsWith(resolve(root) + sep) || path.includes("\0"))
492
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
493
+ const currentExists = existsSync(safe);
494
+ const tracked = await git(root, ["ls-files", "--error-unmatch", "--", path]).then(() => true).catch(() => false)
495
+ || staged && await git(root, ["cat-file", "-e", `HEAD:${relative(root, safe).split(sep).join("/")}`]).then(() => true).catch(() => false);
496
+ if (!tracked && !currentExists)
497
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
498
+ if (!tracked)
499
+ return { path, staged, diff: null, kind: "untracked", currentExists };
500
+ const patch = await readGitDiff(root, ["diff", ...PATCH_OPTIONS, patchContext(fullContext), ...(staged ? ["--cached"] : []), "--", path], fullContext);
501
+ return { path, staged, diff: patch, kind: /^Binary files .* differ$/m.test(patch) ? "binary" : "text", currentExists };
502
+ }
503
+ /** Read the index version for the editable working-tree comparison. The path is resolved beneath the
504
+ * workspace before it becomes a Git object expression, and the blob stays within the file editor's
505
+ * existing size limit. */
506
+ export async function gitIndexFileContent(root, path) {
507
+ const safe = resolve(root, path);
508
+ if (!safe.startsWith(resolve(root) + sep) || path.includes("\0"))
509
+ throw gitFailure("文件路径无效", "path");
510
+ const repoPath = relative(root, safe).split(sep).join("/");
511
+ const object = `:0:${repoPath}`;
512
+ const size = Number((await git(root, ["cat-file", "-s", object])).stdout.trim());
513
+ if (!Number.isSafeInteger(size) || size < 0)
514
+ throw gitFailure("无法读取暂存区中的文件版本", "missing_index_blob");
515
+ if (size > MAX_FILE_BYTES)
516
+ throw gitFailure("文件过大,无法在差异编辑器中编辑", "file_too_large");
517
+ const content = (await git(root, ["show", object], { maxBuffer: MAX_FILE_BYTES * 2 })).stdout;
518
+ if (content.includes("\0"))
519
+ throw gitFailure("二进制文件不能在差异编辑器中编辑", "binary");
520
+ return content;
521
+ }
522
+ /**
523
+ * The content of a file AS IT WAS COMMITTED, or `null` when there is no such version.
524
+ *
525
+ * WHY THIS EXISTS ALONGSIDE `gitDiff`. `gitDiff` answers "what changed relative to HEAD" as a PATCH -
526
+ * which is a good thing to read and a bad thing to diff against: a patch is a set of hunks, and
527
+ * reconstructing the "before" text from it is a lossy operation that a review view should not depend on.
528
+ * The review view needs the two TEXTS, so that the difference between them is computed by one
529
+ * well-tested algorithm rather than by two different ones.
530
+ *
531
+ * `null` covers three different situations, and the caller must not confuse them: the repository has no
532
+ * commits yet (`unborn`), the file was never committed (it is new or untracked), or the file is not in
533
+ * this repository at all. The first two are the same answer for a review - "there is no committed
534
+ * version to compare against" - and the third is a refusal, which the caller reports.
535
+ */
536
+ export async function gitHeadContent(root, path) {
537
+ const safe = resolve(root, path);
538
+ if (!safe.startsWith(resolve(root) + sep))
539
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
540
+ const hasHead = await git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false);
541
+ if (!hasHead)
542
+ return null;
543
+ const tracked = await git(root, ["ls-files", "--error-unmatch", "--", path]).then(() => true).catch(() => false);
544
+ if (!tracked)
545
+ return null;
546
+ try {
547
+ const out = await git(root, ["show", `HEAD:${path}`]);
548
+ return out.stdout;
549
+ }
550
+ catch {
551
+ // The file is tracked but `HEAD:path` does not resolve - a path with characters git quotes, or a
552
+ // repository in a state this server does not model. Treated as "no committed version", which is the
553
+ // honest answer rather than a crash.
554
+ return null;
555
+ }
556
+ }
557
+ // ---------------------------------------------------------------------------------------------
558
+ // Git blame.
559
+ //
560
+ // The blame gutter needs, for one file: who last touched each line, and in which commit. Git's
561
+ // `--line-porcelain` output is the only source for that, and this module is the only place allowed
562
+ // to parse it - the caller receives the structured `GitBlameLine[]` and never sees porcelain text,
563
+ // the same boundary `gitLog` already draws for its own format.
564
+ // ---------------------------------------------------------------------------------------------
565
+ /**
566
+ * A file larger than this is refused for blame (`too_large`) rather than blamed. Blame's cost scales
567
+ * with a text file's LINE count, and a file this size can carry millions of them, so the bound is
568
+ * checked from `stat` (working tree) or `git cat-file -s` (a revision) BEFORE any content is read -
569
+ * an oversized file costs one stat, never a buffer.
570
+ */
571
+ export const MAX_BLAME_FILE_BYTES = 2 * 1024 * 1024;
572
+ /**
573
+ * The most lines one blame response may carry. `--line-porcelain` emits roughly 300-500 bytes of
574
+ * metadata per line, so this cap bounds the response and the parse to single-digit megabytes. A
575
+ * whole-file request for a longer file is answered with the FIRST `MAX_BLAME_LINES` entries and
576
+ * `truncated: true`; a caller that wants more asks for an explicit `startLine`/`endLine` window -
577
+ * which is what the gutter does anyway, and a window may not exceed this cap either.
578
+ */
579
+ export const MAX_BLAME_LINES = 20000;
580
+ /** Output-buffer headroom for the blame process itself: MAX_BLAME_LINES records at ~500 bytes each is
581
+ * ~10MB, and 32MB leaves slack for long author names and summaries without being unbounded. */
582
+ const BLAME_MAX_BUFFER = 32 * 1024 * 1024;
583
+ /** How many leading bytes are sniffed for a NUL byte to classify content as binary - the same
584
+ * heuristic git's own diff machinery uses. A NUL byte cannot appear in UTF-8 text; a binary file's
585
+ * "lines" are meaningless to a gutter, and git blame happily produces metadata for them, so the
586
+ * refusal has to happen here, before the porcelain is ever asked for. */
587
+ const BLAME_SNIFF_BYTES = 8192;
588
+ function unsupportedBlame(path, revision, reason) {
589
+ return { path, revision, lines: [], totalLines: 0, truncated: false, supported: false, reason };
590
+ }
591
+ /** `\n`-delimited line count: a trailing newline does not open a line of its own, an empty file has
592
+ * none, and a lone `\n` is one (empty) line - matching what git blame itself will report. */
593
+ function countTextLines(text) {
594
+ if (text.length === 0)
595
+ return 0;
596
+ let count = 1;
597
+ for (let i = 0; i < text.length; i++)
598
+ if (text.charCodeAt(i) === 10)
599
+ count++;
600
+ if (text.charCodeAt(text.length - 1) === 10)
601
+ count--;
602
+ return count;
603
+ }
604
+ /**
605
+ * One porcelain record per line: `<40-hex sha> <orig-line> <final-line> [<count>]`, followed by the
606
+ * full header (`author`, `author-mail`, `author-time`, `summary`, `filename`, ...), followed by the
607
+ * line's own content prefixed with TAB. `--line-porcelain` repeats the full header for EVERY line, so
608
+ * parsing is stateless per record - no carry-over of "the commit from the previous record", which is
609
+ * the bug plain `--porcelain` invites. Two rules make the parse safe:
610
+ *
611
+ * 1. A record header is a 40-hex sha followed by two decimal numbers, and nothing else in the stream
612
+ * matches that - every other line is either `key value` metadata or TAB-prefixed content. The
613
+ * optional fourth number is the porcelain GROUP size (a run of consecutive lines from one commit);
614
+ * under `--line-porcelain` every line still gets its own record, so it is parsed and discarded.
615
+ * 2. The TAB-prefixed content line is skipped UNREAD. It is the one part of the stream that can hold
616
+ * arbitrary file bytes - NULs, line-splitting illusions, huge runs - and this API's contract is
617
+ * metadata only.
618
+ */
619
+ function parseBlamePorcelain(raw) {
620
+ const lines = [];
621
+ let current = null;
622
+ for (const line of raw.split("\n")) {
623
+ if (line.startsWith("\t"))
624
+ continue;
625
+ const header = /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/.exec(line);
626
+ if (header) {
627
+ const sha = header[1];
628
+ const uncommitted = /^0{40}$/.test(sha);
629
+ current = {
630
+ line: Number(header[3]),
631
+ commit: uncommitted ? null : sha,
632
+ shortCommit: uncommitted ? null : sha.slice(0, 8),
633
+ author: null, authorEmail: null, date: null, summary: null,
634
+ isUncommitted: uncommitted,
635
+ };
636
+ lines.push(current);
637
+ continue;
638
+ }
639
+ if (!current)
640
+ continue;
641
+ // An uncommitted record still carries git's placeholders in its metadata ("Not Committed Yet", a
642
+ // pseudo address, the time of the diff run); the contract nulls every field but the flag, so that
643
+ // metadata is skipped rather than copied into the response.
644
+ if (current.isUncommitted)
645
+ continue;
646
+ const space = line.indexOf(" ");
647
+ const key = space === -1 ? line : line.slice(0, space);
648
+ const value = space === -1 ? "" : line.slice(space + 1);
649
+ if (key === "author")
650
+ current.author = value;
651
+ else if (key === "author-mail")
652
+ current.authorEmail = value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
653
+ else if (key === "author-time") {
654
+ const ms = Number(value) * 1000;
655
+ if (Number.isFinite(ms))
656
+ current.date = new Date(ms).toISOString();
657
+ }
658
+ else if (key === "summary")
659
+ current.summary = value;
660
+ }
661
+ return lines;
662
+ }
663
+ /**
664
+ * Line-by-line provenance for one file: who last touched each line, in which commit.
665
+ *
666
+ * SECURITY BOUNDARY. `path` arrives from a browser and is contained exactly as `gitDiff` and
667
+ * `gitHeadContent` contain it - resolve against the workspace root, refuse anything that lands
668
+ * outside. Backslashes are normalised to `/` FIRST, so a Windows-spelled relative path resolves like
669
+ * the same request spelled with `/` and the git invocation and the response share the one separator
670
+ * this API speaks. `revision` arrives from the same untrusted place: it may not start with `-` (that
671
+ * is how an argument becomes a git FLAG) and may not carry whitespace or NUL. Every git call here is
672
+ * `execFile` with an argument array - no shell, no string interpolation into a command line - and the
673
+ * path always travels after a bare `--`, so no path can be read as an option.
674
+ *
675
+ * FAILURE SHAPE. Facts about the file or repository (`untracked`, `binary`, `too_large`, `no_head`,
676
+ * `not_in_revision`) come back as `supported: false` - the gutter renders them, it does not error on
677
+ * them. Request mistakes (path escapes, a missing file, a bad revision, an illegal range) throw with
678
+ * a stable `code` for the HTTP layer to map. Git's raw stderr never reaches a caller: expected
679
+ * failures are thrown as written sentences, and an unexpected git failure is logged here and thrown
680
+ * as one stable sentence.
681
+ */
682
+ export async function gitBlame(root, path, options = {}) {
683
+ const relativePath = path.replaceAll("\\", "/");
684
+ if (!relativePath || relativePath.endsWith("/") || relativePath.includes("\0")) {
685
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
686
+ }
687
+ const safe = resolve(root, relativePath);
688
+ if (!safe.startsWith(resolve(root) + sep))
689
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
690
+ // The canonical `/`-separated form the response echoes - `sub\inner.txt` and `sub/../sub/inner.txt`
691
+ // both normalise to `sub/inner.txt`, so the client cannot learn a second spelling of one file.
692
+ const canonical = relative(resolve(root), safe).split(sep).join("/");
693
+ const isRepo = await git(root, ["rev-parse", "--git-dir"]).then(() => true).catch(() => false);
694
+ if (!isRepo)
695
+ throw Object.assign(new Error("此工作区不是 Git 仓库"), { code: "not_a_repo" });
696
+ const revision = options.revision?.trim() || undefined;
697
+ if (revision && (revision.startsWith("-") || /[\s\0]/.test(revision))) {
698
+ throw Object.assign(new Error("无效的 revision"), { code: "bad_revision" });
699
+ }
700
+ // An unborn repository has no commit for ANY line to point at, so blame is uniformly unavailable
701
+ // (`no_head`, a supported:false fact) rather than an error - the repository itself is fine, it just
702
+ // has no history yet. Checked before trackedness: the answer does not depend on the file.
703
+ if (!revision) {
704
+ const hasHead = await git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false);
705
+ if (!hasHead)
706
+ return unsupportedBlame(canonical, "HEAD", "no_head");
707
+ }
708
+ // Resolve the anchor to a concrete commit BEFORE anything else uses it - this is what splits "the
709
+ // revision is bogus" (bad_revision) from "the file is not in that revision" (not_in_revision):
710
+ // both are git exit 128, and only ordering gives them distinct, stable codes.
711
+ let revSha;
712
+ if (revision) {
713
+ const resolved = await git(root, ["rev-parse", "--verify", `${revision}^{commit}`]).then((r) => r.stdout.trim()).catch(() => null);
714
+ if (!resolved)
715
+ throw Object.assign(new Error(`无法解析 revision:${revision}`), { code: "bad_revision" });
716
+ revSha = resolved;
717
+ }
718
+ // Trackedness is judged against the index, exactly as `gitDiff` judges it, so every op answers the
719
+ // same question the same way. A file on disk that the index has never heard of is `untracked` (a
720
+ // supported:false fact - the file is real and the gutter may well be showing it). A path that does
721
+ // not exist at all is an ERROR (`not_found`), deliberately distinct from `untracked`: "git does not
722
+ // know this file" and "there is no such file" are different sentences. A file tracked but deleted
723
+ // from the working tree is `not_found` for the default anchor - which reads the working tree, and
724
+ // git itself refuses with `Cannot lstat` there - while an explicit revision does not need the
725
+ // working-tree file at all and is allowed through.
726
+ const tracked = await git(root, ["ls-files", "--error-unmatch", "--", relativePath]).then(() => true).catch(() => false);
727
+ const onDisk = existsSync(safe);
728
+ if (!tracked && !onDisk)
729
+ throw Object.assign(new Error(`文件不存在:${canonical}`), { code: "not_found" });
730
+ if (!tracked)
731
+ return unsupportedBlame(canonical, revision ?? "HEAD", "untracked");
732
+ if (!onDisk && !revision)
733
+ throw Object.assign(new Error(`文件不存在:${canonical}(已从工作区删除)`), { code: "not_found" });
734
+ // Size, binary sniff and line count, from the content blame will actually read: the committed blob
735
+ // for an explicit revision, the working-tree file for the default anchor. One bounded read (capped
736
+ // above at MAX_BLAME_FILE_BYTES) yields all three, so no request ever streams an unbounded file
737
+ // into memory just to count it.
738
+ let content;
739
+ if (revSha) {
740
+ const size = await git(root, ["cat-file", "-s", `${revSha}:${relativePath}`]).then((r) => Number(r.stdout.trim())).catch(() => null);
741
+ if (size === null)
742
+ return unsupportedBlame(canonical, revision ?? "HEAD", "not_in_revision");
743
+ if (size > MAX_BLAME_FILE_BYTES)
744
+ return unsupportedBlame(canonical, revision ?? "HEAD", "too_large");
745
+ const blob = await git(root, ["cat-file", "blob", `${revSha}:${relativePath}`]).catch(() => null);
746
+ if (blob === null)
747
+ return unsupportedBlame(canonical, revision ?? "HEAD", "not_in_revision");
748
+ content = Buffer.from(blob.stdout, "utf8");
749
+ }
750
+ else {
751
+ try {
752
+ const info = await stat(safe);
753
+ if (info.size > MAX_BLAME_FILE_BYTES)
754
+ return unsupportedBlame(canonical, "HEAD", "too_large");
755
+ content = await readFile(safe);
756
+ }
757
+ catch {
758
+ // The file vanished between the existsSync above and this read - the same not_found, reached
759
+ // through a race instead of a pre-check.
760
+ throw Object.assign(new Error(`文件不存在:${canonical}`), { code: "not_found" });
761
+ }
762
+ }
763
+ const sniffEnd = Math.min(content.length, BLAME_SNIFF_BYTES);
764
+ for (let i = 0; i < sniffEnd; i++)
765
+ if (content[i] === 0)
766
+ return unsupportedBlame(canonical, revision ?? "HEAD", "binary");
767
+ const totalLines = countTextLines(content.toString("utf8"));
768
+ // The window. Validated strictly and AFTER totalLines is known, so each rejection can name the real
769
+ // bound ("the file has 12 lines") instead of a guess.
770
+ const startRaw = options.startLine;
771
+ const endRaw = options.endLine;
772
+ if ((startRaw === undefined) !== (endRaw === undefined)) {
773
+ throw Object.assign(new Error("startLine 与 endLine 必须同时提供"), { code: "bad_range" });
774
+ }
775
+ let start = 1;
776
+ let end = totalLines;
777
+ let windowed = false;
778
+ if (startRaw !== undefined && endRaw !== undefined) {
779
+ windowed = true;
780
+ if (!Number.isInteger(startRaw) || startRaw < 1)
781
+ throw Object.assign(new Error(`startLine 必须是正整数,收到 ${startRaw}`), { code: "bad_range" });
782
+ if (!Number.isInteger(endRaw) || endRaw < 1)
783
+ throw Object.assign(new Error(`endLine 必须是正整数,收到 ${endRaw}`), { code: "bad_range" });
784
+ if (startRaw > endRaw)
785
+ throw Object.assign(new Error(`startLine (${startRaw}) 不能大于 endLine (${endRaw})`), { code: "bad_range" });
786
+ if (endRaw > totalLines)
787
+ throw Object.assign(new Error(`endLine (${endRaw}) 超出文件行数 (${totalLines})`), { code: "bad_range" });
788
+ if (endRaw - startRaw + 1 > MAX_BLAME_LINES)
789
+ throw Object.assign(new Error(`行范围过大:单次最多 ${MAX_BLAME_LINES} 行`), { code: "bad_range" });
790
+ start = startRaw;
791
+ end = endRaw;
792
+ }
793
+ else if (totalLines > MAX_BLAME_LINES) {
794
+ // A whole-file request on an over-cap file is answered with the head of the file and `truncated`.
795
+ // The gutter asks in windows and never hits this; the prefix exists so a naive caller gets useful
796
+ // data rather than a refusal or an unbounded response.
797
+ end = MAX_BLAME_LINES;
798
+ }
799
+ const args = ["blame", "--line-porcelain"];
800
+ if (start !== 1 || end !== totalLines)
801
+ args.push("-L", `${start},${end}`);
802
+ if (revSha)
803
+ args.push(revSha);
804
+ args.push("--", relativePath);
805
+ let raw;
806
+ try {
807
+ raw = (await git(root, args, { maxBuffer: BLAME_MAX_BUFFER })).stdout;
808
+ }
809
+ catch (error) {
810
+ // Git's stderr is for this server's log, not for the user: an unexpected blame failure surfaces
811
+ // as one stable sentence with a stable code, and the raw output stays server-side.
812
+ console.error(`git blame failed for ${canonical}:`, error);
813
+ throw Object.assign(new Error("git blame 执行失败"), { code: "git_error" });
814
+ }
815
+ return {
816
+ path: canonical,
817
+ revision: revision ?? "HEAD",
818
+ lines: parseBlamePorcelain(raw),
819
+ totalLines,
820
+ truncated: !windowed && totalLines > MAX_BLAME_LINES,
821
+ supported: true,
822
+ };
823
+ }
824
+ /** Whether the directory is a git repository at all. The review view asks before it offers a git baseline. */
825
+ export async function isGitRepository(root) {
826
+ return git(root, ["rev-parse", "--git-dir"]).then(() => true).catch(() => false);
827
+ }
828
+ function safePath(root, path) {
829
+ const safe = resolve(root, path);
830
+ if (safe !== resolve(root) && !safe.startsWith(resolve(root) + sep))
831
+ throw Object.assign(new Error("文件路径无效"), { code: "path" });
832
+ return path;
833
+ }
834
+ export async function gitMutate(root, op, path, message, cwd = "", target) {
835
+ safePath(root, cwd);
836
+ if (op === "stage-all" || op === "unstage-all") {
837
+ if (op === "stage-all")
838
+ await git(root, ["add", "--", cwd || "."]);
839
+ else {
840
+ const hasHead = await git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false);
841
+ await git(root, hasHead ? ["restore", "--staged", "--", cwd || "."] : ["rm", "--cached", "-r", "-f", "--", cwd || "."]);
842
+ }
843
+ return gitStatus(root, cwd);
844
+ }
845
+ if (op === "stage" || op === "unstage" || op === "discard") {
846
+ if (!path)
847
+ throw Object.assign(new Error("缺少文件路径"), { code: "path" });
848
+ safePath(root, path);
849
+ if (op === "stage")
850
+ await git(root, ["add", "--", path]);
851
+ else if (op === "unstage") {
852
+ const hasHead = await git(root, ["rev-parse", "--verify", "HEAD"]).then(() => true).catch(() => false);
853
+ await git(root, hasHead ? ["restore", "--staged", "--", path] : ["rm", "--cached", "-f", "--", path]);
854
+ }
855
+ else
856
+ await git(root, ["restore", "--", path]);
857
+ }
858
+ else if (op === "commit") {
859
+ if (!message?.trim())
860
+ throw Object.assign(new Error("提交消息不能为空"), { code: "bad_message" });
861
+ const repoRoot = await worktreeRoot(root);
862
+ const indexed = (await git(root, ["diff", "--cached", "--name-only", "--no-renames", "--no-relative", "-z"])).stdout.split("\0").filter(Boolean);
863
+ if (!indexed.length)
864
+ throw Object.assign(new Error("没有已暂存的更改,请先暂存需要提交的文件"), { code: "empty_index" });
865
+ const scope = normalizedPath(resolve(root, cwd));
866
+ if (indexed.some(file => !normalizedPath(resolve(repoRoot, file)).startsWith(scope + sep)))
867
+ throw Object.assign(new Error("暂存区还有当前目录之外的更改,请在共同的仓库目录中提交"), { code: "outside_scope" });
868
+ // A pathspec commit reads working-tree content; an index-only commit preserves partial staging.
869
+ await git(root, ["commit", "-m", message.trim()]);
870
+ }
871
+ else if (op === "fetch" || op === "pull" || op === "push") {
872
+ await git(root, op === "pull" ? [op, "--ff-only"] : [op], { timeout: 60_000 });
873
+ }
874
+ else if (op === "switch" || op === "stash-save" || op === "stash-apply") {
875
+ if (!await canChangeWorktree(root, cwd))
876
+ throw gitFailure("这个操作会改变整个工作树,请切换到 Git 仓库根目录", "outside_scope");
877
+ if (op === "switch") {
878
+ const branch = target?.trim();
879
+ if (!branch || branch.includes("\0") || !await git(root, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).then(() => true).catch(() => false)) {
880
+ throw gitFailure("找不到指定的本地分支", "not_found");
881
+ }
882
+ await git(root, ["switch", "--no-guess", "--no-overwrite-ignore", "--", branch]);
883
+ }
884
+ else if (op === "stash-save") {
885
+ const status = await gitStatus(root);
886
+ if (!status.staged.length && !status.unstaged.length && !status.untracked.length)
887
+ throw gitFailure("工作树没有可贮藏的改动", "empty_worktree");
888
+ // Stash invokes git clean internally. Literal pathspec mode prevents that cleanup of untracked files.
889
+ await exec("git", ["stash", "push", "--include-untracked", ...(message?.trim() ? ["--message", message.trim().slice(0, 200)] : [])], { cwd: root, windowsHide: true });
890
+ }
891
+ else {
892
+ if (!target || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(target))
893
+ throw gitFailure("贮藏记录无效", "not_found");
894
+ const { stdout } = await git(root, ["stash", "list", "--format=%H"]);
895
+ if (!stdout.split(/\r?\n/).includes(target))
896
+ throw gitFailure("贮藏记录已不存在", "not_found");
897
+ await exec("git", ["stash", "apply", "--index", target], { cwd: root, windowsHide: true });
898
+ }
899
+ }
900
+ else
901
+ throw Object.assign(new Error("未知 Git 操作"), { code: "bad_op" });
902
+ return gitStatus(root, cwd);
903
+ }