@orion-agents/orion-code 0.3.65 → 0.4.3

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/CHANGELOG.md +128 -2
  2. package/README.md +78 -361
  3. package/README.zh-CN.md +71 -263
  4. package/bin/orion +4 -1
  5. package/dist/acp/session-updates.d.ts +34 -0
  6. package/dist/acp/session-updates.js +162 -0
  7. package/dist/acp/sessions.d.ts +32 -0
  8. package/dist/acp/sessions.js +315 -0
  9. package/dist/acp/stdio.d.ts +3 -0
  10. package/dist/acp/stdio.js +59 -0
  11. package/dist/cli.js +136 -185
  12. package/dist/commands/context-tool-command-handlers.d.ts +1 -1
  13. package/dist/commands/context-tool-command-handlers.js +24 -3
  14. package/dist/commands/core-command-handlers.js +5 -1
  15. package/dist/commands/diagnostic-command-handlers.js +20 -6
  16. package/dist/commands/diagnostic-commands.js +0 -12
  17. package/dist/commands/init-command.d.ts +3 -0
  18. package/dist/commands/init-command.js +131 -0
  19. package/dist/commands/model-command-handlers.d.ts +1 -2
  20. package/dist/commands/model-command-handlers.js +15 -100
  21. package/dist/commands/model-commands.js +0 -11
  22. package/dist/commands/registry.js +0 -18
  23. package/dist/commands/rsi-command.d.ts +2 -0
  24. package/dist/commands/rsi-command.js +180 -0
  25. package/dist/commands/session-command-handlers.js +28 -19
  26. package/dist/commands/system-commands.js +0 -1
  27. package/dist/commands/tool-commands.js +1 -1
  28. package/dist/commands/types.d.ts +4 -10
  29. package/dist/commands/types.js +1 -21
  30. package/dist/commands/workflow-command-handlers.js +13 -4
  31. package/dist/framework/loop-budget-contract.d.ts +7 -2
  32. package/dist/framework/loop-budget-contract.js +4 -1
  33. package/dist/framework/loop-progress.d.ts +22 -0
  34. package/dist/framework/loop-progress.js +79 -0
  35. package/dist/framework/prompt.d.ts +0 -2
  36. package/dist/framework/prompt.js +9 -27
  37. package/dist/framework/query.d.ts +27 -20
  38. package/dist/framework/query.js +453 -153
  39. package/dist/framework/store.d.ts +6 -10
  40. package/dist/framework/store.js +2 -21
  41. package/dist/framework/tool-call-orchestrator.d.ts +7 -0
  42. package/dist/framework/tool-call-orchestrator.js +8 -3
  43. package/dist/framework/tool-state.d.ts +2 -0
  44. package/dist/framework/tool.d.ts +0 -23
  45. package/dist/framework/verification-command.d.ts +15 -0
  46. package/dist/framework/verification-command.js +32 -0
  47. package/dist/harness/assembler.d.ts +1 -0
  48. package/dist/harness/assembler.js +24 -0
  49. package/dist/harness/capsule.d.ts +1 -1
  50. package/dist/harness/capsule.js +33 -14
  51. package/dist/harness/context-harness.d.ts +31 -12
  52. package/dist/harness/context-harness.js +491 -35
  53. package/dist/harness/contract.js +1 -1
  54. package/dist/harness/drift-guard.d.ts +4 -0
  55. package/dist/harness/drift-guard.js +68 -16
  56. package/dist/harness/intent.js +21 -0
  57. package/dist/harness/ledger.d.ts +6 -11
  58. package/dist/harness/ledger.js +39 -9
  59. package/dist/harness/progress-controller.d.ts +12 -7
  60. package/dist/harness/progress-controller.js +66 -21
  61. package/dist/harness/state.js +9 -1
  62. package/dist/harness/task-checklist.d.ts +16 -0
  63. package/dist/harness/task-checklist.js +95 -0
  64. package/dist/harness/types.d.ts +73 -1
  65. package/dist/harness/verification.d.ts +19 -1
  66. package/dist/harness/verification.js +116 -29
  67. package/dist/index.d.ts +1 -1
  68. package/dist/index.js +1 -3
  69. package/dist/print-ui/event-stream.d.ts +38 -0
  70. package/dist/print-ui/event-stream.js +187 -0
  71. package/dist/print-ui/launch.d.ts +12 -1
  72. package/dist/print-ui/launch.js +173 -11
  73. package/dist/product/environment.d.ts +1 -1
  74. package/dist/product/environment.js +1 -1
  75. package/dist/product/identity.d.ts +1 -1
  76. package/dist/product/identity.js +1 -1
  77. package/dist/product/paths.d.ts +3 -2
  78. package/dist/product/paths.js +6 -2
  79. package/dist/runtime/agent-loop.d.ts +11 -2
  80. package/dist/runtime/agent-loop.js +165 -25
  81. package/dist/runtime/agent-runtime-controller.d.ts +13 -3
  82. package/dist/runtime/agent-runtime-controller.js +347 -183
  83. package/dist/runtime/agent-runtime-protocol.d.ts +10 -18
  84. package/dist/runtime/agent-runtime-runner.d.ts +10 -0
  85. package/dist/runtime/builtin-tool-provider.js +5 -1
  86. package/dist/runtime/capability-receipt-journal.js +1 -0
  87. package/dist/runtime/durable-tool-receipt-reader.js +2 -1
  88. package/dist/runtime/first-party-tool-services.d.ts +1 -0
  89. package/dist/runtime/first-party-tool-services.js +2 -12
  90. package/dist/runtime/first-party-tool-universe.d.ts +1 -0
  91. package/dist/runtime/first-party-tool-universe.js +1 -1
  92. package/dist/runtime/followup-queue-store.d.ts +16 -0
  93. package/dist/runtime/followup-queue-store.js +75 -0
  94. package/dist/runtime/goal-lifecycle-v2.d.ts +11 -1
  95. package/dist/runtime/goal-lifecycle-v2.js +85 -15
  96. package/dist/runtime/goal-runtime-coordinator.d.ts +10 -1
  97. package/dist/runtime/goal-runtime-coordinator.js +81 -24
  98. package/dist/runtime/loop-budget.js +7 -5
  99. package/dist/runtime/mcp/first-party-mcp-adapter.d.ts +2 -0
  100. package/dist/runtime/mcp/first-party-mcp-adapter.js +23 -19
  101. package/dist/runtime/model-coordinator.js +2 -5
  102. package/dist/runtime/orion-runtime-v1.d.ts +18 -2
  103. package/dist/runtime/orion-runtime-v1.js +135 -39
  104. package/dist/runtime/orion-session-runner.d.ts +7 -0
  105. package/dist/runtime/orion-session-runner.js +82 -0
  106. package/dist/runtime/plan-review.d.ts +1 -0
  107. package/dist/runtime/plan-review.js +8 -4
  108. package/dist/runtime/product-bootstrap.d.ts +6 -0
  109. package/dist/runtime/product-bootstrap.js +41 -51
  110. package/dist/runtime/product-orion-runtime.js +128 -52
  111. package/dist/runtime/release-receipts.d.ts +24 -124
  112. package/dist/runtime/release-receipts.js +129 -683
  113. package/dist/runtime/rich-text/layout.js +108 -65
  114. package/dist/runtime/rsi/contracts.d.ts +50 -0
  115. package/dist/runtime/rsi/contracts.js +17 -0
  116. package/dist/runtime/rsi/diagnosis.d.ts +46 -0
  117. package/dist/runtime/rsi/diagnosis.js +98 -0
  118. package/dist/runtime/rsi/evaluation-suite.d.ts +25 -0
  119. package/dist/runtime/rsi/evaluation-suite.js +141 -0
  120. package/dist/runtime/rsi/evaluation-worker.d.ts +19 -0
  121. package/dist/runtime/rsi/evaluation-worker.js +64 -0
  122. package/dist/runtime/rsi/evaluation.d.ts +49 -0
  123. package/dist/runtime/rsi/evaluation.js +351 -0
  124. package/dist/runtime/rsi/lifecycle.d.ts +54 -0
  125. package/dist/runtime/rsi/lifecycle.js +279 -0
  126. package/dist/runtime/rsi/proposal.d.ts +39 -0
  127. package/dist/runtime/rsi/proposal.js +312 -0
  128. package/dist/runtime/rsi/receipt.d.ts +28 -0
  129. package/dist/runtime/rsi/receipt.js +138 -0
  130. package/dist/runtime/rsi/skill-state.d.ts +7 -0
  131. package/dist/runtime/rsi/skill-state.js +50 -0
  132. package/dist/runtime/rsi/trajectory.d.ts +19 -0
  133. package/dist/runtime/rsi/trajectory.js +314 -0
  134. package/dist/runtime/rsi/triage.d.ts +274 -0
  135. package/dist/runtime/rsi/triage.js +58 -0
  136. package/dist/runtime/session-composer-control.d.ts +5 -24
  137. package/dist/runtime/session-composer-control.js +27 -189
  138. package/dist/runtime/step-snapshot.d.ts +1 -0
  139. package/dist/runtime/subagents/policy.js +0 -1
  140. package/dist/runtime/subagents/production.js +1 -1
  141. package/dist/runtime/subagents/runtime-integration.js +2 -4
  142. package/dist/runtime/subagents/types.d.ts +0 -5
  143. package/dist/runtime/subagents/types.js +0 -2
  144. package/dist/runtime/task-context-recovery.d.ts +55 -0
  145. package/dist/runtime/task-context-recovery.js +342 -0
  146. package/dist/runtime/task-context-service.d.ts +16 -10
  147. package/dist/runtime/task-context-service.js +35 -4
  148. package/dist/runtime/thread-admission.d.ts +1 -1
  149. package/dist/runtime/thread-admission.js +12 -6
  150. package/dist/runtime/thread-event-store.d.ts +2 -2
  151. package/dist/runtime/thread-event-store.js +7 -2
  152. package/dist/runtime/thread-projection.js +4 -2
  153. package/dist/runtime/thread-runtime.d.ts +7 -0
  154. package/dist/runtime/thread-runtime.js +43 -0
  155. package/dist/runtime/thread-session-index.d.ts +8 -0
  156. package/dist/runtime/thread-session-index.js +50 -1
  157. package/dist/runtime/thread-session-view.d.ts +2 -1
  158. package/dist/runtime/thread-session-view.js +4 -0
  159. package/dist/runtime/thread-tool-journal.d.ts +1 -0
  160. package/dist/runtime/thread-tool-journal.js +6 -2
  161. package/dist/runtime/thread-ui-adapter.d.ts +1 -0
  162. package/dist/runtime/thread-ui-adapter.js +88 -11
  163. package/dist/runtime/tool-gateway.d.ts +7 -0
  164. package/dist/runtime/tool-gateway.js +20 -0
  165. package/dist/runtime/tool-transcript-entry.d.ts +16 -0
  166. package/dist/runtime/tool-transcript-entry.js +73 -0
  167. package/dist/runtime/turn-commit.d.ts +4 -1
  168. package/dist/runtime/turn-commit.js +19 -15
  169. package/dist/runtime/ui-events.d.ts +12 -0
  170. package/dist/runtime/ui-view-model.d.ts +6 -5
  171. package/dist/runtime/ui-view-model.js +33 -19
  172. package/dist/runtime/workspace-runtime-kernel.js +0 -1
  173. package/dist/services/atomic-write.d.ts +2 -0
  174. package/dist/services/atomic-write.js +12 -1
  175. package/dist/services/code-review/format.d.ts +4 -1
  176. package/dist/services/code-review/format.js +5 -1
  177. package/dist/services/code-review/runner.d.ts +2 -2
  178. package/dist/services/code-review/runner.js +86 -64
  179. package/dist/services/code-review/snapshot.d.ts +9 -9
  180. package/dist/services/code-review/snapshot.js +182 -166
  181. package/dist/services/compact/auto-compact.d.ts +21 -6
  182. package/dist/services/compact/auto-compact.js +148 -22
  183. package/dist/services/compact/background-candidate.d.ts +33 -0
  184. package/dist/services/compact/background-candidate.js +184 -0
  185. package/dist/services/compact/compact.d.ts +4 -1
  186. package/dist/services/compact/compact.js +30 -3
  187. package/dist/services/compact/coordinator.d.ts +10 -4
  188. package/dist/services/compact/coordinator.js +17 -7
  189. package/dist/services/compact/summary-generator.d.ts +4 -2
  190. package/dist/services/compact/summary-generator.js +17 -3
  191. package/dist/services/config.d.ts +5 -5
  192. package/dist/services/config.js +30 -45
  193. package/dist/services/doctor.js +85 -13
  194. package/dist/services/effort.d.ts +5 -5
  195. package/dist/services/effort.js +5 -11
  196. package/dist/services/file-lock.d.ts +9 -3
  197. package/dist/services/file-lock.js +92 -26
  198. package/dist/services/global-config.d.ts +26 -56
  199. package/dist/services/global-config.js +213 -183
  200. package/dist/services/llm.d.ts +40 -4
  201. package/dist/services/llm.js +164 -45
  202. package/dist/services/model-client-pool.d.ts +15 -9
  203. package/dist/services/model-client-pool.js +62 -33
  204. package/dist/services/model-context.d.ts +2 -1
  205. package/dist/services/model-context.js +15 -9
  206. package/dist/services/model-registry.d.ts +4 -15
  207. package/dist/services/model-registry.js +32 -101
  208. package/dist/services/provider-diagnostics.d.ts +7 -0
  209. package/dist/services/provider-diagnostics.js +9 -10
  210. package/dist/services/provider-resilience/coordinator.d.ts +1 -1
  211. package/dist/services/provider-resilience/coordinator.js +10 -6
  212. package/dist/services/provider-resilience/request-gate.d.ts +3 -0
  213. package/dist/services/provider-resilience/request-gate.js +29 -18
  214. package/dist/services/provider-resilience/types.d.ts +2 -0
  215. package/dist/services/session-storage.d.ts +7 -10
  216. package/dist/services/session-storage.js +57 -30
  217. package/dist/services/settings-coordinator.d.ts +0 -6
  218. package/dist/services/settings-coordinator.js +19 -56
  219. package/dist/services/settings-document-repository.d.ts +3 -10
  220. package/dist/services/settings-document-repository.js +7 -85
  221. package/dist/services/usage-state.d.ts +3 -3
  222. package/dist/services/usage-state.js +11 -42
  223. package/dist/terminal-ui/answer-format.d.ts +14 -0
  224. package/dist/terminal-ui/answer-format.js +119 -0
  225. package/dist/terminal-ui/launch.d.ts +7 -6
  226. package/dist/terminal-ui/launch.js +160 -70
  227. package/dist/terminal-ui/output-queue.d.ts +2 -1
  228. package/dist/terminal-ui/output-queue.js +1 -1
  229. package/dist/terminal-ui/raw-editor.d.ts +2 -1
  230. package/dist/terminal-ui/raw-editor.js +56 -15
  231. package/dist/tools/core/edit-file.js +2 -0
  232. package/dist/tools/core/write-file.js +5 -0
  233. package/dist/tools/lsp.d.ts +16 -1
  234. package/dist/tools/lsp.js +60 -19
  235. package/dist/tools/sandbox.d.ts +1 -1
  236. package/dist/tools/sandbox.js +3 -16
  237. package/dist/tools/todo.d.ts +4 -2
  238. package/dist/tools/todo.js +76 -31
  239. package/dist/tui-core/input-parser.d.ts +1 -0
  240. package/dist/tui-core/input-parser.js +6 -0
  241. package/dist/tui-core/style.d.ts +1 -8
  242. package/dist/tui-core/style.js +3 -110
  243. package/dist/tui-ui/chrome-view-model.d.ts +1 -1
  244. package/dist/tui-ui/chrome-view-model.js +22 -27
  245. package/dist/tui-ui/launch.js +14 -14
  246. package/dist/tui-ui/layout.d.ts +5 -7
  247. package/dist/tui-ui/layout.js +129 -124
  248. package/dist/tui-ui/runner.d.ts +11 -12
  249. package/dist/tui-ui/runner.js +88 -67
  250. package/dist/tui-ui/state.d.ts +0 -11
  251. package/dist/tui-ui/state.js +22 -33
  252. package/dist/tui-ui/terminal-image.js +22 -4
  253. package/dist/tui-ui/transcript-inspector-layout.js +6 -3
  254. package/dist/tui-ui/transcript-inspector.d.ts +1 -0
  255. package/dist/tui-ui/transcript-inspector.js +7 -1
  256. package/dist/tui-ui/transcript-layout.js +42 -6
  257. package/dist/utils/terminal-text.d.ts +11 -0
  258. package/dist/utils/terminal-text.js +114 -0
  259. package/docs/cli-guide.md +562 -0
  260. package/docs/orion.example.yaml +42 -0
  261. package/docs/readme.md +12 -57
  262. package/npm-shrinkwrap.json +484 -1855
  263. package/package.json +13 -63
  264. package/dist/migration/command.d.ts +0 -9
  265. package/dist/migration/command.js +0 -100
  266. package/dist/migration/index.d.ts +0 -7
  267. package/dist/migration/index.js +0 -14
  268. package/dist/migration/migrate.d.ts +0 -19
  269. package/dist/migration/migrate.js +0 -406
  270. package/dist/migration/types.d.ts +0 -55
  271. package/dist/migration/types.js +0 -6
  272. package/dist/services/tool-allowlist.d.ts +0 -110
  273. package/dist/services/tool-allowlist.js +0 -299
  274. package/dist/services/yaml-config.d.ts +0 -57
  275. package/dist/services/yaml-config.js +0 -178
  276. package/dist/web/cli-options.d.ts +0 -17
  277. package/dist/web/cli-options.js +0 -51
  278. package/dist/web/code-review-run-service.d.ts +0 -68
  279. package/dist/web/code-review-run-service.js +0 -228
  280. package/dist/web/context-text.d.ts +0 -17
  281. package/dist/web/context-text.js +0 -40
  282. package/dist/web/errors.d.ts +0 -6
  283. package/dist/web/errors.js +0 -13
  284. package/dist/web/event-hub.d.ts +0 -45
  285. package/dist/web/event-hub.js +0 -370
  286. package/dist/web/file-read-service.d.ts +0 -101
  287. package/dist/web/file-read-service.js +0 -593
  288. package/dist/web/file-write-service.d.ts +0 -16
  289. package/dist/web/file-write-service.js +0 -103
  290. package/dist/web/git-compare-service.d.ts +0 -45
  291. package/dist/web/git-compare-service.js +0 -160
  292. package/dist/web/git-diff-document.d.ts +0 -102
  293. package/dist/web/git-diff-document.js +0 -258
  294. package/dist/web/git-file-source.d.ts +0 -25
  295. package/dist/web/git-file-source.js +0 -21
  296. package/dist/web/git-history-service.d.ts +0 -151
  297. package/dist/web/git-history-service.js +0 -619
  298. package/dist/web/git-index-transaction.d.ts +0 -45
  299. package/dist/web/git-index-transaction.js +0 -174
  300. package/dist/web/git-patch-builder.d.ts +0 -30
  301. package/dist/web/git-patch-builder.js +0 -138
  302. package/dist/web/git-read-model-service.d.ts +0 -452
  303. package/dist/web/git-read-model-service.js +0 -1833
  304. package/dist/web/git-version-service.d.ts +0 -79
  305. package/dist/web/git-version-service.js +0 -279
  306. package/dist/web/host-daemon.d.ts +0 -70
  307. package/dist/web/host-daemon.js +0 -237
  308. package/dist/web/index.d.ts +0 -6
  309. package/dist/web/index.js +0 -28
  310. package/dist/web/launch.d.ts +0 -12
  311. package/dist/web/launch.js +0 -89
  312. package/dist/web/native-directory-picker.d.ts +0 -63
  313. package/dist/web/native-directory-picker.js +0 -169
  314. package/dist/web/protocol.d.ts +0 -705
  315. package/dist/web/protocol.js +0 -639
  316. package/dist/web/review-service.d.ts +0 -22
  317. package/dist/web/review-service.js +0 -68
  318. package/dist/web/server.d.ts +0 -20
  319. package/dist/web/server.js +0 -1453
  320. package/dist/web/session-runtime-registry.d.ts +0 -138
  321. package/dist/web/session-runtime-registry.js +0 -471
  322. package/dist/web/terminal-manager.d.ts +0 -156
  323. package/dist/web/terminal-manager.js +0 -779
  324. package/dist/web/terminal-server.d.ts +0 -8
  325. package/dist/web/terminal-server.js +0 -304
  326. package/dist/web/workbench-controller.d.ts +0 -395
  327. package/dist/web/workbench-controller.js +0 -3077
  328. package/dist/web/workspace-discovery.d.ts +0 -92
  329. package/dist/web/workspace-discovery.js +0 -324
  330. package/dist/web/workspace-mutation-arbiter.d.ts +0 -54
  331. package/dist/web/workspace-mutation-arbiter.js +0 -267
  332. package/dist/web/workspace-open-telemetry.d.ts +0 -55
  333. package/dist/web/workspace-open-telemetry.js +0 -73
  334. package/dist/web-client/assets/FilesPanel-iBYj9ZRf.js +0 -1
  335. package/dist/web-client/assets/GitPanel-D33R_bZr.js +0 -4
  336. package/dist/web-client/assets/ReviewPanel-C_0upsDk.js +0 -6
  337. package/dist/web-client/assets/TerminalPanel-C7A8dMNf.js +0 -23
  338. package/dist/web-client/assets/TerminalPanel-DLuoa74B.css +0 -1
  339. package/dist/web-client/assets/index-BaOxrwGB.css +0 -1
  340. package/dist/web-client/assets/index-CqCgJ2ov.js +0 -20
  341. package/dist/web-client/assets/useAutoNotice-C1qM-_Sg.js +0 -1
  342. package/dist/web-client/favicon.svg +0 -9
  343. package/dist/web-client/index.html +0 -17
  344. package/docs/architecture/agent-mode-permission-contract.md +0 -87
  345. package/docs/architecture/v0.3.0-web-api.yaml +0 -1340
  346. package/docs/architecture/v0.3.1-web-api.yaml +0 -2338
  347. package/docs/architecture/v0.3.2-web-api.yaml +0 -3029
  348. package/docs/architecture/v0.3.3-web-api.yaml +0 -3205
  349. package/docs/architecture/v0.3.4-stabilization-contract.md +0 -32
  350. package/docs/migration/v0.1.9-to-v0.2.0.md +0 -98
  351. package/docs/migration/v0.2.2-to-v0.3.0-settings.md +0 -114
  352. package/docs/migration/v0.2.2-to-v0.3.0.md +0 -55
  353. package/docs/migration/v0.3.0-to-v0.3.1.md +0 -88
  354. package/docs/migration/v0.3.1-to-v0.3.2.md +0 -94
  355. package/docs/migration/v0.3.2-to-v0.3.3.md +0 -62
  356. package/docs/migration/v0.3.3-to-v0.3.4.md +0 -36
  357. package/docs/orion.example.json +0 -86
  358. package/docs/plan/v0.2.0-dsh-harness-redesign-plan.md +0 -1234
  359. package/docs/plan/v0.2.0-release-checklist.md +0 -91
  360. package/docs/plan/v0.3.0-node-runtime-compatibility-plan.md +0 -57
  361. package/docs/plan/v0.3.0-settings-integration-plan.md +0 -740
  362. package/docs/plan/v0.3.0-web-workbench-plan.md +0 -376
  363. package/docs/plan/v0.3.1-web-workbench-professional-shell-plan.md +0 -848
  364. package/docs/plan/v0.3.2-web-workbench-layout-and-composer-plan.md +0 -869
  365. package/docs/plan/v0.3.3-plan.md +0 -1113
  366. package/docs/plan/v0.3.4-stabilization-plan.md +0 -89
  367. package/docs/test/v0.3.1-web-workbench-e2e-plan.md +0 -140
  368. package/docs/test/v0.3.2-web-workbench-e2e-plan.md +0 -100
  369. package/docs/test/v0.3.3-web-workbench-e2e-plan.md +0 -79
  370. package/docs/test/v0.3.4-stabilization-e2e-plan.md +0 -54
@@ -1,1833 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GitReadModelServiceV1 = void 0;
4
- exports.normalizeCommitMessage = normalizeCommitMessage;
5
- exports.assertRelativeGitPath = assertRelativeGitPath;
6
- const child_process_1 = require("child_process");
7
- const crypto_1 = require("crypto");
8
- const fs_1 = require("fs");
9
- const promises_1 = require("fs/promises");
10
- const path_1 = require("path");
11
- const redaction_1 = require("../services/redaction");
12
- const errors_1 = require("./errors");
13
- const git_diff_document_1 = require("./git-diff-document");
14
- const git_patch_builder_1 = require("./git-patch-builder");
15
- const git_history_service_1 = require("./git-history-service");
16
- const git_compare_service_1 = require("./git-compare-service");
17
- const git_version_service_1 = require("./git-version-service");
18
- const git_file_source_1 = require("./git-file-source");
19
- const git_index_transaction_1 = require("./git-index-transaction");
20
- const GIT_TIMEOUT_MS = 5000;
21
- /** plan §7.9 — the commit runner gets its own bounded budget for hooks and signing. */
22
- const GIT_COMMIT_TIMEOUT_MS = 60000;
23
- const GIT_MAX_BUFFER = 8 * 1024 * 1024;
24
- const DEFAULT_STATUS_PAGE_SIZE = 200;
25
- const MAX_STATUS_PAGE_SIZE = 2000;
26
- const DEFAULT_LOG_PAGE_SIZE = 30;
27
- const MAX_LOG_PAGE_SIZE = 100;
28
- const DEFAULT_DIFF_LINES = 240;
29
- const MAX_DIFF_LINES = 500;
30
- const DEFAULT_DIFF_BYTES = 256 * 1024;
31
- const MAX_DIFF_BYTES = 1024 * 1024;
32
- const GIT_NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
33
- /** Bounded argv-only Git status/log/diff projection for one active Workspace. */
34
- class GitReadModelServiceV1 {
35
- constructor(workspace, options = {}) {
36
- this.secret = (0, crypto_1.randomBytes)(32);
37
- /**
38
- * v0.3.17 S1 — tokens are keyed by (source, path), not by path alone. A file that is
39
- * both staged and modified in the worktree is two different selectable objects, so a
40
- * path-only key silently conflated the two comparison sources.
41
- */
42
- this.targetById = new Map();
43
- this.idByKey = new Map();
44
- this.performance = { processCount: 0, bytesRead: 0, itemsParsed: 0 };
45
- this.workspace = canonicalDirectory(workspace);
46
- this.commitTimeoutMs = boundedInteger(options.commitTimeoutMs ?? GIT_COMMIT_TIMEOUT_MS, 1000, 600000, 'commitTimeoutMs');
47
- }
48
- performanceCounters() {
49
- return Object.freeze({ ...this.performance });
50
- }
51
- async status(input = {}) {
52
- const snapshot = await this.capture();
53
- const pageSize = boundedInteger(input.pageSize ?? DEFAULT_STATUS_PAGE_SIZE, 1, MAX_STATUS_PAGE_SIZE, 'pageSize');
54
- const group = normalizeSource(input.group);
55
- const query = normalizeQuery(input.query);
56
- // v0.3.17 S1 — the query scope is bound into the cursor, so pages can never be
57
- // stitched across two different filters.
58
- const scope = statusScope(group, query);
59
- const matched = snapshot.records.filter(record => {
60
- if (group && !recordSources(record).includes(group))
61
- return false;
62
- return query === undefined || record.path.toLocaleLowerCase().includes(query);
63
- });
64
- const offset = input.cursor
65
- ? this.decodeCursor(input.cursor, 'status', snapshot.revision, undefined, scope).offset
66
- : 0;
67
- const page = matched.slice(offset, offset + pageSize);
68
- const staged = [];
69
- const unstaged = [];
70
- const untracked = [];
71
- const conflicted = [];
72
- const buckets = {
73
- staged,
74
- unstaged,
75
- untracked,
76
- conflict: conflicted,
77
- };
78
- for (const record of page) {
79
- for (const source of recordSources(record)) {
80
- buckets[source].push(this.projectFile(record, source));
81
- }
82
- }
83
- // Totals cover the whole matched scope, never just the loaded page.
84
- const counts = countSources(matched);
85
- const nextOffset = offset + page.length;
86
- return Object.freeze({
87
- isRepository: snapshot.isRepository,
88
- repositoryKind: snapshot.repositoryKind,
89
- hasWorktree: snapshot.repositoryKind === 'worktree',
90
- repositoryRevision: snapshot.revision,
91
- ...(snapshot.root ? { rootLabel: (0, path_1.basename)(snapshot.root) } : {}),
92
- branch: snapshot.branch,
93
- // v0.3.19 (G317-22) — only a worktree-backed checkout can be "detached". A bare
94
- // repository has no branch either, and reporting that as a detached HEAD invented a
95
- // state the repository is not in.
96
- detached: snapshot.repositoryKind === 'worktree' && !snapshot.branch,
97
- head: snapshot.head ? snapshot.head.slice(0, 12) : null,
98
- upstream: snapshot.upstream,
99
- ahead: snapshot.ahead,
100
- behind: snapshot.behind,
101
- clean: snapshot.records.length === 0,
102
- staged: Object.freeze(staged),
103
- unstaged: Object.freeze(unstaged),
104
- untracked: Object.freeze(untracked),
105
- conflicted: Object.freeze(conflicted),
106
- totalFiles: matched.length,
107
- counts: Object.freeze({ ...counts, loaded: page.length }),
108
- truncated: nextOffset < matched.length,
109
- nextCursor: nextOffset < matched.length
110
- ? this.encodeCursor({
111
- version: 2,
112
- kind: 'status',
113
- revision: snapshot.revision,
114
- offset: nextOffset,
115
- scope,
116
- })
117
- : null,
118
- });
119
- }
120
- async log(input = {}) {
121
- const snapshot = await this.capture();
122
- if (!snapshot.isRepository || !snapshot.root || !snapshot.head) {
123
- return Object.freeze({
124
- repositoryRevision: snapshot.revision,
125
- items: Object.freeze([]),
126
- nextCursor: null,
127
- });
128
- }
129
- const pageSize = boundedInteger(input.pageSize ?? DEFAULT_LOG_PAGE_SIZE, 1, MAX_LOG_PAGE_SIZE, 'pageSize');
130
- const offset = input.cursor
131
- ? this.decodeCursor(input.cursor, 'log', snapshot.revision).offset
132
- : 0;
133
- const raw = await this.runGit([
134
- 'log',
135
- `--skip=${offset}`,
136
- `--max-count=${pageSize + 1}`,
137
- '--format=%H%x1f%h%x1f%ct%x1f%an%x1f%s%x1e',
138
- ], snapshot.root);
139
- const commits = raw
140
- .split('\x1e')
141
- .map(record => record.replace(/^\s+/u, '').replace(/\s+$/u, ''))
142
- .filter(Boolean)
143
- .map(parseCommit);
144
- this.performance.itemsParsed += commits.length;
145
- const hasMore = commits.length > pageSize;
146
- const items = commits.slice(0, pageSize);
147
- return Object.freeze({
148
- repositoryRevision: snapshot.revision,
149
- items: Object.freeze(items),
150
- nextCursor: hasMore
151
- ? this.encodeCursor({
152
- version: 2,
153
- kind: 'log',
154
- revision: snapshot.revision,
155
- offset: offset + items.length,
156
- })
157
- : null,
158
- });
159
- }
160
- async diff(input) {
161
- const snapshot = await this.capture();
162
- if (!snapshot.isRepository || !snapshot.root) {
163
- throw new errors_1.WebWorkbenchError(404, 'Git repository is unavailable.', 'git_not_repository');
164
- }
165
- const target = this.resolveTarget(input.fileId);
166
- const { path } = target;
167
- const record = snapshot.records.find(candidate => candidate.path === path);
168
- if (!record) {
169
- throw new errors_1.WebWorkbenchError(409, 'Git file changed before diff.', 'git_revision_conflict');
170
- }
171
- // A token names one comparison source. If that source no longer exists (the file was
172
- // staged away, or the worktree edit was reverted), the selection is stale rather than
173
- // silently rendered against the other side.
174
- if (!recordStillMatches(record, target.source)) {
175
- throw new errors_1.WebWorkbenchError(409, 'Git file changed before diff.', 'git_revision_conflict');
176
- }
177
- if (isSensitiveGitRecord(record)) {
178
- throw new errors_1.WebWorkbenchError(403, 'Sensitive file content is not available in the Web Workbench.', 'sensitive_file_blocked');
179
- }
180
- const lineLimit = boundedInteger(input.lineLimit ?? DEFAULT_DIFF_LINES, 1, MAX_DIFF_LINES, 'lineLimit');
181
- const byteLimit = boundedInteger(input.byteLimit ?? DEFAULT_DIFF_BYTES, 1024, MAX_DIFF_BYTES, 'byteLimit');
182
- // Defaulted once so the command, the cursor and the document all describe the same view.
183
- const ignoreWhitespace = input.ignoreWhitespace === true;
184
- const wordDiff = input.wordDiff === true;
185
- const offset = input.cursor
186
- ? this.decodeCursor(input.cursor, 'diff', snapshot.revision, input.fileId, diffScope(ignoreWhitespace, wordDiff)).offset
187
- : 0;
188
- const commands = diffCommands(path, target.source, ignoreWhitespace, wordDiff);
189
- const page = await streamDiffPage({
190
- cwd: snapshot.root,
191
- commands,
192
- offset,
193
- lineLimit,
194
- byteLimit,
195
- onProcess: () => {
196
- this.performance.processCount += 1;
197
- },
198
- onBytes: bytes => {
199
- this.performance.bytesRead += bytes;
200
- },
201
- });
202
- this.performance.itemsParsed += page.linesParsed;
203
- if (page.hasMore && page.returnedLines === 0) {
204
- throw new errors_1.WebWorkbenchError(500, 'Git diff pagination could not advance.', 'git_pagination_stalled');
205
- }
206
- const after = await this.capture();
207
- if (after.revision !== snapshot.revision) {
208
- throw new errors_1.WebWorkbenchError(409, 'Repository changed while reading diff.', 'git_revision_conflict');
209
- }
210
- const binary = page.lines.some(line => /^(?:Binary files |GIT binary patch)/u.test(line));
211
- const lines = binary ? page.lines.filter(line => !line.startsWith('literal ')) : page.lines;
212
- return Object.freeze({
213
- fileId: input.fileId,
214
- path: (0, redaction_1.redactTraceText)(path),
215
- source: target.source,
216
- repositoryRevision: snapshot.revision,
217
- binary,
218
- lines: Object.freeze(lines),
219
- nextCursor: page.hasMore
220
- ? this.encodeCursor({
221
- version: 2,
222
- kind: 'diff',
223
- revision: snapshot.revision,
224
- offset: offset + page.returnedLines,
225
- fileId: input.fileId,
226
- scope: diffScope(ignoreWhitespace, wordDiff),
227
- })
228
- : null,
229
- truncated: page.hasMore,
230
- });
231
- }
232
- /**
233
- * v0.3.17 S2 — the structured form of the same comparison. It reuses `diff()` verbatim,
234
- * so the hardened read path, byte/line budget and pagination stay in one place; only the
235
- * projection changes.
236
- */
237
- async diffDocument(input) {
238
- const page = await this.diff(input);
239
- // v0.3.26 #275 — the incoming cursor may carry the hunk state this page
240
- // continues; diff() already validated the cursor, so decoding it here only
241
- // reads the resume state.
242
- const resumeHunk = input.cursor
243
- ? this.decodeCursor(input.cursor, 'diff', page.repositoryRevision, page.fileId, diffScope(input.ignoreWhitespace === true, input.wordDiff === true)).resumeHunk
244
- : undefined;
245
- const document = (0, git_diff_document_1.parseGitDiffDocument)({
246
- fileToken: page.fileId,
247
- path: page.path,
248
- source: page.source,
249
- repositoryRevision: page.repositoryRevision,
250
- lines: page.lines,
251
- hasMore: page.nextCursor !== null,
252
- nextCursor: page.nextCursor,
253
- ...(resumeHunk ? { resume: resumeHunk } : {}),
254
- });
255
- // A page that ends inside a hunk re-mints the cursor with the hunk state so
256
- // the next page resumes it instead of demoting the rows to meta.
257
- if (page.nextCursor && document.pendingHunk) {
258
- const decoded = this.decodeCursor(page.nextCursor, 'diff', page.repositoryRevision, page.fileId, diffScope(input.ignoreWhitespace === true, input.wordDiff === true));
259
- return Object.freeze({
260
- ...document,
261
- nextCursor: this.encodeCursor({ ...decoded, resumeHunk: document.pendingHunk }),
262
- });
263
- }
264
- return document;
265
- }
266
- historyReader() {
267
- this.historyReaderInstance ?? (this.historyReaderInstance = (0, git_history_service_1.createGitHistoryReader)({
268
- runGit: async (args) => this.runGit(args, await this.requireRepositoryRoot()),
269
- requireRoot: () => this.requireRepositoryRoot(),
270
- revision: async () => (await this.capture()).revision,
271
- }));
272
- return this.historyReaderInstance;
273
- }
274
- compareReader() {
275
- this.compareReaderInstance ?? (this.compareReaderInstance = (0, git_compare_service_1.createGitCompareReader)({
276
- runGit: async (args) => this.runGit(args, await this.requireRepositoryRoot()),
277
- }));
278
- return this.compareReaderInstance;
279
- }
280
- /**
281
- * v0.3.17 S5 — branch/version comparison. Read-only.
282
- *
283
- * The resolved OIDs are part of the result on purpose: the UI freezes the opened result
284
- * against them, so a ref that moves afterwards produces a "there is an update" hint
285
- * instead of silently comparing against a different tree.
286
- */
287
- async compare(input) {
288
- return this.compareReader().compare(input);
289
- }
290
- /** Resolves a pair of refs without computing a comparison (used to detect ref movement). */
291
- async resolveComparePair(baseRef, headRef) {
292
- const pair = await this.compareReader().resolvePair(baseRef, headRef);
293
- return Object.freeze({ baseOid: pair.baseOid, headOid: pair.headOid });
294
- }
295
- /**
296
- * v0.3.17 S5 — the diff one file shows between two arbitrary commits.
297
- *
298
- * Same bounded stream as every other diff; the only new thing is that the base is a
299
- * caller-supplied resolved OID instead of a parent. The cursor margin binds the page to
300
- * this exact base/head/path triple, so a different comparison cannot continue it.
301
- */
302
- async compareFileDiffDocument(input) {
303
- const root = await this.requireRepositoryRoot();
304
- const path = assertRelativeGitPath(input.path);
305
- if ((0, redaction_1.isSensitiveFilePath)(path)) {
306
- throw new errors_1.WebWorkbenchError(403, 'Sensitive file content is not available in the Web Workbench.', 'sensitive_file_blocked');
307
- }
308
- for (const oid of [input.baseOid, input.headOid]) {
309
- if (!/^[0-9a-f]{7,64}$/iu.test(oid)) {
310
- throw new errors_1.WebWorkbenchError(400, 'A commit hash is required.', 'git_revision_invalid');
311
- }
312
- }
313
- const snapshot = await this.capture();
314
- const lineLimit = boundedInteger(input.lineLimit ?? DEFAULT_DIFF_LINES, 1, MAX_DIFF_LINES, 'lineLimit');
315
- const byteLimit = boundedInteger(input.byteLimit ?? DEFAULT_DIFF_BYTES, 1024, MAX_DIFF_BYTES, 'byteLimit');
316
- const margin = (0, crypto_1.createHash)('sha256')
317
- .update(`compare-diff:${input.baseOid}:${input.headOid}:${path}:${snapshot.revision}`)
318
- .digest('hex')
319
- .slice(0, 24);
320
- const cursorState = input.cursor ? decodeCommitDiffCursor(input.cursor, margin) : null;
321
- const offset = cursorState?.offset ?? 0;
322
- const page = await streamDiffPage({
323
- cwd: root,
324
- commands: Object.freeze([
325
- {
326
- title: 'Compare',
327
- args: [
328
- 'diff',
329
- '--no-ext-diff',
330
- '--no-textconv',
331
- '--unified=3',
332
- input.baseOid,
333
- input.headOid,
334
- '--',
335
- path,
336
- ],
337
- },
338
- ]),
339
- offset,
340
- lineLimit,
341
- byteLimit,
342
- onProcess: () => {
343
- this.performance.processCount += 1;
344
- },
345
- onBytes: bytes => {
346
- this.performance.bytesRead += bytes;
347
- },
348
- });
349
- this.performance.itemsParsed += page.linesParsed;
350
- const document = (0, git_diff_document_1.parseGitDiffDocument)({
351
- fileToken: `compare_${margin}`,
352
- path,
353
- source: 'commit',
354
- repositoryRevision: snapshot.revision,
355
- lines: page.lines,
356
- hasMore: page.hasMore,
357
- nextCursor: page.hasMore
358
- ? encodeCommitDiffCursor({ margin, offset: offset + page.returnedLines })
359
- : null,
360
- ...(cursorState?.resumeHunk ? { resume: cursorState.resumeHunk } : {}),
361
- });
362
- // v0.3.26 #275 — re-mint the continuation cursor with the split hunk state.
363
- const nextCursor = page.hasMore && document.pendingHunk
364
- ? encodeCommitDiffCursor({
365
- margin,
366
- offset: offset + page.returnedLines,
367
- resumeHunk: document.pendingHunk,
368
- })
369
- : document.nextCursor;
370
- return Object.freeze({
371
- ...document,
372
- nextCursor,
373
- baseOid: input.baseOid,
374
- baseLabel: `比较 ${input.baseOid.slice(0, 10)} → ${input.headOid.slice(0, 10)}`,
375
- });
376
- }
377
- versionReader() {
378
- this.versionReaderInstance ?? (this.versionReaderInstance = (0, git_version_service_1.createGitVersionReader)({
379
- runGit: async (args) => this.runGit(args, await this.requireRepositoryRoot()),
380
- runGitBytes: async (args) => this.runGitBytes(args, await this.requireRepositoryRoot()),
381
- readWorktreeFile: async (relativePath) => this.readContainedWorktreeFile(relativePath),
382
- }));
383
- return this.versionReaderInstance;
384
- }
385
- /**
386
- * v0.3.25 #269 — reads one working-tree file for the conflict view, refusing
387
- * to leave the repository: the requested relative path (already guarded as
388
- * relative and non-sensitive by the version reader) is resolved against the
389
- * repository root and both the file's real path and its parent's real path
390
- * must stay inside the root's real path. Returns null instead of throwing so
391
- * a missing or unreadable file reads as an absent worktree version.
392
- */
393
- async readContainedWorktreeFile(relativePath) {
394
- let root;
395
- try {
396
- root = (0, fs_1.realpathSync)(await this.requireRepositoryRoot());
397
- }
398
- catch {
399
- return null;
400
- }
401
- try {
402
- const absolute = (0, path_1.resolve)(root, relativePath);
403
- const fileReal = (0, fs_1.realpathSync)(absolute);
404
- const parentReal = (0, fs_1.realpathSync)((0, path_1.resolve)(fileReal, '..'));
405
- if (fileReal !== root && !fileReal.startsWith(root + path_1.sep))
406
- return null;
407
- if (parentReal !== root && !parentReal.startsWith(root + path_1.sep))
408
- return null;
409
- const stat = (0, fs_1.statSync)(fileReal);
410
- if (!stat.isFile())
411
- return null;
412
- return await (0, promises_1.readFile)(fileReal);
413
- }
414
- catch {
415
- return null;
416
- }
417
- }
418
- /**
419
- * v0.3.17 S5 — base / ours / theirs / worktree for a conflicted file.
420
- *
421
- * Read from index stages 1/2/3 rather than assembled from two diffs: a modify/delete
422
- * conflict genuinely has no base, and pretending otherwise is what plan G6 forbids.
423
- */
424
- async conflictVersions(path) {
425
- return this.versionReader().conflict(path);
426
- }
427
- /** Reads one file at a revision — including a file that no longer exists locally. */
428
- async fileBlob(input) {
429
- return this.versionReader().blob(input);
430
- }
431
- /** Recorded gitlink SHAs only; submodules are never traversed (plan G6). */
432
- async submodules() {
433
- return this.versionReader().submodules();
434
- }
435
- async refs() {
436
- return this.historyReader().refs();
437
- }
438
- async history(query) {
439
- return this.historyReader().history(query);
440
- }
441
- async commitDetail(oid, parentIndex = 0) {
442
- return this.historyReader().commit(oid, parentIndex);
443
- }
444
- async commitFiles(oid, parentIndex = 0) {
445
- return this.historyReader().commitFiles(oid, parentIndex);
446
- }
447
- async graph(input = {}) {
448
- return this.historyReader().graph(input);
449
- }
450
- async blame(input) {
451
- return this.historyReader().blame(input);
452
- }
453
- async fileHistory(input) {
454
- return this.historyReader().fileHistory(input);
455
- }
456
- /**
457
- * v0.3.17 S4 — the diff a commit introduced to one file.
458
- *
459
- * Rebuilds the comparison from the commit's real base (first parent, a chosen parent, or the
460
- * empty tree for a root commit) and reuses `streamDiffPage`, so the byte/line budget,
461
- * pagination and `--no-ext-diff`/`--no-textconv` hardening are the same code the working-tree
462
- * diff uses. There is no second diff implementation to keep in sync.
463
- */
464
- async commitDiffDocument(input) {
465
- const root = await this.requireRepositoryRoot();
466
- const path = assertRelativeGitPath(input.path);
467
- if ((0, redaction_1.isSensitiveFilePath)(path)) {
468
- throw new errors_1.WebWorkbenchError(403, 'Sensitive file content is not available in the Web Workbench.', 'sensitive_file_blocked');
469
- }
470
- const parentIndex = input.parentIndex ?? 0;
471
- const detail = await this.commitDetail(input.oid, parentIndex);
472
- const snapshot = await this.capture();
473
- const lineLimit = boundedInteger(input.lineLimit ?? DEFAULT_DIFF_LINES, 1, MAX_DIFF_LINES, 'lineLimit');
474
- const byteLimit = boundedInteger(input.byteLimit ?? DEFAULT_DIFF_BYTES, 1024, MAX_DIFF_BYTES, 'byteLimit');
475
- // The margin decides which comparison this page belongs to; a different commit or parent
476
- // is a different document, not a continuation.
477
- const margin = (0, crypto_1.createHash)('sha256')
478
- .update(`commit-diff:${detail.id}:${detail.baseOid}:${parentIndex}:${snapshot.revision}`)
479
- .digest('hex')
480
- .slice(0, 24);
481
- const cursorState = input.cursor ? decodeCommitDiffCursor(input.cursor, margin) : null;
482
- const offset = cursorState?.offset ?? 0;
483
- const page = await streamDiffPage({
484
- cwd: root,
485
- commands: Object.freeze([
486
- {
487
- title: 'Commit',
488
- args: [
489
- 'diff',
490
- '--no-ext-diff',
491
- '--no-textconv',
492
- '--unified=3',
493
- detail.baseOid,
494
- detail.id,
495
- '--',
496
- path,
497
- ],
498
- },
499
- ]),
500
- offset,
501
- lineLimit,
502
- byteLimit,
503
- onProcess: () => {
504
- this.performance.processCount += 1;
505
- },
506
- onBytes: bytes => {
507
- this.performance.bytesRead += bytes;
508
- },
509
- });
510
- this.performance.itemsParsed += page.linesParsed;
511
- const document = (0, git_diff_document_1.parseGitDiffDocument)({
512
- fileToken: `commit_${margin}`,
513
- path,
514
- source: 'commit',
515
- repositoryRevision: snapshot.revision,
516
- lines: page.lines,
517
- hasMore: page.hasMore,
518
- nextCursor: page.hasMore
519
- ? encodeCommitDiffCursor({ margin, offset: offset + page.returnedLines })
520
- : null,
521
- ...(cursorState?.resumeHunk ? { resume: cursorState.resumeHunk } : {}),
522
- });
523
- // v0.3.26 #275 — re-mint the continuation cursor with the split hunk state.
524
- const nextCursor = page.hasMore && document.pendingHunk
525
- ? encodeCommitDiffCursor({
526
- margin,
527
- offset: offset + page.returnedLines,
528
- resumeHunk: document.pendingHunk,
529
- })
530
- : document.nextCursor;
531
- return Object.freeze({
532
- ...document,
533
- nextCursor,
534
- baseLabel: detail.baseLabel,
535
- baseOid: detail.baseOid,
536
- });
537
- }
538
- async capture() {
539
- let root;
540
- let repositoryKind = 'absent';
541
- try {
542
- root =
543
- this.repositoryRoot ??
544
- (0, fs_1.realpathSync)((await this.runGit(['rev-parse', '--show-toplevel'], this.workspace)).trim());
545
- if (!isWithinRoot(root, this.workspace))
546
- throw new Error('repository root escaped workspace');
547
- this.repositoryRoot = root;
548
- repositoryKind = 'worktree';
549
- }
550
- catch {
551
- // v0.3.19 (G317-22) — `--show-toplevel` fails for a bare repository too, so the failure
552
- // alone cannot say which case this is. Ask directly. Conflating "no repository" with
553
- // "a repository that has no working tree" told the reader the wrong thing about a
554
- // directory that is in fact a valid repository.
555
- const bare = (await this.tryGit(['rev-parse', '--is-bare-repository'], this.workspace))
556
- ?.trim()
557
- .toLowerCase();
558
- repositoryKind = bare === 'true' ? 'bare' : 'absent';
559
- }
560
- if (repositoryKind === 'bare') {
561
- // A bare repository has no index and no working tree, so there is nothing to report as
562
- // changed — but its HEAD is real and worth stating. `clean` stays true in `status()`
563
- // because zero files differ from an index that does not exist; `hasWorktree` is what
564
- // tells the reader not to trust that as "you have nothing to commit".
565
- const [branchResult, headResult] = await Promise.all([
566
- this.tryGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], this.workspace),
567
- this.tryGit(['rev-parse', 'HEAD'], this.workspace),
568
- ]);
569
- const branch = branchResult?.trim() || null;
570
- const head = headResult?.trim() || null;
571
- const revision = (0, crypto_1.createHash)('sha256')
572
- .update(JSON.stringify({ bare: this.workspace, branch, head }))
573
- .digest('hex');
574
- return Object.freeze({
575
- isRepository: true,
576
- repositoryKind: 'bare',
577
- branch,
578
- head,
579
- upstream: null,
580
- ahead: 0,
581
- behind: 0,
582
- records: Object.freeze([]),
583
- rawStatus: '',
584
- stagedRecords: 0,
585
- conflictedRecords: 0,
586
- indexDigest: (0, crypto_1.createHash)('sha256').update('').digest('hex'),
587
- revision,
588
- });
589
- }
590
- if (repositoryKind === 'absent') {
591
- const revision = (0, crypto_1.createHash)('sha256').update(`not-git:${this.workspace}`).digest('hex');
592
- return Object.freeze({
593
- isRepository: false,
594
- repositoryKind: 'absent',
595
- branch: null,
596
- head: null,
597
- upstream: null,
598
- ahead: 0,
599
- behind: 0,
600
- records: Object.freeze([]),
601
- rawStatus: '',
602
- stagedRecords: 0,
603
- conflictedRecords: 0,
604
- indexDigest: (0, crypto_1.createHash)('sha256').update('').digest('hex'),
605
- revision,
606
- });
607
- }
608
- if (!root) {
609
- // Only the `worktree` branch assigns a root and both other kinds returned above, so this
610
- // is unreachable today — it exists so the invariant is enforced, not merely inferred.
611
- throw new Error('Resolved a non-worktree repository without a root.');
612
- }
613
- const [rawStatus, branchResult, headResult, upstreamResult, indexListing] = await Promise.all([
614
- this.runGit(['status', '--porcelain=v1', '-z', '--untracked-files=all'], root),
615
- this.tryGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], root),
616
- this.tryGit(['rev-parse', 'HEAD'], root),
617
- this.tryGit(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], root),
618
- // v0.3.17 S1 — the index snapshot is what makes a state revision change on
619
- // stage/unstage even though HEAD does not move. `--stage` yields
620
- // mode/oid/stage/path for every entry, including unmerged stages.
621
- this.tryGit(['ls-files', '--stage', '-z'], root),
622
- ]);
623
- const branch = branchResult?.trim() || null;
624
- const head = headResult?.trim() || null;
625
- const upstream = upstreamResult?.trim() || null;
626
- let ahead = 0;
627
- let behind = 0;
628
- if (upstream) {
629
- const counts = await this.tryGit(['rev-list', '--left-right', '--count', `HEAD...${upstream}`], root);
630
- const [aheadValue, behindValue] = (counts ?? '').trim().split(/\s+/u).map(Number);
631
- ahead = Number.isSafeInteger(aheadValue) ? aheadValue : 0;
632
- behind = Number.isSafeInteger(behindValue) ? behindValue : 0;
633
- }
634
- const records = parsePorcelainV1(rawStatus);
635
- this.performance.itemsParsed += records.length;
636
- let stagedRecords = 0;
637
- let conflictedRecords = 0;
638
- for (const record of records) {
639
- const sources = recordSources(record);
640
- if (sources.includes('conflict'))
641
- conflictedRecords += 1;
642
- else if (sources.includes('staged'))
643
- stagedRecords += 1;
644
- }
645
- const fileFingerprints = records.map(record => fingerprintWorktreePath(root, record.path));
646
- // Hash the index listing on its own so a large index never builds a second full copy
647
- // of itself inside the JSON payload.
648
- const indexDigest = (0, crypto_1.createHash)('sha256')
649
- .update(indexListing ?? '')
650
- .digest('hex');
651
- const revision = (0, crypto_1.createHash)('sha256')
652
- .update(JSON.stringify({
653
- root,
654
- branch,
655
- head,
656
- upstream,
657
- ahead,
658
- behind,
659
- rawStatus,
660
- fileFingerprints,
661
- indexDigest,
662
- }))
663
- .digest('hex');
664
- return Object.freeze({
665
- isRepository: true,
666
- repositoryKind: 'worktree',
667
- root,
668
- branch,
669
- head,
670
- upstream,
671
- ahead,
672
- behind,
673
- records: Object.freeze(records),
674
- rawStatus,
675
- stagedRecords,
676
- conflictedRecords,
677
- indexDigest,
678
- revision,
679
- });
680
- }
681
- projectFile(record, source) {
682
- return Object.freeze({
683
- fileId: this.rememberTarget(source, record.path),
684
- path: (0, redaction_1.redactTraceText)(record.path),
685
- source,
686
- indexStatus: record.indexStatus,
687
- worktreeStatus: record.worktreeStatus,
688
- ...(record.renamedFrom ? { renamedFrom: (0, redaction_1.redactTraceText)(record.renamedFrom) } : {}),
689
- });
690
- }
691
- rememberTarget(source, path) {
692
- const key = `${source}\u0000${path}`;
693
- const existing = this.idByKey.get(key);
694
- if (existing)
695
- return existing;
696
- const id = `git_${(0, crypto_1.createHmac)('sha256', this.secret)
697
- .update(key)
698
- .digest('base64url')
699
- .slice(0, 32)}`;
700
- this.idByKey.set(key, id);
701
- this.targetById.set(id, Object.freeze({ source, path }));
702
- return id;
703
- }
704
- /**
705
- * v0.3.17 S1 — the single place a Git file token becomes a path. Git mutations resolve
706
- * tokens here instead of going through FileReadService, whose token space is unrelated.
707
- */
708
- resolveTarget(fileId) {
709
- if (typeof fileId !== 'string' || fileId.length === 0 || fileId.length > 256) {
710
- throw new errors_1.WebWorkbenchError(400, 'A Git file id is invalid.', 'file_id_invalid');
711
- }
712
- const target = this.targetById.get(fileId);
713
- if (!target) {
714
- throw new errors_1.WebWorkbenchError(404, 'Git file was not found.', 'git_file_not_found');
715
- }
716
- return target;
717
- }
718
- /**
719
- * v0.3.17 S1 — resolve Git file tokens for a mutation and enforce the source each
720
- * action may write. This replaces FileReadService token lookup, whose token space is
721
- * unrelated to Git and silently rejected every real Git list token.
722
- */
723
- resolveMutationPaths(action, fileIds) {
724
- if (!Array.isArray(fileIds) || fileIds.length === 0 || fileIds.length > 200) {
725
- throw new errors_1.WebWorkbenchError(400, 'fileIds must list 1 through 200 files.');
726
- }
727
- const paths = [];
728
- for (const fileId of fileIds) {
729
- const target = this.resolveTarget(fileId);
730
- const writable = action === 'stage'
731
- ? target.source === 'unstaged' || target.source === 'untracked'
732
- : target.source === 'staged';
733
- if (!writable) {
734
- // Conflict entries are deliberately not writable in this version (plan G3).
735
- throw new errors_1.WebWorkbenchError(409, `A ${target.source} file cannot be ${action === 'stage' ? 'staged' : 'unstaged'}.`, 'git_source_not_writable');
736
- }
737
- paths.push(target.path);
738
- }
739
- assertSafeGitPaths(paths);
740
- return paths;
741
- }
742
- /** v0.3.12 S3 — guarded stage: paths are host-resolved file ids only. */
743
- async stagePaths(paths) {
744
- assertSafeGitPaths(paths);
745
- if (paths.length === 0)
746
- throw new Error('stage requires at least one path.');
747
- const pathsInfo = await this.resolveIndexPaths();
748
- await (0, git_index_transaction_1.withIndexTransaction)(pathsInfo, context => this.readTreeEmpty(context), async (context) => {
749
- await this.runGit(['add', '--', ...paths], pathsInfo.root, 'index', context.env);
750
- await this.assertIndexMatchesWorktree(pathsInfo.root, context.env, paths);
751
- });
752
- return this.mutationResult();
753
- }
754
- /**
755
- * v0.3.17 S3 — prove the index entry for each path really equals what `git add` should
756
- * have produced.
757
- *
758
- * Checking "the path is present in the index" is not enough: the path was usually already
759
- * there, so a silent no-op would pass. `hash-object --path` applies exactly the filters and
760
- * attributes git itself would, so comparing the two oids is a precise postcondition — and
761
- * it is what turns a stat-cache no-op into a loud failure instead of a lost edit.
762
- */
763
- async assertIndexMatchesWorktree(root, env, paths) {
764
- const entries = await this.indexEntries(root, env);
765
- for (const path of paths) {
766
- const entry = entries.get(path);
767
- const absolute = (0, path_1.resolve)(root, path);
768
- if (!isWithinRoot(absolute, root)) {
769
- throw new errors_1.WebWorkbenchError(400, 'A path escaped the repository.', 'git_path_unsafe');
770
- }
771
- if (!(0, fs_1.existsSync)(absolute)) {
772
- // A worktree deletion must have dropped the index entry.
773
- if (entry !== undefined) {
774
- throw new errors_1.WebWorkbenchError(409, `The index still records a deleted file: ${path}`, 'git_index_verify_failed');
775
- }
776
- continue;
777
- }
778
- const expected = (await this.runGit(['hash-object', `--path=${path}`, '--', absolute], root, 'index', env)).trim();
779
- if (entry !== expected) {
780
- throw new errors_1.WebWorkbenchError(409, `The index did not record the current content of ${path}.`, 'git_index_verify_failed');
781
- }
782
- }
783
- }
784
- async unstagePaths(paths) {
785
- assertSafeGitPaths(paths);
786
- if (paths.length === 0)
787
- throw new Error('unstage requires at least one path.');
788
- const pathsInfo = await this.resolveIndexPaths();
789
- const head = (await this.tryGit(['rev-parse', '--verify', 'HEAD'], pathsInfo.root)) !== undefined;
790
- // Captured up front so the postcondition is checked against a frozen expectation.
791
- const headBlobs = new Map();
792
- for (const path of paths) {
793
- headBlobs.set(path, head
794
- ? ((await this.tryGit(['rev-parse', `HEAD:${path}`], pathsInfo.root))?.trim() ?? null)
795
- : null);
796
- }
797
- await (0, git_index_transaction_1.withIndexTransaction)(pathsInfo, context => this.readTreeEmpty(context), async (context) => {
798
- // A repository without HEAD cannot `reset`; `rm --cached` is the index operation
799
- // that matches a first-commit workflow and leaves worktree files alone (plan G3).
800
- const args = head
801
- ? ['reset', '-q', '--', ...paths]
802
- : ['rm', '--cached', '-q', '--', ...paths];
803
- await this.runGit(args, pathsInfo.root, 'index', context.env);
804
- const entries = await this.indexEntries(pathsInfo.root, context.env);
805
- for (const path of paths) {
806
- const entry = entries.get(path);
807
- const expected = headBlobs.get(path) ?? null;
808
- if (expected === null) {
809
- if (entry !== undefined) {
810
- throw new errors_1.WebWorkbenchError(409, 'The index did not drop the expected entry.', 'git_index_verify_failed');
811
- }
812
- }
813
- else if (entry !== expected) {
814
- throw new errors_1.WebWorkbenchError(409, 'The index did not return to the committed version.', 'git_index_verify_failed');
815
- }
816
- }
817
- });
818
- return this.mutationResult();
819
- }
820
- /**
821
- * v0.3.17 S3 — apply a hunk or line selection to the index only (plan §7.6/§7.8).
822
- *
823
- * The document is re-read on the Host, the patch is rebuilt from it, and `--check` runs
824
- * before the write. The browser only ever sends ids, never patch text.
825
- */
826
- async applySelection(input) {
827
- const document = await this.diffDocument({ fileId: input.fileId });
828
- const built = (0, git_patch_builder_1.buildSelectionPatch)(document, {
829
- ...(input.hunkIds ? { hunkIds: input.hunkIds } : {}),
830
- ...(input.lineIds ? { lineIds: input.lineIds } : {}),
831
- });
832
- if (!built.ok) {
833
- throw new errors_1.WebWorkbenchError(409, built.reason, 'git_patch_not_applicable');
834
- }
835
- // Unstaging a selection is the same patch applied backwards against the index.
836
- const reverse = document.source === 'staged';
837
- return this.applyIndexPatch(built.patch, { reverse });
838
- }
839
- /**
840
- * Applies a Host-rebuilt patch to the index only (plan §7.6). The patch never comes from
841
- * the browser: it is rebuilt from the reviewed document, and `--check` runs first so a
842
- * patch that cannot apply is rejected before anything is written into the private index.
843
- */
844
- async applyIndexPatch(patch, options = {}) {
845
- if (typeof patch !== 'string' || patch.length === 0 || patch.length > 1000000) {
846
- throw new errors_1.WebWorkbenchError(400, 'A patch must be a bounded string.', 'git_patch_invalid');
847
- }
848
- const pathsInfo = await this.resolveIndexPaths();
849
- const direction = options.reverse ? ['--reverse'] : [];
850
- await (0, git_index_transaction_1.withIndexTransaction)(pathsInfo, context => this.readTreeEmpty(context), async (context) => {
851
- // `--recount` derives line counts from the body, so a partially rebuilt hunk still
852
- // applies exactly as written. `--check` first: nothing is written on a failed check.
853
- await this.runGit(['apply', '--cached', '--check', '--recount', ...direction, '-'], pathsInfo.root, 'index', context.env, patch).catch(error => {
854
- const message = error instanceof Error ? error.message : '';
855
- // A patch rebuilt from the reviewed document can still be inapplicable to the real
856
- // index. CRLF line endings are the common cause: the diff text cannot represent them
857
- // unambiguously, so the rebuilt context does not match the stored bytes. The plan
858
- // requires such a selection to be refused explicitly rather than to fail as a Git
859
- // error — nothing has been written at this point.
860
- throw new errors_1.WebWorkbenchError(409, /patch failed|patch does not apply/iu.test(message)
861
- ? 'This selection cannot be applied to the index (CRLF line endings are a common cause).'
862
- : message, 'git_patch_not_applicable');
863
- });
864
- await this.runGit(['apply', '--cached', '--recount', ...direction, '-'], pathsInfo.root, 'index', context.env, patch);
865
- });
866
- return this.mutationResult();
867
- }
868
- async readTreeEmpty(context) {
869
- const root = await this.requireRepositoryRoot();
870
- await this.runGit(['read-tree', '--empty'], root, 'index', context.env);
871
- }
872
- /** `ls-files --stage -z` parsed into path → blob oid, honouring a private index env. */
873
- async indexEntries(root, env) {
874
- const raw = await this.runGit(['ls-files', '--stage', '-z'], root, 'index', env);
875
- const entries = new Map();
876
- for (const record of raw.split('\0')) {
877
- if (!record)
878
- continue;
879
- const tab = record.indexOf('\t');
880
- if (tab < 0)
881
- continue;
882
- const meta = record.slice(0, tab).split(' ');
883
- const path = record.slice(tab + 1);
884
- // Unmerged stages share a path; the first stage recorded is enough for verification.
885
- if (!entries.has(path))
886
- entries.set(path, meta[1] ?? '');
887
- }
888
- return entries;
889
- }
890
- /** Resolves root, git dir and the real index path (worktree-aware). */
891
- async resolveIndexPaths() {
892
- const root = await this.requireRepositoryRoot();
893
- // `--git-path index` resolves into `.git/worktrees/<name>/index` for a linked worktree,
894
- // which is the index this workspace actually writes — not the main worktree's.
895
- const indexPath = (0, path_1.resolve)(root, (await this.runGit(['rev-parse', '--git-path', 'index'], root)).trim());
896
- const gitDir = (await this.runGit(['rev-parse', '--absolute-git-dir'], root)).trim();
897
- return { root, gitDir, indexPath };
898
- }
899
- async mutationResult() {
900
- return { repositoryRevision: await this.revisionAfterMutation() };
901
- }
902
- /**
903
- * v0.3.17 S3 — what a commit would actually include.
904
- *
905
- * This is deliberately independent of the change-list filter: plan G3 requires the form to
906
- * show the real index, not the currently filtered view, so the reader can never commit a
907
- * subset they did not intend.
908
- */
909
- async commitPreview() {
910
- const snapshot = await this.capture();
911
- if (!snapshot.isRepository || !snapshot.root) {
912
- throw new errors_1.WebWorkbenchError(409, 'Git repository is unavailable.', 'git_not_repository');
913
- }
914
- const root = snapshot.root;
915
- const entries = [];
916
- for (const record of snapshot.records) {
917
- const sources = recordSources(record);
918
- if (sources.includes('conflict')) {
919
- entries.push(Object.freeze({
920
- path: (0, redaction_1.redactTraceText)(record.path),
921
- source: 'conflict',
922
- status: `${record.indexStatus}${record.worktreeStatus}`,
923
- }));
924
- continue;
925
- }
926
- if (sources.includes('staged')) {
927
- entries.push(Object.freeze({
928
- path: (0, redaction_1.redactTraceText)(record.path),
929
- source: 'staged',
930
- status: `${record.indexStatus}${record.worktreeStatus}`,
931
- }));
932
- }
933
- }
934
- const stats = await this.stagedNumstat(root);
935
- const identity = await this.describeCommitConfiguration(root);
936
- const hasConflict = snapshot.conflictedRecords > 0;
937
- const blockedReason = hasConflict
938
- ? '存在未解决的冲突,请先在 Files 中处理。'
939
- : entries.length === 0
940
- ? '暂存区为空,没有可提交的改动。'
941
- : null;
942
- return Object.freeze({
943
- repositoryRevision: snapshot.revision,
944
- branch: snapshot.branch,
945
- detached: !snapshot.branch,
946
- entries: Object.freeze(entries),
947
- additions: stats.additions,
948
- deletions: stats.deletions,
949
- filesChanged: entries.length,
950
- identity,
951
- canCommit: blockedReason === null,
952
- blockedReason,
953
- });
954
- }
955
- /** Bounded `--cached --numstat` read; used only for the summary line of the form. */
956
- async stagedNumstat(root) {
957
- const raw = await this.tryGit(['diff', '--cached', '--numstat', '--no-ext-diff', '--no-textconv', '-z'], root);
958
- if (!raw)
959
- return { additions: 0, deletions: 0 };
960
- let additions = 0;
961
- let deletions = 0;
962
- for (const record of raw.split('\0')) {
963
- if (!record)
964
- continue;
965
- const [added, removed] = record.split('\t');
966
- // Binary entries report `-` for both counts and contribute nothing to the totals.
967
- if (/^\d+$/u.test(added ?? ''))
968
- additions += Number(added);
969
- if (/^\d+$/u.test(removed ?? ''))
970
- deletions += Number(removed);
971
- }
972
- return { additions, deletions };
973
- }
974
- /**
975
- * v0.3.17 S3 — commit against a frozen expectation of HEAD and the index tree (plan §7.9).
976
- *
977
- * Differences from the previous implementation, all deliberate:
978
- * - a **separate runner** that leaves the repository's own hooks and signing
979
- * configuration in place, instead of the read hardening that disables hooks;
980
- * - the message may contain real newlines (summary + body) and is rejected only for
981
- * control characters that would corrupt a commit object;
982
- * - the index and HEAD are captured before and re-read after, and any change that is not
983
- * ours is reported rather than rolled back;
984
- * - a timeout is not treated as "not committed": the outcome is queried by requestId.
985
- */
986
- async commit(input) {
987
- const message = normalizeCommitMessage(input.summary, input.body);
988
- if (typeof input.requestId !== 'string' || !/^[A-Za-z0-9_-]{8,64}$/u.test(input.requestId)) {
989
- throw new errors_1.WebWorkbenchError(400, 'requestId is invalid.', 'git_request_id_invalid');
990
- }
991
- const pathsInfo = await this.resolveIndexPaths();
992
- const before = await this.capture();
993
- if (!before.isRepository) {
994
- throw new errors_1.WebWorkbenchError(409, 'Git repository is unavailable.', 'git_not_repository');
995
- }
996
- if (before.revision !== input.expectedRepositoryRevision) {
997
- throw new errors_1.WebWorkbenchError(409, 'Repository changed before commit.', 'git_revision_conflict');
998
- }
999
- if (before.conflictedRecords > 0) {
1000
- throw new errors_1.WebWorkbenchError(409, 'Unresolved conflicts must be handled before committing.', 'git_conflict_unresolved');
1001
- }
1002
- if (before.stagedRecords === 0) {
1003
- throw new errors_1.WebWorkbenchError(409, 'Nothing is staged to commit.', 'git_nothing_staged');
1004
- }
1005
- const previousHead = before.head;
1006
- const identity = await this.describeCommitConfiguration(pathsInfo.root);
1007
- const startedAt = Date.now();
1008
- try {
1009
- // `-F -` so the message travels as a literal payload; no shell, no argument parsing.
1010
- await this.runGit(['commit', '-F', '-'], pathsInfo.root, 'commit', undefined, message);
1011
- }
1012
- catch (error) {
1013
- // A timed-out or interrupted commit may still have landed. Always report the truth.
1014
- const recovery = await this.recoverCommit(pathsInfo.root, previousHead);
1015
- if (recovery.committed && recovery.commitSha) {
1016
- return Object.freeze({
1017
- status: 'committed',
1018
- commitSha: recovery.commitSha,
1019
- repositoryRevision: await this.revisionAfterMutation(),
1020
- durationMs: Date.now() - startedAt,
1021
- identity,
1022
- warning: `提交进程报告失败,但提交已实际完成:${describeError(error)}`,
1023
- });
1024
- }
1025
- throw error;
1026
- }
1027
- const after = await this.recoverCommit(pathsInfo.root, previousHead);
1028
- if (!after.committed || !after.commitSha) {
1029
- throw new errors_1.WebWorkbenchError(503, 'The commit did not produce a new HEAD.', 'git_commit_unconfirmed');
1030
- }
1031
- return Object.freeze({
1032
- status: 'committed',
1033
- commitSha: after.commitSha,
1034
- repositoryRevision: await this.revisionAfterMutation(),
1035
- durationMs: Date.now() - startedAt,
1036
- identity,
1037
- });
1038
- }
1039
- /**
1040
- * A commit is confirmed by HEAD having moved to a *new* commit, never by exit code alone.
1041
- * This is what makes the timeout path safe: we ask Git what actually happened.
1042
- */
1043
- async recoverCommit(root, previousHead) {
1044
- const head = (await this.tryGit(['rev-parse', '--verify', 'HEAD'], root))?.trim() ?? null;
1045
- if (!head)
1046
- return { committed: false, commitSha: null };
1047
- if (head === previousHead)
1048
- return { committed: false, commitSha: null };
1049
- return { committed: true, commitSha: head };
1050
- }
1051
- /** Identity and hook configuration the commit will actually run under (plan §7.9). */
1052
- async describeCommitConfiguration(root) {
1053
- const name = (await this.tryGit(['config', 'user.name'], root))?.trim() ?? null;
1054
- const email = (await this.tryGit(['config', 'user.email'], root))?.trim() ?? null;
1055
- const signingKey = (await this.tryGit(['config', 'user.signingkey'], root))?.trim() ?? null;
1056
- const gpgsign = (await this.tryGit(['config', 'commit.gpgsign'], root))?.trim() ?? null;
1057
- // `rev-parse --git-path hooks` accounts for core.hooksPath; a missing directory means no
1058
- // hooks will run, which the form states instead of silently skipping them.
1059
- const hooksPath = (await this.tryGit(['rev-parse', '--git-path', 'hooks'], root))?.trim() ?? null;
1060
- const hooksDir = hooksPath ? (0, path_1.resolve)(root, hooksPath) : null;
1061
- return Object.freeze({
1062
- name,
1063
- email,
1064
- signingKey,
1065
- signingEnabled: gpgsign === 'true',
1066
- hooksDir,
1067
- hooksPresent: hooksDir !== null && (0, fs_1.existsSync)(hooksDir),
1068
- });
1069
- }
1070
- async mutate(args) {
1071
- const root = await this.requireRepositoryRoot();
1072
- await this.runGit(args, root, 'index');
1073
- }
1074
- async requireRepositoryRoot() {
1075
- const snapshot = await this.capture();
1076
- if (snapshot.repositoryKind === 'bare') {
1077
- // v0.3.19 (G317-22) — a bare repository *is* a repository, so "unavailable" was the
1078
- // wrong word for it. What it lacks is a working tree, and this panel is worktree-based:
1079
- // the limit is stated rather than worked around, and reading from a different working
1080
- // tree would widen access in a way the workspace boundary does not allow.
1081
- throw new Error('This workspace is a bare repository. The Git panel reads a working tree, so it has no changes or history to show here.');
1082
- }
1083
- if (!snapshot.isRepository || !snapshot.root) {
1084
- throw new Error('Git repository is unavailable.');
1085
- }
1086
- return snapshot.root;
1087
- }
1088
- /**
1089
- * v0.3.17 S1 — a mutation reports the same state digest `status()` reports. Returning
1090
- * `rev-parse HEAD` was a different value space AND did not move on stage/unstage, so it
1091
- * could never express "the index changed".
1092
- *
1093
- * NOTE: this is post-write verification, not an atomic compare-and-swap. The real
1094
- * check-write window is S3 scope (plan §7.7); until then nothing may claim atomicity.
1095
- */
1096
- async revisionAfterMutation() {
1097
- const snapshot = await this.capture();
1098
- if (!snapshot.isRepository)
1099
- throw new Error('Git repository is unavailable.');
1100
- return snapshot.revision;
1101
- }
1102
- /**
1103
- * v0.3.17 S3 — one exec path, three explicit profiles.
1104
- *
1105
- * `read` keeps every hardening from v0.3.12. `index` relaxes only what staging must
1106
- * resolve (user config for filters/CRLF) while keeping hooks disabled. `commit` is the
1107
- * deliberate exception from plan §7.9: it lets the repository's own hooks and signing
1108
- * configuration run, and gets its own bounded budget instead of the 5s read budget.
1109
- * The profiles are separate on purpose — enabling commit hooks must not relax reads.
1110
- *
1111
- * Implemented with `spawn` rather than `execFile` for two reasons found the hard way:
1112
- * 1. the async `execFile`/`exec` `input` option is silently ignored, so `git apply -`
1113
- * blocked forever waiting for stdin that never closed;
1114
- * 2. a timeout must kill the whole process group, otherwise a slow `pre-commit` hook
1115
- * survives as an orphan while we report failure.
1116
- */
1117
- runGit(args, cwd, profile = 'read', env, input) {
1118
- return this.runGitBytes(args, cwd, profile, env, input).then(buffer => buffer.toString('utf8'));
1119
- }
1120
- /**
1121
- * v0.3.17 S5 — the byte-level primitive behind `runGit`.
1122
- *
1123
- * Historical file content may not be valid UTF-8, so blob reads must not round-trip
1124
- * through a string. Everything else (hardening prefix, profile, byte budget, timeout,
1125
- * process-group kill) is shared, which is why this is the same body and not a copy.
1126
- */
1127
- runGitBytes(args, cwd, profile = 'read', env,
1128
- /** stdin payload, used by `git apply -` and `git commit -F -`. Never browser input. */
1129
- input) {
1130
- const prefix = profile === 'read'
1131
- ? hardenedGitPrefix()
1132
- : profile === 'index'
1133
- ? (0, git_index_transaction_1.writeGitPrefix)()
1134
- : commitGitPrefix();
1135
- const environment = profile === 'read' ? gitEnvironment() : (env ?? (0, git_index_transaction_1.writeGitEnvironment)());
1136
- const timeout = profile === 'commit' ? this.commitTimeoutMs : GIT_TIMEOUT_MS;
1137
- return new Promise((resolvePromise, reject) => {
1138
- this.performance.processCount += 1;
1139
- const child = (0, child_process_1.spawn)('git', [...prefix, ...args], {
1140
- cwd,
1141
- env: environment,
1142
- stdio: ['pipe', 'pipe', 'pipe'],
1143
- // Own process group, so a timeout can take the hook processes down with it.
1144
- detached: true,
1145
- });
1146
- const stdout = [];
1147
- const stderr = [];
1148
- let bytes = 0;
1149
- let settled = false;
1150
- let timedOut = false;
1151
- let overflowed = false;
1152
- const timer = setTimeout(() => {
1153
- timedOut = true;
1154
- killProcessTree(child);
1155
- }, timeout);
1156
- child.stdout.on('data', (chunk) => {
1157
- bytes += chunk.length;
1158
- this.performance.bytesRead += chunk.length;
1159
- if (bytes > GIT_MAX_BUFFER) {
1160
- overflowed = true;
1161
- killProcessTree(child);
1162
- return;
1163
- }
1164
- stdout.push(chunk);
1165
- });
1166
- child.stderr.on('data', (chunk) => {
1167
- bytes += chunk.length;
1168
- this.performance.bytesRead += chunk.length;
1169
- if (bytes > GIT_MAX_BUFFER) {
1170
- overflowed = true;
1171
- killProcessTree(child);
1172
- return;
1173
- }
1174
- stderr.push(chunk);
1175
- });
1176
- const settle = (error) => {
1177
- if (settled)
1178
- return;
1179
- settled = true;
1180
- clearTimeout(timer);
1181
- if (error) {
1182
- reject(error);
1183
- return;
1184
- }
1185
- resolvePromise(Buffer.concat(stdout));
1186
- };
1187
- child.on('error', (error) => {
1188
- settle(new errors_1.WebWorkbenchError(503, (0, redaction_1.redactTraceText)(error.message), 'git_command_failed'));
1189
- });
1190
- child.on('close', (code) => {
1191
- if (timedOut) {
1192
- settle(new errors_1.WebWorkbenchError(503, 'Git command timed out.', 'git_timeout'));
1193
- return;
1194
- }
1195
- if (overflowed) {
1196
- settle(new errors_1.WebWorkbenchError(503, 'Git output exceeded the bounded read limit.', 'git_output_too_large'));
1197
- return;
1198
- }
1199
- if (code === 0) {
1200
- settle();
1201
- return;
1202
- }
1203
- const message = Buffer.concat(stderr).toString('utf8').trim();
1204
- settle(new errors_1.WebWorkbenchError(503, (0, redaction_1.redactTraceText)(message || `Git exited with code ${code ?? 'unknown'}.`), 'git_command_failed'));
1205
- });
1206
- if (input === undefined) {
1207
- child.stdin.end();
1208
- return;
1209
- }
1210
- // stdin must be explicitly closed; a `-` argument otherwise blocks the child forever.
1211
- child.stdin.on('error', () => {
1212
- // The child may exit before consuming the payload; the close handler already decided.
1213
- });
1214
- child.stdin.end(input, 'utf8');
1215
- });
1216
- }
1217
- async tryGit(args, cwd) {
1218
- try {
1219
- return await this.runGit(args, cwd);
1220
- }
1221
- catch {
1222
- return undefined;
1223
- }
1224
- }
1225
- encodeCursor(payload) {
1226
- const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
1227
- const signature = (0, crypto_1.createHmac)('sha256', this.secret).update(body).digest('base64url');
1228
- return `${body}.${signature}`;
1229
- }
1230
- decodeCursor(cursor, kind, revision, fileId, scope) {
1231
- if (!cursor || cursor.length > 4096)
1232
- return invalidCursor();
1233
- const [body, encodedSignature, extra] = cursor.split('.');
1234
- if (!body || !encodedSignature || extra)
1235
- return invalidCursor();
1236
- const expected = (0, crypto_1.createHmac)('sha256', this.secret).update(body).digest();
1237
- let actual;
1238
- try {
1239
- actual = Buffer.from(encodedSignature, 'base64url');
1240
- }
1241
- catch {
1242
- return invalidCursor();
1243
- }
1244
- if (actual.length !== expected.length || !(0, crypto_1.timingSafeEqual)(actual, expected)) {
1245
- return invalidCursor();
1246
- }
1247
- try {
1248
- const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
1249
- if (parsed.version !== 2 ||
1250
- parsed.kind !== kind ||
1251
- parsed.fileId !== fileId ||
1252
- parsed.scope !== scope ||
1253
- !Number.isSafeInteger(parsed.offset) ||
1254
- parsed.offset < 0) {
1255
- return invalidCursor();
1256
- }
1257
- if (parsed.resumeHunk !== undefined && !isDiffHunkResume(parsed.resumeHunk)) {
1258
- return invalidCursor();
1259
- }
1260
- if (parsed.revision !== revision) {
1261
- throw new errors_1.WebWorkbenchError(409, 'Git cursor revision is stale.', 'git_revision_conflict');
1262
- }
1263
- return parsed;
1264
- }
1265
- catch (error) {
1266
- if (error instanceof errors_1.WebWorkbenchError)
1267
- throw error;
1268
- return invalidCursor();
1269
- }
1270
- }
1271
- }
1272
- exports.GitReadModelServiceV1 = GitReadModelServiceV1;
1273
- /** v0.3.26 #275 — the hunk header shape, mirrored for cursor validation. */
1274
- const HUNK_HEADER_PATTERN = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/u;
1275
- /** v0.3.26 #275 — validates a cursor-carried hunk resume state. */
1276
- function isDiffHunkResume(value) {
1277
- if (!value || typeof value !== 'object')
1278
- return false;
1279
- const candidate = value;
1280
- return (typeof candidate.header === 'string' &&
1281
- HUNK_HEADER_PATTERN.test(candidate.header) &&
1282
- Number.isSafeInteger(candidate.index) &&
1283
- candidate.index >= 0 &&
1284
- Number.isSafeInteger(candidate.oldCursor) &&
1285
- candidate.oldCursor >= 1 &&
1286
- Number.isSafeInteger(candidate.newCursor) &&
1287
- candidate.newCursor >= 1);
1288
- }
1289
- function parsePorcelainV1(output) {
1290
- const fields = output.split('\0');
1291
- const records = [];
1292
- for (let index = 0; index < fields.length; index += 1) {
1293
- const field = fields[index];
1294
- if (!field || field.length < 4)
1295
- continue;
1296
- const indexStatus = field[0];
1297
- const worktreeStatus = field[1];
1298
- const path = field.slice(3);
1299
- if (!safeGitPath(path))
1300
- continue;
1301
- const renamed = indexStatus === 'R' || indexStatus === 'C' || worktreeStatus === 'R';
1302
- const renamedFrom = renamed ? fields[++index] : undefined;
1303
- records.push(Object.freeze({
1304
- path,
1305
- indexStatus,
1306
- worktreeStatus,
1307
- ...(renamedFrom && safeGitPath(renamedFrom) ? { renamedFrom } : {}),
1308
- }));
1309
- }
1310
- return records.sort((left, right) => left.path.localeCompare(right.path));
1311
- }
1312
- function safeGitPath(path) {
1313
- return (Boolean(path) &&
1314
- path.length <= 4096 &&
1315
- !path.includes('\0') &&
1316
- !path.includes('\r') &&
1317
- !path.includes('\n') &&
1318
- !(0, path_1.isAbsolute)(path) &&
1319
- path !== '..' &&
1320
- !path.startsWith('../') &&
1321
- !path.includes('/../'));
1322
- }
1323
- function recordStillMatches(record, source) {
1324
- return recordSources(record).includes(source);
1325
- }
1326
- function parseCommit(record) {
1327
- const [id, shortId, timestamp, authorName, subject] = record.split('\x1f');
1328
- if (!id || !shortId || !timestamp || !authorName || subject === undefined) {
1329
- throw new errors_1.WebWorkbenchError(502, 'Git log record is invalid.', 'git_output_invalid');
1330
- }
1331
- const authoredAt = new Date(Number(timestamp) * 1000);
1332
- if (!Number.isFinite(authoredAt.valueOf())) {
1333
- throw new errors_1.WebWorkbenchError(502, 'Git log timestamp is invalid.', 'git_output_invalid');
1334
- }
1335
- return Object.freeze({
1336
- id,
1337
- shortId,
1338
- authoredAt: authoredAt.toISOString(),
1339
- authorName: (0, redaction_1.redactTraceText)(authorName),
1340
- subject: (0, redaction_1.redactTraceText)(subject),
1341
- });
1342
- }
1343
- /**
1344
- * v0.3.17 S1 — the token's source decides the command, so exactly one comparison is
1345
- * produced. Previously a mixed (`MM`) file emitted both `--cached` and worktree diffs and
1346
- * the caller merged them into one page, making the two sources indistinguishable.
1347
- */
1348
- function diffCommands(path, source, ignoreWhitespace = false, wordDiff = false) {
1349
- const modes = [
1350
- ...(ignoreWhitespace ? ['--ignore-all-space'] : []),
1351
- ...(wordDiff ? ['--word-diff=plain'] : []),
1352
- ];
1353
- if (source === 'staged') {
1354
- return Object.freeze([
1355
- {
1356
- title: 'Staged',
1357
- args: [
1358
- 'diff',
1359
- '--cached',
1360
- ...modes,
1361
- '--no-ext-diff',
1362
- '--no-textconv',
1363
- '--unified=3',
1364
- '--',
1365
- path,
1366
- ],
1367
- },
1368
- ]);
1369
- }
1370
- if (source === 'unstaged') {
1371
- return Object.freeze([
1372
- {
1373
- title: 'Working tree',
1374
- args: ['diff', ...modes, '--no-ext-diff', '--no-textconv', '--unified=3', '--', path],
1375
- },
1376
- ]);
1377
- }
1378
- if (source === 'untracked') {
1379
- return Object.freeze([
1380
- {
1381
- title: 'Untracked',
1382
- args: [
1383
- 'diff',
1384
- '--no-index',
1385
- ...modes,
1386
- '--no-ext-diff',
1387
- '--no-textconv',
1388
- '--unified=3',
1389
- '--',
1390
- GIT_NULL_DEVICE,
1391
- path,
1392
- ],
1393
- acceptedExitCodes: [0, 1],
1394
- },
1395
- ]);
1396
- }
1397
- // Conflict version selection (base / ours / theirs) is S5 scope. Until then keep the
1398
- // pre-existing index-vs-worktree pair so nothing regresses.
1399
- return Object.freeze([
1400
- {
1401
- title: 'Staged',
1402
- args: ['diff', '--cached', '--no-ext-diff', '--no-textconv', '--unified=3', '--', path],
1403
- },
1404
- {
1405
- title: 'Working tree',
1406
- args: ['diff', '--no-ext-diff', '--no-textconv', '--unified=3', '--', path],
1407
- },
1408
- ]);
1409
- }
1410
- /** v0.3.17 S1 — every comparison source a status record participates in. */
1411
- // A status record is always a working-tree state; typing the result narrowly makes the
1412
- // compiler enforce that no comparison-only source can ever leak into a status bucket.
1413
- function recordSources(record) {
1414
- if (isConflictRecord(record))
1415
- return Object.freeze(['conflict']);
1416
- if (record.indexStatus === '?')
1417
- return Object.freeze(['untracked']);
1418
- const sources = [];
1419
- if (record.indexStatus !== ' ')
1420
- sources.push('staged');
1421
- if (record.worktreeStatus !== ' ')
1422
- sources.push('unstaged');
1423
- return Object.freeze(sources);
1424
- }
1425
- function countSources(records) {
1426
- let conflicted = 0;
1427
- let staged = 0;
1428
- let unstaged = 0;
1429
- let untracked = 0;
1430
- for (const record of records) {
1431
- for (const source of recordSources(record)) {
1432
- if (source === 'staged')
1433
- staged += 1;
1434
- else if (source === 'unstaged')
1435
- unstaged += 1;
1436
- else if (source === 'untracked')
1437
- untracked += 1;
1438
- else
1439
- conflicted += 1;
1440
- }
1441
- }
1442
- return { total: records.length, conflicted, staged, unstaged, untracked };
1443
- }
1444
- /**
1445
- * v0.3.17 S4 — the status group filter accepts only a working-tree source.
1446
- *
1447
- * The distinction is load-bearing: passing the wider comparison-source union here would let a
1448
- * caller ask for the `commit` group and silently get nothing, hiding the mistake. It is
1449
- * rejected up front with a clear code instead.
1450
- */
1451
- function normalizeSource(value) {
1452
- if (value === undefined || value === null || value === '')
1453
- return undefined;
1454
- if (!git_file_source_1.GIT_WORKTREE_SOURCES_V1.includes(value)) {
1455
- throw new errors_1.WebWorkbenchError(400, 'group must be a known Git file source.', 'git_query_invalid');
1456
- }
1457
- return value;
1458
- }
1459
- function normalizeQuery(value) {
1460
- if (value === undefined || value === null || value === '')
1461
- return undefined;
1462
- if (typeof value !== 'string' || value.length > 256) {
1463
- throw new errors_1.WebWorkbenchError(400, 'query must be a string of at most 256 characters.', 'git_query_invalid');
1464
- }
1465
- const trimmed = value.trim();
1466
- return trimmed ? trimmed.toLocaleLowerCase() : undefined;
1467
- }
1468
- /** Binds the active filter into the cursor so pages never mix two query scopes. */
1469
- function statusScope(group, query) {
1470
- return (0, crypto_1.createHash)('sha256')
1471
- .update(`${group ?? '*'}\u0000${query ?? '*'}`)
1472
- .digest('hex')
1473
- .slice(0, 16);
1474
- }
1475
- function isConflictRecord(record) {
1476
- return (record.indexStatus === 'U' ||
1477
- record.worktreeStatus === 'U' ||
1478
- `${record.indexStatus}${record.worktreeStatus}` === 'AA' ||
1479
- `${record.indexStatus}${record.worktreeStatus}` === 'DD');
1480
- }
1481
- function isSensitiveGitRecord(record) {
1482
- return ((0, redaction_1.isSensitiveFilePath)(record.path) ||
1483
- (record.renamedFrom !== undefined && (0, redaction_1.isSensitiveFilePath)(record.renamedFrom)));
1484
- }
1485
- async function streamDiffPage(input) {
1486
- const lines = [];
1487
- let virtualLine = 0;
1488
- let bytes = 0;
1489
- let hasMore = false;
1490
- let oversizedLine = false;
1491
- let linesParsed = 0;
1492
- const acceptLine = (raw) => {
1493
- linesParsed += 1;
1494
- const line = (0, redaction_1.redactTraceText)(raw.split(input.cwd).join('[WORKSPACE]'));
1495
- const lineBytes = Buffer.byteLength(line, 'utf8') + 1;
1496
- if (lineBytes > input.byteLimit) {
1497
- oversizedLine = true;
1498
- return false;
1499
- }
1500
- if (virtualLine < input.offset) {
1501
- virtualLine += 1;
1502
- return true;
1503
- }
1504
- if (lines.length >= input.lineLimit || bytes + lineBytes > input.byteLimit) {
1505
- hasMore = true;
1506
- return false;
1507
- }
1508
- lines.push(line);
1509
- bytes += lineBytes;
1510
- virtualLine += 1;
1511
- return true;
1512
- };
1513
- for (const command of input.commands) {
1514
- if (!acceptLine(`## ${command.title}`))
1515
- break;
1516
- const completed = await streamGitLines({
1517
- cwd: input.cwd,
1518
- args: command.args,
1519
- acceptedExitCodes: command.acceptedExitCodes ?? [0],
1520
- onLine: acceptLine,
1521
- onProcess: input.onProcess,
1522
- onBytes: input.onBytes,
1523
- });
1524
- if (!completed) {
1525
- hasMore = true;
1526
- break;
1527
- }
1528
- }
1529
- if (oversizedLine) {
1530
- throw new errors_1.WebWorkbenchError(413, 'A Git diff line exceeds the bounded page size.', 'git_line_too_long');
1531
- }
1532
- return Object.freeze({ lines, returnedLines: lines.length, hasMore, linesParsed });
1533
- }
1534
- function streamGitLines(input) {
1535
- return new Promise((resolvePromise, reject) => {
1536
- input.onProcess();
1537
- const child = (0, child_process_1.spawn)('git', [...hardenedGitPrefix(), ...input.args], {
1538
- cwd: input.cwd,
1539
- env: gitEnvironment(),
1540
- stdio: ['ignore', 'pipe', 'pipe'],
1541
- });
1542
- let buffer = '';
1543
- let stderr = '';
1544
- let outputBytes = 0;
1545
- let paginationStopped = false;
1546
- let timedOut = false;
1547
- let outputTooLarge = false;
1548
- let settled = false;
1549
- const timer = setTimeout(() => {
1550
- timedOut = true;
1551
- child.kill('SIGTERM');
1552
- }, GIT_TIMEOUT_MS);
1553
- timer.unref();
1554
- child.stdout.setEncoding('utf8');
1555
- child.stdout.on('data', (chunk) => {
1556
- input.onBytes(Buffer.byteLength(chunk, 'utf8'));
1557
- if (paginationStopped || timedOut || outputTooLarge)
1558
- return;
1559
- outputBytes += Buffer.byteLength(chunk, 'utf8');
1560
- if (outputBytes > GIT_MAX_BUFFER) {
1561
- outputTooLarge = true;
1562
- buffer = '';
1563
- clearTimeout(timer);
1564
- child.kill('SIGTERM');
1565
- return;
1566
- }
1567
- buffer += chunk;
1568
- for (;;) {
1569
- const newline = buffer.indexOf('\n');
1570
- if (newline < 0)
1571
- break;
1572
- const line = buffer.slice(0, newline).replace(/\r$/u, '');
1573
- buffer = buffer.slice(newline + 1);
1574
- if (!input.onLine(line)) {
1575
- paginationStopped = true;
1576
- clearTimeout(timer);
1577
- child.kill('SIGTERM');
1578
- break;
1579
- }
1580
- }
1581
- });
1582
- child.stderr.setEncoding('utf8');
1583
- child.stderr.on('data', (chunk) => {
1584
- input.onBytes(Buffer.byteLength(chunk, 'utf8'));
1585
- outputBytes += Buffer.byteLength(chunk, 'utf8');
1586
- if (outputBytes > GIT_MAX_BUFFER && !outputTooLarge) {
1587
- outputTooLarge = true;
1588
- clearTimeout(timer);
1589
- child.kill('SIGTERM');
1590
- }
1591
- if (stderr.length < 4096)
1592
- stderr += chunk.slice(0, 4096 - stderr.length);
1593
- });
1594
- child.once('error', error => {
1595
- if (settled)
1596
- return;
1597
- settled = true;
1598
- clearTimeout(timer);
1599
- reject(timedOut
1600
- ? new errors_1.WebWorkbenchError(503, 'Git command timed out.', 'git_timeout')
1601
- : outputTooLarge
1602
- ? new errors_1.WebWorkbenchError(503, 'Git output exceeded the bounded read limit.', 'git_output_too_large')
1603
- : new errors_1.WebWorkbenchError(503, (0, redaction_1.redactTraceText)(error.message), 'git_command_failed'));
1604
- });
1605
- child.once('close', code => {
1606
- if (settled)
1607
- return;
1608
- settled = true;
1609
- clearTimeout(timer);
1610
- if (timedOut) {
1611
- reject(new errors_1.WebWorkbenchError(503, 'Git command timed out.', 'git_timeout'));
1612
- return;
1613
- }
1614
- if (outputTooLarge) {
1615
- reject(new errors_1.WebWorkbenchError(503, 'Git output exceeded the bounded read limit.', 'git_output_too_large'));
1616
- return;
1617
- }
1618
- if (!paginationStopped && buffer && !input.onLine(buffer))
1619
- paginationStopped = true;
1620
- if (!paginationStopped && !input.acceptedExitCodes.includes(code ?? -1)) {
1621
- reject(new errors_1.WebWorkbenchError(503, (0, redaction_1.redactTraceText)(stderr || 'Git diff command failed.'), 'git_command_failed'));
1622
- return;
1623
- }
1624
- resolvePromise(!paginationStopped);
1625
- });
1626
- });
1627
- }
1628
- function assertSafeGitPaths(paths) {
1629
- for (const path of paths) {
1630
- if (typeof path !== 'string' ||
1631
- path.length === 0 ||
1632
- path.length > 4096 ||
1633
- path.includes('\0') ||
1634
- path.startsWith('-') ||
1635
- path.includes('/../') ||
1636
- path === '..' ||
1637
- path.startsWith('../')) {
1638
- throw new Error(`Unsafe Git path rejected: ${JSON.stringify(path)}`);
1639
- }
1640
- }
1641
- }
1642
- function gitEnvironment() {
1643
- return {
1644
- PATH: process.env.PATH,
1645
- HOME: process.env.HOME,
1646
- LANG: 'C.UTF-8',
1647
- LC_ALL: 'C.UTF-8',
1648
- GIT_TERMINAL_PROMPT: '0',
1649
- GIT_OPTIONAL_LOCKS: '0',
1650
- GIT_CONFIG_NOSYSTEM: '1',
1651
- GIT_CONFIG_GLOBAL: GIT_NULL_DEVICE,
1652
- GIT_PAGER: 'cat',
1653
- PAGER: 'cat',
1654
- };
1655
- }
1656
- function hardenedGitPrefix() {
1657
- return [
1658
- '-c',
1659
- 'core.quotepath=false',
1660
- '-c',
1661
- 'core.fsmonitor=false',
1662
- '-c',
1663
- `core.hooksPath=${GIT_NULL_DEVICE}`,
1664
- '-c',
1665
- 'log.showSignature=false',
1666
- '--literal-pathspecs',
1667
- ];
1668
- }
1669
- /**
1670
- * v0.3.17 S3 — commit runner prefix.
1671
- *
1672
- * This is the one place where hooks are deliberately **not** disabled and the user's own
1673
- * configuration is authoritative (plan §7.9). It is a separate function, not a parameter on
1674
- * the read prefix, so enabling commit hooks can never leak into Git reads.
1675
- */
1676
- function commitGitPrefix() {
1677
- return ['-c', 'core.quotepath=false', '--literal-pathspecs'];
1678
- }
1679
- /**
1680
- * v0.3.17 S3 — summary plus optional body.
1681
- *
1682
- * The previous validator rejected any newline, which made a real commit body impossible
1683
- * (plan G3 asks for exactly that fix). What must still be rejected are characters that would
1684
- * corrupt or truncate the commit object: NUL and other C0 controls, except the newlines and
1685
- * tabs a message legitimately contains.
1686
- */
1687
- function normalizeCommitMessage(summary, body) {
1688
- if (typeof summary !== 'string') {
1689
- throw new errors_1.WebWorkbenchError(400, 'A commit summary is required.', 'git_message_invalid');
1690
- }
1691
- const trimmedSummary = summary.trim();
1692
- if (!trimmedSummary) {
1693
- throw new errors_1.WebWorkbenchError(400, 'A commit summary is required.', 'git_message_invalid');
1694
- }
1695
- if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/u.test(trimmedSummary)) {
1696
- throw new errors_1.WebWorkbenchError(400, 'A commit summary must not contain control characters.', 'git_message_invalid');
1697
- }
1698
- const trimmedBody = (body ?? '').replace(/\r\n/gu, '\n').trim();
1699
- if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/u.test(trimmedBody)) {
1700
- throw new errors_1.WebWorkbenchError(400, 'A commit body must not contain control characters.', 'git_message_invalid');
1701
- }
1702
- const message = trimmedBody ? `${trimmedSummary}\n\n${trimmedBody}\n` : `${trimmedSummary}\n`;
1703
- // Bound the whole payload, not just each half.
1704
- if (message.length > 20000) {
1705
- throw new errors_1.WebWorkbenchError(400, 'A commit message is too long.', 'git_message_invalid');
1706
- }
1707
- return message;
1708
- }
1709
- /** Binds the two content-changing diff modes into the pagination cursor scope. */
1710
- function diffScope(ignoreWhitespace, wordDiff) {
1711
- return `iw:${ignoreWhitespace ? 1 : 0}:wd:${wordDiff ? 1 : 0}`;
1712
- }
1713
- function describeError(error) {
1714
- return (0, redaction_1.redactTraceText)(error instanceof Error ? error.message : 'unknown error');
1715
- }
1716
- /**
1717
- * v0.3.17 S4 — a repository-relative path coming from a history request.
1718
- *
1719
- * Validated, never escaped: anything that could be read as a revision expression, a pathspec
1720
- * magic prefix or an absolute path is refused outright rather than passed to argv.
1721
- */
1722
- function assertRelativeGitPath(path) {
1723
- if (typeof path !== 'string' || !path || path.length > 1024) {
1724
- throw new errors_1.WebWorkbenchError(400, 'A file path is required.', 'git_path_invalid');
1725
- }
1726
- if (path.startsWith('/') || path.includes('\0') || path.startsWith(':')) {
1727
- throw new errors_1.WebWorkbenchError(400, 'Unsafe Git path.', 'git_path_unsafe');
1728
- }
1729
- const segments = path.split('/');
1730
- if (segments.some(segment => segment === '..' || segment === '.' || segment === '')) {
1731
- throw new errors_1.WebWorkbenchError(400, 'Unsafe Git path.', 'git_path_unsafe');
1732
- }
1733
- return path;
1734
- }
1735
- /**
1736
- * A commit-diff cursor carries its comparison identity, so a page from a different commit,
1737
- * base or parent is rejected instead of silently stitched onto the wrong document.
1738
- */
1739
- function encodeCommitDiffCursor(input) {
1740
- return Buffer.from(JSON.stringify({ v: 1, ...input }), 'utf8').toString('base64url');
1741
- }
1742
- function decodeCommitDiffCursor(cursor, margin) {
1743
- let parsed;
1744
- try {
1745
- parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
1746
- }
1747
- catch {
1748
- throw new errors_1.WebWorkbenchError(400, 'Diff cursor is not valid.', 'git_cursor_invalid');
1749
- }
1750
- const candidate = parsed;
1751
- if (candidate.margin !== margin ||
1752
- typeof candidate.offset !== 'number' ||
1753
- !Number.isInteger(candidate.offset) ||
1754
- candidate.offset < 0) {
1755
- throw new errors_1.WebWorkbenchError(409, 'Diff changed; reload before paginating.', 'git_cursor_invalid');
1756
- }
1757
- if (candidate.resumeHunk !== undefined && !isDiffHunkResume(candidate.resumeHunk)) {
1758
- throw new errors_1.WebWorkbenchError(400, 'Diff cursor is not valid.', 'git_cursor_invalid');
1759
- }
1760
- return {
1761
- margin,
1762
- offset: candidate.offset,
1763
- ...(candidate.resumeHunk !== undefined
1764
- ? { resumeHunk: candidate.resumeHunk }
1765
- : {}),
1766
- };
1767
- }
1768
- /**
1769
- * Kills a detached child and everything it spawned.
1770
- *
1771
- * A `pre-commit` hook runs as a child of `git`, so killing only `git` on timeout would leave
1772
- * the hook running and, worse, leave `index.lock` behind if the hook owned it.
1773
- */
1774
- function killProcessTree(child) {
1775
- if (child.pid === undefined)
1776
- return;
1777
- try {
1778
- process.kill(-child.pid, 'SIGKILL');
1779
- }
1780
- catch {
1781
- try {
1782
- child.kill('SIGKILL');
1783
- }
1784
- catch {
1785
- // Already gone.
1786
- }
1787
- }
1788
- }
1789
- function canonicalDirectory(path) {
1790
- try {
1791
- const canonical = (0, fs_1.realpathSync)((0, path_1.resolve)(path));
1792
- if (!(0, fs_1.statSync)(canonical).isDirectory())
1793
- throw new Error('not a directory');
1794
- return canonical;
1795
- }
1796
- catch {
1797
- throw new errors_1.WebWorkbenchError(400, 'Workspace directory is unavailable.');
1798
- }
1799
- }
1800
- function fingerprintWorktreePath(root, path) {
1801
- const candidate = (0, path_1.resolve)(root, path);
1802
- if (!isWithinRoot(candidate, root))
1803
- return Object.freeze([path, 'outside']);
1804
- try {
1805
- const stat = (0, fs_1.lstatSync)(candidate, { bigint: true });
1806
- return Object.freeze([
1807
- path,
1808
- stat.dev.toString(),
1809
- stat.ino.toString(),
1810
- stat.mode.toString(),
1811
- stat.size.toString(),
1812
- stat.mtimeNs.toString(),
1813
- stat.ctimeNs.toString(),
1814
- ]);
1815
- }
1816
- catch {
1817
- return Object.freeze([path, 'missing']);
1818
- }
1819
- }
1820
- function isWithinRoot(candidate, root) {
1821
- const rel = (0, path_1.relative)(root, candidate);
1822
- return rel === '' || (!rel.startsWith(`..${path_1.sep}`) && rel !== '..' && !(0, path_1.isAbsolute)(rel));
1823
- }
1824
- function boundedInteger(value, min, max, name) {
1825
- if (!Number.isSafeInteger(value) || value < min || value > max) {
1826
- throw new errors_1.WebWorkbenchError(400, `${name} must be an integer from ${min} through ${max}.`);
1827
- }
1828
- return value;
1829
- }
1830
- function invalidCursor() {
1831
- throw new errors_1.WebWorkbenchError(400, 'Git cursor is invalid.', 'git_cursor_invalid');
1832
- }
1833
- //# sourceMappingURL=git-read-model-service.js.map