@zyro-sec/core 1.0.2 → 1.0.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 (1086) hide show
  1. package/AGENTS.md +7 -7
  2. package/README.md +3 -3
  3. package/bunfig.toml +2 -2
  4. package/drizzle.config.ts +10 -10
  5. package/package.json +8 -8
  6. package/perf/location.bench.ts +44 -44
  7. package/perf/location.ts +140 -140
  8. package/perf/session.bench.ts +22 -22
  9. package/perf/snapshot.bench.ts +67 -67
  10. package/perf/snapshot.ts +423 -423
  11. package/schema.json +2763 -2763
  12. package/script/build.ts +44 -44
  13. package/script/fix-node-pty.ts +28 -28
  14. package/script/generate-api-skill.ts +361 -361
  15. package/script/migration.ts +216 -216
  16. package/script/models-snapshot.ts +82 -82
  17. package/script/pack.ts +5 -5
  18. package/script/snapshot-parity-compare.ts +22 -22
  19. package/script/snapshot-parity-run.sh +20 -20
  20. package/script/snapshot-parity.ts +710 -710
  21. package/script/test.ts +53 -53
  22. package/script/update-models-snapshot.ts +14 -14
  23. package/script/wellknown-server.ts +112 -112
  24. package/src/account/sql.ts +36 -36
  25. package/src/agent.ts +115 -115
  26. package/src/aisdk-native.ts +397 -397
  27. package/src/aisdk.ts +1063 -1063
  28. package/src/app.ts +31 -31
  29. package/src/artifact.ts +617 -617
  30. package/src/automation/author.ts +10 -10
  31. package/src/automation/code.ts +269 -269
  32. package/src/automation/event.ts +35 -35
  33. package/src/automation/shell.ts +82 -82
  34. package/src/automation/sql.ts +50 -50
  35. package/src/automation.ts +1293 -1293
  36. package/src/blob-store.ts +115 -115
  37. package/src/bus.ts +909 -909
  38. package/src/codemode/api.ts +44 -44
  39. package/src/codemode/bun.ts +550 -550
  40. package/src/codemode/catalog.ts +177 -177
  41. package/src/codemode/diffs.ts +134 -134
  42. package/src/codemode/execution.ts +9 -9
  43. package/src/codemode/fetch.ts +179 -179
  44. package/src/codemode/instructions.ts +169 -169
  45. package/src/codemode/job.ts +144 -144
  46. package/src/codemode/path.ts +45 -45
  47. package/src/codemode/tool.ts +564 -564
  48. package/src/command.ts +109 -109
  49. package/src/config/discovery.ts +183 -183
  50. package/src/config/integration.ts +134 -134
  51. package/src/config/managed.ts +6 -6
  52. package/src/config/markdown.ts +123 -123
  53. package/src/config/normalize.ts +870 -870
  54. package/src/config/plugin/agent.ts +192 -192
  55. package/src/config/plugin/command.ts +229 -229
  56. package/src/config/plugin/compaction.ts +27 -27
  57. package/src/config/plugin/compatibility.ts +94 -94
  58. package/src/config/plugin/entry-observer.ts +79 -79
  59. package/src/config/plugin/formatter.ts +76 -76
  60. package/src/config/plugin/image.ts +29 -29
  61. package/src/config/plugin/instruction.ts +260 -260
  62. package/src/config/plugin/location-watcher.ts +22 -22
  63. package/src/config/plugin/mcp.ts +57 -57
  64. package/src/config/plugin/policy.ts +117 -117
  65. package/src/config/plugin/provider.ts +274 -274
  66. package/src/config/plugin/reference.ts +67 -67
  67. package/src/config/plugin/session-search.ts +21 -21
  68. package/src/config/plugin/shell.ts +20 -20
  69. package/src/config/plugin/skill-file.ts +62 -62
  70. package/src/config/plugin/skill-scan.ts +46 -46
  71. package/src/config/plugin/skill.ts +202 -202
  72. package/src/config/plugin/snapshot.ts +21 -21
  73. package/src/config/plugin/source.ts +194 -194
  74. package/src/config/plugin/tool-output.ts +24 -24
  75. package/src/config/plugin/websearch.ts +19 -19
  76. package/src/config/plugin/worktree.ts +35 -35
  77. package/src/config/variable.ts +84 -84
  78. package/src/config/watch.ts +73 -73
  79. package/src/config.ts +574 -574
  80. package/src/console-access.ts +22 -22
  81. package/src/credential/sql.ts +14 -14
  82. package/src/credential.ts +350 -350
  83. package/src/database/batch.ts +21 -21
  84. package/src/database/database.ts +126 -126
  85. package/src/database/drizzle/README.md +35 -35
  86. package/src/database/drizzle/effect-sqlite/driver.ts +78 -78
  87. package/src/database/drizzle/effect-sqlite/index.ts +4 -4
  88. package/src/database/drizzle/effect-sqlite/session.ts +252 -252
  89. package/src/database/drizzle/index.ts +5 -5
  90. package/src/database/drizzle/internal/drizzle-utils.ts +147 -147
  91. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -58
  92. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -243
  93. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -261
  94. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -10
  95. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -340
  96. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -198
  97. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -49
  98. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -278
  99. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -421
  100. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -402
  101. package/src/database/drizzle.ts +1 -1
  102. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -109
  103. package/src/database/migration/20260211171708_add_project_commands.ts +13 -13
  104. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -25
  105. package/src/database/migration/20260225215848_workspace.ts +21 -21
  106. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -14
  107. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -32
  108. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -17
  109. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -17
  110. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -18
  111. package/src/database/migration/20260323234822_events.ts +28 -28
  112. package/src/database/migration/20260410174513_workspace-name.ts +34 -34
  113. package/src/database/migration/20260413175956_chief_energizer.ts +26 -26
  114. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -16
  115. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -32
  116. package/src/database/migration/20260428004200_add_session_path.ts +13 -13
  117. package/src/database/migration/20260501142318_next_venus.ts +14 -14
  118. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -13
  119. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -13
  120. package/src/database/migration/20260510033149_session_usage.ts +58 -58
  121. package/src/database/migration/20260511000411_data_migration_state.ts +18 -18
  122. package/src/database/migration/20260511173437_session-metadata.ts +18 -18
  123. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -24
  124. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -13
  125. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -26
  126. package/src/database/migration/20260602182828_add_project_directories.ts +22 -22
  127. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -21
  128. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -21
  129. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -27
  130. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -22
  131. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -49
  132. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -23
  133. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -13
  134. package/src/database/migration/20260611035744_credential.ts +27 -27
  135. package/src/database/migration/20260611192811_lush_chimera.ts +27 -27
  136. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -31
  137. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -15
  138. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -17
  139. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -19
  140. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -173
  141. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -109
  142. package/src/database/migration/20260808023530_workspace_domain.ts +22 -22
  143. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -13
  144. package/src/database/migration/20260812181746_session_inbox.ts +30 -30
  145. package/src/database/migration/20260812213948_worktree.ts +35 -35
  146. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -15
  147. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -27
  148. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -13
  149. package/src/database/migration/20260923013825_project_time_active.ts +14 -14
  150. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -21
  151. package/src/database/migration/20261010180456_project_time_archived.ts +13 -13
  152. package/src/database/migration/20261024002554_session_allowance.ts +13 -13
  153. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -13
  154. package/src/database/migration/20261025123711_blob.ts +36 -36
  155. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -16
  156. package/src/database/migration/20261026223005_schedule.ts +38 -38
  157. package/src/database/migration/20261029002625_session_part.ts +30 -30
  158. package/src/database/migration/20261029073502_session_time_busy.ts +13 -13
  159. package/src/database/migration/20261029165540_schedule_checks.ts +16 -16
  160. package/src/database/migration/20261030054400_job.ts +60 -60
  161. package/src/database/migration/20261116043204_automation.ts +83 -83
  162. package/src/database/migration/20261116181958_automation_event_position.ts +13 -13
  163. package/src/database/migration/20261116213417_automation_active_index.ts +16 -16
  164. package/src/database/migration/20261119211416_machine.ts +18 -18
  165. package/src/database/migration/20261120004954_machine-key.ts +14 -14
  166. package/src/database/migration.gen.ts +132 -132
  167. package/src/database/migration.ts +155 -155
  168. package/src/database/path.ts +98 -98
  169. package/src/database/schema.gen.ts +363 -363
  170. package/src/database/schema.sql.ts +10 -10
  171. package/src/database/sqlite.bun.ts +17 -17
  172. package/src/database/sqlite.node.ts +25 -25
  173. package/src/database/sqlite.workerd.ts +227 -227
  174. package/src/database/storage-failure.ts +58 -58
  175. package/src/database/v1-migration.bun.ts +1234 -1234
  176. package/src/database/v1-migration.noop.ts +11 -11
  177. package/src/database/v1-migration.ts +2 -2
  178. package/src/effect/app-node-builder.ts +30 -30
  179. package/src/effect/app-node-platform.ts +71 -71
  180. package/src/effect/client-tls/client-tls.bun.ts +8 -8
  181. package/src/effect/client-tls/client-tls.node.ts +17 -17
  182. package/src/effect/client-tls/client-tls.ts +12 -12
  183. package/src/effect/client-tls/client-tls.workerd.ts +8 -8
  184. package/src/effect/keyed-mutex.ts +45 -45
  185. package/src/effect/websocket-constructor.ts +81 -81
  186. package/src/environment/driver.ts +68 -68
  187. package/src/environment/environment.ts +152 -152
  188. package/src/environment/environments.ts +78 -78
  189. package/src/environment/exec-defaults.ts +200 -200
  190. package/src/environment/files.ts +79 -79
  191. package/src/environment/index.ts +34 -34
  192. package/src/environment/local.ts +101 -101
  193. package/src/environment/memory.ts +186 -186
  194. package/src/environment/path.ts +68 -68
  195. package/src/environment/unavailable.ts +17 -17
  196. package/src/event/sql.ts +26 -26
  197. package/src/event-logger.ts +19 -19
  198. package/src/file-access.ts +352 -352
  199. package/src/file-mutation.ts +185 -185
  200. package/src/file-retention.ts +23 -23
  201. package/src/file-write.ts +110 -110
  202. package/src/filesystem/fff.bun.ts +15 -15
  203. package/src/filesystem/fff.node.ts +12 -12
  204. package/src/filesystem/fff.ts +67 -67
  205. package/src/filesystem/fff.workerd.ts +12 -12
  206. package/src/filesystem/file-watch.ts +164 -164
  207. package/src/filesystem/location-watcher-policy.ts +64 -64
  208. package/src/filesystem/location-watcher.ts +108 -108
  209. package/src/filesystem/protected.ts +31 -31
  210. package/src/filesystem/search.ts +251 -251
  211. package/src/filesystem/watcher-binding.ts +14 -14
  212. package/src/filesystem/watcher.ts +282 -282
  213. package/src/filesystem.ts +270 -270
  214. package/src/flag/resolve.ts +66 -66
  215. package/src/flag.ts +64 -64
  216. package/src/form.ts +370 -370
  217. package/src/formatter/builtins.ts +294 -294
  218. package/src/formatter.ts +108 -108
  219. package/src/generate.ts +397 -397
  220. package/src/git.ts +1609 -1609
  221. package/src/github-copilot/models.ts +289 -289
  222. package/src/image/notice.ts +8 -8
  223. package/src/image/photon-normalize.ts +148 -148
  224. package/src/image/photon-wasm.bun.ts +4 -4
  225. package/src/image/photon-wasm.node.ts +4 -4
  226. package/src/image/photon-wasm.workerd.ts +4 -4
  227. package/src/image/photon-worker.ts +26 -26
  228. package/src/image/photon.ts +156 -156
  229. package/src/image.ts +95 -95
  230. package/src/instance/service.ts +21 -21
  231. package/src/instance.ts +191 -191
  232. package/src/instruction-discovery.ts +165 -165
  233. package/src/instructions/agent.ts +50 -50
  234. package/src/instructions/builtins.ts +103 -103
  235. package/src/instructions/index.ts +287 -287
  236. package/src/integration/connection.ts +26 -26
  237. package/src/integration.ts +869 -869
  238. package/src/job/list.ts +160 -160
  239. package/src/job/recovery.ts +51 -51
  240. package/src/job/sql.ts +27 -27
  241. package/src/job.ts +766 -766
  242. package/src/kv/sql.ts +9 -9
  243. package/src/kv.ts +92 -92
  244. package/src/location-activity.ts +130 -130
  245. package/src/location-lifecycle.ts +97 -97
  246. package/src/location-service-map.ts +50 -50
  247. package/src/location-services.ts +125 -125
  248. package/src/location.ts +44 -44
  249. package/src/machine/driver.ts +487 -487
  250. package/src/machine/frames.ts +133 -133
  251. package/src/machine/identity.ts +187 -187
  252. package/src/machine/index.ts +4 -4
  253. package/src/machine/instructions.ts +61 -61
  254. package/src/machine/iroh-binding.ts +18 -18
  255. package/src/machine/iroh.ts +157 -157
  256. package/src/machine/join.ts +54 -54
  257. package/src/machine/link.ts +313 -313
  258. package/src/machine/machines.ts +280 -280
  259. package/src/machine/noise.ts +326 -326
  260. package/src/machine/sql.ts +13 -13
  261. package/src/machine/wire.ts +140 -140
  262. package/src/machine/worker-client.ts +276 -276
  263. package/src/managed-policy.ts +65 -65
  264. package/src/markdown.d.ts +4 -4
  265. package/src/mcp/client.ts +1198 -1198
  266. package/src/mcp/connection.ts +292 -292
  267. package/src/mcp/event-stream.ts +34 -34
  268. package/src/mcp/index.ts +1349 -1349
  269. package/src/mcp/instructions.ts +108 -108
  270. package/src/mcp/oauth.ts +665 -665
  271. package/src/mcp/pool.ts +386 -386
  272. package/src/mcp/socket-client.ts +86 -86
  273. package/src/mcp/stdio.ts +227 -227
  274. package/src/mime.ts +75 -75
  275. package/src/modal/models.ts +150 -150
  276. package/src/model-resolver.ts +639 -639
  277. package/src/model-retry.ts +134 -134
  278. package/src/model.ts +373 -373
  279. package/src/models-dev/v1.ts +203 -203
  280. package/src/models-dev.ts +899 -899
  281. package/src/node-ffi.d.ts +18 -18
  282. package/src/oauth/page.ts +260 -260
  283. package/src/oauth/redirect.ts +42 -42
  284. package/src/pentest/mcp-catalog.ts +175 -144
  285. package/src/permission/policy.ts +240 -240
  286. package/src/permission/saved.ts +140 -140
  287. package/src/permission/sql.ts +20 -20
  288. package/src/permission.ts +419 -419
  289. package/src/persistent-pty/binary.bun.ts +85 -85
  290. package/src/persistent-pty/binary.node.ts +5 -5
  291. package/src/persistent-pty/binary.workerd.ts +5 -5
  292. package/src/persistent-pty/daemon.ts +750 -750
  293. package/src/persistent-pty/index.ts +661 -661
  294. package/src/persistent-pty/pty-binding.ts +6 -6
  295. package/src/persistent-pty.ts +1 -1
  296. package/src/plugin/agent.ts +235 -235
  297. package/src/plugin/command/automation.txt +7 -7
  298. package/src/plugin/command/initialize.txt +65 -65
  299. package/src/plugin/command/review.txt +100 -100
  300. package/src/plugin/command.ts +113 -113
  301. package/src/plugin/fork-notice.ts +30 -30
  302. package/src/plugin/goal/continuation.txt +13 -13
  303. package/src/plugin/goal/judge.txt +20 -20
  304. package/src/plugin/goal/kickoff.txt +13 -13
  305. package/src/plugin/goal/reminder.txt +9 -9
  306. package/src/plugin/goal.ts +501 -501
  307. package/src/plugin/home-memory.ts +155 -155
  308. package/src/plugin/hooks.ts +108 -108
  309. package/src/plugin/host.ts +770 -770
  310. package/src/plugin/identity.ts +31 -31
  311. package/src/plugin/instance.ts +45 -45
  312. package/src/plugin/internal.ts +360 -360
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -41
  314. package/src/plugin/mcp-skill.ts +171 -171
  315. package/src/plugin/models-dev.ts +128 -128
  316. package/src/plugin/module.ts +186 -186
  317. package/src/plugin/optimize.ts +97 -97
  318. package/src/plugin/plan.ts +52 -52
  319. package/src/plugin/promise.ts +3 -3
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -121
  321. package/src/plugin/provider/azure.ts +568 -568
  322. package/src/plugin/provider/cerebras.ts +16 -16
  323. package/src/plugin/provider/chatgpt.ts +594 -594
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -36
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -104
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -1
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -4
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -10
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -34
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -88
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -124
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -143
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -17
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -162
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -508
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -66
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -96
  338. package/src/plugin/provider/claude-agent/index.ts +63 -63
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -54
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -62
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -49
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -112
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -139
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -55
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -5
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -28
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -58
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -178
  349. package/src/plugin/provider/claude-agent/session.ts +61 -61
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -21
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -41
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -58
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -117
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -42
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -23
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -30
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -72
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -110
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -34
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -57
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -68
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -70
  363. package/src/plugin/provider/configured.ts +18 -18
  364. package/src/plugin/provider/credential-settings.ts +77 -77
  365. package/src/plugin/provider/databricks.ts +31 -31
  366. package/src/plugin/provider/digitalocean.ts +197 -197
  367. package/src/plugin/provider/dynamic.ts +19 -19
  368. package/src/plugin/provider/github-copilot.ts +646 -646
  369. package/src/plugin/provider/gitlab.ts +496 -496
  370. package/src/plugin/provider/google-vertex.ts +231 -231
  371. package/src/plugin/provider/kilo.ts +17 -17
  372. package/src/plugin/provider/llmgateway.ts +27 -27
  373. package/src/plugin/provider/lmstudio.ts +52 -52
  374. package/src/plugin/provider/local.ts +240 -240
  375. package/src/plugin/provider/modal.ts +72 -72
  376. package/src/plugin/provider/neon.ts +12 -12
  377. package/src/plugin/provider/nvidia.ts +22 -22
  378. package/src/plugin/provider/ollama.ts +92 -92
  379. package/src/plugin/provider/openai-context-caps.ts +52 -52
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -59
  381. package/src/plugin/provider/openai.ts +447 -447
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -216
  383. package/src/plugin/provider/opencode-watches.ts +753 -753
  384. package/src/plugin/provider/opencode.ts +883 -883
  385. package/src/plugin/provider/openrouter.ts +30 -30
  386. package/src/plugin/provider/poe.ts +176 -176
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -37
  388. package/src/plugin/provider/refresh.ts +80 -80
  389. package/src/plugin/provider/sap-ai-core.ts +39 -39
  390. package/src/plugin/provider/sdk-factory.ts +24 -24
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -266
  392. package/src/plugin/provider/vllm.ts +34 -34
  393. package/src/plugin/provider/xai.ts +236 -236
  394. package/src/plugin/provider/zenmux.ts +21 -21
  395. package/src/plugin/provider.ts +64 -64
  396. package/src/plugin/sdk.ts +44 -44
  397. package/src/plugin/service.ts +42 -42
  398. package/src/plugin/skill/opencode/api/agent.md +18 -18
  399. package/src/plugin/skill/opencode/api/automation.md +63 -63
  400. package/src/plugin/skill/opencode/api/blob.md +10 -10
  401. package/src/plugin/skill/opencode/api/command.md +12 -12
  402. package/src/plugin/skill/opencode/api/form.md +22 -22
  403. package/src/plugin/skill/opencode/api/generate.md +96 -96
  404. package/src/plugin/skill/opencode/api/info.md +11 -11
  405. package/src/plugin/skill/opencode/api/location.md +17 -17
  406. package/src/plugin/skill/opencode/api/model.md +22 -22
  407. package/src/plugin/skill/opencode/api/permission.md +13 -13
  408. package/src/plugin/skill/opencode/api/project.md +29 -29
  409. package/src/plugin/skill/opencode/api/provider.md +18 -18
  410. package/src/plugin/skill/opencode/api/session.md +313 -313
  411. package/src/plugin/skill/opencode/api/skill.md +12 -12
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -60
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -49
  414. package/src/plugin/skill/opencode/api.md +119 -119
  415. package/src/plugin/skill/opencode/api.ts +40 -40
  416. package/src/plugin/skill/opencode-api.md +17 -17
  417. package/src/plugin/skill/opencode.md +154 -154
  418. package/src/plugin/skill/report.md +152 -152
  419. package/src/plugin/skill.ts +111 -111
  420. package/src/plugin/source-directory.ts +33 -33
  421. package/src/plugin/supervisor.ts +288 -288
  422. package/src/plugin/system-prompt/AGENTS.md +5 -5
  423. package/src/plugin/system-prompt/anthropic.txt +2 -2
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -71
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -46
  426. package/src/plugin/system-prompt/gpt.txt +40 -40
  427. package/src/plugin/system-prompt/kimi.txt +96 -96
  428. package/src/plugin/system-prompt/meta.txt +56 -56
  429. package/src/plugin/system-prompt/trinity.txt +98 -98
  430. package/src/plugin/tool-input-repair.ts +232 -232
  431. package/src/plugin/update.ts +87 -87
  432. package/src/plugin/vcs/git.ts +802 -802
  433. package/src/plugin/vcs/hg.ts +234 -234
  434. package/src/plugin/verbosity.ts +58 -58
  435. package/src/plugin/warming.ts +224 -224
  436. package/src/plugin/websearch/exa.ts +69 -69
  437. package/src/plugin/websearch/firecrawl.ts +71 -71
  438. package/src/plugin/websearch/index.ts +13 -13
  439. package/src/plugin/websearch/mcp.ts +69 -69
  440. package/src/plugin/websearch/parallel.ts +90 -90
  441. package/src/plugin/websearch/provider.ts +44 -44
  442. package/src/plugin/websearch/tavily.ts +73 -73
  443. package/src/plugin/websearch/tinyfish.ts +131 -131
  444. package/src/plugin.ts +320 -320
  445. package/src/project/icon.ts +167 -167
  446. package/src/project/schema.ts +25 -25
  447. package/src/project/sql.ts +63 -63
  448. package/src/project.ts +536 -536
  449. package/src/provider.ts +553 -553
  450. package/src/pty/protocol.ts +37 -37
  451. package/src/pty/pty.bun.ts +44 -44
  452. package/src/pty/pty.node.ts +34 -34
  453. package/src/pty/pty.ts +25 -25
  454. package/src/pty/pty.workerd.ts +9 -9
  455. package/src/pty/ticket.ts +74 -74
  456. package/src/pty.ts +311 -311
  457. package/src/push/crypto.ts +39 -39
  458. package/src/push/list.ts +380 -380
  459. package/src/push/sender.ts +185 -185
  460. package/src/push/watcher.ts +169 -169
  461. package/src/reference/instructions.ts +82 -82
  462. package/src/reference.ts +129 -129
  463. package/src/repository-cache.ts +251 -251
  464. package/src/repository.ts +205 -205
  465. package/src/ripgrep/binary.ts +166 -166
  466. package/src/ripgrep.ts +311 -311
  467. package/src/rpc.ts +288 -288
  468. package/src/schema.ts +39 -39
  469. package/src/session/affinity.ts +8 -8
  470. package/src/session/background-result.ts +5 -5
  471. package/src/session/background.ts +125 -125
  472. package/src/session/blob.ts +503 -503
  473. package/src/session/command.ts +38 -38
  474. package/src/session/compaction-background.ts +55 -55
  475. package/src/session/compaction-subagents.ts +103 -103
  476. package/src/session/compaction.ts +1320 -1320
  477. package/src/session/context.ts +296 -296
  478. package/src/session/cwd-instructions.ts +147 -147
  479. package/src/session/cwd-store.ts +66 -66
  480. package/src/session/cwd.ts +75 -75
  481. package/src/session/diff.ts +149 -149
  482. package/src/session/environment.ts +33 -33
  483. package/src/session/error.ts +105 -105
  484. package/src/session/event.ts +2 -2
  485. package/src/session/execution/restart.ts +558 -558
  486. package/src/session/execution/subagent-report.ts +203 -203
  487. package/src/session/execution.ts +241 -241
  488. package/src/session/generate.ts +78 -78
  489. package/src/session/history.ts +405 -405
  490. package/src/session/inbox.ts +625 -625
  491. package/src/session/info.ts +62 -62
  492. package/src/session/instruction-entry.ts +171 -171
  493. package/src/session/instruction-state.ts +277 -277
  494. package/src/session/instructions.ts +126 -126
  495. package/src/session/message-updater.ts +497 -497
  496. package/src/session/message.ts +2 -2
  497. package/src/session/model-request.ts +474 -474
  498. package/src/session/model-transport.ts +571 -571
  499. package/src/session/move.ts +199 -199
  500. package/src/session/projector.ts +1197 -1197
  501. package/src/session/prompt.ts +253 -253
  502. package/src/session/recent-text.ts +93 -93
  503. package/src/session/revert.ts +112 -112
  504. package/src/session/run-coordinator.ts +198 -198
  505. package/src/session/runner/index.ts +46 -46
  506. package/src/session/runner/live-tool-metadata.ts +41 -41
  507. package/src/session/runner/llm.ts +481 -481
  508. package/src/session/runner/max-steps.ts +16 -16
  509. package/src/session/runner/model.ts +138 -138
  510. package/src/session/runner/prompt/system.txt +16 -16
  511. package/src/session/runner/publish-llm-event.ts +642 -642
  512. package/src/session/runner/retry.ts +78 -78
  513. package/src/session/runner/step.ts +401 -401
  514. package/src/session/runner/to-llm-message.ts +341 -341
  515. package/src/session/schema.ts +9 -9
  516. package/src/session/search-build.ts +116 -116
  517. package/src/session/search-index.ts +552 -552
  518. package/src/session/search.ts +672 -672
  519. package/src/session/session.ts +407 -407
  520. package/src/session/shell.ts +35 -35
  521. package/src/session/skill.ts +16 -16
  522. package/src/session/sql.ts +215 -215
  523. package/src/session/stats.ts +463 -463
  524. package/src/session/store.ts +323 -323
  525. package/src/session/stored.ts +44 -44
  526. package/src/session/subagent-completion.ts +95 -95
  527. package/src/session/subagent-depth.ts +21 -21
  528. package/src/session/subagent-job.ts +61 -61
  529. package/src/session/synthetic.ts +49 -49
  530. package/src/session/system-prompt.ts +28 -28
  531. package/src/session/title.ts +174 -174
  532. package/src/session/to-session-error.ts +179 -179
  533. package/src/session/transfer.ts +369 -369
  534. package/src/session/usage.ts +64 -64
  535. package/src/session.ts +602 -602
  536. package/src/shared-cache.ts +103 -103
  537. package/src/shell/parse.ts +645 -645
  538. package/src/shell/permissions.ts +60 -60
  539. package/src/shell/result.ts +115 -115
  540. package/src/shell/scan.ts +2585 -2585
  541. package/src/shell/select.ts +241 -241
  542. package/src/shell.ts +1274 -1274
  543. package/src/skill/discovery.ts +205 -205
  544. package/src/skill/instructions.ts +84 -84
  545. package/src/skill.ts +277 -277
  546. package/src/snapshot.ts +248 -248
  547. package/src/state.ts +271 -271
  548. package/src/tool/AGENTS.md +71 -71
  549. package/src/tool/html-markdown.ts +651 -651
  550. package/src/tool/http-body.ts +30 -30
  551. package/src/tool/mcp.ts +177 -177
  552. package/src/tool/model-policy.ts +38 -38
  553. package/src/tool/patch-grammar.txt +19 -19
  554. package/src/tool/patch.txt +33 -33
  555. package/src/tool/plugin/artifact.ts +171 -171
  556. package/src/tool/plugin/automation.ts +246 -246
  557. package/src/tool/plugin/cd.ts +103 -103
  558. package/src/tool/plugin/edit.ts +371 -371
  559. package/src/tool/plugin/file-diff.ts +42 -42
  560. package/src/tool/plugin/glob.ts +123 -123
  561. package/src/tool/plugin/grep.ts +152 -152
  562. package/src/tool/plugin/image-generate.ts +396 -396
  563. package/src/tool/plugin/machine.ts +36 -36
  564. package/src/tool/plugin/mcp-events.ts +72 -72
  565. package/src/tool/plugin/mcp-resource.ts +100 -100
  566. package/src/tool/plugin/opencode.ts +316 -316
  567. package/src/tool/plugin/patch.ts +358 -358
  568. package/src/tool/plugin/question.ts +130 -130
  569. package/src/tool/plugin/read.ts +413 -413
  570. package/src/tool/plugin/session-interrupt.ts +63 -63
  571. package/src/tool/plugin/session-search.ts +99 -99
  572. package/src/tool/plugin/shell.ts +594 -594
  573. package/src/tool/plugin/skill.ts +74 -74
  574. package/src/tool/plugin/subagent.ts +269 -269
  575. package/src/tool/plugin/todo.ts +83 -83
  576. package/src/tool/plugin/video-generate.ts +403 -403
  577. package/src/tool/plugin/webfetch.ts +214 -214
  578. package/src/tool/plugin/websearch.ts +196 -196
  579. package/src/tool/plugin/write.ts +72 -72
  580. package/src/tool/read-filesystem.ts +350 -350
  581. package/src/tool/runtime.ts +311 -311
  582. package/src/tool/search.ts +34 -34
  583. package/src/tool/todowrite.txt +7 -7
  584. package/src/tool-output.ts +220 -220
  585. package/src/tool.ts +579 -579
  586. package/src/usage-limits.ts +192 -192
  587. package/src/util/canonical-json.ts +11 -11
  588. package/src/util/error-summary.ts +33 -33
  589. package/src/util/git-executable.ts +59 -59
  590. package/src/util/lazy.ts +11 -11
  591. package/src/util/slug.ts +74 -74
  592. package/src/util/token.ts +5 -5
  593. package/src/util/which.ts +37 -37
  594. package/src/util/wildcard.ts +15 -15
  595. package/src/v1/config/agent.ts +69 -69
  596. package/src/v1/config/command.ts +13 -13
  597. package/src/v1/config/mcp.ts +69 -69
  598. package/src/v1/config/migrate.ts +269 -269
  599. package/src/v1/config/permission.ts +42 -42
  600. package/src/v1/config/plugin.ts +9 -9
  601. package/src/v1/config/provider-options.ts +59 -59
  602. package/src/v1/config/provider.ts +113 -113
  603. package/src/variant.ts +699 -699
  604. package/src/vcs/patch.ts +106 -106
  605. package/src/vcs.ts +262 -262
  606. package/src/video-generation.ts +344 -344
  607. package/src/voice.ts +194 -194
  608. package/src/websearch.ts +239 -239
  609. package/src/wellknown/plugin.ts +36 -36
  610. package/src/wellknown.ts +230 -230
  611. package/src/workspace/driver.ts +89 -89
  612. package/src/workspace/sql.ts +11 -11
  613. package/src/workspace.ts +566 -566
  614. package/src/worktree/directory.ts +16 -16
  615. package/src/worktree/git.ts +39 -39
  616. package/src/worktree/sql.ts +21 -21
  617. package/src/worktree/strategies.ts +74 -74
  618. package/src/worktree.ts +357 -357
  619. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -6
  620. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -6
  621. package/test/fixture/app-execution-alias.ts +17 -17
  622. package/test/fixture/codemode.ts +63 -63
  623. package/test/fixture/config-nodes.ts +40 -40
  624. package/test/fixture/durable-object-storage.ts +58 -58
  625. package/test/fixture/effect-flock-worker.ts +60 -60
  626. package/test/fixture/env.ts +22 -22
  627. package/test/fixture/environment.ts +52 -52
  628. package/test/fixture/event-server.ts +65 -65
  629. package/test/fixture/flock-worker.ts +72 -72
  630. package/test/fixture/git.ts +86 -86
  631. package/test/fixture/global.ts +26 -26
  632. package/test/fixture/held-stdio.cjs +36 -36
  633. package/test/fixture/html-markdown.ts +7 -7
  634. package/test/fixture/link-v1-transcript.json +27 -27
  635. package/test/fixture/location.ts +27 -27
  636. package/test/fixture/lock-worker.ts +53 -53
  637. package/test/fixture/machine-v2.json +66 -66
  638. package/test/fixture/machine-worker.ts +284 -284
  639. package/test/fixture/mcp-echo.ts +14 -14
  640. package/test/fixture/mcp-legacy-silent.ts +22 -22
  641. package/test/fixture/mcp-modern-stdio.ts +15 -15
  642. package/test/fixture/mcp-output-schema.ts +63 -63
  643. package/test/fixture/mcp-prompts.ts +29 -29
  644. package/test/fixture/mcp-timeout.ts +32 -32
  645. package/test/fixture/mcp-union-output-schema.ts +41 -41
  646. package/test/fixture/mcp.ts +44 -44
  647. package/test/fixture/models.ts +6 -6
  648. package/test/fixture/native/2.0.14-media.json +22 -22
  649. package/test/fixture/noise-xx-vectors.json +75 -75
  650. package/test/fixture/persistent-pty-daemon.ts +347 -347
  651. package/test/fixture/persistent-pty.ts +9 -9
  652. package/test/fixture/photon-crash-worker.ts +10 -10
  653. package/test/fixture/photon-exit.ts +29 -29
  654. package/test/fixture/photon-hang-worker.ts +2 -2
  655. package/test/fixture/policy.ts +98 -98
  656. package/test/fixture/prompt-location.ts +33 -33
  657. package/test/fixture/pty-windows.ts +69 -69
  658. package/test/fixture/selector.ts +12 -12
  659. package/test/fixture/shell-daemon.ts +122 -122
  660. package/test/fixture/spawn.ts +24 -24
  661. package/test/fixture/sqlite-node-client.ts +100 -100
  662. package/test/fixture/target-environment.ts +58 -58
  663. package/test/fixture/tmpdir.ts +44 -44
  664. package/test/fixture/v1-config/attachment.ts +25 -25
  665. package/test/fixture/v1-config/config.ts +182 -182
  666. package/test/fixture/v1-config/formatter.ts +13 -13
  667. package/test/fixture/v1-config/layout.ts +6 -6
  668. package/test/fixture/v1-config/lsp.ts +80 -80
  669. package/test/fixture/v1-config/server.ts +19 -19
  670. package/test/fixture/v1-config/skills.ts +13 -13
  671. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -27
  672. package/test/lib/clock.ts +43 -43
  673. package/test/lib/effect.ts +80 -80
  674. package/test/lib/environment-conformance.ts +204 -204
  675. package/test/lib/eventually.ts +20 -20
  676. package/test/lib/image.ts +7 -7
  677. package/test/lib/instructions.ts +47 -47
  678. package/test/lib/permission.ts +12 -12
  679. package/test/lib/project.ts +26 -26
  680. package/test/lib/session-message.ts +26 -26
  681. package/test/lib/tool.ts +102 -102
  682. package/test/lib/websearch.ts +63 -63
  683. package/test/lib/websocket-server.ts +73 -73
  684. package/test/plugin/fixture.ts +174 -174
  685. package/test/plugin/fixtures/greeting.ts +14 -14
  686. package/test/plugin/fixtures/models-dev-reasoning.json +811 -811
  687. package/test/plugin/fixtures/models-dev.json +92 -92
  688. package/test/plugin/fixtures/provider-factory.ts +9 -9
  689. package/test/plugin/host.ts +540 -540
  690. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -68
  691. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -16
  692. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -107
  693. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -133
  694. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -4
  695. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -52
  696. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -73
  697. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -37
  698. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -21
  699. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -35
  700. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -62
  701. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -63
  702. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -58
  703. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -80
  704. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -58
  705. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -74
  706. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -28
  707. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -13
  708. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -411
  709. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -20
  710. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -61
  711. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -126
  712. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -95
  713. package/test/plugin/websearch-fixture.ts +63 -63
  714. package/test/preload.ts +2 -2
  715. package/test/session-sql.types.ts +25 -25
  716. package/tsconfig.build.json +11 -11
  717. package/tsconfig.json +18 -18
  718. package/tsconfig.tests.json +13 -13
  719. package/test/agent.test.ts +0 -224
  720. package/test/aisdk-native.test.ts +0 -590
  721. package/test/aisdk.test.ts +0 -1259
  722. package/test/app.test.ts +0 -6
  723. package/test/artifact.test.ts +0 -216
  724. package/test/automation-event.test.ts +0 -688
  725. package/test/automation-shell.test.ts +0 -293
  726. package/test/automation.test.ts +0 -1950
  727. package/test/blob-store.test.ts +0 -37
  728. package/test/boot-work.test.ts +0 -215
  729. package/test/browser-attach.test.ts +0 -150
  730. package/test/browser-idle.test.ts +0 -107
  731. package/test/bus-session-routing.test.ts +0 -334
  732. package/test/bus-unpersisted.test.ts +0 -50
  733. package/test/bus.test.ts +0 -1347
  734. package/test/catalog.test.ts +0 -704
  735. package/test/codemode/catalog.test.ts +0 -339
  736. package/test/codemode/diffs.test.ts +0 -90
  737. package/test/codemode/instructions.test.ts +0 -123
  738. package/test/codemode-execute-options.test.ts +0 -172
  739. package/test/codemode-script-diffs.test.ts +0 -131
  740. package/test/codemode.test.ts +0 -132
  741. package/test/command.test.ts +0 -71
  742. package/test/config/agent.test.ts +0 -847
  743. package/test/config/command-subagent.test.ts +0 -165
  744. package/test/config/command.test.ts +0 -628
  745. package/test/config/compaction.test.ts +0 -184
  746. package/test/config/config.test.ts +0 -2113
  747. package/test/config/discovery.test.ts +0 -150
  748. package/test/config/entry-observer.test.ts +0 -51
  749. package/test/config/image.test.ts +0 -78
  750. package/test/config/markdown.test.ts +0 -129
  751. package/test/config/model.test.ts +0 -28
  752. package/test/config/normalization.test.ts +0 -854
  753. package/test/config/overlay.test.ts +0 -205
  754. package/test/config/policy.test.ts +0 -432
  755. package/test/config/provider-options.test.ts +0 -55
  756. package/test/config/provider.test.ts +0 -1338
  757. package/test/config/reload.test.ts +0 -526
  758. package/test/config/session-search.test.ts +0 -61
  759. package/test/config/shell.test.ts +0 -42
  760. package/test/config/skill.test.ts +0 -602
  761. package/test/config/snapshot.test.ts +0 -61
  762. package/test/config/tool-output.test.ts +0 -59
  763. package/test/config/watch.test.ts +0 -53
  764. package/test/config/websearch.test.ts +0 -45
  765. package/test/credential-refresh.test.ts +0 -113
  766. package/test/credential.test.ts +0 -271
  767. package/test/database-drizzle.test.ts +0 -228
  768. package/test/database-migration.test.ts +0 -783
  769. package/test/database.test.ts +0 -39
  770. package/test/effect/cross-spawn-spawner.test.ts +0 -522
  771. package/test/effect/keyed-mutex.test.ts +0 -73
  772. package/test/effect/layer-node/layer-node-types.test.ts +0 -230
  773. package/test/effect/layer-node/layer-node.test.ts +0 -467
  774. package/test/effect/layer-node/node-build.test.ts +0 -148
  775. package/test/effect/observability.test.ts +0 -141
  776. package/test/effect-app-node-platform.test.ts +0 -86
  777. package/test/effect-simplification-types.test.ts +0 -12
  778. package/test/environment.test.ts +0 -154
  779. package/test/environments.test.ts +0 -406
  780. package/test/event-logger.test.ts +0 -50
  781. package/test/file-access-path.test.ts +0 -336
  782. package/test/file-access.test.ts +0 -178
  783. package/test/file-mutation.test.ts +0 -244
  784. package/test/filesystem/file-watch.test.ts +0 -213
  785. package/test/filesystem/filesystem.test.ts +0 -383
  786. package/test/filesystem/location-watcher-policy.test.ts +0 -70
  787. package/test/filesystem/search.test.ts +0 -385
  788. package/test/filesystem/watcher.test.ts +0 -719
  789. package/test/flag.test.ts +0 -203
  790. package/test/form.test.ts +0 -357
  791. package/test/formatter-target-environment.test.ts +0 -138
  792. package/test/formatter.test.ts +0 -350
  793. package/test/generate.test.ts +0 -752
  794. package/test/git.test.ts +0 -666
  795. package/test/github-copilot/models.test.ts +0 -167
  796. package/test/image-photon.test.ts +0 -177
  797. package/test/instance-vanilla.test.ts +0 -124
  798. package/test/instruction-discovery.test.ts +0 -804
  799. package/test/instruction-state.test.ts +0 -537
  800. package/test/instructions/builtins.test.ts +0 -83
  801. package/test/instructions/index.test.ts +0 -248
  802. package/test/integration-refresh.test.ts +0 -118
  803. package/test/integration.test.ts +0 -716
  804. package/test/job.test.ts +0 -968
  805. package/test/kv.test.ts +0 -81
  806. package/test/location-activity.test.ts +0 -315
  807. package/test/location-filesystem.test.ts +0 -332
  808. package/test/location-layer.test.ts +0 -784
  809. package/test/location-missing-project.test.ts +0 -71
  810. package/test/location-retain.test.ts +0 -98
  811. package/test/location.test.ts +0 -46
  812. package/test/logging.test.ts +0 -14
  813. package/test/machine-frames.test.ts +0 -768
  814. package/test/machine-instructions.test.ts +0 -135
  815. package/test/machine-join.test.ts +0 -223
  816. package/test/machine-link.test.ts +0 -527
  817. package/test/machine-noise.test.ts +0 -429
  818. package/test/machine-path.test.ts +0 -1202
  819. package/test/machine.test.ts +0 -786
  820. package/test/machines.test.ts +0 -730
  821. package/test/mcp-attach.test.ts +0 -403
  822. package/test/mcp-events.test.ts +0 -299
  823. package/test/mcp-import-boundary.test.ts +0 -44
  824. package/test/mcp-instructions.test.ts +0 -221
  825. package/test/mcp-oauth.test.ts +0 -1289
  826. package/test/mcp-skills.test.ts +0 -274
  827. package/test/mcp-socket-client.test.ts +0 -210
  828. package/test/mcp-stdio.test.ts +0 -145
  829. package/test/mcp.test.ts +0 -4196
  830. package/test/mime.test.ts +0 -80
  831. package/test/modal/models.test.ts +0 -137
  832. package/test/model-free.test.ts +0 -120
  833. package/test/model-plugins.test.ts +0 -469
  834. package/test/model-resolver.test.ts +0 -1695
  835. package/test/model.test.ts +0 -16
  836. package/test/models.test.ts +0 -1404
  837. package/test/network-guard.test.ts +0 -56
  838. package/test/npm-config.test.ts +0 -42
  839. package/test/npm.test.ts +0 -545
  840. package/test/oauth-page.test.ts +0 -15
  841. package/test/opencode-api-skill.test.ts +0 -16
  842. package/test/patch.test.ts +0 -509
  843. package/test/permission.test.ts +0 -1179
  844. package/test/persistent-pty-daemon.test.ts +0 -337
  845. package/test/persistent-pty-session.test.ts +0 -295
  846. package/test/plugin/automation.test.ts +0 -124
  847. package/test/plugin/command.test.ts +0 -137
  848. package/test/plugin/goal-watchdog.test.ts +0 -212
  849. package/test/plugin/goal.test.ts +0 -609
  850. package/test/plugin/home-memory.test.ts +0 -131
  851. package/test/plugin/host-model.test.ts +0 -34
  852. package/test/plugin/identity.test.ts +0 -60
  853. package/test/plugin/internal-flag.test.ts +0 -101
  854. package/test/plugin/mcp-codemode-defaults.test.ts +0 -124
  855. package/test/plugin/models-dev.test.ts +0 -1406
  856. package/test/plugin/module.test.ts +0 -494
  857. package/test/plugin/optimize.test.ts +0 -343
  858. package/test/plugin/permission-assert.test.ts +0 -94
  859. package/test/plugin/plan.test.ts +0 -162
  860. package/test/plugin/promise-tool-cancel.test.ts +0 -279
  861. package/test/plugin/promise-tool.test.ts +0 -227
  862. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +0 -326
  863. package/test/plugin/provider/claude-agent/claude/branches.test.ts +0 -300
  864. package/test/plugin/provider/claude-agent/claude/probe.test.ts +0 -99
  865. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +0 -19
  866. package/test/plugin/provider/claude-agent/claude/session.test.ts +0 -30
  867. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +0 -490
  868. package/test/plugin/provider/claude-agent/claude/status.test.ts +0 -67
  869. package/test/plugin/provider/claude-agent/claude/sync.test.ts +0 -70
  870. package/test/plugin/provider/claude-agent/claude/tools.test.ts +0 -382
  871. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +0 -95
  872. package/test/plugin/provider/claude-agent/language-model/error.test.ts +0 -94
  873. package/test/plugin/provider/claude-agent/plugin.test.ts +0 -651
  874. package/test/plugin/provider/claude-agent/sync/sync.test.ts +0 -213
  875. package/test/plugin/provider/claude-agent/tools/tools.test.ts +0 -85
  876. package/test/plugin/provider/claude-agent/websearch.test.ts +0 -106
  877. package/test/plugin/provider-amazon-bedrock.test.ts +0 -225
  878. package/test/plugin/provider-azure.test.ts +0 -793
  879. package/test/plugin/provider-cerebras.test.ts +0 -62
  880. package/test/plugin/provider-chatgpt.test.ts +0 -1278
  881. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +0 -160
  882. package/test/plugin/provider-cloudflare-workers-ai.test.ts +0 -158
  883. package/test/plugin/provider-databricks.test.ts +0 -45
  884. package/test/plugin/provider-digitalocean.test.ts +0 -322
  885. package/test/plugin/provider-dynamic.test.ts +0 -179
  886. package/test/plugin/provider-github-copilot.test.ts +0 -806
  887. package/test/plugin/provider-gitlab-oauth.test.ts +0 -407
  888. package/test/plugin/provider-gitlab.test.ts +0 -546
  889. package/test/plugin/provider-google-vertex.test.ts +0 -288
  890. package/test/plugin/provider-kilo.test.ts +0 -66
  891. package/test/plugin/provider-llmgateway.test.ts +0 -72
  892. package/test/plugin/provider-lmstudio.test.ts +0 -487
  893. package/test/plugin/provider-nvidia.test.ts +0 -84
  894. package/test/plugin/provider-ollama.test.ts +0 -312
  895. package/test/plugin/provider-openai-context-caps.test.ts +0 -80
  896. package/test/plugin/provider-openai.test.ts +0 -447
  897. package/test/plugin/provider-opencode-artifacts.test.ts +0 -236
  898. package/test/plugin/provider-opencode-watches.test.ts +0 -1103
  899. package/test/plugin/provider-opencode.test.ts +0 -2590
  900. package/test/plugin/provider-openrouter.test.ts +0 -83
  901. package/test/plugin/provider-poe.test.ts +0 -360
  902. package/test/plugin/provider-sap-ai-core.test.ts +0 -138
  903. package/test/plugin/provider-snowflake-cortex.test.ts +0 -294
  904. package/test/plugin/provider-vllm.test.ts +0 -382
  905. package/test/plugin/provider-xai.test.ts +0 -92
  906. package/test/plugin/provider-zenmux.test.ts +0 -100
  907. package/test/plugin/session-compact.test.ts +0 -52
  908. package/test/plugin/session-instructions.test.ts +0 -197
  909. package/test/plugin/session-list.test.ts +0 -52
  910. package/test/plugin/session-remove.test.ts +0 -61
  911. package/test/plugin/skill.test.ts +0 -81
  912. package/test/plugin/supervisor-reload.test.ts +0 -401
  913. package/test/plugin/supervisor.test.ts +0 -485
  914. package/test/plugin/tool-input-repair-integration.test.ts +0 -296
  915. package/test/plugin/tool-input-repair.test.ts +0 -457
  916. package/test/plugin/vcs-init.test.ts +0 -48
  917. package/test/plugin/verbosity.test.ts +0 -163
  918. package/test/plugin/warming.test.ts +0 -314
  919. package/test/plugin/websearch.test.ts +0 -368
  920. package/test/plugin/worktree.test.ts +0 -52
  921. package/test/plugin-failure.test.ts +0 -305
  922. package/test/plugin.test.ts +0 -756
  923. package/test/preload.test.ts +0 -32
  924. package/test/process/process.test.ts +0 -340
  925. package/test/project-activate.test.ts +0 -144
  926. package/test/project-icon.test.ts +0 -198
  927. package/test/project.test.ts +0 -754
  928. package/test/provider.test.ts +0 -92
  929. package/test/pty/info-schema.test.ts +0 -23
  930. package/test/pty/protocol.test.ts +0 -27
  931. package/test/pty/pty-session.test.ts +0 -224
  932. package/test/pty/pty-windows.test.ts +0 -41
  933. package/test/pty/ticket.test.ts +0 -76
  934. package/test/push-list.test.ts +0 -257
  935. package/test/push-sender.test.ts +0 -235
  936. package/test/push-watcher.test.ts +0 -359
  937. package/test/reference-instructions.test.ts +0 -112
  938. package/test/reference.test.ts +0 -209
  939. package/test/repository-cache.test.ts +0 -235
  940. package/test/repository.test.ts +0 -89
  941. package/test/ripgrep.test.ts +0 -253
  942. package/test/rpc-handler-errors.test.ts +0 -62
  943. package/test/session-activation.test.ts +0 -75
  944. package/test/session-archive.test.ts +0 -81
  945. package/test/session-background.test.ts +0 -97
  946. package/test/session-checkpoint-transport.test.ts +0 -168
  947. package/test/session-compact.test.ts +0 -171
  948. package/test/session-compaction-transport.test.ts +0 -131
  949. package/test/session-compaction.test.ts +0 -1871
  950. package/test/session-create.test.ts +0 -1643
  951. package/test/session-cwd-instructions.test.ts +0 -304
  952. package/test/session-cwd.test.ts +0 -484
  953. package/test/session-diff.test.ts +0 -207
  954. package/test/session-environment.test.ts +0 -30
  955. package/test/session-error.test.ts +0 -434
  956. package/test/session-execution.test.ts +0 -2298
  957. package/test/session-generate.test.ts +0 -502
  958. package/test/session-instructions.test.ts +0 -378
  959. package/test/session-list.test.ts +0 -72
  960. package/test/session-live-tool-metadata.test.ts +0 -43
  961. package/test/session-log.test.ts +0 -123
  962. package/test/session-model-request-hooks.test.ts +0 -270
  963. package/test/session-model-request.test.ts +0 -243
  964. package/test/session-model-transport-live.test.ts +0 -329
  965. package/test/session-model-transport.test.ts +0 -1109
  966. package/test/session-move.test.ts +0 -671
  967. package/test/session-native-compaction.test.ts +0 -425
  968. package/test/session-native.test.ts +0 -359
  969. package/test/session-owned.test.ts +0 -1073
  970. package/test/session-projector.test.ts +0 -2797
  971. package/test/session-prompt.test.ts +0 -1549
  972. package/test/session-remove.test.ts +0 -117
  973. package/test/session-revert.test.ts +0 -121
  974. package/test/session-run-coordinator.test.ts +0 -711
  975. package/test/session-runner-message.test.ts +0 -1574
  976. package/test/session-runner-recorded.test.ts +0 -288
  977. package/test/session-runner-retry.test.ts +0 -130
  978. package/test/session-runner-tool-events.test.ts +0 -662
  979. package/test/session-runner.test.ts +0 -7859
  980. package/test/session-search-build.test.ts +0 -214
  981. package/test/session-search-index.test.ts +0 -524
  982. package/test/session-search.test.ts +0 -375
  983. package/test/session-shell.test.ts +0 -437
  984. package/test/session-skill.test.ts +0 -228
  985. package/test/session-stats.test.ts +0 -429
  986. package/test/session-step.test.ts +0 -435
  987. package/test/session-store.test.ts +0 -543
  988. package/test/session-system-prompt.test.ts +0 -8
  989. package/test/session-title.test.ts +0 -767
  990. package/test/session-tool-progress.test.ts +0 -159
  991. package/test/session-usage.test.ts +0 -24
  992. package/test/session-view.test.ts +0 -218
  993. package/test/session-wait.test.ts +0 -41
  994. package/test/shared-cache.test.ts +0 -161
  995. package/test/shared-schema.test.ts +0 -187
  996. package/test/shell-cleanup.test.ts +0 -52
  997. package/test/shell-daemon.test.ts +0 -663
  998. package/test/shell-parse-compatibility.test.ts +0 -451
  999. package/test/shell-parse-parity.test.ts +0 -170
  1000. package/test/shell-parse-syntax.test.ts +0 -201
  1001. package/test/shell-parse.test.ts +0 -251
  1002. package/test/shell-restart.test.ts +0 -268
  1003. package/test/shell-result.test.ts +0 -65
  1004. package/test/shell-retention.test.ts +0 -162
  1005. package/test/shell-scan/adversarial.test.ts +0 -112
  1006. package/test/shell-scan/arithmetic.test.ts +0 -143
  1007. package/test/shell-scan/bash-safety.test.ts +0 -291
  1008. package/test/shell-scan/bash-syntax.test.ts +0 -361
  1009. package/test/shell-scan/closure.test.ts +0 -47
  1010. package/test/shell-scan/compound-parity.test.ts +0 -131
  1011. package/test/shell-scan/generated.test.ts +0 -201
  1012. package/test/shell-scan/oracle.test.ts +0 -762
  1013. package/test/shell-scan/parity-regressions.test.ts +0 -146
  1014. package/test/shell-scan/powershell-runtime.test.ts +0 -604
  1015. package/test/shell-scan/powershell-safety.test.ts +0 -470
  1016. package/test/shell-scan/powershell-syntax.test.ts +0 -177
  1017. package/test/shell-scan/redirect.test.ts +0 -168
  1018. package/test/shell-scan/scan.test.ts +0 -496
  1019. package/test/shell.test.ts +0 -140
  1020. package/test/skill/instructions.test.ts +0 -216
  1021. package/test/skill-discovery.test.ts +0 -154
  1022. package/test/skill.test.ts +0 -297
  1023. package/test/snapshot.test.ts +0 -488
  1024. package/test/sqlite-bundle.test.ts +0 -53
  1025. package/test/sqlite-interrupt.test.ts +0 -86
  1026. package/test/sqlite-node.test.ts +0 -80
  1027. package/test/sqlite-workerd.test.ts +0 -111
  1028. package/test/state-group.test.ts +0 -138
  1029. package/test/state-replay.test.ts +0 -207
  1030. package/test/state.test.ts +0 -679
  1031. package/test/storage-failure.test.ts +0 -88
  1032. package/test/subagent-completion.test.ts +0 -170
  1033. package/test/subagent-idle-e2e.test.ts +0 -825
  1034. package/test/subagent-lifetime.test.ts +0 -146
  1035. package/test/subagent-report.test.ts +0 -834
  1036. package/test/tool/file-diff.test.ts +0 -45
  1037. package/test/tool-automation.test.ts +0 -345
  1038. package/test/tool-cd.test.ts +0 -372
  1039. package/test/tool-edit.test.ts +0 -888
  1040. package/test/tool-execute.test.ts +0 -1077
  1041. package/test/tool-html-markdown-budget.test.ts +0 -68
  1042. package/test/tool-image-generate.test.ts +0 -547
  1043. package/test/tool-machine.test.ts +0 -84
  1044. package/test/tool-mcp-events.test.ts +0 -90
  1045. package/test/tool-media-target-environment.test.ts +0 -213
  1046. package/test/tool-model-policy.test.ts +0 -289
  1047. package/test/tool-opencode.test.ts +0 -303
  1048. package/test/tool-output.test.ts +0 -334
  1049. package/test/tool-patch-target-environment.test.ts +0 -239
  1050. package/test/tool-patch.test.ts +0 -1265
  1051. package/test/tool-question.test.ts +0 -260
  1052. package/test/tool-read-filesystem.test.ts +0 -833
  1053. package/test/tool-read.test.ts +0 -1341
  1054. package/test/tool-registry.test.ts +0 -1662
  1055. package/test/tool-schema.test.ts +0 -538
  1056. package/test/tool-search-target-environment.test.ts +0 -103
  1057. package/test/tool-search.test.ts +0 -411
  1058. package/test/tool-session-search.test.ts +0 -178
  1059. package/test/tool-shell-target-environment.test.ts +0 -193
  1060. package/test/tool-shell.test.ts +0 -2650
  1061. package/test/tool-skill.test.ts +0 -203
  1062. package/test/tool-subagent.test.ts +0 -1046
  1063. package/test/tool-target-environment.test.ts +0 -183
  1064. package/test/tool-todo.test.ts +0 -75
  1065. package/test/tool-video-generate.test.ts +0 -227
  1066. package/test/tool-webfetch.test.ts +0 -737
  1067. package/test/tool-websearch.test.ts +0 -482
  1068. package/test/tool-write.test.ts +0 -440
  1069. package/test/usage-limits.test.ts +0 -210
  1070. package/test/util/effect-flock.test.ts +0 -331
  1071. package/test/util/error-summary.test.ts +0 -19
  1072. package/test/util/flock.test.ts +0 -326
  1073. package/test/util/fs-util.test.ts +0 -50
  1074. package/test/util/git-executable.test.ts +0 -80
  1075. package/test/util/which.test.ts +0 -99
  1076. package/test/v1-migration.test.ts +0 -1508
  1077. package/test/variant.test.ts +0 -575
  1078. package/test/vcs-hg.test.ts +0 -239
  1079. package/test/vcs.test.ts +0 -1396
  1080. package/test/video-generation.test.ts +0 -146
  1081. package/test/voice.test.ts +0 -332
  1082. package/test/websearch.test.ts +0 -593
  1083. package/test/wellknown.test.ts +0 -132
  1084. package/test/worker-client.test.ts +0 -529
  1085. package/test/workspace.test.ts +0 -828
  1086. package/test/worktree.test.ts +0 -944
package/src/git.ts CHANGED
@@ -1,1609 +1,1609 @@
1
- export * as Git from "./git.js"
2
-
3
- import os from "os"
4
- import path from "path"
5
- import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Schedule, Schema } from "effect"
6
- import { ChildProcess } from "effect/process"
7
- import { AbsolutePath, RelativePath } from "./schema.js"
8
- import { FSUtil } from "@zyro-sec/util/fs-util"
9
- import { AppProcess } from "@zyro-sec/util/process"
10
- import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
11
- import { FileDiff } from "@zyro-sec/schema/file-diff"
12
- import { KeyedMutex } from "./effect/keyed-mutex.js"
13
- import { VcsPatch } from "./vcs/patch.js"
14
- import { gitExecutable } from "./util/git-executable.js"
15
-
16
- export class Repository extends Schema.Class<Repository>("Git.Repository")({
17
- worktree: AbsolutePath,
18
- gitDirectory: AbsolutePath,
19
- commonDirectory: AbsolutePath,
20
- }) {}
21
-
22
- // Included from $GIT_DIR/config via include.path (git >= 1.7.10); OpenCode owns
23
- // this file entirely, so updates are plain rewrites with no config parsing.
24
- const snapshotConfigFile = "opencode.gitconfig"
25
- const snapshotConfigInclude = `[include]
26
- path = ${snapshotConfigFile}
27
- `
28
- const snapshotConfig = `[core]
29
- autocrlf = false
30
- longpaths = true
31
- symlinks = true
32
- fsmonitor = false
33
- untrackedCache = true
34
- # A split index cannot name its shared file once manyFiles skips index checksums.
35
- splitIndex = false
36
- [feature]
37
- manyFiles = true
38
- [index]
39
- version = 4
40
- threads = true
41
- `
42
-
43
- export const TreeID = Schema.String.pipe(Schema.brand("Git.TreeID"))
44
- export type TreeID = typeof TreeID.Type
45
-
46
- const temporaryIndexPrefix = "index.opencode-"
47
- // Like `git gc --auto`, pack once loose objects accumulate, and combine packs before lookups slow down.
48
- // Room for paths on one Git command line after the Git path, repository flags, and quoting. Windows caps a command
49
- // line at 32,767 characters. macOS caps arguments plus environment at 1 MiB, and Linux caps them at 2 MiB by default.
50
- const argumentBudget = process.platform === "win32" ? 24_000 : 128 * 1024
51
- const looseObjectLimit = 2048
52
- const packCountLimit = 16
53
-
54
- export interface CaptureInput {
55
- readonly repository: Repository
56
- readonly scopes: readonly RelativePath[]
57
- /**
58
- * Source repository whose ignore rules decide which paths are recorded. Its index also
59
- * rebuilds an unreadable snapshot index without rehashing every tracked file.
60
- */
61
- readonly ignores?: Repository
62
- readonly maximumUntrackedFileBytes?: number
63
- }
64
-
65
- export class OperationError extends Schema.TaggedError<OperationError>()("Git.OperationError", {
66
- operation: Schema.Literals([
67
- "clone",
68
- "fetch",
69
- "checkout",
70
- "reset",
71
- "create",
72
- "refresh",
73
- "write_tree",
74
- "list_files",
75
- "diff",
76
- "restore",
77
- "pack",
78
- ]),
79
- message: Schema.String,
80
- directory: Schema.optional(AbsolutePath),
81
- cause: Schema.optional(Schema.Defect()),
82
- }) {}
83
-
84
- /** Git could not answer: the spawn failed or it exited with an unexpected status. */
85
- export class CommandError extends Schema.TaggedError<CommandError>()("Git.CommandError", {
86
- args: Schema.Array(Schema.String),
87
- exitCode: Schema.optional(Schema.Number),
88
- cause: Schema.optional(Schema.Defect()),
89
- }) {}
90
-
91
- export class Worktree extends Schema.Class<Worktree>("Git.Worktree")({
92
- directory: AbsolutePath,
93
- kind: Schema.Literals(["main", "linked"]),
94
- }) {}
95
-
96
- export class WorktreeError extends Schema.TaggedError<WorktreeError>()("Git.WorktreeError", {
97
- operation: Schema.Literals(["create", "remove", "list"]),
98
- message: Schema.String,
99
- directory: Schema.optional(AbsolutePath),
100
- forceRequired: Schema.optional(Schema.Boolean),
101
- cause: Schema.optional(Schema.Defect()),
102
- }) {}
103
-
104
- export interface Interface {
105
- readonly repo: {
106
- readonly discover: (input: AbsolutePath) => Effect.Effect<Repository | undefined>
107
- /**
108
- * Spawn-free stamp of the metadata that `discover`, `remote.get` and `history.rootCommits`
109
- * read for the `.git` entry at `dotGit`: undefined when it isn't a readable repository.
110
- */
111
- readonly fingerprint: (dotGit: AbsolutePath) => Effect.Effect<string | undefined>
112
- readonly clone: (input: {
113
- remote: string
114
- directory: AbsolutePath
115
- branch?: string
116
- depth?: number
117
- }) => Effect.Effect<Repository, OperationError>
118
- readonly create: (input: {
119
- worktree: AbsolutePath
120
- gitDirectory: AbsolutePath
121
- seed?: Repository
122
- }) => Effect.Effect<Repository, OperationError>
123
- }
124
- readonly remote: {
125
- /** Undefined when the remote doesn't exist. */
126
- readonly get: (repository: Repository, name?: string) => Effect.Effect<string | undefined, CommandError>
127
- }
128
- readonly history: {
129
- readonly head: (repository: Repository) => Effect.Effect<string | undefined>
130
- readonly branch: (repository: Repository) => Effect.Effect<string | undefined>
131
- readonly defaultRemoteBranch: (repository: Repository, remote?: string) => Effect.Effect<string | undefined>
132
- /** Empty when HEAD is unborn. */
133
- readonly rootCommits: (repository: Repository) => Effect.Effect<readonly string[], CommandError>
134
- }
135
- readonly sync: {
136
- readonly fetchRemotes: (repository: Repository, input?: { prune?: boolean }) => Effect.Effect<void, OperationError>
137
- readonly fetchBranch: (
138
- repository: Repository,
139
- input: { remote?: string; branch: string; force?: boolean },
140
- ) => Effect.Effect<void, OperationError>
141
- readonly checkoutRemoteBranch: (
142
- repository: Repository,
143
- input: { remote?: string; branch: string; reset?: boolean },
144
- ) => Effect.Effect<void, OperationError>
145
- readonly resetHard: (repository: Repository, revision: string) => Effect.Effect<void, OperationError>
146
- }
147
- readonly worktree: {
148
- readonly create: (input: {
149
- repository: Repository
150
- directory: AbsolutePath
151
- ref?: string
152
- }) => Effect.Effect<Repository, WorktreeError>
153
- readonly remove: (input: {
154
- repository: Repository
155
- directory: AbsolutePath
156
- force: boolean
157
- }) => Effect.Effect<void, WorktreeError>
158
- readonly list: (repository: Repository) => Effect.Effect<readonly Worktree[], WorktreeError>
159
- }
160
- readonly index: {
161
- /** Refresh only the requested project-relative scope, preserving all other entries. */
162
- readonly refresh: (input: {
163
- repository: Repository
164
- scope: RelativePath
165
- ignores?: Repository
166
- maximumUntrackedFileBytes?: number
167
- }) => Effect.Effect<{ readonly skipped: readonly RelativePath[] }, OperationError>
168
- readonly ignored: (input: {
169
- repository: Repository
170
- paths: readonly RelativePath[]
171
- }) => Effect.Effect<ReadonlySet<RelativePath>, OperationError>
172
- }
173
- readonly tree: {
174
- readonly capture: (input: CaptureInput) => Effect.Effect<TreeID, OperationError>
175
- readonly write: (repository: Repository) => Effect.Effect<TreeID, OperationError>
176
- readonly files: (input: {
177
- repository: Repository
178
- from: TreeID
179
- to: TreeID
180
- }) => Effect.Effect<readonly RelativePath[], OperationError>
181
- readonly diff: (input: {
182
- repository: Repository
183
- from: TreeID
184
- to: TreeID
185
- context?: number
186
- paths?: readonly RelativePath[]
187
- }) => Effect.Effect<readonly FileDiff.Info[], OperationError>
188
- readonly restore: (input: {
189
- repository: Repository
190
- files: ReadonlyMap<RelativePath, TreeID>
191
- }) => Effect.Effect<void, OperationError>
192
- }
193
- readonly objects: {
194
- /**
195
- * Pack loose objects and combine small packs without dropping any object,
196
- * reachable or not. Returns without work below the thresholds; safe to run
197
- * concurrently with captures and with other processes.
198
- */
199
- readonly pack: (repository: Repository) => Effect.Effect<void, OperationError>
200
- }
201
- }
202
-
203
- export class Service extends Context.Service<Service, Interface>()("@zyro-sec/Git") {}
204
-
205
- const layer = Layer.effect(
206
- Service,
207
- Effect.gen(function* () {
208
- const fs = yield* FSUtil.Service
209
- const proc = yield* AppProcess.Service
210
- const locks = KeyedMutex.makeUnsafe<string>()
211
- const locked = <A, E, R>(repository: Repository, effect: Effect.Effect<A, E, R>) =>
212
- locks.withLock(repository.gitDirectory)(effect)
213
-
214
- const discover = Effect.fn("Git.repo.discover")(function* (input: AbsolutePath) {
215
- const dotgit = yield* fs.up({ targets: [".git"], start: input, mode: "first" }).pipe(
216
- Effect.map((matches) => matches[0]),
217
- Effect.orElseSucceed(() => undefined),
218
- )
219
- if (!dotgit) return undefined
220
-
221
- const cwd = path.dirname(dotgit)
222
- const result = yield* run(cwd, proc, ["rev-parse", "--git-dir", "--git-common-dir", "--show-toplevel"])
223
- const [gitDir, commonDir, topLevel] = result.text.split(/\r?\n/)
224
- if (!gitDir || !commonDir) return undefined
225
-
226
- return new Repository({
227
- worktree: AbsolutePath.make(topLevel ? resolvePath(cwd, topLevel) : cwd),
228
- gitDirectory: AbsolutePath.make(resolvePath(cwd, gitDir)),
229
- commonDirectory: AbsolutePath.make(resolvePath(cwd, commonDir)),
230
- })
231
- })
232
-
233
- const stamp = (target: string) =>
234
- fs.stat(target).pipe(
235
- Effect.map((info) =>
236
- [info.type, Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(
237
- ":",
238
- ),
239
- ),
240
- Effect.orElseSucceed(() => "missing"),
241
- )
242
- const readText = (target: string) => fs.readFileStringSafe(target).pipe(Effect.orElseSucceed(() => undefined))
243
-
244
- // Covers linked worktrees (gitdir file + commondir), HEAD and the ref it points at,
245
- // loose/packed/reftable refs, repository/worktree/global/XDG/system config, and the
246
- // cached `opencode` project id, so external `git init`, a first commit or `git remote`
247
- // edits change the stamp.
248
- const fingerprint = Effect.fn("Git.repo.fingerprint")(function* (dotGit: AbsolutePath) {
249
- const dot = yield* fs.stat(dotGit).pipe(Effect.orElseSucceed(() => undefined))
250
- if (!dot || (dot.type !== "File" && dot.type !== "Directory")) return undefined
251
- const gitFile = dot.type === "File" ? (yield* readText(dotGit))?.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim() : ""
252
- if (gitFile === undefined) return undefined
253
- const gitDir = gitFile ? yield* fs.resolve(path.resolve(path.dirname(dotGit), gitFile)) : dotGit
254
- const commondir = (yield* readText(path.join(gitDir, "commondir")))?.trim()
255
- const commonDir = commondir ? yield* fs.resolve(path.resolve(gitDir, commondir)) : gitDir
256
- const head = (yield* readText(path.join(gitDir, "HEAD")))?.trim()
257
- if (head === undefined) return undefined
258
- const ref = head.startsWith("ref:") ? head.slice(4).trim() : undefined
259
-
260
- const home = process.env.HOME || os.homedir()
261
- const nosystem = ["1", "true", "yes", "on"].includes((process.env.GIT_CONFIG_NOSYSTEM ?? "").toLowerCase())
262
- const files = [
263
- path.join(gitDir, "HEAD"),
264
- path.join(commonDir, "config"),
265
- path.join(commonDir, "config.worktree"),
266
- path.join(gitDir, "config.worktree"),
267
- path.join(commonDir, "packed-refs"),
268
- path.join(commonDir, "reftable", "tables.list"),
269
- path.join(commonDir, "opencode"),
270
- ...(ref ? [path.join(commonDir, ref), path.join(gitDir, ref)] : []),
271
- process.env.GIT_CONFIG_GLOBAL || path.join(home, ".gitconfig"),
272
- path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "config"),
273
- ...(nosystem ? [] : [process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig"]),
274
- ]
275
- const stamps = yield* Effect.forEach([dotGit, ...files], stamp, { concurrency: "unbounded" })
276
- return [gitDir, commonDir, head, ...files, ...stamps].join("\0")
277
- })
278
-
279
- const command = (cwd: string, args: string[]) =>
280
- execute(cwd, proc, args).pipe(Effect.mapError((cause) => new CommandError({ args, cause })))
281
-
282
- const remote = Effect.fn("Git.remote.get")(function* (repository: Repository, name = "origin") {
283
- const args = ["remote", "get-url", name]
284
- const result = yield* command(repository.worktree, args)
285
- // Exit 2: no such remote.
286
- if (result.exitCode === 2) return undefined
287
- if (result.exitCode !== 0) return yield* new CommandError({ args, exitCode: result.exitCode })
288
- return result.text.trim() || undefined
289
- })
290
-
291
- const roots = Effect.fn("Git.history.rootCommits")(function* (repository: Repository) {
292
- const args = ["rev-list", "--max-parents=0", "HEAD"]
293
- const result = yield* command(repository.worktree, args)
294
- if (result.exitCode === 0)
295
- return result.text
296
- .split("\n")
297
- .map((item) => item.trim())
298
- .filter(Boolean)
299
- .toSorted()
300
- // `rev-parse -q --verify` exits 1 only when HEAD doesn't resolve, i.e. it is unborn.
301
- const verify = yield* command(repository.worktree, ["rev-parse", "-q", "--verify", "HEAD"])
302
- if (verify.exitCode === 1) return []
303
- return yield* new CommandError({ args, exitCode: result.exitCode })
304
- })
305
-
306
- const head = Effect.fn("Git.history.head")(function* (repository: Repository) {
307
- const result = yield* run(repository.worktree, proc, ["rev-parse", "HEAD"])
308
- if (result.exitCode !== 0) return undefined
309
- return result.text.trim() || undefined
310
- })
311
-
312
- const branch = Effect.fn("Git.history.branch")(function* (repository: Repository) {
313
- const result = yield* run(repository.worktree, proc, ["symbolic-ref", "--quiet", "--short", "HEAD"])
314
- if (result.exitCode !== 0) return undefined
315
- return result.text.trim() || undefined
316
- })
317
-
318
- const remoteHead = Effect.fn("Git.history.defaultRemoteBranch")(function* (
319
- repository: Repository,
320
- remoteName = "origin",
321
- ) {
322
- const result = yield* run(repository.worktree, proc, ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`])
323
- if (result.exitCode !== 0) return undefined
324
- return result.text.trim().replace(new RegExp(`^refs/remotes/${remoteName}/`), "") || undefined
325
- })
326
-
327
- const operation = Effect.fnUntraced(function* (
328
- operation: OperationError["operation"],
329
- directory: AbsolutePath,
330
- args: string[],
331
- ) {
332
- const result = yield* execute(directory, proc, args).pipe(Effect.mapError(spawnFailure(operation, directory)))
333
- if (result.exitCode === 0) return
334
- return yield* commandFailure(operation, directory, result)
335
- })
336
-
337
- const clone = Effect.fn("Git.repo.clone")(function* (input: {
338
- remote: string
339
- directory: AbsolutePath
340
- branch?: string
341
- depth?: number
342
- }) {
343
- yield* operation("clone", AbsolutePath.make(path.dirname(input.directory)), [
344
- "clone",
345
- "--depth",
346
- String(input.depth ?? 100),
347
- ...(input.branch ? ["--branch", input.branch] : []),
348
- "--",
349
- input.remote,
350
- input.directory,
351
- ])
352
- const repository = yield* discover(input.directory)
353
- if (repository) return repository
354
- return yield* new OperationError({
355
- operation: "clone",
356
- directory: input.directory,
357
- message: "Cloned repository could not be opened",
358
- })
359
- })
360
-
361
- const fetch = Effect.fn("Git.sync.fetchRemotes")(function* (
362
- repository: Repository,
363
- input: { prune?: boolean } = {},
364
- ) {
365
- yield* operation("fetch", repository.worktree, ["fetch", "--all", ...(input.prune === false ? [] : ["--prune"])])
366
- })
367
-
368
- const fetchBranch = Effect.fn("Git.sync.fetchBranch")(function* (
369
- repository: Repository,
370
- input: { remote?: string; branch: string; force?: boolean },
371
- ) {
372
- const remoteName = input.remote ?? "origin"
373
- const spec = `refs/heads/${input.branch}:refs/remotes/${remoteName}/${input.branch}`
374
- yield* operation("fetch", repository.worktree, ["fetch", remoteName, input.force === false ? spec : `+${spec}`])
375
- })
376
-
377
- const checkout = Effect.fn("Git.sync.checkoutRemoteBranch")(function* (
378
- repository: Repository,
379
- input: { remote?: string; branch: string; reset?: boolean },
380
- ) {
381
- const remoteName = input.remote ?? "origin"
382
- yield* operation("checkout", repository.worktree, [
383
- "checkout",
384
- ...(input.reset === false ? [input.branch] : ["-B", input.branch, `${remoteName}/${input.branch}`]),
385
- ])
386
- })
387
-
388
- const reset = Effect.fn("Git.sync.resetHard")(function* (repository: Repository, revision: string) {
389
- yield* operation("reset", repository.worktree, ["reset", "--hard", revision])
390
- })
391
-
392
- const repositoryArgs = (repository: Repository, args: string[]) => [
393
- "--git-dir",
394
- repository.gitDirectory,
395
- "--work-tree",
396
- repository.worktree,
397
- ...args,
398
- ]
399
-
400
- const repositoryRun = (
401
- operationName: OperationError["operation"],
402
- repository: Repository,
403
- args: string[],
404
- options?: RepositoryOptions,
405
- ) =>
406
- proc
407
- .run(
408
- ChildProcess.make(gitExecutable(), repositoryArgs(repository, args), {
409
- cwd: repository.worktree,
410
- env: options?.index ? { ...options.env, GIT_INDEX_FILE: options.index } : options?.env,
411
- extendEnv: true,
412
- }),
413
- { stdin: options?.stdin, maxOutputBytes: options?.maxOutputBytes },
414
- )
415
- .pipe(Effect.mapError(spawnFailure(operationName, repository.worktree)))
416
-
417
- const repositoryOperation = Effect.fnUntraced(function* (
418
- operationName: OperationError["operation"],
419
- repository: Repository,
420
- args: string[],
421
- options?: RepositoryOptions,
422
- ) {
423
- const result = yield* repositoryRun(operationName, repository, args, options)
424
- const text = result.stdout.toString("utf8")
425
- const stderr = result.stderr.toString("utf8")
426
- if (result.exitCode === 0) return { text, stderr, truncated: result.stdoutTruncated }
427
- return yield* commandFailure(operationName, repository.worktree, { text, stderr })
428
- })
429
-
430
- /**
431
- * On Windows, Git exits non-zero instead of reusing a loose object that another process is finalizing at the
432
- * same moment. Objects are content-addressed, so one of at most two retries finds that copy in place. Only a Git
433
- * exit is retried, never a failure to start Git, and other platforms fail on the first attempt.
434
- */
435
- const retryConcurrentObjectWrite = <A, R>(effect: Effect.Effect<A, OperationError, R>) =>
436
- process.platform === "win32"
437
- ? effect.pipe(
438
- Effect.retry({
439
- times: 2,
440
- schedule: Schedule.spaced("50 millis"),
441
- while: (error) => error.cause === undefined,
442
- }),
443
- )
444
- : effect
445
-
446
- /**
447
- * A new store is initialized in a temporary sibling directory and renamed into
448
- * place, so processes racing to create the same store never observe or write a
449
- * half-initialized one; the loser discards its copy and adopts the winner's.
450
- */
451
- const create = Effect.fn("Git.repo.create")(function* (input: {
452
- worktree: AbsolutePath
453
- gitDirectory: AbsolutePath
454
- seed?: Repository
455
- }) {
456
- const repository = new Repository({
457
- worktree: input.worktree,
458
- gitDirectory: input.gitDirectory,
459
- commonDirectory: input.gitDirectory,
460
- })
461
- if (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD"))) {
462
- yield* initRepository({ ...input, directory: input.gitDirectory })
463
- return repository
464
- }
465
- const temporaryDirectory = AbsolutePath.make(`${input.gitDirectory}.init-${uniqueSuffix()}`)
466
- yield* Effect.gen(function* () {
467
- yield* initRepository({ ...input, directory: temporaryDirectory })
468
- const renamed = yield* fs.rename(temporaryDirectory, input.gitDirectory).pipe(Effect.exit)
469
- if (Exit.isSuccess(renamed) || (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD")))) return
470
- return yield* new OperationError({
471
- operation: "create",
472
- directory: input.gitDirectory,
473
- message: "Failed to move Git storage into place",
474
- cause: Cause.squash(renamed.cause),
475
- })
476
- }).pipe(Effect.ensuring(fs.remove(temporaryDirectory, { recursive: true, force: true }).pipe(Effect.ignore)))
477
- return repository
478
- })
479
-
480
- const initRepository = Effect.fnUntraced(function* (input: {
481
- worktree: AbsolutePath
482
- gitDirectory: AbsolutePath
483
- directory: AbsolutePath
484
- seed?: Repository
485
- }) {
486
- const operationError = (message: string) => (cause: unknown) =>
487
- new OperationError({ operation: "create", directory: input.gitDirectory, message, cause })
488
- yield* fs.ensureDir(input.directory).pipe(Effect.mapError(operationError("Failed to create Git storage")))
489
- yield* repositoryOperation(
490
- "create",
491
- new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
492
- ["init"],
493
- )
494
- yield* Effect.gen(function* () {
495
- yield* fs.writeFileString(path.join(input.directory, snapshotConfigFile), snapshotConfig)
496
- const config = path.join(input.directory, "config")
497
- const current = yield* fs.readFileString(config)
498
- if (current.includes(snapshotConfigInclude)) return
499
- yield* fs.writeFileString(config, `${current.endsWith("\n") ? "\n" : "\n\n"}${snapshotConfigInclude}`, {
500
- flag: "a",
501
- })
502
- }).pipe(Effect.mapError(operationError("Failed to configure Git storage")))
503
- if (!input.seed) return
504
- yield* fs
505
- .ensureDir(path.join(input.directory, "objects", "info"))
506
- .pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
507
- yield* fs
508
- .writeFileString(
509
- path.join(input.directory, "objects", "info", "alternates"),
510
- path.join(input.seed.commonDirectory, "objects") + "\n",
511
- )
512
- .pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
513
- const index = path.join(input.directory, "index")
514
- yield* seedIndex(
515
- new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
516
- input.seed,
517
- index,
518
- ).pipe(
519
- Effect.catch(() => fs.remove(index, { force: true })),
520
- Effect.ignore,
521
- )
522
- })
523
-
524
- /**
525
- * Both commands only read the index, so they never take `index.lock`. Two parallel processes beat one combined
526
- * `ls-files -m -o`, whose lstat pass is not threaded like diff-files'.
527
- */
528
- const listChanges = Effect.fnUntraced(function* (
529
- repository: Repository,
530
- scope: RelativePath,
531
- index?: string,
532
- excludeFrom?: string,
533
- ) {
534
- const list = (args: string[]) =>
535
- repositoryOperation("refresh", repository, args, { index }).pipe(
536
- // Embedded repositories are listed as `dir/`; update-index records them as gitlinks.
537
- Effect.map((result) => nuls(result.text).map((file) => RelativePath.make(file.replace(/\/$/, "")))),
538
- )
539
- const [tracked, untracked] = yield* Effect.all(
540
- [
541
- list(["diff-files", "--name-only", "-z", "--", literalPathspec(scope)]),
542
- list([
543
- "ls-files",
544
- "--others",
545
- ...(excludeFrom ? [`--exclude-from=${excludeFrom}`] : []),
546
- "--exclude-standard",
547
- "-z",
548
- "--",
549
- literalPathspec(scope),
550
- ]),
551
- ],
552
- { concurrency: 2 },
553
- )
554
- return { tracked, untracked }
555
- })
556
-
557
- const updateIndex = Effect.fnUntraced(function* (input: {
558
- repository: Repository
559
- changes: { tracked: readonly RelativePath[]; untracked: readonly RelativePath[] }
560
- ignores?: Repository
561
- maximumUntrackedFileBytes?: number
562
- index?: string
563
- excluded?: ReadonlySet<RelativePath>
564
- }) {
565
- const candidates = [...input.changes.tracked, ...input.changes.untracked]
566
- if (!candidates.length) return { skipped: [] }
567
- const excluded =
568
- input.excluded ??
569
- (input.ignores ? yield* ignored({ repository: input.ignores, paths: candidates }) : new Set<RelativePath>())
570
- const maximum = input.maximumUntrackedFileBytes
571
- const skipped = maximum
572
- ? (yield* Effect.forEach(
573
- input.changes.untracked.filter((item) => !excluded.has(item)),
574
- (item) =>
575
- fs.stat(path.join(input.repository.worktree, item)).pipe(
576
- Effect.map((info) => (info.type === "File" && Number(info.size) > maximum ? item : undefined)),
577
- Effect.orElseSucceed(() => undefined),
578
- ),
579
- { concurrency: 8 },
580
- )).filter((item): item is RelativePath => item !== undefined)
581
- : []
582
- const skip = new Set(skipped)
583
- const added = candidates.filter((item) => !excluded.has(item) && !skip.has(item))
584
- // Untracked paths are not in the index, so only tracked paths that are now ignored need removing.
585
- const removed = input.changes.tracked.filter((item) => excluded.has(item))
586
- // update-index takes literal paths, so large lists avoid add's quadratic pathspec matching.
587
- if (removed.length)
588
- yield* repositoryOperation("refresh", input.repository, ["update-index", "--force-remove", "-z", "--stdin"], {
589
- stdin: removed.join("\0") + "\0",
590
- index: input.index,
591
- })
592
- // update-index drops a tracked file replaced by an embedded repository; a second line for the same path,
593
- // in the same call, records its gitlink. For a path that already is a gitlink the repeat is a no-op.
594
- const embedded = (yield* Effect.forEach(
595
- input.changes.tracked.filter((item) => !excluded.has(item)),
596
- (item) =>
597
- fs
598
- .existsSafe(path.join(input.repository.worktree, item, ".git"))
599
- .pipe(Effect.map((found) => (found ? item : undefined))),
600
- { concurrency: 8 },
601
- )).filter((item): item is RelativePath => item !== undefined)
602
- if (added.length)
603
- yield* retryConcurrentObjectWrite(
604
- repositoryOperation(
605
- "refresh",
606
- input.repository,
607
- ["update-index", "--add", "--remove", "--replace", "-z", "--stdin"],
608
- { stdin: [...added, ...embedded].join("\0") + "\0", index: input.index },
609
- ),
610
- )
611
- return { skipped }
612
- })
613
-
614
- const refresh = Effect.fn("Git.index.refresh")(function* (input: {
615
- repository: Repository
616
- scope: RelativePath
617
- ignores?: Repository
618
- maximumUntrackedFileBytes?: number
619
- }) {
620
- return yield* updateIndex({ ...input, changes: yield* listChanges(input.repository, input.scope) })
621
- })
622
-
623
- const ignored = Effect.fn("Git.index.ignored")(function* (input: {
624
- repository: Repository
625
- paths: readonly RelativePath[]
626
- }) {
627
- if (!input.paths.length) return new Set<RelativePath>()
628
- const result = yield* repositoryRun(
629
- "list_files",
630
- input.repository,
631
- ["check-ignore", "--no-index", "--stdin", "-z"],
632
- { stdin: input.paths.join("\0") + "\0" },
633
- )
634
- // Exit 1: none of the paths are ignored.
635
- if (result.exitCode !== 0 && result.exitCode !== 1)
636
- return yield* new OperationError({
637
- operation: "list_files",
638
- directory: input.repository.worktree,
639
- message: result.stderr.toString("utf8").trim() || "Failed to check ignored paths",
640
- })
641
- return new Set(nuls(result.stdout.toString("utf8")).map((file) => RelativePath.make(file)))
642
- })
643
-
644
- const writeTree = Effect.fn("Git.tree.write")(function* (repository: Repository, index?: string) {
645
- const tree = (yield* retryConcurrentObjectWrite(
646
- repositoryOperation("write_tree", repository, ["write-tree"], { index }),
647
- )).text.trim()
648
- if (/^[0-9a-f]{40,64}$/.test(tree)) return TreeID.make(tree)
649
- return yield* new OperationError({
650
- operation: "write_tree",
651
- directory: repository.worktree,
652
- message: `Invalid tree ID: ${tree}`,
653
- })
654
- })
655
-
656
- const indexFile = (repository: Repository) => path.join(repository.gitDirectory, "index")
657
- /** Git only replaces an index by renaming a new file into place, so every write changes its inode. */
658
- const indexFingerprint = (file: string) =>
659
- fs.stat(file).pipe(
660
- Effect.map((info) =>
661
- [Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(":"),
662
- ),
663
- Effect.orElseSucceed(() => undefined),
664
- )
665
-
666
- /** A copied index must keep the timestamp Git uses to detect racily clean entries. */
667
- const copyIndex = Effect.fnUntraced(function* (from: string, to: string) {
668
- const info = yield* fs.stat(from)
669
- yield* fs.copyFile(from, to)
670
- const mtime = Option.getOrUndefined(info.mtime)
671
- if (mtime)
672
- yield* fs
673
- .utimes(
674
- to,
675
- Option.getOrElse(info.atime, () => mtime),
676
- mtime,
677
- )
678
- .pipe(Effect.ignore)
679
- })
680
-
681
- /**
682
- * Copy the source index into the store. A split index names a shared index file in
683
- * its own Git directory, so those files are linked in just long enough to rewrite the
684
- * copy as a complete index.
685
- */
686
- const seedIndex = Effect.fnUntraced(function* (store: Repository, source: Repository, target: string) {
687
- yield* copyIndex(path.join(source.gitDirectory, "index"), target)
688
- const shared = (yield* fs.readDirectory(source.gitDirectory)).filter((entry) => entry.startsWith("sharedindex."))
689
- if (shared.length === 0) return
690
- yield* Effect.forEach(shared, (entry) => {
691
- const from = path.join(source.gitDirectory, entry)
692
- const to = path.join(store.gitDirectory, entry)
693
- return fs.link(from, to).pipe(Effect.catch(() => fs.copyFile(from, to)))
694
- }).pipe(
695
- Effect.andThen(repositoryOperation("refresh", store, ["update-index", "--no-split-index"], { index: target })),
696
- Effect.ensuring(
697
- Effect.forEach(shared, (entry) =>
698
- fs.remove(path.join(store.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
699
- ),
700
- ),
701
- )
702
- })
703
-
704
- /**
705
- * Run index writes against a temporary index, then rename it over the store's
706
- * index. Processes never contend on `index.lock`, an interrupted or killed
707
- * writer cannot leave a partial index behind, and a stale lock is irrelevant.
708
- * Git never writes an index in place, it writes a lock file and renames it over
709
- * the temporary name, so a hard-linked temporary index leaves the store's index
710
- * untouched; a copy is the fallback when linking fails. The index is only a stat
711
- * cache over the object store; when writers race, the last rename wins and the
712
- * next capture reconciles against the worktree.
713
- */
714
- const withTemporaryIndex = <A, E, R>(repository: Repository, use: (index: string) => Effect.Effect<A, E, R>) =>
715
- Effect.acquireUseRelease(
716
- Effect.gen(function* () {
717
- const current = indexFile(repository)
718
- const index = temporaryIndex(repository)
719
- if (!(yield* fs.existsSafe(current))) return index
720
- const linked = yield* fs.link(current, index).pipe(
721
- Effect.as(true),
722
- Effect.orElseSucceed(() => false),
723
- )
724
- if (linked) return index
725
- yield* copyIndex(current, index).pipe(
726
- Effect.mapError(
727
- (cause) =>
728
- new OperationError({
729
- operation: "refresh",
730
- directory: repository.gitDirectory,
731
- message: "Failed to prepare a temporary index",
732
- cause,
733
- }),
734
- ),
735
- )
736
- return index
737
- }),
738
- (index) =>
739
- Effect.gen(function* () {
740
- const value = yield* use(index)
741
- const installed = yield* Effect.uninterruptible(
742
- Effect.gen(function* () {
743
- // Fingerprint before the rename, so a concurrent writer's index can never be paired with this tree.
744
- const fingerprint = yield* indexFingerprint(index)
745
- const renamed = yield* fs.rename(index, indexFile(repository)).pipe(
746
- // Windows reports a transient sharing violation while another process reads the index.
747
- Effect.retry({ times: 3, schedule: Schedule.spaced("20 millis") }),
748
- Effect.as(true),
749
- Effect.orElseSucceed(() => false),
750
- )
751
- return renamed ? fingerprint : undefined
752
- }),
753
- )
754
- return { value, installed }
755
- }),
756
- (index) => fs.remove(index, { force: true }).pipe(Effect.ignore),
757
- )
758
-
759
- // A clean capture returns the tree last written from the exact index it scanned.
760
- const lastCaptures = new Map<string, { readonly fingerprint: string; readonly tree: TreeID }>()
761
- const preparedStores = new Set<string>()
762
- const pendingCaptures = new Map<string, Deferred.Deferred<TreeID, OperationError>>()
763
- // Untracked files skipped for size, by path, with the stamp they had when skipped.
764
- const oversizedFiles = new Map<string, Map<RelativePath, string>>()
765
-
766
- /**
767
- * Changes are listed against the temporary index they are written to, never the
768
- * store's index, which another process may replace at any moment. Each tree is
769
- * therefore exactly its own index plus the worktree changes against it.
770
- */
771
- const attemptCapture = Effect.fnUntraced(function* (input: CaptureInput) {
772
- const sourceExclude = input.ignores ? path.join(input.ignores.commonDirectory, "info", "exclude") : undefined
773
- const excludeFrom = sourceExclude && (yield* fs.existsSafe(sourceExclude)) ? sourceExclude : undefined
774
- const result = yield* withTemporaryIndex(input.repository, (index) =>
775
- Effect.gen(function* () {
776
- const scanned = yield* indexFingerprint(index)
777
- const changes = yield* Effect.forEach(
778
- input.scopes,
779
- (scope) => listChanges(input.repository, scope, index, excludeFrom),
780
- { concurrency: "unbounded" },
781
- )
782
- const last = lastCaptures.get(input.repository.gitDirectory)
783
- const untracked = changes.flatMap((change) => change.untracked)
784
- const oversized = oversizedFiles.get(input.repository.gitDirectory)
785
- const stillOversized = new Set(
786
- oversized
787
- ? (yield* Effect.forEach(
788
- untracked.filter((file) => oversized.has(file)),
789
- (file) =>
790
- oversizedStamp(input, file).pipe(
791
- Effect.map((current) => (current && current === oversized.get(file) ? file : undefined)),
792
- ),
793
- { concurrency: 8 },
794
- )).filter((file): file is RelativePath => file !== undefined)
795
- : [],
796
- )
797
- // Paths the source ignores are listed as untracked on every scan; they leave the index unchanged.
798
- const excluded =
799
- scanned && last?.fingerprint === scanned && changes.every((change) => !change.tracked.length)
800
- ? input.ignores
801
- ? yield* ignored({
802
- repository: input.ignores,
803
- paths: untracked.filter((file) => !stillOversized.has(file)),
804
- })
805
- : new Set<RelativePath>()
806
- : undefined
807
- if (last && excluded && untracked.every((file) => excluded.has(file) || stillOversized.has(file)))
808
- return last.tree
809
- const skipped = (yield* Effect.forEach(changes, (change) =>
810
- updateIndex({ ...input, changes: change, index, excluded }),
811
- )).flatMap((update) => update.skipped)
812
- oversizedFiles.set(
813
- input.repository.gitDirectory,
814
- new Map(
815
- (yield* Effect.forEach(
816
- skipped,
817
- (file) => oversizedStamp(input, file).pipe(Effect.map((value) => [file, value] as const)),
818
- { concurrency: 8 },
819
- )).filter((entry): entry is readonly [RelativePath, string] => entry[1] !== undefined),
820
- ),
821
- )
822
- return yield* writeTree(input.repository, index)
823
- }),
824
- )
825
- if (result.installed)
826
- lastCaptures.set(input.repository.gitDirectory, { fingerprint: result.installed, tree: result.value })
827
- if (!result.installed) lastCaptures.delete(input.repository.gitDirectory)
828
- return result.value
829
- })
830
-
831
- const oversizedStamp = (input: CaptureInput, file: RelativePath) =>
832
- fs.stat(path.join(input.repository.worktree, file)).pipe(
833
- Effect.map((info) =>
834
- input.maximumUntrackedFileBytes && info.type === "File" && Number(info.size) > input.maximumUntrackedFileBytes
835
- ? `${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`
836
- : undefined,
837
- ),
838
- Effect.orElseSucceed(() => undefined),
839
- )
840
-
841
- /**
842
- * Callers queued behind a running capture share the next one, which starts after they all asked, so it still
843
- * sees every change made before each call.
844
- */
845
- const captureTree = Effect.fn("Git.tree.capture")(function* (input: CaptureInput) {
846
- const key = JSON.stringify([
847
- input.repository.gitDirectory,
848
- input.repository.worktree,
849
- input.scopes,
850
- input.ignores?.gitDirectory,
851
- input.maximumUntrackedFileBytes,
852
- ])
853
- const pending = pendingCaptures.get(key)
854
- if (pending) {
855
- const exit = yield* Effect.exit(Deferred.await(pending))
856
- if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) return yield* exit
857
- }
858
- const deferred = Deferred.makeUnsafe<TreeID, OperationError>()
859
- const release = () => {
860
- if (pendingCaptures.get(key) === deferred) pendingCaptures.delete(key)
861
- }
862
- return yield* Effect.uninterruptibleMask((restore) => {
863
- pendingCaptures.set(key, deferred)
864
- return restore(captureLocked(input, release)).pipe(
865
- Effect.onExit((exit) => {
866
- release()
867
- return Deferred.done(deferred, exit)
868
- }),
869
- )
870
- })
871
- })
872
-
873
- const captureLocked = (input: CaptureInput, onStart: () => void) =>
874
- locked(
875
- input.repository,
876
- Effect.gen(function* () {
877
- onStart()
878
- if (!preparedStores.has(input.repository.gitDirectory)) {
879
- preparedStores.add(input.repository.gitDirectory)
880
- yield* sweepTemporaryIndexes(input.repository)
881
- yield* ensureSnapshotConfig(input.repository)
882
- }
883
- return yield* attemptCapture(input).pipe(
884
- Effect.catch((error) =>
885
- Effect.gen(function* () {
886
- if (!(yield* isIndexUnreadable(input.repository))) return yield* error
887
- yield* Effect.logWarning("rebuilding unreadable snapshot index", {
888
- directory: input.repository.gitDirectory,
889
- message: error.message,
890
- })
891
- yield* rebuildIndex(input.repository, input.ignores)
892
- return yield* attemptCapture(input)
893
- }),
894
- ),
895
- )
896
- }),
897
- )
898
-
899
- /**
900
- * Only an index Git itself cannot read is rebuilt, decided by exit status rather
901
- * than by localized messages. Other failures, such as an unreadable worktree
902
- * file or a process that could not start, surface unchanged.
903
- */
904
- const isIndexUnreadable = Effect.fnUntraced(function* (repository: Repository) {
905
- if (!(yield* fs.existsSafe(indexFile(repository)))) return false
906
- return yield* repositoryOperation("refresh", repository, [
907
- "ls-files",
908
- "-z",
909
- "--",
910
- literalPathspec(".opencode-probe"),
911
- ]).pipe(Effect.match({ onSuccess: () => false, onFailure: (error) => error.cause === undefined }))
912
- })
913
-
914
- const rebuildIndex = Effect.fnUntraced(function* (repository: Repository, source?: Repository) {
915
- lastCaptures.delete(repository.gitDirectory)
916
- const temporary = temporaryIndex(repository)
917
- // The source's stat cache and cache-tree spare recovery from rehashing every tracked file.
918
- const copied = source
919
- ? yield* seedIndex(repository, source, temporary).pipe(
920
- Effect.as(true),
921
- Effect.orElseSucceed(() => false),
922
- )
923
- : false
924
- yield* (
925
- copied ? fs.rename(temporary, indexFile(repository)) : fs.remove(indexFile(repository), { force: true })
926
- ).pipe(Effect.ignore, Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)))
927
- })
928
-
929
- // Stores created by earlier releases would otherwise keep their original settings; only OpenCode's include file is rewritten, never `config`.
930
- const ensureSnapshotConfig = Effect.fnUntraced(function* (repository: Repository) {
931
- const file = path.join(repository.gitDirectory, snapshotConfigFile)
932
- const current = yield* fs.readFileStringSafe(file).pipe(Effect.orElseSucceed(() => undefined))
933
- if (current === undefined || current === snapshotConfig) return
934
- // Concurrent Git processes must never read a partially written file.
935
- const temporary = `${file}.${uniqueSuffix()}`
936
- yield* fs
937
- .writeFileString(temporary, snapshotConfig)
938
- .pipe(
939
- Effect.andThen(fs.rename(temporary, file)),
940
- Effect.ignore,
941
- Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)),
942
- )
943
- })
944
-
945
- const temporaryIndex = (repository: Repository) =>
946
- path.join(repository.gitDirectory, `${temporaryIndexPrefix}${Date.now()}-${uniqueSuffix()}`)
947
-
948
- /**
949
- * Temporary indexes left by killed processes. Age comes from the creation time in
950
- * the name, because a hard-linked index keeps the store index's old mtime; live
951
- * captures finish long before the cutoff.
952
- */
953
- const sweepTemporaryIndexes = Effect.fnUntraced(function* (repository: Repository) {
954
- const cutoff = Date.now() - 60 * 60 * 1000
955
- const entries = yield* fs.readDirectory(repository.gitDirectory).pipe(Effect.orElseSucceed(() => []))
956
- yield* Effect.forEach(
957
- entries.filter(
958
- (entry) =>
959
- entry.startsWith(temporaryIndexPrefix) &&
960
- Number(entry.slice(temporaryIndexPrefix.length).split("-")[0]) < cutoff,
961
- ),
962
- (entry) => fs.remove(path.join(repository.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
963
- { discard: true },
964
- )
965
- })
966
-
967
- const treeFiles = Effect.fn("Git.tree.files")(function* (input: {
968
- repository: Repository
969
- from: TreeID
970
- to: TreeID
971
- }) {
972
- // Undo needs both paths of a rename, not only its destination.
973
- return nuls(
974
- (yield* repositoryOperation("list_files", input.repository, [
975
- "diff",
976
- "--name-only",
977
- "--no-renames",
978
- "-z",
979
- input.from,
980
- input.to,
981
- ])).text,
982
- ).map((file) => RelativePath.make(file))
983
- })
984
-
985
- const treeDiff = Effect.fn("Git.tree.diff")(function* (input: {
986
- repository: Repository
987
- from: TreeID
988
- to: TreeID
989
- context?: number
990
- paths?: readonly RelativePath[]
991
- }) {
992
- if (input.paths?.length === 0) return []
993
- const groups = input.paths ? pathGroups(input.paths) : [undefined]
994
- const diffs: FileDiff.Info[] = []
995
- let patchBudget = VcsPatch.MAX_TOTAL_PATCH_BYTES
996
- for (const paths of groups) {
997
- const group = yield* diffGroup({ ...input, paths }, patchBudget)
998
- diffs.push(...group.diffs)
999
- patchBudget = group.truncated ? 0 : patchBudget - group.patchBytes
1000
- }
1001
- return diffs
1002
- })
1003
-
1004
- const diffGroup = Effect.fnUntraced(function* (
1005
- input: { repository: Repository; from: TreeID; to: TreeID; context?: number; paths?: readonly RelativePath[] },
1006
- patchBudget: number,
1007
- ) {
1008
- const args = ["--no-renames", input.from, input.to, "--", ...(input.paths ?? [])]
1009
- // Patch headers have no -z form: unquoted paths keep chunksByFile matching non-ASCII names.
1010
- const [names, numbers, patch] = yield* Effect.all(
1011
- [
1012
- repositoryOperation("diff", input.repository, [
1013
- "--literal-pathspecs",
1014
- "diff",
1015
- "--name-status",
1016
- "-z",
1017
- ...args,
1018
- ]),
1019
- repositoryOperation("diff", input.repository, ["--literal-pathspecs", "diff", "--numstat", "-z", ...args]),
1020
- patchBudget > 0
1021
- ? repositoryOperation(
1022
- "diff",
1023
- input.repository,
1024
- [
1025
- "--literal-pathspecs",
1026
- "-c",
1027
- "core.quotepath=false",
1028
- "diff",
1029
- "--no-ext-diff",
1030
- `--unified=${input.context ?? 3}`,
1031
- ...args,
1032
- ],
1033
- { maxOutputBytes: patchBudget },
1034
- )
1035
- : Effect.succeed({ text: "", stderr: "", truncated: true }),
1036
- ],
1037
- { concurrency: 3 },
1038
- )
1039
- const statuses = nuls(names.text)
1040
- const files = statuses.flatMap((code, index) => {
1041
- const file = statuses[index + 1]
1042
- if (index % 2 !== 0 || !file) return []
1043
- return [
1044
- {
1045
- file: RelativePath.make(file),
1046
- status: code.startsWith("A") ? "added" : code.startsWith("D") ? "deleted" : "modified",
1047
- } as const,
1048
- ]
1049
- })
1050
- const stats = new Map(
1051
- nuls(numbers.text).flatMap((line) => {
1052
- const [additions, deletions, ...file] = line.split("\t")
1053
- if (!additions || !deletions || file.length === 0) return []
1054
- return [
1055
- [
1056
- file.join("\t"),
1057
- additions === "-" || deletions === "-"
1058
- ? { binary: true, additions: 0, deletions: 0 }
1059
- : { binary: false, additions: Number(additions), deletions: Number(deletions) },
1060
- ] as const,
1061
- ]
1062
- }),
1063
- )
1064
- const patches = VcsPatch.chunksByFile(patch, (index) => files[index]?.file)
1065
- return {
1066
- diffs: files.map((entry) => {
1067
- const stat = stats.get(entry.file)
1068
- return {
1069
- ...entry,
1070
- additions: stat?.additions ?? 0,
1071
- deletions: stat?.deletions ?? 0,
1072
- patch: stat?.binary ? "" : (patches.get(entry.file) ?? VcsPatch.emptyPatch(entry.file)),
1073
- } satisfies FileDiff.Info
1074
- }),
1075
- patchBytes: Buffer.byteLength(patch.text),
1076
- truncated: patch.truncated,
1077
- }
1078
- })
1079
-
1080
- const hasEntry = Effect.fnUntraced(function* (repository: Repository, tree: TreeID, file: RelativePath) {
1081
- const text = (yield* repositoryOperation("restore", repository, [
1082
- "ls-tree",
1083
- "-z",
1084
- tree,
1085
- "--",
1086
- literalPathspec(file),
1087
- ])).text.replace(/\0$/, "")
1088
- if (!text) return false
1089
- if (!/^\d+\s+\w+\s+[0-9a-f]+\t/.test(text))
1090
- return yield* new OperationError({
1091
- operation: "restore",
1092
- directory: repository.worktree,
1093
- message: `Invalid tree entry for ${file}`,
1094
- })
1095
- return true
1096
- })
1097
-
1098
- const removePath = (repository: Repository, file: RelativePath) =>
1099
- fs.remove(path.join(repository.worktree, file), { recursive: true, force: true }).pipe(
1100
- Effect.mapError(
1101
- (cause) =>
1102
- new OperationError({
1103
- operation: "restore",
1104
- directory: repository.worktree,
1105
- message: `Failed to remove ${file}`,
1106
- cause,
1107
- }),
1108
- ),
1109
- )
1110
-
1111
- const pathsInTree = Effect.fnUntraced(function* (
1112
- repository: Repository,
1113
- tree: TreeID,
1114
- files: readonly RelativePath[],
1115
- ) {
1116
- const pathspecs = files.map(literalPathspec)
1117
- const fits = pathspecs.reduce((length, pathspec) => length + pathspec.length + 1, 0) <= argumentBudget
1118
- const result = yield* repositoryOperation(
1119
- "restore",
1120
- repository,
1121
- fits ? ["ls-tree", "-z", tree, "--", ...pathspecs] : ["ls-tree", "-r", "-t", "-z", "--full-tree", tree],
1122
- )
1123
- const listed = yield* Effect.forEach(nuls(result.text), (record) => {
1124
- const match = /^\d+ \w+ [0-9a-f]+\t(.*)$/s.exec(record)
1125
- if (match) return Effect.succeed(RelativePath.make(match[1]!))
1126
- return Effect.fail(
1127
- new OperationError({
1128
- operation: "restore",
1129
- directory: repository.worktree,
1130
- message: `Invalid tree entry: ${record}`,
1131
- }),
1132
- )
1133
- })
1134
- return new Set(listed)
1135
- })
1136
-
1137
- /** Batched paths cost one ls-tree and one checkout per source tree instead of two processes per file. */
1138
- const restore = Effect.fn("Git.tree.restore")(
1139
- (input: { repository: Repository; files: ReadonlyMap<RelativePath, TreeID> }) =>
1140
- locked(
1141
- input.repository,
1142
- Effect.gen(function* () {
1143
- if (!input.files.size) return
1144
- if (!canBatchRestore([...input.files.keys()]))
1145
- return yield* Effect.forEach(
1146
- input.files,
1147
- ([file, tree]) =>
1148
- Effect.gen(function* () {
1149
- if (!(yield* hasEntry(input.repository, tree, file)))
1150
- return yield* removePath(input.repository, file)
1151
- yield* withTemporaryIndex(input.repository, (index) =>
1152
- repositoryOperation(
1153
- "restore",
1154
- input.repository,
1155
- ["checkout", tree, "--", literalPathspec(file)],
1156
- {
1157
- index,
1158
- },
1159
- ),
1160
- )
1161
- }),
1162
- { discard: true },
1163
- )
1164
- const groups = new Map<TreeID, RelativePath[]>()
1165
- input.files.forEach((tree, file) => groups.set(tree, [...(groups.get(tree) ?? []), file]))
1166
- const plan = yield* Effect.forEach(groups, ([tree, files]) =>
1167
- pathsInTree(input.repository, tree, files).pipe(
1168
- Effect.map((present) => ({
1169
- tree,
1170
- present: files.filter((file) => present.has(file)),
1171
- absent: files.filter((file) => !present.has(file)),
1172
- })),
1173
- ),
1174
- )
1175
- // Checkouts go first, so one failing removal cannot stop the other files from being restored.
1176
- const checkouts = plan.filter((item) => item.present.length)
1177
- if (checkouts.length)
1178
- yield* withTemporaryIndex(input.repository, (index) =>
1179
- Effect.forEach(
1180
- checkouts,
1181
- (item) =>
1182
- repositoryOperation(
1183
- "restore",
1184
- input.repository,
1185
- ["checkout", item.tree, "--pathspec-from-file=-", "--pathspec-file-nul"],
1186
- { stdin: item.present.map(literalPathspec).join("\0") + "\0", index },
1187
- ),
1188
- { discard: true },
1189
- ),
1190
- )
1191
- yield* Effect.forEach(
1192
- plan.flatMap((item) => item.absent),
1193
- (file) => removePath(input.repository, file),
1194
- { concurrency: 16, discard: true },
1195
- )
1196
- }),
1197
- ),
1198
- )
1199
-
1200
- /**
1201
- * Snapshot trees have no refs, so Git's own repack and prune would treat every
1202
- * snapshot as garbage. Packing instead hands pack-objects an explicit list of
1203
- * every loose object (and, when combining, every object in the old packs), checks
1204
- * the new index lists all of them, and only then deletes the loose copies and
1205
- * the combined packs. Nothing is pruned, and objects are never delegated to the
1206
- * source repository through alternates.
1207
- */
1208
- const packObjects = Effect.fn("Git.objects.pack")(function* (repository: Repository) {
1209
- const objects = path.join(repository.gitDirectory, "objects")
1210
- const packDirectory = path.join(objects, "pack")
1211
- const loose = yield* looseObjects(objects)
1212
- const packs = yield* localPacks(packDirectory)
1213
- const combinePacks = packs.length >= packCountLimit
1214
- if (loose.length < looseObjectLimit && !combinePacks) return
1215
- yield* withPackLock(
1216
- repository,
1217
- Effect.gen(function* () {
1218
- yield* sweepTemporaryPacks(packDirectory)
1219
- const combined = combinePacks
1220
- ? yield* Effect.forEach(packs, (pack) =>
1221
- packIndex(repository, path.join(packDirectory, `${pack}.idx`)).pipe(
1222
- Effect.map((oids) => ({ pack, oids })),
1223
- ),
1224
- )
1225
- : []
1226
- const objectIds = [...new Set([...loose.map((item) => item.oid), ...combined.flatMap((item) => item.oids)])]
1227
- if (!objectIds.length) return
1228
- const newPacks = (yield* repositoryOperation(
1229
- "pack",
1230
- repository,
1231
- [
1232
- "-c",
1233
- "pack.threads=2",
1234
- "-c",
1235
- "pack.windowMemory=64m",
1236
- "pack-objects",
1237
- "-q",
1238
- "--non-empty",
1239
- path.join(packDirectory, "pack"),
1240
- ],
1241
- { stdin: objectIds.join("\n") + "\n" },
1242
- )).text
1243
- .split("\n")
1244
- .map((line) => line.trim())
1245
- .filter(Boolean)
1246
- const packedIds = new Set(
1247
- (yield* Effect.forEach(newPacks, (name) =>
1248
- packIndex(repository, path.join(packDirectory, `pack-${name}.idx`)),
1249
- )).flat(),
1250
- )
1251
- const missing = objectIds.filter((oid) => !packedIds.has(oid))
1252
- if (missing.length)
1253
- return yield* new OperationError({
1254
- operation: "pack",
1255
- directory: repository.gitDirectory,
1256
- message: `Packed ${packedIds.size} objects but ${missing.length} are missing; nothing was removed`,
1257
- })
1258
- // Deletion is quick and must not stop halfway, which could strand a pack without its index.
1259
- yield* Effect.uninterruptible(
1260
- Effect.gen(function* () {
1261
- yield* Effect.forEach(loose, (item) => fs.remove(item.file, { force: true }).pipe(Effect.ignore), {
1262
- concurrency: 16,
1263
- discard: true,
1264
- })
1265
- const newPackNames = new Set(newPacks.map((name) => `pack-${name}`))
1266
- yield* Effect.forEach(
1267
- combined.filter((item) => !newPackNames.has(item.pack)),
1268
- (item) =>
1269
- // The index goes first so readers never see an index without its pack.
1270
- Effect.forEach(
1271
- [".idx", ".pack", ".rev", ".bitmap", ".mtimes"],
1272
- (extension) =>
1273
- fs
1274
- .remove(path.join(packDirectory, `${item.pack}${extension}`), { force: true })
1275
- .pipe(Effect.ignore),
1276
- { discard: true },
1277
- ),
1278
- { discard: true },
1279
- )
1280
- }),
1281
- )
1282
- }),
1283
- )
1284
- })
1285
-
1286
- const looseObjects = Effect.fnUntraced(function* (objects: string) {
1287
- const fanout = (yield* fs.readDirectory(objects).pipe(Effect.orElseSucceed(() => []))).filter((entry) =>
1288
- /^[0-9a-f]{2}$/.test(entry),
1289
- )
1290
- const listed = yield* Effect.forEach(
1291
- fanout,
1292
- (prefix) =>
1293
- fs.readDirectory(path.join(objects, prefix)).pipe(
1294
- Effect.orElseSucceed(() => []),
1295
- Effect.map((entries) =>
1296
- entries
1297
- .filter((entry) => /^[0-9a-f]{38}$|^[0-9a-f]{62}$/.test(entry))
1298
- .map((entry) => ({ oid: prefix + entry, file: path.join(objects, prefix, entry) })),
1299
- ),
1300
- ),
1301
- { concurrency: 16 },
1302
- )
1303
- return listed.flat()
1304
- })
1305
-
1306
- // Packs with a .keep marker or a promisor file belong to someone else's policy and are left alone.
1307
- const localPacks = Effect.fnUntraced(function* (directory: string) {
1308
- const entries = new Set(yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])))
1309
- return [...entries]
1310
- .filter((entry) => entry.startsWith("pack-") && entry.endsWith(".pack"))
1311
- .map((entry) => entry.slice(0, -".pack".length))
1312
- .filter(
1313
- (pack) => entries.has(`${pack}.idx`) && !entries.has(`${pack}.keep`) && !entries.has(`${pack}.promisor`),
1314
- )
1315
- })
1316
-
1317
- const packIndex = Effect.fnUntraced(function* (repository: Repository, file: string) {
1318
- const bytes = yield* fs.readFile(file).pipe(
1319
- Effect.mapError(
1320
- (cause) =>
1321
- new OperationError({
1322
- operation: "pack",
1323
- directory: repository.gitDirectory,
1324
- message: `Failed to read ${file}`,
1325
- cause,
1326
- }),
1327
- ),
1328
- )
1329
- const parsed = packIndexObjectIDs(bytes)
1330
- if (parsed) return parsed
1331
- const result = yield* repositoryOperation("pack", repository, ["show-index"], { stdin: bytes })
1332
- return result.text.split("\n").flatMap((line) => {
1333
- const oid = line.split(" ")[1]
1334
- return oid ? [oid] : []
1335
- })
1336
- })
1337
-
1338
- /**
1339
- * pack-objects writes tmp_* files and renames them; leftovers mean a killed
1340
- * process. A pack without its index is unreadable to Git, so removing one is
1341
- * lossless; the age cutoff skips a pack whose index is still being renamed.
1342
- */
1343
- const sweepTemporaryPacks = Effect.fnUntraced(function* (directory: string) {
1344
- const cutoff = Date.now() - 60 * 60 * 1000
1345
- const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []))
1346
- const indexed = new Set(entries.filter((entry) => entry.endsWith(".idx")).map((entry) => entry.slice(0, -4)))
1347
- yield* Effect.forEach(
1348
- entries.filter(
1349
- (entry) =>
1350
- entry.startsWith("tmp_") ||
1351
- (entry.startsWith("pack-") && entry.endsWith(".pack") && !indexed.has(entry.slice(0, -5))),
1352
- ),
1353
- (entry) =>
1354
- fs.stat(path.join(directory, entry)).pipe(
1355
- Effect.flatMap((info) =>
1356
- (Option.getOrUndefined(info.mtime)?.getTime() ?? 0) < cutoff
1357
- ? fs.remove(path.join(directory, entry), { force: true })
1358
- : Effect.void,
1359
- ),
1360
- Effect.ignore,
1361
- ),
1362
- { discard: true },
1363
- )
1364
- })
1365
-
1366
- // Cross-process exclusion: concurrent packing would stay lossless but duplicate work and objects.
1367
- const withPackLock = <A, E, R>(repository: Repository, effect: Effect.Effect<A, E, R>) => {
1368
- const file = path.join(repository.gitDirectory, "opencode-pack.lock")
1369
- return Effect.gen(function* () {
1370
- const stale = yield* fs.stat(file).pipe(
1371
- Effect.map((info) => (Option.getOrUndefined(info.mtime)?.getTime() ?? 0) < Date.now() - 60 * 60 * 1000),
1372
- Effect.orElseSucceed(() => false),
1373
- )
1374
- if (stale) yield* fs.remove(file, { force: true }).pipe(Effect.ignore)
1375
- const acquired = yield* fs.writeFileString(file, String(process.pid), { flag: "wx" }).pipe(
1376
- Effect.as(true),
1377
- Effect.orElseSucceed(() => false),
1378
- )
1379
- if (!acquired) return
1380
- yield* effect.pipe(Effect.ensuring(fs.remove(file, { force: true }).pipe(Effect.ignore)))
1381
- })
1382
- }
1383
-
1384
- const worktreeRun = Effect.fnUntraced(function* (
1385
- operation: "create" | "remove" | "list",
1386
- repository: Repository,
1387
- args: string[],
1388
- worktreeDirectory?: AbsolutePath,
1389
- cwd = repository.worktree,
1390
- ) {
1391
- const result = yield* proc
1392
- .run(ChildProcess.make(gitExecutable(), args, { cwd, extendEnv: true, stdin: "ignore" }))
1393
- .pipe(
1394
- Effect.mapError(
1395
- (cause) => new WorktreeError({ operation, directory: worktreeDirectory, message: cause.message, cause }),
1396
- ),
1397
- )
1398
- if (result.exitCode === 0) return result.stdout.toString("utf8")
1399
- const message = result.stderr.toString("utf8").trim() || result.stdout.toString("utf8").trim() || "Git failed"
1400
- return yield* new WorktreeError({
1401
- operation,
1402
- directory: worktreeDirectory,
1403
- message,
1404
- forceRequired: operation === "remove" && /contains modified or untracked files|is dirty/i.test(message),
1405
- })
1406
- })
1407
-
1408
- const worktreeCreate = Effect.fn("Git.worktree.create")(function* (input: {
1409
- repository: Repository
1410
- directory: AbsolutePath
1411
- ref?: string
1412
- }) {
1413
- yield* worktreeRun(
1414
- "create",
1415
- input.repository,
1416
- ["worktree", "add", "--detach", "--", input.directory, input.ref ?? "HEAD"],
1417
- input.directory,
1418
- )
1419
- const repository = yield* discover(input.directory)
1420
- if (repository) return repository
1421
- return yield* new WorktreeError({
1422
- operation: "create",
1423
- directory: input.directory,
1424
- message: "Created worktree could not be opened",
1425
- })
1426
- })
1427
-
1428
- const worktreeRemove = Effect.fn("Git.worktree.remove")(function* (input: {
1429
- repository: Repository
1430
- directory: AbsolutePath
1431
- force: boolean
1432
- }) {
1433
- yield* worktreeRun(
1434
- "remove",
1435
- input.repository,
1436
- ["worktree", "remove", ...(input.force ? ["--force"] : []), input.directory],
1437
- input.directory,
1438
- input.repository.commonDirectory,
1439
- )
1440
- })
1441
-
1442
- const worktreeList = Effect.fn("Git.worktree.list")(function* (repository: Repository) {
1443
- return (yield* worktreeRun("list", repository, ["worktree", "list", "--porcelain"]))
1444
- .split("\n")
1445
- .filter((line) => line.startsWith("worktree "))
1446
- .map(
1447
- (line, index) =>
1448
- new Worktree({
1449
- directory: AbsolutePath.make(resolvePath(repository.worktree, line.slice("worktree ".length).trim())),
1450
- kind: index === 0 ? "main" : "linked",
1451
- }),
1452
- )
1453
- })
1454
-
1455
- return Service.of({
1456
- repo: { discover, fingerprint, clone, create },
1457
- remote: { get: remote },
1458
- history: { head, branch, defaultRemoteBranch: remoteHead, rootCommits: roots },
1459
- sync: { fetchRemotes: fetch, fetchBranch, checkoutRemoteBranch: checkout, resetHard: reset },
1460
- worktree: { create: worktreeCreate, remove: worktreeRemove, list: worktreeList },
1461
- index: { refresh, ignored },
1462
- tree: {
1463
- capture: captureTree,
1464
- write: (repository) => writeTree(repository),
1465
- files: treeFiles,
1466
- diff: treeDiff,
1467
- restore,
1468
- },
1469
- objects: { pack: packObjects },
1470
- })
1471
- }),
1472
- )
1473
-
1474
- export const node = makeGlobalNode({ service: Service, layer: layer, deps: [FSUtil.node, AppProcess.node] })
1475
-
1476
- interface Result {
1477
- readonly exitCode: number
1478
- readonly text: string
1479
- readonly stderr: string
1480
- }
1481
-
1482
- interface RepositoryOptions {
1483
- readonly stdin?: string | Uint8Array
1484
- readonly env?: Record<string, string>
1485
- readonly maxOutputBytes?: number
1486
- readonly index?: string
1487
- }
1488
-
1489
- function spawnFailure(operation: OperationError["operation"], directory: AbsolutePath) {
1490
- return (cause: { readonly message: string }) =>
1491
- new OperationError({ operation, directory, message: cause.message, cause })
1492
- }
1493
-
1494
- function commandFailure(
1495
- operation: OperationError["operation"],
1496
- directory: AbsolutePath,
1497
- result: { readonly text: string; readonly stderr: string },
1498
- ) {
1499
- return new OperationError({
1500
- operation,
1501
- directory,
1502
- message: result.stderr.trim() || result.text.trim() || `Git ${operation} failed`,
1503
- })
1504
- }
1505
-
1506
- function run(cwd: string, proc: AppProcess.Interface, args: string[]) {
1507
- return execute(cwd, proc, args).pipe(Effect.orElseSucceed(() => ({ exitCode: 1, text: "", stderr: "" })))
1508
- }
1509
-
1510
- function execute(cwd: string, proc: AppProcess.Interface, args: string[]) {
1511
- return proc
1512
- .run(
1513
- ChildProcess.make(gitExecutable(), args, {
1514
- cwd,
1515
- extendEnv: true,
1516
- stdin: "ignore",
1517
- }),
1518
- )
1519
- .pipe(
1520
- Effect.map(
1521
- (result) =>
1522
- ({
1523
- exitCode: result.exitCode,
1524
- text: result.stdout.toString("utf8"),
1525
- stderr: result.stderr.toString("utf8"),
1526
- }) satisfies Result,
1527
- ),
1528
- )
1529
- }
1530
-
1531
- /** Split NUL-terminated git output into its records. */
1532
- function nuls(text: string) {
1533
- return text.split("\0").filter(Boolean)
1534
- }
1535
-
1536
- /** Pathspec magic that matches exactly one path, so names with `*`, `?`, `[`, or a leading `:` are not patterns. */
1537
- function literalPathspec(file: string) {
1538
- return `:(literal)${file}`
1539
- }
1540
-
1541
- /**
1542
- * Paths whose restore operations commute: none inside another, and every segment
1543
- * printable ASCII that no platform rewrites. Git precomposes Unicode, filesystems
1544
- * may fold case, and Windows drops trailing dots and spaces and treats `\` and
1545
- * `:` specially, so anything else takes the ordered path.
1546
- */
1547
- function canBatchRestore(files: readonly string[]) {
1548
- const canonical = files.every((file) =>
1549
- file.split("/").every((part) => /^[\x20-\x7e]+$/.test(part) && !/[\\:]/.test(part) && !/[. ]$/.test(part)),
1550
- )
1551
- if (!canonical) return false
1552
- const folded = new Set(files.map((file) => file.toLowerCase()))
1553
- if (folded.size !== files.length) return false
1554
- return files.every((file) => {
1555
- const parts = file.toLowerCase().split("/")
1556
- return parts.slice(1).every((_, index) => !folded.has(parts.slice(0, index + 1).join("/")))
1557
- })
1558
- }
1559
-
1560
- /**
1561
- * Object IDs from a version 2 pack index: magic, version, a 256-entry fan-out
1562
- * table whose last entry is the object count, then the sorted IDs. Returns
1563
- * undefined for version 1 indexes and for packs with 64-bit offsets (over 2 GiB),
1564
- * whose hash length this size check cannot derive.
1565
- */
1566
- function packIndexObjectIDs(bytes: Uint8Array) {
1567
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
1568
- if (bytes.length < 1032 || view.getUint32(0) !== 0xff744f63 || view.getUint32(4) !== 2) return undefined
1569
- const count = view.getUint32(8 + 255 * 4)
1570
- const hash = (bytes.length - 1032 - 8 * count) / (count + 2)
1571
- if (hash !== 20 && hash !== 32) return undefined
1572
- return Array.from({ length: count }, (_, index) =>
1573
- Buffer.from(bytes.subarray(1032 + index * hash, 1032 + (index + 1) * hash)).toString("hex"),
1574
- )
1575
- }
1576
-
1577
- /**
1578
- * Groups are sorted like Git's output, so groups of file paths concatenate in the
1579
- * order one call prints them. Each path is counted with room for the quotes Windows
1580
- * adds around spaces.
1581
- */
1582
- function pathGroups(paths: readonly RelativePath[]) {
1583
- return paths
1584
- .toSorted((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)))
1585
- .reduce<{ groups: RelativePath[][]; length: number }>(
1586
- (state, file) => {
1587
- const cost = file.length + 3
1588
- const current = state.groups.at(-1)
1589
- if (current && state.length + cost <= argumentBudget) {
1590
- current.push(file)
1591
- return { groups: state.groups, length: state.length + cost }
1592
- }
1593
- return { groups: [...state.groups, [file]], length: cost }
1594
- },
1595
- { groups: [], length: 0 },
1596
- ).groups
1597
- }
1598
-
1599
- function uniqueSuffix() {
1600
- return `${process.pid}-${Math.random().toString(36).slice(2)}`
1601
- }
1602
-
1603
- function resolvePath(cwd: string, value: string) {
1604
- const trimmed = value.replace(/[\r\n]+$/, "")
1605
- if (!trimmed) return cwd
1606
- const normalized = FSUtil.windowsPath(trimmed)
1607
- if (path.isAbsolute(normalized)) return path.normalize(normalized)
1608
- return path.resolve(cwd, normalized)
1609
- }
1
+ export * as Git from "./git.js"
2
+
3
+ import os from "os"
4
+ import path from "path"
5
+ import { Cause, Context, Deferred, Effect, Exit, Layer, Option, Schedule, Schema } from "effect"
6
+ import { ChildProcess } from "effect/process"
7
+ import { AbsolutePath, RelativePath } from "./schema.js"
8
+ import { FSUtil } from "@zyro-sec/util/fs-util"
9
+ import { AppProcess } from "@zyro-sec/util/process"
10
+ import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
11
+ import { FileDiff } from "@zyro-sec/schema/file-diff"
12
+ import { KeyedMutex } from "./effect/keyed-mutex.js"
13
+ import { VcsPatch } from "./vcs/patch.js"
14
+ import { gitExecutable } from "./util/git-executable.js"
15
+
16
+ export class Repository extends Schema.Class<Repository>("Git.Repository")({
17
+ worktree: AbsolutePath,
18
+ gitDirectory: AbsolutePath,
19
+ commonDirectory: AbsolutePath,
20
+ }) {}
21
+
22
+ // Included from $GIT_DIR/config via include.path (git >= 1.7.10); OpenCode owns
23
+ // this file entirely, so updates are plain rewrites with no config parsing.
24
+ const snapshotConfigFile = "opencode.gitconfig"
25
+ const snapshotConfigInclude = `[include]
26
+ path = ${snapshotConfigFile}
27
+ `
28
+ const snapshotConfig = `[core]
29
+ autocrlf = false
30
+ longpaths = true
31
+ symlinks = true
32
+ fsmonitor = false
33
+ untrackedCache = true
34
+ # A split index cannot name its shared file once manyFiles skips index checksums.
35
+ splitIndex = false
36
+ [feature]
37
+ manyFiles = true
38
+ [index]
39
+ version = 4
40
+ threads = true
41
+ `
42
+
43
+ export const TreeID = Schema.String.pipe(Schema.brand("Git.TreeID"))
44
+ export type TreeID = typeof TreeID.Type
45
+
46
+ const temporaryIndexPrefix = "index.opencode-"
47
+ // Like `git gc --auto`, pack once loose objects accumulate, and combine packs before lookups slow down.
48
+ // Room for paths on one Git command line after the Git path, repository flags, and quoting. Windows caps a command
49
+ // line at 32,767 characters. macOS caps arguments plus environment at 1 MiB, and Linux caps them at 2 MiB by default.
50
+ const argumentBudget = process.platform === "win32" ? 24_000 : 128 * 1024
51
+ const looseObjectLimit = 2048
52
+ const packCountLimit = 16
53
+
54
+ export interface CaptureInput {
55
+ readonly repository: Repository
56
+ readonly scopes: readonly RelativePath[]
57
+ /**
58
+ * Source repository whose ignore rules decide which paths are recorded. Its index also
59
+ * rebuilds an unreadable snapshot index without rehashing every tracked file.
60
+ */
61
+ readonly ignores?: Repository
62
+ readonly maximumUntrackedFileBytes?: number
63
+ }
64
+
65
+ export class OperationError extends Schema.TaggedError<OperationError>()("Git.OperationError", {
66
+ operation: Schema.Literals([
67
+ "clone",
68
+ "fetch",
69
+ "checkout",
70
+ "reset",
71
+ "create",
72
+ "refresh",
73
+ "write_tree",
74
+ "list_files",
75
+ "diff",
76
+ "restore",
77
+ "pack",
78
+ ]),
79
+ message: Schema.String,
80
+ directory: Schema.optional(AbsolutePath),
81
+ cause: Schema.optional(Schema.Defect()),
82
+ }) {}
83
+
84
+ /** Git could not answer: the spawn failed or it exited with an unexpected status. */
85
+ export class CommandError extends Schema.TaggedError<CommandError>()("Git.CommandError", {
86
+ args: Schema.Array(Schema.String),
87
+ exitCode: Schema.optional(Schema.Number),
88
+ cause: Schema.optional(Schema.Defect()),
89
+ }) {}
90
+
91
+ export class Worktree extends Schema.Class<Worktree>("Git.Worktree")({
92
+ directory: AbsolutePath,
93
+ kind: Schema.Literals(["main", "linked"]),
94
+ }) {}
95
+
96
+ export class WorktreeError extends Schema.TaggedError<WorktreeError>()("Git.WorktreeError", {
97
+ operation: Schema.Literals(["create", "remove", "list"]),
98
+ message: Schema.String,
99
+ directory: Schema.optional(AbsolutePath),
100
+ forceRequired: Schema.optional(Schema.Boolean),
101
+ cause: Schema.optional(Schema.Defect()),
102
+ }) {}
103
+
104
+ export interface Interface {
105
+ readonly repo: {
106
+ readonly discover: (input: AbsolutePath) => Effect.Effect<Repository | undefined>
107
+ /**
108
+ * Spawn-free stamp of the metadata that `discover`, `remote.get` and `history.rootCommits`
109
+ * read for the `.git` entry at `dotGit`: undefined when it isn't a readable repository.
110
+ */
111
+ readonly fingerprint: (dotGit: AbsolutePath) => Effect.Effect<string | undefined>
112
+ readonly clone: (input: {
113
+ remote: string
114
+ directory: AbsolutePath
115
+ branch?: string
116
+ depth?: number
117
+ }) => Effect.Effect<Repository, OperationError>
118
+ readonly create: (input: {
119
+ worktree: AbsolutePath
120
+ gitDirectory: AbsolutePath
121
+ seed?: Repository
122
+ }) => Effect.Effect<Repository, OperationError>
123
+ }
124
+ readonly remote: {
125
+ /** Undefined when the remote doesn't exist. */
126
+ readonly get: (repository: Repository, name?: string) => Effect.Effect<string | undefined, CommandError>
127
+ }
128
+ readonly history: {
129
+ readonly head: (repository: Repository) => Effect.Effect<string | undefined>
130
+ readonly branch: (repository: Repository) => Effect.Effect<string | undefined>
131
+ readonly defaultRemoteBranch: (repository: Repository, remote?: string) => Effect.Effect<string | undefined>
132
+ /** Empty when HEAD is unborn. */
133
+ readonly rootCommits: (repository: Repository) => Effect.Effect<readonly string[], CommandError>
134
+ }
135
+ readonly sync: {
136
+ readonly fetchRemotes: (repository: Repository, input?: { prune?: boolean }) => Effect.Effect<void, OperationError>
137
+ readonly fetchBranch: (
138
+ repository: Repository,
139
+ input: { remote?: string; branch: string; force?: boolean },
140
+ ) => Effect.Effect<void, OperationError>
141
+ readonly checkoutRemoteBranch: (
142
+ repository: Repository,
143
+ input: { remote?: string; branch: string; reset?: boolean },
144
+ ) => Effect.Effect<void, OperationError>
145
+ readonly resetHard: (repository: Repository, revision: string) => Effect.Effect<void, OperationError>
146
+ }
147
+ readonly worktree: {
148
+ readonly create: (input: {
149
+ repository: Repository
150
+ directory: AbsolutePath
151
+ ref?: string
152
+ }) => Effect.Effect<Repository, WorktreeError>
153
+ readonly remove: (input: {
154
+ repository: Repository
155
+ directory: AbsolutePath
156
+ force: boolean
157
+ }) => Effect.Effect<void, WorktreeError>
158
+ readonly list: (repository: Repository) => Effect.Effect<readonly Worktree[], WorktreeError>
159
+ }
160
+ readonly index: {
161
+ /** Refresh only the requested project-relative scope, preserving all other entries. */
162
+ readonly refresh: (input: {
163
+ repository: Repository
164
+ scope: RelativePath
165
+ ignores?: Repository
166
+ maximumUntrackedFileBytes?: number
167
+ }) => Effect.Effect<{ readonly skipped: readonly RelativePath[] }, OperationError>
168
+ readonly ignored: (input: {
169
+ repository: Repository
170
+ paths: readonly RelativePath[]
171
+ }) => Effect.Effect<ReadonlySet<RelativePath>, OperationError>
172
+ }
173
+ readonly tree: {
174
+ readonly capture: (input: CaptureInput) => Effect.Effect<TreeID, OperationError>
175
+ readonly write: (repository: Repository) => Effect.Effect<TreeID, OperationError>
176
+ readonly files: (input: {
177
+ repository: Repository
178
+ from: TreeID
179
+ to: TreeID
180
+ }) => Effect.Effect<readonly RelativePath[], OperationError>
181
+ readonly diff: (input: {
182
+ repository: Repository
183
+ from: TreeID
184
+ to: TreeID
185
+ context?: number
186
+ paths?: readonly RelativePath[]
187
+ }) => Effect.Effect<readonly FileDiff.Info[], OperationError>
188
+ readonly restore: (input: {
189
+ repository: Repository
190
+ files: ReadonlyMap<RelativePath, TreeID>
191
+ }) => Effect.Effect<void, OperationError>
192
+ }
193
+ readonly objects: {
194
+ /**
195
+ * Pack loose objects and combine small packs without dropping any object,
196
+ * reachable or not. Returns without work below the thresholds; safe to run
197
+ * concurrently with captures and with other processes.
198
+ */
199
+ readonly pack: (repository: Repository) => Effect.Effect<void, OperationError>
200
+ }
201
+ }
202
+
203
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/Git") {}
204
+
205
+ const layer = Layer.effect(
206
+ Service,
207
+ Effect.gen(function* () {
208
+ const fs = yield* FSUtil.Service
209
+ const proc = yield* AppProcess.Service
210
+ const locks = KeyedMutex.makeUnsafe<string>()
211
+ const locked = <A, E, R>(repository: Repository, effect: Effect.Effect<A, E, R>) =>
212
+ locks.withLock(repository.gitDirectory)(effect)
213
+
214
+ const discover = Effect.fn("Git.repo.discover")(function* (input: AbsolutePath) {
215
+ const dotgit = yield* fs.up({ targets: [".git"], start: input, mode: "first" }).pipe(
216
+ Effect.map((matches) => matches[0]),
217
+ Effect.orElseSucceed(() => undefined),
218
+ )
219
+ if (!dotgit) return undefined
220
+
221
+ const cwd = path.dirname(dotgit)
222
+ const result = yield* run(cwd, proc, ["rev-parse", "--git-dir", "--git-common-dir", "--show-toplevel"])
223
+ const [gitDir, commonDir, topLevel] = result.text.split(/\r?\n/)
224
+ if (!gitDir || !commonDir) return undefined
225
+
226
+ return new Repository({
227
+ worktree: AbsolutePath.make(topLevel ? resolvePath(cwd, topLevel) : cwd),
228
+ gitDirectory: AbsolutePath.make(resolvePath(cwd, gitDir)),
229
+ commonDirectory: AbsolutePath.make(resolvePath(cwd, commonDir)),
230
+ })
231
+ })
232
+
233
+ const stamp = (target: string) =>
234
+ fs.stat(target).pipe(
235
+ Effect.map((info) =>
236
+ [info.type, Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(
237
+ ":",
238
+ ),
239
+ ),
240
+ Effect.orElseSucceed(() => "missing"),
241
+ )
242
+ const readText = (target: string) => fs.readFileStringSafe(target).pipe(Effect.orElseSucceed(() => undefined))
243
+
244
+ // Covers linked worktrees (gitdir file + commondir), HEAD and the ref it points at,
245
+ // loose/packed/reftable refs, repository/worktree/global/XDG/system config, and the
246
+ // cached `opencode` project id, so external `git init`, a first commit or `git remote`
247
+ // edits change the stamp.
248
+ const fingerprint = Effect.fn("Git.repo.fingerprint")(function* (dotGit: AbsolutePath) {
249
+ const dot = yield* fs.stat(dotGit).pipe(Effect.orElseSucceed(() => undefined))
250
+ if (!dot || (dot.type !== "File" && dot.type !== "Directory")) return undefined
251
+ const gitFile = dot.type === "File" ? (yield* readText(dotGit))?.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim() : ""
252
+ if (gitFile === undefined) return undefined
253
+ const gitDir = gitFile ? yield* fs.resolve(path.resolve(path.dirname(dotGit), gitFile)) : dotGit
254
+ const commondir = (yield* readText(path.join(gitDir, "commondir")))?.trim()
255
+ const commonDir = commondir ? yield* fs.resolve(path.resolve(gitDir, commondir)) : gitDir
256
+ const head = (yield* readText(path.join(gitDir, "HEAD")))?.trim()
257
+ if (head === undefined) return undefined
258
+ const ref = head.startsWith("ref:") ? head.slice(4).trim() : undefined
259
+
260
+ const home = process.env.HOME || os.homedir()
261
+ const nosystem = ["1", "true", "yes", "on"].includes((process.env.GIT_CONFIG_NOSYSTEM ?? "").toLowerCase())
262
+ const files = [
263
+ path.join(gitDir, "HEAD"),
264
+ path.join(commonDir, "config"),
265
+ path.join(commonDir, "config.worktree"),
266
+ path.join(gitDir, "config.worktree"),
267
+ path.join(commonDir, "packed-refs"),
268
+ path.join(commonDir, "reftable", "tables.list"),
269
+ path.join(commonDir, "opencode"),
270
+ ...(ref ? [path.join(commonDir, ref), path.join(gitDir, ref)] : []),
271
+ process.env.GIT_CONFIG_GLOBAL || path.join(home, ".gitconfig"),
272
+ path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "config"),
273
+ ...(nosystem ? [] : [process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig"]),
274
+ ]
275
+ const stamps = yield* Effect.forEach([dotGit, ...files], stamp, { concurrency: "unbounded" })
276
+ return [gitDir, commonDir, head, ...files, ...stamps].join("\0")
277
+ })
278
+
279
+ const command = (cwd: string, args: string[]) =>
280
+ execute(cwd, proc, args).pipe(Effect.mapError((cause) => new CommandError({ args, cause })))
281
+
282
+ const remote = Effect.fn("Git.remote.get")(function* (repository: Repository, name = "origin") {
283
+ const args = ["remote", "get-url", name]
284
+ const result = yield* command(repository.worktree, args)
285
+ // Exit 2: no such remote.
286
+ if (result.exitCode === 2) return undefined
287
+ if (result.exitCode !== 0) return yield* new CommandError({ args, exitCode: result.exitCode })
288
+ return result.text.trim() || undefined
289
+ })
290
+
291
+ const roots = Effect.fn("Git.history.rootCommits")(function* (repository: Repository) {
292
+ const args = ["rev-list", "--max-parents=0", "HEAD"]
293
+ const result = yield* command(repository.worktree, args)
294
+ if (result.exitCode === 0)
295
+ return result.text
296
+ .split("\n")
297
+ .map((item) => item.trim())
298
+ .filter(Boolean)
299
+ .toSorted()
300
+ // `rev-parse -q --verify` exits 1 only when HEAD doesn't resolve, i.e. it is unborn.
301
+ const verify = yield* command(repository.worktree, ["rev-parse", "-q", "--verify", "HEAD"])
302
+ if (verify.exitCode === 1) return []
303
+ return yield* new CommandError({ args, exitCode: result.exitCode })
304
+ })
305
+
306
+ const head = Effect.fn("Git.history.head")(function* (repository: Repository) {
307
+ const result = yield* run(repository.worktree, proc, ["rev-parse", "HEAD"])
308
+ if (result.exitCode !== 0) return undefined
309
+ return result.text.trim() || undefined
310
+ })
311
+
312
+ const branch = Effect.fn("Git.history.branch")(function* (repository: Repository) {
313
+ const result = yield* run(repository.worktree, proc, ["symbolic-ref", "--quiet", "--short", "HEAD"])
314
+ if (result.exitCode !== 0) return undefined
315
+ return result.text.trim() || undefined
316
+ })
317
+
318
+ const remoteHead = Effect.fn("Git.history.defaultRemoteBranch")(function* (
319
+ repository: Repository,
320
+ remoteName = "origin",
321
+ ) {
322
+ const result = yield* run(repository.worktree, proc, ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`])
323
+ if (result.exitCode !== 0) return undefined
324
+ return result.text.trim().replace(new RegExp(`^refs/remotes/${remoteName}/`), "") || undefined
325
+ })
326
+
327
+ const operation = Effect.fnUntraced(function* (
328
+ operation: OperationError["operation"],
329
+ directory: AbsolutePath,
330
+ args: string[],
331
+ ) {
332
+ const result = yield* execute(directory, proc, args).pipe(Effect.mapError(spawnFailure(operation, directory)))
333
+ if (result.exitCode === 0) return
334
+ return yield* commandFailure(operation, directory, result)
335
+ })
336
+
337
+ const clone = Effect.fn("Git.repo.clone")(function* (input: {
338
+ remote: string
339
+ directory: AbsolutePath
340
+ branch?: string
341
+ depth?: number
342
+ }) {
343
+ yield* operation("clone", AbsolutePath.make(path.dirname(input.directory)), [
344
+ "clone",
345
+ "--depth",
346
+ String(input.depth ?? 100),
347
+ ...(input.branch ? ["--branch", input.branch] : []),
348
+ "--",
349
+ input.remote,
350
+ input.directory,
351
+ ])
352
+ const repository = yield* discover(input.directory)
353
+ if (repository) return repository
354
+ return yield* new OperationError({
355
+ operation: "clone",
356
+ directory: input.directory,
357
+ message: "Cloned repository could not be opened",
358
+ })
359
+ })
360
+
361
+ const fetch = Effect.fn("Git.sync.fetchRemotes")(function* (
362
+ repository: Repository,
363
+ input: { prune?: boolean } = {},
364
+ ) {
365
+ yield* operation("fetch", repository.worktree, ["fetch", "--all", ...(input.prune === false ? [] : ["--prune"])])
366
+ })
367
+
368
+ const fetchBranch = Effect.fn("Git.sync.fetchBranch")(function* (
369
+ repository: Repository,
370
+ input: { remote?: string; branch: string; force?: boolean },
371
+ ) {
372
+ const remoteName = input.remote ?? "origin"
373
+ const spec = `refs/heads/${input.branch}:refs/remotes/${remoteName}/${input.branch}`
374
+ yield* operation("fetch", repository.worktree, ["fetch", remoteName, input.force === false ? spec : `+${spec}`])
375
+ })
376
+
377
+ const checkout = Effect.fn("Git.sync.checkoutRemoteBranch")(function* (
378
+ repository: Repository,
379
+ input: { remote?: string; branch: string; reset?: boolean },
380
+ ) {
381
+ const remoteName = input.remote ?? "origin"
382
+ yield* operation("checkout", repository.worktree, [
383
+ "checkout",
384
+ ...(input.reset === false ? [input.branch] : ["-B", input.branch, `${remoteName}/${input.branch}`]),
385
+ ])
386
+ })
387
+
388
+ const reset = Effect.fn("Git.sync.resetHard")(function* (repository: Repository, revision: string) {
389
+ yield* operation("reset", repository.worktree, ["reset", "--hard", revision])
390
+ })
391
+
392
+ const repositoryArgs = (repository: Repository, args: string[]) => [
393
+ "--git-dir",
394
+ repository.gitDirectory,
395
+ "--work-tree",
396
+ repository.worktree,
397
+ ...args,
398
+ ]
399
+
400
+ const repositoryRun = (
401
+ operationName: OperationError["operation"],
402
+ repository: Repository,
403
+ args: string[],
404
+ options?: RepositoryOptions,
405
+ ) =>
406
+ proc
407
+ .run(
408
+ ChildProcess.make(gitExecutable(), repositoryArgs(repository, args), {
409
+ cwd: repository.worktree,
410
+ env: options?.index ? { ...options.env, GIT_INDEX_FILE: options.index } : options?.env,
411
+ extendEnv: true,
412
+ }),
413
+ { stdin: options?.stdin, maxOutputBytes: options?.maxOutputBytes },
414
+ )
415
+ .pipe(Effect.mapError(spawnFailure(operationName, repository.worktree)))
416
+
417
+ const repositoryOperation = Effect.fnUntraced(function* (
418
+ operationName: OperationError["operation"],
419
+ repository: Repository,
420
+ args: string[],
421
+ options?: RepositoryOptions,
422
+ ) {
423
+ const result = yield* repositoryRun(operationName, repository, args, options)
424
+ const text = result.stdout.toString("utf8")
425
+ const stderr = result.stderr.toString("utf8")
426
+ if (result.exitCode === 0) return { text, stderr, truncated: result.stdoutTruncated }
427
+ return yield* commandFailure(operationName, repository.worktree, { text, stderr })
428
+ })
429
+
430
+ /**
431
+ * On Windows, Git exits non-zero instead of reusing a loose object that another process is finalizing at the
432
+ * same moment. Objects are content-addressed, so one of at most two retries finds that copy in place. Only a Git
433
+ * exit is retried, never a failure to start Git, and other platforms fail on the first attempt.
434
+ */
435
+ const retryConcurrentObjectWrite = <A, R>(effect: Effect.Effect<A, OperationError, R>) =>
436
+ process.platform === "win32"
437
+ ? effect.pipe(
438
+ Effect.retry({
439
+ times: 2,
440
+ schedule: Schedule.spaced("50 millis"),
441
+ while: (error) => error.cause === undefined,
442
+ }),
443
+ )
444
+ : effect
445
+
446
+ /**
447
+ * A new store is initialized in a temporary sibling directory and renamed into
448
+ * place, so processes racing to create the same store never observe or write a
449
+ * half-initialized one; the loser discards its copy and adopts the winner's.
450
+ */
451
+ const create = Effect.fn("Git.repo.create")(function* (input: {
452
+ worktree: AbsolutePath
453
+ gitDirectory: AbsolutePath
454
+ seed?: Repository
455
+ }) {
456
+ const repository = new Repository({
457
+ worktree: input.worktree,
458
+ gitDirectory: input.gitDirectory,
459
+ commonDirectory: input.gitDirectory,
460
+ })
461
+ if (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD"))) {
462
+ yield* initRepository({ ...input, directory: input.gitDirectory })
463
+ return repository
464
+ }
465
+ const temporaryDirectory = AbsolutePath.make(`${input.gitDirectory}.init-${uniqueSuffix()}`)
466
+ yield* Effect.gen(function* () {
467
+ yield* initRepository({ ...input, directory: temporaryDirectory })
468
+ const renamed = yield* fs.rename(temporaryDirectory, input.gitDirectory).pipe(Effect.exit)
469
+ if (Exit.isSuccess(renamed) || (yield* fs.existsSafe(path.join(input.gitDirectory, "HEAD")))) return
470
+ return yield* new OperationError({
471
+ operation: "create",
472
+ directory: input.gitDirectory,
473
+ message: "Failed to move Git storage into place",
474
+ cause: Cause.squash(renamed.cause),
475
+ })
476
+ }).pipe(Effect.ensuring(fs.remove(temporaryDirectory, { recursive: true, force: true }).pipe(Effect.ignore)))
477
+ return repository
478
+ })
479
+
480
+ const initRepository = Effect.fnUntraced(function* (input: {
481
+ worktree: AbsolutePath
482
+ gitDirectory: AbsolutePath
483
+ directory: AbsolutePath
484
+ seed?: Repository
485
+ }) {
486
+ const operationError = (message: string) => (cause: unknown) =>
487
+ new OperationError({ operation: "create", directory: input.gitDirectory, message, cause })
488
+ yield* fs.ensureDir(input.directory).pipe(Effect.mapError(operationError("Failed to create Git storage")))
489
+ yield* repositoryOperation(
490
+ "create",
491
+ new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
492
+ ["init"],
493
+ )
494
+ yield* Effect.gen(function* () {
495
+ yield* fs.writeFileString(path.join(input.directory, snapshotConfigFile), snapshotConfig)
496
+ const config = path.join(input.directory, "config")
497
+ const current = yield* fs.readFileString(config)
498
+ if (current.includes(snapshotConfigInclude)) return
499
+ yield* fs.writeFileString(config, `${current.endsWith("\n") ? "\n" : "\n\n"}${snapshotConfigInclude}`, {
500
+ flag: "a",
501
+ })
502
+ }).pipe(Effect.mapError(operationError("Failed to configure Git storage")))
503
+ if (!input.seed) return
504
+ yield* fs
505
+ .ensureDir(path.join(input.directory, "objects", "info"))
506
+ .pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
507
+ yield* fs
508
+ .writeFileString(
509
+ path.join(input.directory, "objects", "info", "alternates"),
510
+ path.join(input.seed.commonDirectory, "objects") + "\n",
511
+ )
512
+ .pipe(Effect.mapError(operationError("Failed to configure shared Git objects")))
513
+ const index = path.join(input.directory, "index")
514
+ yield* seedIndex(
515
+ new Repository({ worktree: input.worktree, gitDirectory: input.directory, commonDirectory: input.directory }),
516
+ input.seed,
517
+ index,
518
+ ).pipe(
519
+ Effect.catch(() => fs.remove(index, { force: true })),
520
+ Effect.ignore,
521
+ )
522
+ })
523
+
524
+ /**
525
+ * Both commands only read the index, so they never take `index.lock`. Two parallel processes beat one combined
526
+ * `ls-files -m -o`, whose lstat pass is not threaded like diff-files'.
527
+ */
528
+ const listChanges = Effect.fnUntraced(function* (
529
+ repository: Repository,
530
+ scope: RelativePath,
531
+ index?: string,
532
+ excludeFrom?: string,
533
+ ) {
534
+ const list = (args: string[]) =>
535
+ repositoryOperation("refresh", repository, args, { index }).pipe(
536
+ // Embedded repositories are listed as `dir/`; update-index records them as gitlinks.
537
+ Effect.map((result) => nuls(result.text).map((file) => RelativePath.make(file.replace(/\/$/, "")))),
538
+ )
539
+ const [tracked, untracked] = yield* Effect.all(
540
+ [
541
+ list(["diff-files", "--name-only", "-z", "--", literalPathspec(scope)]),
542
+ list([
543
+ "ls-files",
544
+ "--others",
545
+ ...(excludeFrom ? [`--exclude-from=${excludeFrom}`] : []),
546
+ "--exclude-standard",
547
+ "-z",
548
+ "--",
549
+ literalPathspec(scope),
550
+ ]),
551
+ ],
552
+ { concurrency: 2 },
553
+ )
554
+ return { tracked, untracked }
555
+ })
556
+
557
+ const updateIndex = Effect.fnUntraced(function* (input: {
558
+ repository: Repository
559
+ changes: { tracked: readonly RelativePath[]; untracked: readonly RelativePath[] }
560
+ ignores?: Repository
561
+ maximumUntrackedFileBytes?: number
562
+ index?: string
563
+ excluded?: ReadonlySet<RelativePath>
564
+ }) {
565
+ const candidates = [...input.changes.tracked, ...input.changes.untracked]
566
+ if (!candidates.length) return { skipped: [] }
567
+ const excluded =
568
+ input.excluded ??
569
+ (input.ignores ? yield* ignored({ repository: input.ignores, paths: candidates }) : new Set<RelativePath>())
570
+ const maximum = input.maximumUntrackedFileBytes
571
+ const skipped = maximum
572
+ ? (yield* Effect.forEach(
573
+ input.changes.untracked.filter((item) => !excluded.has(item)),
574
+ (item) =>
575
+ fs.stat(path.join(input.repository.worktree, item)).pipe(
576
+ Effect.map((info) => (info.type === "File" && Number(info.size) > maximum ? item : undefined)),
577
+ Effect.orElseSucceed(() => undefined),
578
+ ),
579
+ { concurrency: 8 },
580
+ )).filter((item): item is RelativePath => item !== undefined)
581
+ : []
582
+ const skip = new Set(skipped)
583
+ const added = candidates.filter((item) => !excluded.has(item) && !skip.has(item))
584
+ // Untracked paths are not in the index, so only tracked paths that are now ignored need removing.
585
+ const removed = input.changes.tracked.filter((item) => excluded.has(item))
586
+ // update-index takes literal paths, so large lists avoid add's quadratic pathspec matching.
587
+ if (removed.length)
588
+ yield* repositoryOperation("refresh", input.repository, ["update-index", "--force-remove", "-z", "--stdin"], {
589
+ stdin: removed.join("\0") + "\0",
590
+ index: input.index,
591
+ })
592
+ // update-index drops a tracked file replaced by an embedded repository; a second line for the same path,
593
+ // in the same call, records its gitlink. For a path that already is a gitlink the repeat is a no-op.
594
+ const embedded = (yield* Effect.forEach(
595
+ input.changes.tracked.filter((item) => !excluded.has(item)),
596
+ (item) =>
597
+ fs
598
+ .existsSafe(path.join(input.repository.worktree, item, ".git"))
599
+ .pipe(Effect.map((found) => (found ? item : undefined))),
600
+ { concurrency: 8 },
601
+ )).filter((item): item is RelativePath => item !== undefined)
602
+ if (added.length)
603
+ yield* retryConcurrentObjectWrite(
604
+ repositoryOperation(
605
+ "refresh",
606
+ input.repository,
607
+ ["update-index", "--add", "--remove", "--replace", "-z", "--stdin"],
608
+ { stdin: [...added, ...embedded].join("\0") + "\0", index: input.index },
609
+ ),
610
+ )
611
+ return { skipped }
612
+ })
613
+
614
+ const refresh = Effect.fn("Git.index.refresh")(function* (input: {
615
+ repository: Repository
616
+ scope: RelativePath
617
+ ignores?: Repository
618
+ maximumUntrackedFileBytes?: number
619
+ }) {
620
+ return yield* updateIndex({ ...input, changes: yield* listChanges(input.repository, input.scope) })
621
+ })
622
+
623
+ const ignored = Effect.fn("Git.index.ignored")(function* (input: {
624
+ repository: Repository
625
+ paths: readonly RelativePath[]
626
+ }) {
627
+ if (!input.paths.length) return new Set<RelativePath>()
628
+ const result = yield* repositoryRun(
629
+ "list_files",
630
+ input.repository,
631
+ ["check-ignore", "--no-index", "--stdin", "-z"],
632
+ { stdin: input.paths.join("\0") + "\0" },
633
+ )
634
+ // Exit 1: none of the paths are ignored.
635
+ if (result.exitCode !== 0 && result.exitCode !== 1)
636
+ return yield* new OperationError({
637
+ operation: "list_files",
638
+ directory: input.repository.worktree,
639
+ message: result.stderr.toString("utf8").trim() || "Failed to check ignored paths",
640
+ })
641
+ return new Set(nuls(result.stdout.toString("utf8")).map((file) => RelativePath.make(file)))
642
+ })
643
+
644
+ const writeTree = Effect.fn("Git.tree.write")(function* (repository: Repository, index?: string) {
645
+ const tree = (yield* retryConcurrentObjectWrite(
646
+ repositoryOperation("write_tree", repository, ["write-tree"], { index }),
647
+ )).text.trim()
648
+ if (/^[0-9a-f]{40,64}$/.test(tree)) return TreeID.make(tree)
649
+ return yield* new OperationError({
650
+ operation: "write_tree",
651
+ directory: repository.worktree,
652
+ message: `Invalid tree ID: ${tree}`,
653
+ })
654
+ })
655
+
656
+ const indexFile = (repository: Repository) => path.join(repository.gitDirectory, "index")
657
+ /** Git only replaces an index by renaming a new file into place, so every write changes its inode. */
658
+ const indexFingerprint = (file: string) =>
659
+ fs.stat(file).pipe(
660
+ Effect.map((info) =>
661
+ [Option.getOrUndefined(info.ino), info.size, Option.getOrUndefined(info.mtime)?.getTime()].join(":"),
662
+ ),
663
+ Effect.orElseSucceed(() => undefined),
664
+ )
665
+
666
+ /** A copied index must keep the timestamp Git uses to detect racily clean entries. */
667
+ const copyIndex = Effect.fnUntraced(function* (from: string, to: string) {
668
+ const info = yield* fs.stat(from)
669
+ yield* fs.copyFile(from, to)
670
+ const mtime = Option.getOrUndefined(info.mtime)
671
+ if (mtime)
672
+ yield* fs
673
+ .utimes(
674
+ to,
675
+ Option.getOrElse(info.atime, () => mtime),
676
+ mtime,
677
+ )
678
+ .pipe(Effect.ignore)
679
+ })
680
+
681
+ /**
682
+ * Copy the source index into the store. A split index names a shared index file in
683
+ * its own Git directory, so those files are linked in just long enough to rewrite the
684
+ * copy as a complete index.
685
+ */
686
+ const seedIndex = Effect.fnUntraced(function* (store: Repository, source: Repository, target: string) {
687
+ yield* copyIndex(path.join(source.gitDirectory, "index"), target)
688
+ const shared = (yield* fs.readDirectory(source.gitDirectory)).filter((entry) => entry.startsWith("sharedindex."))
689
+ if (shared.length === 0) return
690
+ yield* Effect.forEach(shared, (entry) => {
691
+ const from = path.join(source.gitDirectory, entry)
692
+ const to = path.join(store.gitDirectory, entry)
693
+ return fs.link(from, to).pipe(Effect.catch(() => fs.copyFile(from, to)))
694
+ }).pipe(
695
+ Effect.andThen(repositoryOperation("refresh", store, ["update-index", "--no-split-index"], { index: target })),
696
+ Effect.ensuring(
697
+ Effect.forEach(shared, (entry) =>
698
+ fs.remove(path.join(store.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
699
+ ),
700
+ ),
701
+ )
702
+ })
703
+
704
+ /**
705
+ * Run index writes against a temporary index, then rename it over the store's
706
+ * index. Processes never contend on `index.lock`, an interrupted or killed
707
+ * writer cannot leave a partial index behind, and a stale lock is irrelevant.
708
+ * Git never writes an index in place, it writes a lock file and renames it over
709
+ * the temporary name, so a hard-linked temporary index leaves the store's index
710
+ * untouched; a copy is the fallback when linking fails. The index is only a stat
711
+ * cache over the object store; when writers race, the last rename wins and the
712
+ * next capture reconciles against the worktree.
713
+ */
714
+ const withTemporaryIndex = <A, E, R>(repository: Repository, use: (index: string) => Effect.Effect<A, E, R>) =>
715
+ Effect.acquireUseRelease(
716
+ Effect.gen(function* () {
717
+ const current = indexFile(repository)
718
+ const index = temporaryIndex(repository)
719
+ if (!(yield* fs.existsSafe(current))) return index
720
+ const linked = yield* fs.link(current, index).pipe(
721
+ Effect.as(true),
722
+ Effect.orElseSucceed(() => false),
723
+ )
724
+ if (linked) return index
725
+ yield* copyIndex(current, index).pipe(
726
+ Effect.mapError(
727
+ (cause) =>
728
+ new OperationError({
729
+ operation: "refresh",
730
+ directory: repository.gitDirectory,
731
+ message: "Failed to prepare a temporary index",
732
+ cause,
733
+ }),
734
+ ),
735
+ )
736
+ return index
737
+ }),
738
+ (index) =>
739
+ Effect.gen(function* () {
740
+ const value = yield* use(index)
741
+ const installed = yield* Effect.uninterruptible(
742
+ Effect.gen(function* () {
743
+ // Fingerprint before the rename, so a concurrent writer's index can never be paired with this tree.
744
+ const fingerprint = yield* indexFingerprint(index)
745
+ const renamed = yield* fs.rename(index, indexFile(repository)).pipe(
746
+ // Windows reports a transient sharing violation while another process reads the index.
747
+ Effect.retry({ times: 3, schedule: Schedule.spaced("20 millis") }),
748
+ Effect.as(true),
749
+ Effect.orElseSucceed(() => false),
750
+ )
751
+ return renamed ? fingerprint : undefined
752
+ }),
753
+ )
754
+ return { value, installed }
755
+ }),
756
+ (index) => fs.remove(index, { force: true }).pipe(Effect.ignore),
757
+ )
758
+
759
+ // A clean capture returns the tree last written from the exact index it scanned.
760
+ const lastCaptures = new Map<string, { readonly fingerprint: string; readonly tree: TreeID }>()
761
+ const preparedStores = new Set<string>()
762
+ const pendingCaptures = new Map<string, Deferred.Deferred<TreeID, OperationError>>()
763
+ // Untracked files skipped for size, by path, with the stamp they had when skipped.
764
+ const oversizedFiles = new Map<string, Map<RelativePath, string>>()
765
+
766
+ /**
767
+ * Changes are listed against the temporary index they are written to, never the
768
+ * store's index, which another process may replace at any moment. Each tree is
769
+ * therefore exactly its own index plus the worktree changes against it.
770
+ */
771
+ const attemptCapture = Effect.fnUntraced(function* (input: CaptureInput) {
772
+ const sourceExclude = input.ignores ? path.join(input.ignores.commonDirectory, "info", "exclude") : undefined
773
+ const excludeFrom = sourceExclude && (yield* fs.existsSafe(sourceExclude)) ? sourceExclude : undefined
774
+ const result = yield* withTemporaryIndex(input.repository, (index) =>
775
+ Effect.gen(function* () {
776
+ const scanned = yield* indexFingerprint(index)
777
+ const changes = yield* Effect.forEach(
778
+ input.scopes,
779
+ (scope) => listChanges(input.repository, scope, index, excludeFrom),
780
+ { concurrency: "unbounded" },
781
+ )
782
+ const last = lastCaptures.get(input.repository.gitDirectory)
783
+ const untracked = changes.flatMap((change) => change.untracked)
784
+ const oversized = oversizedFiles.get(input.repository.gitDirectory)
785
+ const stillOversized = new Set(
786
+ oversized
787
+ ? (yield* Effect.forEach(
788
+ untracked.filter((file) => oversized.has(file)),
789
+ (file) =>
790
+ oversizedStamp(input, file).pipe(
791
+ Effect.map((current) => (current && current === oversized.get(file) ? file : undefined)),
792
+ ),
793
+ { concurrency: 8 },
794
+ )).filter((file): file is RelativePath => file !== undefined)
795
+ : [],
796
+ )
797
+ // Paths the source ignores are listed as untracked on every scan; they leave the index unchanged.
798
+ const excluded =
799
+ scanned && last?.fingerprint === scanned && changes.every((change) => !change.tracked.length)
800
+ ? input.ignores
801
+ ? yield* ignored({
802
+ repository: input.ignores,
803
+ paths: untracked.filter((file) => !stillOversized.has(file)),
804
+ })
805
+ : new Set<RelativePath>()
806
+ : undefined
807
+ if (last && excluded && untracked.every((file) => excluded.has(file) || stillOversized.has(file)))
808
+ return last.tree
809
+ const skipped = (yield* Effect.forEach(changes, (change) =>
810
+ updateIndex({ ...input, changes: change, index, excluded }),
811
+ )).flatMap((update) => update.skipped)
812
+ oversizedFiles.set(
813
+ input.repository.gitDirectory,
814
+ new Map(
815
+ (yield* Effect.forEach(
816
+ skipped,
817
+ (file) => oversizedStamp(input, file).pipe(Effect.map((value) => [file, value] as const)),
818
+ { concurrency: 8 },
819
+ )).filter((entry): entry is readonly [RelativePath, string] => entry[1] !== undefined),
820
+ ),
821
+ )
822
+ return yield* writeTree(input.repository, index)
823
+ }),
824
+ )
825
+ if (result.installed)
826
+ lastCaptures.set(input.repository.gitDirectory, { fingerprint: result.installed, tree: result.value })
827
+ if (!result.installed) lastCaptures.delete(input.repository.gitDirectory)
828
+ return result.value
829
+ })
830
+
831
+ const oversizedStamp = (input: CaptureInput, file: RelativePath) =>
832
+ fs.stat(path.join(input.repository.worktree, file)).pipe(
833
+ Effect.map((info) =>
834
+ input.maximumUntrackedFileBytes && info.type === "File" && Number(info.size) > input.maximumUntrackedFileBytes
835
+ ? `${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`
836
+ : undefined,
837
+ ),
838
+ Effect.orElseSucceed(() => undefined),
839
+ )
840
+
841
+ /**
842
+ * Callers queued behind a running capture share the next one, which starts after they all asked, so it still
843
+ * sees every change made before each call.
844
+ */
845
+ const captureTree = Effect.fn("Git.tree.capture")(function* (input: CaptureInput) {
846
+ const key = JSON.stringify([
847
+ input.repository.gitDirectory,
848
+ input.repository.worktree,
849
+ input.scopes,
850
+ input.ignores?.gitDirectory,
851
+ input.maximumUntrackedFileBytes,
852
+ ])
853
+ const pending = pendingCaptures.get(key)
854
+ if (pending) {
855
+ const exit = yield* Effect.exit(Deferred.await(pending))
856
+ if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) return yield* exit
857
+ }
858
+ const deferred = Deferred.makeUnsafe<TreeID, OperationError>()
859
+ const release = () => {
860
+ if (pendingCaptures.get(key) === deferred) pendingCaptures.delete(key)
861
+ }
862
+ return yield* Effect.uninterruptibleMask((restore) => {
863
+ pendingCaptures.set(key, deferred)
864
+ return restore(captureLocked(input, release)).pipe(
865
+ Effect.onExit((exit) => {
866
+ release()
867
+ return Deferred.done(deferred, exit)
868
+ }),
869
+ )
870
+ })
871
+ })
872
+
873
+ const captureLocked = (input: CaptureInput, onStart: () => void) =>
874
+ locked(
875
+ input.repository,
876
+ Effect.gen(function* () {
877
+ onStart()
878
+ if (!preparedStores.has(input.repository.gitDirectory)) {
879
+ preparedStores.add(input.repository.gitDirectory)
880
+ yield* sweepTemporaryIndexes(input.repository)
881
+ yield* ensureSnapshotConfig(input.repository)
882
+ }
883
+ return yield* attemptCapture(input).pipe(
884
+ Effect.catch((error) =>
885
+ Effect.gen(function* () {
886
+ if (!(yield* isIndexUnreadable(input.repository))) return yield* error
887
+ yield* Effect.logWarning("rebuilding unreadable snapshot index", {
888
+ directory: input.repository.gitDirectory,
889
+ message: error.message,
890
+ })
891
+ yield* rebuildIndex(input.repository, input.ignores)
892
+ return yield* attemptCapture(input)
893
+ }),
894
+ ),
895
+ )
896
+ }),
897
+ )
898
+
899
+ /**
900
+ * Only an index Git itself cannot read is rebuilt, decided by exit status rather
901
+ * than by localized messages. Other failures, such as an unreadable worktree
902
+ * file or a process that could not start, surface unchanged.
903
+ */
904
+ const isIndexUnreadable = Effect.fnUntraced(function* (repository: Repository) {
905
+ if (!(yield* fs.existsSafe(indexFile(repository)))) return false
906
+ return yield* repositoryOperation("refresh", repository, [
907
+ "ls-files",
908
+ "-z",
909
+ "--",
910
+ literalPathspec(".opencode-probe"),
911
+ ]).pipe(Effect.match({ onSuccess: () => false, onFailure: (error) => error.cause === undefined }))
912
+ })
913
+
914
+ const rebuildIndex = Effect.fnUntraced(function* (repository: Repository, source?: Repository) {
915
+ lastCaptures.delete(repository.gitDirectory)
916
+ const temporary = temporaryIndex(repository)
917
+ // The source's stat cache and cache-tree spare recovery from rehashing every tracked file.
918
+ const copied = source
919
+ ? yield* seedIndex(repository, source, temporary).pipe(
920
+ Effect.as(true),
921
+ Effect.orElseSucceed(() => false),
922
+ )
923
+ : false
924
+ yield* (
925
+ copied ? fs.rename(temporary, indexFile(repository)) : fs.remove(indexFile(repository), { force: true })
926
+ ).pipe(Effect.ignore, Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)))
927
+ })
928
+
929
+ // Stores created by earlier releases would otherwise keep their original settings; only OpenCode's include file is rewritten, never `config`.
930
+ const ensureSnapshotConfig = Effect.fnUntraced(function* (repository: Repository) {
931
+ const file = path.join(repository.gitDirectory, snapshotConfigFile)
932
+ const current = yield* fs.readFileStringSafe(file).pipe(Effect.orElseSucceed(() => undefined))
933
+ if (current === undefined || current === snapshotConfig) return
934
+ // Concurrent Git processes must never read a partially written file.
935
+ const temporary = `${file}.${uniqueSuffix()}`
936
+ yield* fs
937
+ .writeFileString(temporary, snapshotConfig)
938
+ .pipe(
939
+ Effect.andThen(fs.rename(temporary, file)),
940
+ Effect.ignore,
941
+ Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)),
942
+ )
943
+ })
944
+
945
+ const temporaryIndex = (repository: Repository) =>
946
+ path.join(repository.gitDirectory, `${temporaryIndexPrefix}${Date.now()}-${uniqueSuffix()}`)
947
+
948
+ /**
949
+ * Temporary indexes left by killed processes. Age comes from the creation time in
950
+ * the name, because a hard-linked index keeps the store index's old mtime; live
951
+ * captures finish long before the cutoff.
952
+ */
953
+ const sweepTemporaryIndexes = Effect.fnUntraced(function* (repository: Repository) {
954
+ const cutoff = Date.now() - 60 * 60 * 1000
955
+ const entries = yield* fs.readDirectory(repository.gitDirectory).pipe(Effect.orElseSucceed(() => []))
956
+ yield* Effect.forEach(
957
+ entries.filter(
958
+ (entry) =>
959
+ entry.startsWith(temporaryIndexPrefix) &&
960
+ Number(entry.slice(temporaryIndexPrefix.length).split("-")[0]) < cutoff,
961
+ ),
962
+ (entry) => fs.remove(path.join(repository.gitDirectory, entry), { force: true }).pipe(Effect.ignore),
963
+ { discard: true },
964
+ )
965
+ })
966
+
967
+ const treeFiles = Effect.fn("Git.tree.files")(function* (input: {
968
+ repository: Repository
969
+ from: TreeID
970
+ to: TreeID
971
+ }) {
972
+ // Undo needs both paths of a rename, not only its destination.
973
+ return nuls(
974
+ (yield* repositoryOperation("list_files", input.repository, [
975
+ "diff",
976
+ "--name-only",
977
+ "--no-renames",
978
+ "-z",
979
+ input.from,
980
+ input.to,
981
+ ])).text,
982
+ ).map((file) => RelativePath.make(file))
983
+ })
984
+
985
+ const treeDiff = Effect.fn("Git.tree.diff")(function* (input: {
986
+ repository: Repository
987
+ from: TreeID
988
+ to: TreeID
989
+ context?: number
990
+ paths?: readonly RelativePath[]
991
+ }) {
992
+ if (input.paths?.length === 0) return []
993
+ const groups = input.paths ? pathGroups(input.paths) : [undefined]
994
+ const diffs: FileDiff.Info[] = []
995
+ let patchBudget = VcsPatch.MAX_TOTAL_PATCH_BYTES
996
+ for (const paths of groups) {
997
+ const group = yield* diffGroup({ ...input, paths }, patchBudget)
998
+ diffs.push(...group.diffs)
999
+ patchBudget = group.truncated ? 0 : patchBudget - group.patchBytes
1000
+ }
1001
+ return diffs
1002
+ })
1003
+
1004
+ const diffGroup = Effect.fnUntraced(function* (
1005
+ input: { repository: Repository; from: TreeID; to: TreeID; context?: number; paths?: readonly RelativePath[] },
1006
+ patchBudget: number,
1007
+ ) {
1008
+ const args = ["--no-renames", input.from, input.to, "--", ...(input.paths ?? [])]
1009
+ // Patch headers have no -z form: unquoted paths keep chunksByFile matching non-ASCII names.
1010
+ const [names, numbers, patch] = yield* Effect.all(
1011
+ [
1012
+ repositoryOperation("diff", input.repository, [
1013
+ "--literal-pathspecs",
1014
+ "diff",
1015
+ "--name-status",
1016
+ "-z",
1017
+ ...args,
1018
+ ]),
1019
+ repositoryOperation("diff", input.repository, ["--literal-pathspecs", "diff", "--numstat", "-z", ...args]),
1020
+ patchBudget > 0
1021
+ ? repositoryOperation(
1022
+ "diff",
1023
+ input.repository,
1024
+ [
1025
+ "--literal-pathspecs",
1026
+ "-c",
1027
+ "core.quotepath=false",
1028
+ "diff",
1029
+ "--no-ext-diff",
1030
+ `--unified=${input.context ?? 3}`,
1031
+ ...args,
1032
+ ],
1033
+ { maxOutputBytes: patchBudget },
1034
+ )
1035
+ : Effect.succeed({ text: "", stderr: "", truncated: true }),
1036
+ ],
1037
+ { concurrency: 3 },
1038
+ )
1039
+ const statuses = nuls(names.text)
1040
+ const files = statuses.flatMap((code, index) => {
1041
+ const file = statuses[index + 1]
1042
+ if (index % 2 !== 0 || !file) return []
1043
+ return [
1044
+ {
1045
+ file: RelativePath.make(file),
1046
+ status: code.startsWith("A") ? "added" : code.startsWith("D") ? "deleted" : "modified",
1047
+ } as const,
1048
+ ]
1049
+ })
1050
+ const stats = new Map(
1051
+ nuls(numbers.text).flatMap((line) => {
1052
+ const [additions, deletions, ...file] = line.split("\t")
1053
+ if (!additions || !deletions || file.length === 0) return []
1054
+ return [
1055
+ [
1056
+ file.join("\t"),
1057
+ additions === "-" || deletions === "-"
1058
+ ? { binary: true, additions: 0, deletions: 0 }
1059
+ : { binary: false, additions: Number(additions), deletions: Number(deletions) },
1060
+ ] as const,
1061
+ ]
1062
+ }),
1063
+ )
1064
+ const patches = VcsPatch.chunksByFile(patch, (index) => files[index]?.file)
1065
+ return {
1066
+ diffs: files.map((entry) => {
1067
+ const stat = stats.get(entry.file)
1068
+ return {
1069
+ ...entry,
1070
+ additions: stat?.additions ?? 0,
1071
+ deletions: stat?.deletions ?? 0,
1072
+ patch: stat?.binary ? "" : (patches.get(entry.file) ?? VcsPatch.emptyPatch(entry.file)),
1073
+ } satisfies FileDiff.Info
1074
+ }),
1075
+ patchBytes: Buffer.byteLength(patch.text),
1076
+ truncated: patch.truncated,
1077
+ }
1078
+ })
1079
+
1080
+ const hasEntry = Effect.fnUntraced(function* (repository: Repository, tree: TreeID, file: RelativePath) {
1081
+ const text = (yield* repositoryOperation("restore", repository, [
1082
+ "ls-tree",
1083
+ "-z",
1084
+ tree,
1085
+ "--",
1086
+ literalPathspec(file),
1087
+ ])).text.replace(/\0$/, "")
1088
+ if (!text) return false
1089
+ if (!/^\d+\s+\w+\s+[0-9a-f]+\t/.test(text))
1090
+ return yield* new OperationError({
1091
+ operation: "restore",
1092
+ directory: repository.worktree,
1093
+ message: `Invalid tree entry for ${file}`,
1094
+ })
1095
+ return true
1096
+ })
1097
+
1098
+ const removePath = (repository: Repository, file: RelativePath) =>
1099
+ fs.remove(path.join(repository.worktree, file), { recursive: true, force: true }).pipe(
1100
+ Effect.mapError(
1101
+ (cause) =>
1102
+ new OperationError({
1103
+ operation: "restore",
1104
+ directory: repository.worktree,
1105
+ message: `Failed to remove ${file}`,
1106
+ cause,
1107
+ }),
1108
+ ),
1109
+ )
1110
+
1111
+ const pathsInTree = Effect.fnUntraced(function* (
1112
+ repository: Repository,
1113
+ tree: TreeID,
1114
+ files: readonly RelativePath[],
1115
+ ) {
1116
+ const pathspecs = files.map(literalPathspec)
1117
+ const fits = pathspecs.reduce((length, pathspec) => length + pathspec.length + 1, 0) <= argumentBudget
1118
+ const result = yield* repositoryOperation(
1119
+ "restore",
1120
+ repository,
1121
+ fits ? ["ls-tree", "-z", tree, "--", ...pathspecs] : ["ls-tree", "-r", "-t", "-z", "--full-tree", tree],
1122
+ )
1123
+ const listed = yield* Effect.forEach(nuls(result.text), (record) => {
1124
+ const match = /^\d+ \w+ [0-9a-f]+\t(.*)$/s.exec(record)
1125
+ if (match) return Effect.succeed(RelativePath.make(match[1]!))
1126
+ return Effect.fail(
1127
+ new OperationError({
1128
+ operation: "restore",
1129
+ directory: repository.worktree,
1130
+ message: `Invalid tree entry: ${record}`,
1131
+ }),
1132
+ )
1133
+ })
1134
+ return new Set(listed)
1135
+ })
1136
+
1137
+ /** Batched paths cost one ls-tree and one checkout per source tree instead of two processes per file. */
1138
+ const restore = Effect.fn("Git.tree.restore")(
1139
+ (input: { repository: Repository; files: ReadonlyMap<RelativePath, TreeID> }) =>
1140
+ locked(
1141
+ input.repository,
1142
+ Effect.gen(function* () {
1143
+ if (!input.files.size) return
1144
+ if (!canBatchRestore([...input.files.keys()]))
1145
+ return yield* Effect.forEach(
1146
+ input.files,
1147
+ ([file, tree]) =>
1148
+ Effect.gen(function* () {
1149
+ if (!(yield* hasEntry(input.repository, tree, file)))
1150
+ return yield* removePath(input.repository, file)
1151
+ yield* withTemporaryIndex(input.repository, (index) =>
1152
+ repositoryOperation(
1153
+ "restore",
1154
+ input.repository,
1155
+ ["checkout", tree, "--", literalPathspec(file)],
1156
+ {
1157
+ index,
1158
+ },
1159
+ ),
1160
+ )
1161
+ }),
1162
+ { discard: true },
1163
+ )
1164
+ const groups = new Map<TreeID, RelativePath[]>()
1165
+ input.files.forEach((tree, file) => groups.set(tree, [...(groups.get(tree) ?? []), file]))
1166
+ const plan = yield* Effect.forEach(groups, ([tree, files]) =>
1167
+ pathsInTree(input.repository, tree, files).pipe(
1168
+ Effect.map((present) => ({
1169
+ tree,
1170
+ present: files.filter((file) => present.has(file)),
1171
+ absent: files.filter((file) => !present.has(file)),
1172
+ })),
1173
+ ),
1174
+ )
1175
+ // Checkouts go first, so one failing removal cannot stop the other files from being restored.
1176
+ const checkouts = plan.filter((item) => item.present.length)
1177
+ if (checkouts.length)
1178
+ yield* withTemporaryIndex(input.repository, (index) =>
1179
+ Effect.forEach(
1180
+ checkouts,
1181
+ (item) =>
1182
+ repositoryOperation(
1183
+ "restore",
1184
+ input.repository,
1185
+ ["checkout", item.tree, "--pathspec-from-file=-", "--pathspec-file-nul"],
1186
+ { stdin: item.present.map(literalPathspec).join("\0") + "\0", index },
1187
+ ),
1188
+ { discard: true },
1189
+ ),
1190
+ )
1191
+ yield* Effect.forEach(
1192
+ plan.flatMap((item) => item.absent),
1193
+ (file) => removePath(input.repository, file),
1194
+ { concurrency: 16, discard: true },
1195
+ )
1196
+ }),
1197
+ ),
1198
+ )
1199
+
1200
+ /**
1201
+ * Snapshot trees have no refs, so Git's own repack and prune would treat every
1202
+ * snapshot as garbage. Packing instead hands pack-objects an explicit list of
1203
+ * every loose object (and, when combining, every object in the old packs), checks
1204
+ * the new index lists all of them, and only then deletes the loose copies and
1205
+ * the combined packs. Nothing is pruned, and objects are never delegated to the
1206
+ * source repository through alternates.
1207
+ */
1208
+ const packObjects = Effect.fn("Git.objects.pack")(function* (repository: Repository) {
1209
+ const objects = path.join(repository.gitDirectory, "objects")
1210
+ const packDirectory = path.join(objects, "pack")
1211
+ const loose = yield* looseObjects(objects)
1212
+ const packs = yield* localPacks(packDirectory)
1213
+ const combinePacks = packs.length >= packCountLimit
1214
+ if (loose.length < looseObjectLimit && !combinePacks) return
1215
+ yield* withPackLock(
1216
+ repository,
1217
+ Effect.gen(function* () {
1218
+ yield* sweepTemporaryPacks(packDirectory)
1219
+ const combined = combinePacks
1220
+ ? yield* Effect.forEach(packs, (pack) =>
1221
+ packIndex(repository, path.join(packDirectory, `${pack}.idx`)).pipe(
1222
+ Effect.map((oids) => ({ pack, oids })),
1223
+ ),
1224
+ )
1225
+ : []
1226
+ const objectIds = [...new Set([...loose.map((item) => item.oid), ...combined.flatMap((item) => item.oids)])]
1227
+ if (!objectIds.length) return
1228
+ const newPacks = (yield* repositoryOperation(
1229
+ "pack",
1230
+ repository,
1231
+ [
1232
+ "-c",
1233
+ "pack.threads=2",
1234
+ "-c",
1235
+ "pack.windowMemory=64m",
1236
+ "pack-objects",
1237
+ "-q",
1238
+ "--non-empty",
1239
+ path.join(packDirectory, "pack"),
1240
+ ],
1241
+ { stdin: objectIds.join("\n") + "\n" },
1242
+ )).text
1243
+ .split("\n")
1244
+ .map((line) => line.trim())
1245
+ .filter(Boolean)
1246
+ const packedIds = new Set(
1247
+ (yield* Effect.forEach(newPacks, (name) =>
1248
+ packIndex(repository, path.join(packDirectory, `pack-${name}.idx`)),
1249
+ )).flat(),
1250
+ )
1251
+ const missing = objectIds.filter((oid) => !packedIds.has(oid))
1252
+ if (missing.length)
1253
+ return yield* new OperationError({
1254
+ operation: "pack",
1255
+ directory: repository.gitDirectory,
1256
+ message: `Packed ${packedIds.size} objects but ${missing.length} are missing; nothing was removed`,
1257
+ })
1258
+ // Deletion is quick and must not stop halfway, which could strand a pack without its index.
1259
+ yield* Effect.uninterruptible(
1260
+ Effect.gen(function* () {
1261
+ yield* Effect.forEach(loose, (item) => fs.remove(item.file, { force: true }).pipe(Effect.ignore), {
1262
+ concurrency: 16,
1263
+ discard: true,
1264
+ })
1265
+ const newPackNames = new Set(newPacks.map((name) => `pack-${name}`))
1266
+ yield* Effect.forEach(
1267
+ combined.filter((item) => !newPackNames.has(item.pack)),
1268
+ (item) =>
1269
+ // The index goes first so readers never see an index without its pack.
1270
+ Effect.forEach(
1271
+ [".idx", ".pack", ".rev", ".bitmap", ".mtimes"],
1272
+ (extension) =>
1273
+ fs
1274
+ .remove(path.join(packDirectory, `${item.pack}${extension}`), { force: true })
1275
+ .pipe(Effect.ignore),
1276
+ { discard: true },
1277
+ ),
1278
+ { discard: true },
1279
+ )
1280
+ }),
1281
+ )
1282
+ }),
1283
+ )
1284
+ })
1285
+
1286
+ const looseObjects = Effect.fnUntraced(function* (objects: string) {
1287
+ const fanout = (yield* fs.readDirectory(objects).pipe(Effect.orElseSucceed(() => []))).filter((entry) =>
1288
+ /^[0-9a-f]{2}$/.test(entry),
1289
+ )
1290
+ const listed = yield* Effect.forEach(
1291
+ fanout,
1292
+ (prefix) =>
1293
+ fs.readDirectory(path.join(objects, prefix)).pipe(
1294
+ Effect.orElseSucceed(() => []),
1295
+ Effect.map((entries) =>
1296
+ entries
1297
+ .filter((entry) => /^[0-9a-f]{38}$|^[0-9a-f]{62}$/.test(entry))
1298
+ .map((entry) => ({ oid: prefix + entry, file: path.join(objects, prefix, entry) })),
1299
+ ),
1300
+ ),
1301
+ { concurrency: 16 },
1302
+ )
1303
+ return listed.flat()
1304
+ })
1305
+
1306
+ // Packs with a .keep marker or a promisor file belong to someone else's policy and are left alone.
1307
+ const localPacks = Effect.fnUntraced(function* (directory: string) {
1308
+ const entries = new Set(yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])))
1309
+ return [...entries]
1310
+ .filter((entry) => entry.startsWith("pack-") && entry.endsWith(".pack"))
1311
+ .map((entry) => entry.slice(0, -".pack".length))
1312
+ .filter(
1313
+ (pack) => entries.has(`${pack}.idx`) && !entries.has(`${pack}.keep`) && !entries.has(`${pack}.promisor`),
1314
+ )
1315
+ })
1316
+
1317
+ const packIndex = Effect.fnUntraced(function* (repository: Repository, file: string) {
1318
+ const bytes = yield* fs.readFile(file).pipe(
1319
+ Effect.mapError(
1320
+ (cause) =>
1321
+ new OperationError({
1322
+ operation: "pack",
1323
+ directory: repository.gitDirectory,
1324
+ message: `Failed to read ${file}`,
1325
+ cause,
1326
+ }),
1327
+ ),
1328
+ )
1329
+ const parsed = packIndexObjectIDs(bytes)
1330
+ if (parsed) return parsed
1331
+ const result = yield* repositoryOperation("pack", repository, ["show-index"], { stdin: bytes })
1332
+ return result.text.split("\n").flatMap((line) => {
1333
+ const oid = line.split(" ")[1]
1334
+ return oid ? [oid] : []
1335
+ })
1336
+ })
1337
+
1338
+ /**
1339
+ * pack-objects writes tmp_* files and renames them; leftovers mean a killed
1340
+ * process. A pack without its index is unreadable to Git, so removing one is
1341
+ * lossless; the age cutoff skips a pack whose index is still being renamed.
1342
+ */
1343
+ const sweepTemporaryPacks = Effect.fnUntraced(function* (directory: string) {
1344
+ const cutoff = Date.now() - 60 * 60 * 1000
1345
+ const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []))
1346
+ const indexed = new Set(entries.filter((entry) => entry.endsWith(".idx")).map((entry) => entry.slice(0, -4)))
1347
+ yield* Effect.forEach(
1348
+ entries.filter(
1349
+ (entry) =>
1350
+ entry.startsWith("tmp_") ||
1351
+ (entry.startsWith("pack-") && entry.endsWith(".pack") && !indexed.has(entry.slice(0, -5))),
1352
+ ),
1353
+ (entry) =>
1354
+ fs.stat(path.join(directory, entry)).pipe(
1355
+ Effect.flatMap((info) =>
1356
+ (Option.getOrUndefined(info.mtime)?.getTime() ?? 0) < cutoff
1357
+ ? fs.remove(path.join(directory, entry), { force: true })
1358
+ : Effect.void,
1359
+ ),
1360
+ Effect.ignore,
1361
+ ),
1362
+ { discard: true },
1363
+ )
1364
+ })
1365
+
1366
+ // Cross-process exclusion: concurrent packing would stay lossless but duplicate work and objects.
1367
+ const withPackLock = <A, E, R>(repository: Repository, effect: Effect.Effect<A, E, R>) => {
1368
+ const file = path.join(repository.gitDirectory, "opencode-pack.lock")
1369
+ return Effect.gen(function* () {
1370
+ const stale = yield* fs.stat(file).pipe(
1371
+ Effect.map((info) => (Option.getOrUndefined(info.mtime)?.getTime() ?? 0) < Date.now() - 60 * 60 * 1000),
1372
+ Effect.orElseSucceed(() => false),
1373
+ )
1374
+ if (stale) yield* fs.remove(file, { force: true }).pipe(Effect.ignore)
1375
+ const acquired = yield* fs.writeFileString(file, String(process.pid), { flag: "wx" }).pipe(
1376
+ Effect.as(true),
1377
+ Effect.orElseSucceed(() => false),
1378
+ )
1379
+ if (!acquired) return
1380
+ yield* effect.pipe(Effect.ensuring(fs.remove(file, { force: true }).pipe(Effect.ignore)))
1381
+ })
1382
+ }
1383
+
1384
+ const worktreeRun = Effect.fnUntraced(function* (
1385
+ operation: "create" | "remove" | "list",
1386
+ repository: Repository,
1387
+ args: string[],
1388
+ worktreeDirectory?: AbsolutePath,
1389
+ cwd = repository.worktree,
1390
+ ) {
1391
+ const result = yield* proc
1392
+ .run(ChildProcess.make(gitExecutable(), args, { cwd, extendEnv: true, stdin: "ignore" }))
1393
+ .pipe(
1394
+ Effect.mapError(
1395
+ (cause) => new WorktreeError({ operation, directory: worktreeDirectory, message: cause.message, cause }),
1396
+ ),
1397
+ )
1398
+ if (result.exitCode === 0) return result.stdout.toString("utf8")
1399
+ const message = result.stderr.toString("utf8").trim() || result.stdout.toString("utf8").trim() || "Git failed"
1400
+ return yield* new WorktreeError({
1401
+ operation,
1402
+ directory: worktreeDirectory,
1403
+ message,
1404
+ forceRequired: operation === "remove" && /contains modified or untracked files|is dirty/i.test(message),
1405
+ })
1406
+ })
1407
+
1408
+ const worktreeCreate = Effect.fn("Git.worktree.create")(function* (input: {
1409
+ repository: Repository
1410
+ directory: AbsolutePath
1411
+ ref?: string
1412
+ }) {
1413
+ yield* worktreeRun(
1414
+ "create",
1415
+ input.repository,
1416
+ ["worktree", "add", "--detach", "--", input.directory, input.ref ?? "HEAD"],
1417
+ input.directory,
1418
+ )
1419
+ const repository = yield* discover(input.directory)
1420
+ if (repository) return repository
1421
+ return yield* new WorktreeError({
1422
+ operation: "create",
1423
+ directory: input.directory,
1424
+ message: "Created worktree could not be opened",
1425
+ })
1426
+ })
1427
+
1428
+ const worktreeRemove = Effect.fn("Git.worktree.remove")(function* (input: {
1429
+ repository: Repository
1430
+ directory: AbsolutePath
1431
+ force: boolean
1432
+ }) {
1433
+ yield* worktreeRun(
1434
+ "remove",
1435
+ input.repository,
1436
+ ["worktree", "remove", ...(input.force ? ["--force"] : []), input.directory],
1437
+ input.directory,
1438
+ input.repository.commonDirectory,
1439
+ )
1440
+ })
1441
+
1442
+ const worktreeList = Effect.fn("Git.worktree.list")(function* (repository: Repository) {
1443
+ return (yield* worktreeRun("list", repository, ["worktree", "list", "--porcelain"]))
1444
+ .split("\n")
1445
+ .filter((line) => line.startsWith("worktree "))
1446
+ .map(
1447
+ (line, index) =>
1448
+ new Worktree({
1449
+ directory: AbsolutePath.make(resolvePath(repository.worktree, line.slice("worktree ".length).trim())),
1450
+ kind: index === 0 ? "main" : "linked",
1451
+ }),
1452
+ )
1453
+ })
1454
+
1455
+ return Service.of({
1456
+ repo: { discover, fingerprint, clone, create },
1457
+ remote: { get: remote },
1458
+ history: { head, branch, defaultRemoteBranch: remoteHead, rootCommits: roots },
1459
+ sync: { fetchRemotes: fetch, fetchBranch, checkoutRemoteBranch: checkout, resetHard: reset },
1460
+ worktree: { create: worktreeCreate, remove: worktreeRemove, list: worktreeList },
1461
+ index: { refresh, ignored },
1462
+ tree: {
1463
+ capture: captureTree,
1464
+ write: (repository) => writeTree(repository),
1465
+ files: treeFiles,
1466
+ diff: treeDiff,
1467
+ restore,
1468
+ },
1469
+ objects: { pack: packObjects },
1470
+ })
1471
+ }),
1472
+ )
1473
+
1474
+ export const node = makeGlobalNode({ service: Service, layer: layer, deps: [FSUtil.node, AppProcess.node] })
1475
+
1476
+ interface Result {
1477
+ readonly exitCode: number
1478
+ readonly text: string
1479
+ readonly stderr: string
1480
+ }
1481
+
1482
+ interface RepositoryOptions {
1483
+ readonly stdin?: string | Uint8Array
1484
+ readonly env?: Record<string, string>
1485
+ readonly maxOutputBytes?: number
1486
+ readonly index?: string
1487
+ }
1488
+
1489
+ function spawnFailure(operation: OperationError["operation"], directory: AbsolutePath) {
1490
+ return (cause: { readonly message: string }) =>
1491
+ new OperationError({ operation, directory, message: cause.message, cause })
1492
+ }
1493
+
1494
+ function commandFailure(
1495
+ operation: OperationError["operation"],
1496
+ directory: AbsolutePath,
1497
+ result: { readonly text: string; readonly stderr: string },
1498
+ ) {
1499
+ return new OperationError({
1500
+ operation,
1501
+ directory,
1502
+ message: result.stderr.trim() || result.text.trim() || `Git ${operation} failed`,
1503
+ })
1504
+ }
1505
+
1506
+ function run(cwd: string, proc: AppProcess.Interface, args: string[]) {
1507
+ return execute(cwd, proc, args).pipe(Effect.orElseSucceed(() => ({ exitCode: 1, text: "", stderr: "" })))
1508
+ }
1509
+
1510
+ function execute(cwd: string, proc: AppProcess.Interface, args: string[]) {
1511
+ return proc
1512
+ .run(
1513
+ ChildProcess.make(gitExecutable(), args, {
1514
+ cwd,
1515
+ extendEnv: true,
1516
+ stdin: "ignore",
1517
+ }),
1518
+ )
1519
+ .pipe(
1520
+ Effect.map(
1521
+ (result) =>
1522
+ ({
1523
+ exitCode: result.exitCode,
1524
+ text: result.stdout.toString("utf8"),
1525
+ stderr: result.stderr.toString("utf8"),
1526
+ }) satisfies Result,
1527
+ ),
1528
+ )
1529
+ }
1530
+
1531
+ /** Split NUL-terminated git output into its records. */
1532
+ function nuls(text: string) {
1533
+ return text.split("\0").filter(Boolean)
1534
+ }
1535
+
1536
+ /** Pathspec magic that matches exactly one path, so names with `*`, `?`, `[`, or a leading `:` are not patterns. */
1537
+ function literalPathspec(file: string) {
1538
+ return `:(literal)${file}`
1539
+ }
1540
+
1541
+ /**
1542
+ * Paths whose restore operations commute: none inside another, and every segment
1543
+ * printable ASCII that no platform rewrites. Git precomposes Unicode, filesystems
1544
+ * may fold case, and Windows drops trailing dots and spaces and treats `\` and
1545
+ * `:` specially, so anything else takes the ordered path.
1546
+ */
1547
+ function canBatchRestore(files: readonly string[]) {
1548
+ const canonical = files.every((file) =>
1549
+ file.split("/").every((part) => /^[\x20-\x7e]+$/.test(part) && !/[\\:]/.test(part) && !/[. ]$/.test(part)),
1550
+ )
1551
+ if (!canonical) return false
1552
+ const folded = new Set(files.map((file) => file.toLowerCase()))
1553
+ if (folded.size !== files.length) return false
1554
+ return files.every((file) => {
1555
+ const parts = file.toLowerCase().split("/")
1556
+ return parts.slice(1).every((_, index) => !folded.has(parts.slice(0, index + 1).join("/")))
1557
+ })
1558
+ }
1559
+
1560
+ /**
1561
+ * Object IDs from a version 2 pack index: magic, version, a 256-entry fan-out
1562
+ * table whose last entry is the object count, then the sorted IDs. Returns
1563
+ * undefined for version 1 indexes and for packs with 64-bit offsets (over 2 GiB),
1564
+ * whose hash length this size check cannot derive.
1565
+ */
1566
+ function packIndexObjectIDs(bytes: Uint8Array) {
1567
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
1568
+ if (bytes.length < 1032 || view.getUint32(0) !== 0xff744f63 || view.getUint32(4) !== 2) return undefined
1569
+ const count = view.getUint32(8 + 255 * 4)
1570
+ const hash = (bytes.length - 1032 - 8 * count) / (count + 2)
1571
+ if (hash !== 20 && hash !== 32) return undefined
1572
+ return Array.from({ length: count }, (_, index) =>
1573
+ Buffer.from(bytes.subarray(1032 + index * hash, 1032 + (index + 1) * hash)).toString("hex"),
1574
+ )
1575
+ }
1576
+
1577
+ /**
1578
+ * Groups are sorted like Git's output, so groups of file paths concatenate in the
1579
+ * order one call prints them. Each path is counted with room for the quotes Windows
1580
+ * adds around spaces.
1581
+ */
1582
+ function pathGroups(paths: readonly RelativePath[]) {
1583
+ return paths
1584
+ .toSorted((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)))
1585
+ .reduce<{ groups: RelativePath[][]; length: number }>(
1586
+ (state, file) => {
1587
+ const cost = file.length + 3
1588
+ const current = state.groups.at(-1)
1589
+ if (current && state.length + cost <= argumentBudget) {
1590
+ current.push(file)
1591
+ return { groups: state.groups, length: state.length + cost }
1592
+ }
1593
+ return { groups: [...state.groups, [file]], length: cost }
1594
+ },
1595
+ { groups: [], length: 0 },
1596
+ ).groups
1597
+ }
1598
+
1599
+ function uniqueSuffix() {
1600
+ return `${process.pid}-${Math.random().toString(36).slice(2)}`
1601
+ }
1602
+
1603
+ function resolvePath(cwd: string, value: string) {
1604
+ const trimmed = value.replace(/[\r\n]+$/, "")
1605
+ if (!trimmed) return cwd
1606
+ const normalized = FSUtil.windowsPath(trimmed)
1607
+ if (path.isAbsolute(normalized)) return path.normalize(normalized)
1608
+ return path.resolve(cwd, normalized)
1609
+ }