@zyro-sec/core 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1087) hide show
  1. package/AGENTS.md +7 -0
  2. package/bunfig.toml +2 -0
  3. package/drizzle.config.ts +10 -0
  4. package/package.json +24 -30
  5. package/perf/location.bench.ts +44 -0
  6. package/perf/location.ts +140 -0
  7. package/perf/session.bench.ts +22 -0
  8. package/perf/snapshot.bench.ts +67 -0
  9. package/perf/snapshot.ts +423 -0
  10. package/schema.json +2763 -0
  11. package/script/build.ts +44 -0
  12. package/script/fix-node-pty.ts +28 -0
  13. package/script/generate-api-skill.ts +361 -0
  14. package/script/migration.ts +216 -0
  15. package/script/models-snapshot.ts +82 -0
  16. package/script/pack.ts +5 -0
  17. package/script/snapshot-parity-compare.ts +22 -0
  18. package/script/snapshot-parity-run.sh +20 -0
  19. package/script/snapshot-parity.ts +710 -0
  20. package/script/test.ts +53 -0
  21. package/script/update-models-snapshot.ts +14 -0
  22. package/script/wellknown-server.ts +112 -0
  23. package/src/account/sql.ts +36 -0
  24. package/src/agent.ts +115 -0
  25. package/src/aisdk-native.ts +397 -0
  26. package/src/aisdk.ts +1063 -0
  27. package/src/app.ts +31 -0
  28. package/src/artifact.ts +617 -0
  29. package/src/automation/author.ts +10 -0
  30. package/src/automation/code.ts +269 -0
  31. package/src/automation/event.ts +35 -0
  32. package/src/automation/shell.ts +82 -0
  33. package/src/automation/sql.ts +50 -0
  34. package/src/automation.ts +1293 -0
  35. package/src/blob-store.ts +115 -0
  36. package/src/bus.ts +909 -0
  37. package/src/codemode/api.ts +44 -0
  38. package/src/codemode/bun.ts +550 -0
  39. package/src/codemode/catalog.ts +177 -0
  40. package/src/codemode/diffs.ts +134 -0
  41. package/src/codemode/execution.ts +9 -0
  42. package/src/codemode/fetch.ts +179 -0
  43. package/src/codemode/instructions.ts +169 -0
  44. package/src/codemode/job.ts +144 -0
  45. package/src/codemode/path.ts +45 -0
  46. package/src/codemode/tool.ts +564 -0
  47. package/src/command.ts +109 -0
  48. package/src/config/discovery.ts +183 -0
  49. package/src/config/integration.ts +134 -0
  50. package/src/config/managed.ts +6 -0
  51. package/src/config/markdown.ts +123 -0
  52. package/src/config/normalize.ts +870 -0
  53. package/src/config/plugin/agent.ts +192 -0
  54. package/src/config/plugin/command.ts +229 -0
  55. package/src/config/plugin/compaction.ts +27 -0
  56. package/src/config/plugin/compatibility.ts +94 -0
  57. package/src/config/plugin/entry-observer.ts +79 -0
  58. package/src/config/plugin/formatter.ts +76 -0
  59. package/src/config/plugin/image.ts +29 -0
  60. package/src/config/plugin/instruction.ts +260 -0
  61. package/src/config/plugin/location-watcher.ts +22 -0
  62. package/src/config/plugin/mcp.ts +57 -0
  63. package/src/config/plugin/policy.ts +117 -0
  64. package/src/config/plugin/provider.ts +274 -0
  65. package/src/config/plugin/reference.ts +67 -0
  66. package/src/config/plugin/session-search.ts +21 -0
  67. package/src/config/plugin/shell.ts +20 -0
  68. package/src/config/plugin/skill-file.ts +62 -0
  69. package/src/config/plugin/skill-scan.ts +46 -0
  70. package/src/config/plugin/skill.ts +202 -0
  71. package/src/config/plugin/snapshot.ts +21 -0
  72. package/src/config/plugin/source.ts +194 -0
  73. package/src/config/plugin/tool-output.ts +24 -0
  74. package/src/config/plugin/websearch.ts +19 -0
  75. package/src/config/plugin/worktree.ts +35 -0
  76. package/src/config/variable.ts +84 -0
  77. package/src/config/watch.ts +73 -0
  78. package/src/config.ts +574 -0
  79. package/src/console-access.ts +22 -0
  80. package/src/credential/sql.ts +14 -0
  81. package/src/credential.ts +350 -0
  82. package/src/database/batch.ts +21 -0
  83. package/src/database/database.ts +126 -0
  84. package/src/database/drizzle/README.md +35 -0
  85. package/src/database/drizzle/effect-sqlite/driver.ts +78 -0
  86. package/src/database/drizzle/effect-sqlite/index.ts +4 -0
  87. package/src/database/drizzle/effect-sqlite/session.ts +252 -0
  88. package/src/database/drizzle/index.ts +5 -0
  89. package/src/database/drizzle/internal/drizzle-utils.ts +147 -0
  90. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -0
  91. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -0
  92. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -0
  93. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -0
  94. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -0
  95. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -0
  96. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -0
  97. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -0
  98. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -0
  99. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -0
  100. package/src/database/drizzle.ts +1 -0
  101. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -0
  102. package/src/database/migration/20260211171708_add_project_commands.ts +13 -0
  103. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -0
  104. package/src/database/migration/20260225215848_workspace.ts +21 -0
  105. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -0
  106. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -0
  107. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -0
  108. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -0
  109. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -0
  110. package/src/database/migration/20260323234822_events.ts +28 -0
  111. package/src/database/migration/20260410174513_workspace-name.ts +34 -0
  112. package/src/database/migration/20260413175956_chief_energizer.ts +26 -0
  113. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -0
  114. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -0
  115. package/src/database/migration/20260428004200_add_session_path.ts +13 -0
  116. package/src/database/migration/20260501142318_next_venus.ts +14 -0
  117. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -0
  118. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -0
  119. package/src/database/migration/20260510033149_session_usage.ts +58 -0
  120. package/src/database/migration/20260511000411_data_migration_state.ts +18 -0
  121. package/src/database/migration/20260511173437_session-metadata.ts +18 -0
  122. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -0
  123. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -0
  124. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -0
  125. package/src/database/migration/20260602182828_add_project_directories.ts +22 -0
  126. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -0
  127. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -0
  128. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -0
  129. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -0
  130. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -0
  131. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -0
  132. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -0
  133. package/src/database/migration/20260611035744_credential.ts +27 -0
  134. package/src/database/migration/20260611192811_lush_chimera.ts +27 -0
  135. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -0
  136. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -0
  137. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -0
  138. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -0
  139. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -0
  140. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -0
  141. package/src/database/migration/20260808023530_workspace_domain.ts +22 -0
  142. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -0
  143. package/src/database/migration/20260812181746_session_inbox.ts +30 -0
  144. package/src/database/migration/20260812213948_worktree.ts +35 -0
  145. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -0
  146. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -0
  147. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -0
  148. package/src/database/migration/20260923013825_project_time_active.ts +14 -0
  149. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -0
  150. package/src/database/migration/20261010180456_project_time_archived.ts +13 -0
  151. package/src/database/migration/20261024002554_session_allowance.ts +13 -0
  152. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -0
  153. package/src/database/migration/20261025123711_blob.ts +36 -0
  154. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -0
  155. package/src/database/migration/20261026223005_schedule.ts +38 -0
  156. package/src/database/migration/20261029002625_session_part.ts +30 -0
  157. package/src/database/migration/20261029073502_session_time_busy.ts +13 -0
  158. package/src/database/migration/20261029165540_schedule_checks.ts +16 -0
  159. package/src/database/migration/20261030054400_job.ts +60 -0
  160. package/src/database/migration/20261116043204_automation.ts +83 -0
  161. package/src/database/migration/20261116181958_automation_event_position.ts +13 -0
  162. package/src/database/migration/20261116213417_automation_active_index.ts +16 -0
  163. package/src/database/migration/20261119211416_machine.ts +18 -0
  164. package/src/database/migration/20261120004954_machine-key.ts +14 -0
  165. package/src/database/migration.gen.ts +132 -0
  166. package/src/database/migration.ts +155 -0
  167. package/src/database/path.ts +98 -0
  168. package/src/database/schema.gen.ts +363 -0
  169. package/src/database/schema.sql.ts +10 -0
  170. package/src/database/sqlite.bun.ts +17 -0
  171. package/src/database/sqlite.node.ts +25 -0
  172. package/src/database/sqlite.workerd.ts +227 -0
  173. package/src/database/storage-failure.ts +58 -0
  174. package/src/database/v1-migration.bun.ts +1234 -0
  175. package/src/database/v1-migration.noop.ts +11 -0
  176. package/src/database/v1-migration.ts +2 -0
  177. package/src/effect/app-node-builder.ts +30 -0
  178. package/src/effect/app-node-platform.ts +71 -0
  179. package/src/effect/client-tls/client-tls.bun.ts +8 -0
  180. package/src/effect/client-tls/client-tls.node.ts +17 -0
  181. package/src/effect/client-tls/client-tls.ts +12 -0
  182. package/src/effect/client-tls/client-tls.workerd.ts +8 -0
  183. package/src/effect/keyed-mutex.ts +45 -0
  184. package/src/effect/websocket-constructor.ts +81 -0
  185. package/src/environment/driver.ts +68 -0
  186. package/src/environment/environment.ts +152 -0
  187. package/src/environment/environments.ts +78 -0
  188. package/src/environment/exec-defaults.ts +200 -0
  189. package/src/environment/files.ts +79 -0
  190. package/src/environment/index.ts +34 -0
  191. package/src/environment/local.ts +101 -0
  192. package/src/environment/memory.ts +186 -0
  193. package/src/environment/path.ts +68 -0
  194. package/src/environment/unavailable.ts +17 -0
  195. package/src/event/sql.ts +26 -0
  196. package/src/event-logger.ts +19 -0
  197. package/src/file-access.ts +352 -0
  198. package/src/file-mutation.ts +185 -0
  199. package/src/file-retention.ts +23 -0
  200. package/src/file-write.ts +110 -0
  201. package/src/filesystem/fff.bun.ts +15 -0
  202. package/src/filesystem/fff.node.ts +12 -0
  203. package/src/filesystem/fff.ts +67 -0
  204. package/src/filesystem/fff.workerd.ts +12 -0
  205. package/src/filesystem/file-watch.ts +164 -0
  206. package/src/filesystem/location-watcher-policy.ts +64 -0
  207. package/src/filesystem/location-watcher.ts +108 -0
  208. package/src/filesystem/protected.ts +31 -0
  209. package/src/filesystem/search.ts +251 -0
  210. package/src/filesystem/watcher-binding.ts +14 -0
  211. package/src/filesystem/watcher.ts +282 -0
  212. package/src/filesystem.ts +270 -0
  213. package/src/flag/resolve.ts +66 -0
  214. package/src/flag.ts +64 -0
  215. package/src/form.ts +370 -0
  216. package/src/formatter/builtins.ts +294 -0
  217. package/src/formatter.ts +108 -0
  218. package/src/generate.ts +397 -0
  219. package/src/git.ts +1609 -0
  220. package/src/github-copilot/models.ts +289 -0
  221. package/src/image/notice.ts +8 -0
  222. package/src/image/photon-normalize.ts +148 -0
  223. package/src/image/photon-wasm.bun.ts +4 -0
  224. package/src/image/photon-wasm.node.ts +4 -0
  225. package/src/image/photon-wasm.workerd.ts +4 -0
  226. package/src/image/photon-worker.ts +26 -0
  227. package/src/image/photon.ts +156 -0
  228. package/src/image.ts +95 -0
  229. package/src/instance/service.ts +21 -0
  230. package/src/instance.ts +191 -0
  231. package/src/instruction-discovery.ts +165 -0
  232. package/src/instructions/agent.ts +50 -0
  233. package/src/instructions/builtins.ts +103 -0
  234. package/src/instructions/index.ts +287 -0
  235. package/src/integration/connection.ts +26 -0
  236. package/src/integration.ts +869 -0
  237. package/src/job/list.ts +160 -0
  238. package/src/job/recovery.ts +51 -0
  239. package/src/job/sql.ts +27 -0
  240. package/src/job.ts +766 -0
  241. package/src/kv/sql.ts +9 -0
  242. package/src/kv.ts +92 -0
  243. package/src/location-activity.ts +130 -0
  244. package/src/location-lifecycle.ts +97 -0
  245. package/src/location-service-map.ts +50 -0
  246. package/src/location-services.ts +125 -0
  247. package/src/location.ts +44 -0
  248. package/src/machine/driver.ts +487 -0
  249. package/src/machine/frames.ts +133 -0
  250. package/src/machine/identity.ts +187 -0
  251. package/src/machine/index.ts +4 -0
  252. package/src/machine/instructions.ts +61 -0
  253. package/src/machine/iroh-binding.ts +18 -0
  254. package/src/machine/iroh.ts +157 -0
  255. package/src/machine/join.ts +54 -0
  256. package/src/machine/link.ts +313 -0
  257. package/src/machine/machines.ts +280 -0
  258. package/src/machine/noise.ts +326 -0
  259. package/src/machine/sql.ts +13 -0
  260. package/src/machine/wire.ts +140 -0
  261. package/src/machine/worker-client.ts +276 -0
  262. package/src/managed-policy.ts +65 -0
  263. package/src/markdown.d.ts +4 -0
  264. package/src/mcp/client.ts +1198 -0
  265. package/src/mcp/connection.ts +292 -0
  266. package/src/mcp/event-stream.ts +34 -0
  267. package/src/mcp/index.ts +1349 -0
  268. package/src/mcp/instructions.ts +108 -0
  269. package/src/mcp/oauth.ts +665 -0
  270. package/src/mcp/pool.ts +386 -0
  271. package/src/mcp/socket-client.ts +86 -0
  272. package/src/mcp/stdio.ts +227 -0
  273. package/src/mime.ts +75 -0
  274. package/src/modal/models.ts +150 -0
  275. package/src/model-resolver.ts +639 -0
  276. package/src/model-retry.ts +134 -0
  277. package/src/model.ts +373 -0
  278. package/src/models-dev/snapshot.txt +1 -0
  279. package/src/models-dev/v1.ts +203 -0
  280. package/src/models-dev.ts +899 -0
  281. package/src/node-ffi.d.ts +18 -0
  282. package/src/oauth/page.ts +260 -0
  283. package/src/oauth/redirect.ts +42 -0
  284. package/src/pentest/mcp-catalog.ts +144 -0
  285. package/src/permission/policy.ts +240 -0
  286. package/src/permission/saved.ts +140 -0
  287. package/src/permission/sql.ts +20 -0
  288. package/src/permission.ts +419 -0
  289. package/src/persistent-pty/binary.bun.ts +85 -0
  290. package/src/persistent-pty/binary.node.ts +5 -0
  291. package/src/persistent-pty/binary.workerd.ts +5 -0
  292. package/src/persistent-pty/daemon.ts +750 -0
  293. package/src/persistent-pty/index.ts +661 -0
  294. package/src/persistent-pty/pty-binding.ts +6 -0
  295. package/src/persistent-pty.ts +1 -0
  296. package/src/plugin/agent.ts +235 -0
  297. package/src/plugin/command/automation.txt +7 -0
  298. package/src/plugin/command/initialize.txt +65 -0
  299. package/src/plugin/command/review.txt +100 -0
  300. package/src/plugin/command.ts +113 -0
  301. package/src/plugin/fork-notice.ts +30 -0
  302. package/src/plugin/goal/continuation.txt +13 -0
  303. package/src/plugin/goal/judge.txt +20 -0
  304. package/src/plugin/goal/kickoff.txt +13 -0
  305. package/src/plugin/goal/reminder.txt +9 -0
  306. package/src/plugin/goal.ts +501 -0
  307. package/src/plugin/home-memory.ts +155 -0
  308. package/src/plugin/hooks.ts +108 -0
  309. package/src/plugin/host.ts +770 -0
  310. package/src/plugin/identity.ts +31 -0
  311. package/src/plugin/instance.ts +45 -0
  312. package/src/plugin/internal.ts +360 -0
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -0
  314. package/src/plugin/mcp-skill.ts +171 -0
  315. package/src/plugin/models-dev.ts +128 -0
  316. package/src/plugin/module.ts +186 -0
  317. package/src/plugin/optimize.ts +97 -0
  318. package/src/plugin/plan.ts +52 -0
  319. package/src/plugin/promise.ts +3 -0
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -0
  321. package/src/plugin/provider/azure.ts +568 -0
  322. package/src/plugin/provider/cerebras.ts +16 -0
  323. package/src/plugin/provider/chatgpt.ts +594 -0
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -0
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -0
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -0
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -0
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -0
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -0
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -0
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -0
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -0
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -0
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -0
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -0
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -0
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -0
  338. package/src/plugin/provider/claude-agent/index.ts +63 -0
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -0
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -0
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -0
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -0
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -0
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -0
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -0
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -0
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -0
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -0
  349. package/src/plugin/provider/claude-agent/session.ts +61 -0
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -0
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -0
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -0
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -0
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -0
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -0
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -0
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -0
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -0
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -0
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -0
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -0
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -0
  363. package/src/plugin/provider/configured.ts +18 -0
  364. package/src/plugin/provider/credential-settings.ts +77 -0
  365. package/src/plugin/provider/databricks.ts +31 -0
  366. package/src/plugin/provider/digitalocean.ts +197 -0
  367. package/src/plugin/provider/dynamic.ts +19 -0
  368. package/src/plugin/provider/github-copilot.ts +646 -0
  369. package/src/plugin/provider/gitlab.ts +496 -0
  370. package/src/plugin/provider/google-vertex.ts +231 -0
  371. package/src/plugin/provider/kilo.ts +17 -0
  372. package/src/plugin/provider/llmgateway.ts +27 -0
  373. package/src/plugin/provider/lmstudio.ts +52 -0
  374. package/src/plugin/provider/local.ts +240 -0
  375. package/src/plugin/provider/modal.ts +72 -0
  376. package/src/plugin/provider/neon.ts +12 -0
  377. package/src/plugin/provider/nvidia.ts +22 -0
  378. package/src/plugin/provider/ollama.ts +92 -0
  379. package/src/plugin/provider/openai-context-caps.ts +52 -0
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -0
  381. package/src/plugin/provider/openai.ts +447 -0
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -0
  383. package/src/plugin/provider/opencode-watches.ts +753 -0
  384. package/src/plugin/provider/opencode.ts +883 -0
  385. package/src/plugin/provider/openrouter.ts +30 -0
  386. package/src/plugin/provider/poe.ts +176 -0
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -0
  388. package/src/plugin/provider/refresh.ts +80 -0
  389. package/src/plugin/provider/sap-ai-core.ts +39 -0
  390. package/src/plugin/provider/sdk-factory.ts +24 -0
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -0
  392. package/src/plugin/provider/vllm.ts +34 -0
  393. package/src/plugin/provider/xai.ts +236 -0
  394. package/src/plugin/provider/zenmux.ts +21 -0
  395. package/src/plugin/provider.ts +64 -0
  396. package/src/plugin/sdk.ts +44 -0
  397. package/src/plugin/service.ts +42 -0
  398. package/src/plugin/skill/opencode/api/agent.md +18 -0
  399. package/src/plugin/skill/opencode/api/automation.md +63 -0
  400. package/src/plugin/skill/opencode/api/blob.md +10 -0
  401. package/src/plugin/skill/opencode/api/command.md +12 -0
  402. package/src/plugin/skill/opencode/api/form.md +22 -0
  403. package/src/plugin/skill/opencode/api/generate.md +96 -0
  404. package/src/plugin/skill/opencode/api/info.md +11 -0
  405. package/src/plugin/skill/opencode/api/location.md +17 -0
  406. package/src/plugin/skill/opencode/api/model.md +22 -0
  407. package/src/plugin/skill/opencode/api/permission.md +13 -0
  408. package/src/plugin/skill/opencode/api/project.md +29 -0
  409. package/src/plugin/skill/opencode/api/provider.md +18 -0
  410. package/src/plugin/skill/opencode/api/session.md +313 -0
  411. package/src/plugin/skill/opencode/api/skill.md +12 -0
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -0
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -0
  414. package/src/plugin/skill/opencode/api.md +119 -0
  415. package/src/plugin/skill/opencode/api.ts +40 -0
  416. package/src/plugin/skill/opencode-api.md +17 -0
  417. package/src/plugin/skill/opencode.md +154 -0
  418. package/src/plugin/skill/report.md +152 -0
  419. package/src/plugin/skill.ts +111 -0
  420. package/src/plugin/source-directory.ts +33 -0
  421. package/src/plugin/supervisor.ts +288 -0
  422. package/src/plugin/system-prompt/AGENTS.md +5 -0
  423. package/src/plugin/system-prompt/anthropic.txt +2 -0
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -0
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -0
  426. package/src/plugin/system-prompt/gpt.txt +40 -0
  427. package/src/plugin/system-prompt/kimi.txt +96 -0
  428. package/src/plugin/system-prompt/meta.txt +56 -0
  429. package/src/plugin/system-prompt/trinity.txt +98 -0
  430. package/src/plugin/tool-input-repair.ts +232 -0
  431. package/src/plugin/update.ts +87 -0
  432. package/src/plugin/vcs/git.ts +802 -0
  433. package/src/plugin/vcs/hg.ts +234 -0
  434. package/src/plugin/verbosity.ts +58 -0
  435. package/src/plugin/warming.ts +224 -0
  436. package/src/plugin/websearch/exa.ts +69 -0
  437. package/src/plugin/websearch/firecrawl.ts +71 -0
  438. package/src/plugin/websearch/index.ts +13 -0
  439. package/src/plugin/websearch/mcp.ts +69 -0
  440. package/src/plugin/websearch/parallel.ts +90 -0
  441. package/src/plugin/websearch/provider.ts +44 -0
  442. package/src/plugin/websearch/tavily.ts +73 -0
  443. package/src/plugin/websearch/tinyfish.ts +131 -0
  444. package/src/plugin.ts +320 -0
  445. package/src/project/icon.ts +167 -0
  446. package/src/project/schema.ts +25 -0
  447. package/src/project/sql.ts +63 -0
  448. package/src/project.ts +536 -0
  449. package/src/provider.ts +553 -0
  450. package/src/pty/protocol.ts +37 -0
  451. package/src/pty/pty.bun.ts +44 -0
  452. package/src/pty/pty.node.ts +34 -0
  453. package/src/pty/pty.ts +25 -0
  454. package/src/pty/pty.workerd.ts +9 -0
  455. package/src/pty/ticket.ts +74 -0
  456. package/src/pty.ts +311 -0
  457. package/src/push/crypto.ts +39 -0
  458. package/src/push/list.ts +380 -0
  459. package/src/push/sender.ts +185 -0
  460. package/src/push/watcher.ts +169 -0
  461. package/src/reference/instructions.ts +82 -0
  462. package/src/reference.ts +129 -0
  463. package/src/repository-cache.ts +251 -0
  464. package/src/repository.ts +205 -0
  465. package/src/ripgrep/binary.ts +166 -0
  466. package/src/ripgrep.ts +311 -0
  467. package/src/rpc.ts +288 -0
  468. package/src/schema.ts +39 -0
  469. package/src/session/affinity.ts +8 -0
  470. package/src/session/background-result.ts +5 -0
  471. package/src/session/background.ts +125 -0
  472. package/src/session/blob.ts +503 -0
  473. package/src/session/command.ts +38 -0
  474. package/src/session/compaction-background.ts +55 -0
  475. package/src/session/compaction-subagents.ts +103 -0
  476. package/src/session/compaction.ts +1320 -0
  477. package/src/session/context.ts +296 -0
  478. package/src/session/cwd-instructions.ts +147 -0
  479. package/src/session/cwd-store.ts +66 -0
  480. package/src/session/cwd.ts +75 -0
  481. package/src/session/diff.ts +149 -0
  482. package/src/session/environment.ts +33 -0
  483. package/src/session/error.ts +105 -0
  484. package/src/session/event.ts +2 -0
  485. package/src/session/execution/restart.ts +558 -0
  486. package/src/session/execution/subagent-report.ts +203 -0
  487. package/src/session/execution.ts +241 -0
  488. package/src/session/generate.ts +78 -0
  489. package/src/session/history.ts +405 -0
  490. package/src/session/inbox.ts +625 -0
  491. package/src/session/info.ts +62 -0
  492. package/src/session/instruction-entry.ts +171 -0
  493. package/src/session/instruction-state.ts +277 -0
  494. package/src/session/instructions.ts +126 -0
  495. package/src/session/message-updater.ts +497 -0
  496. package/src/session/message.ts +2 -0
  497. package/src/session/model-request.ts +474 -0
  498. package/src/session/model-transport.ts +571 -0
  499. package/src/session/move.ts +199 -0
  500. package/src/session/projector.ts +1197 -0
  501. package/src/session/prompt.ts +253 -0
  502. package/src/session/recent-text.ts +93 -0
  503. package/src/session/revert.ts +112 -0
  504. package/src/session/run-coordinator.ts +198 -0
  505. package/src/session/runner/index.ts +46 -0
  506. package/src/session/runner/live-tool-metadata.ts +41 -0
  507. package/src/session/runner/llm.ts +481 -0
  508. package/src/session/runner/max-steps.ts +16 -0
  509. package/src/session/runner/model.ts +138 -0
  510. package/src/session/runner/prompt/system.txt +16 -0
  511. package/src/session/runner/publish-llm-event.ts +642 -0
  512. package/src/session/runner/retry.ts +78 -0
  513. package/src/session/runner/step.ts +401 -0
  514. package/src/session/runner/to-llm-message.ts +341 -0
  515. package/src/session/schema.ts +9 -0
  516. package/src/session/search-build.ts +116 -0
  517. package/src/session/search-index.ts +552 -0
  518. package/src/session/search.ts +672 -0
  519. package/src/session/session.ts +407 -0
  520. package/src/session/shell.ts +35 -0
  521. package/src/session/skill.ts +16 -0
  522. package/src/session/sql.ts +215 -0
  523. package/src/session/stats.ts +463 -0
  524. package/src/session/store.ts +323 -0
  525. package/src/session/stored.ts +44 -0
  526. package/src/session/subagent-completion.ts +95 -0
  527. package/src/session/subagent-depth.ts +21 -0
  528. package/src/session/subagent-job.ts +61 -0
  529. package/src/session/synthetic.ts +49 -0
  530. package/src/session/system-prompt.ts +28 -0
  531. package/src/session/title.ts +174 -0
  532. package/src/session/to-session-error.ts +179 -0
  533. package/src/session/transfer.ts +369 -0
  534. package/src/session/usage.ts +64 -0
  535. package/src/session.ts +602 -0
  536. package/src/shared-cache.ts +103 -0
  537. package/src/shell/parse.ts +645 -0
  538. package/src/shell/permissions.ts +60 -0
  539. package/src/shell/result.ts +115 -0
  540. package/src/shell/scan.ts +2585 -0
  541. package/src/shell/select.ts +241 -0
  542. package/src/shell.ts +1274 -0
  543. package/src/skill/discovery.ts +205 -0
  544. package/src/skill/instructions.ts +84 -0
  545. package/src/skill.ts +277 -0
  546. package/src/snapshot.ts +248 -0
  547. package/src/state.ts +271 -0
  548. package/src/tool/AGENTS.md +71 -0
  549. package/src/tool/html-markdown.ts +651 -0
  550. package/src/tool/http-body.ts +30 -0
  551. package/src/tool/mcp.ts +177 -0
  552. package/src/tool/model-policy.ts +38 -0
  553. package/src/tool/patch-grammar.txt +19 -0
  554. package/src/tool/patch.txt +33 -0
  555. package/src/tool/plugin/artifact.ts +171 -0
  556. package/src/tool/plugin/automation.ts +246 -0
  557. package/src/tool/plugin/cd.ts +103 -0
  558. package/src/tool/plugin/edit.ts +371 -0
  559. package/src/tool/plugin/file-diff.ts +42 -0
  560. package/src/tool/plugin/glob.ts +123 -0
  561. package/src/tool/plugin/grep.ts +152 -0
  562. package/src/tool/plugin/image-generate.ts +396 -0
  563. package/src/tool/plugin/machine.ts +36 -0
  564. package/src/tool/plugin/mcp-events.ts +72 -0
  565. package/src/tool/plugin/mcp-resource.ts +100 -0
  566. package/src/tool/plugin/opencode.ts +316 -0
  567. package/src/tool/plugin/patch.ts +358 -0
  568. package/src/tool/plugin/question.ts +130 -0
  569. package/src/tool/plugin/read.ts +413 -0
  570. package/src/tool/plugin/session-interrupt.ts +63 -0
  571. package/src/tool/plugin/session-search.ts +99 -0
  572. package/src/tool/plugin/shell.ts +594 -0
  573. package/src/tool/plugin/skill.ts +74 -0
  574. package/src/tool/plugin/subagent.ts +269 -0
  575. package/src/tool/plugin/todo.ts +83 -0
  576. package/src/tool/plugin/video-generate.ts +403 -0
  577. package/src/tool/plugin/webfetch.ts +214 -0
  578. package/src/tool/plugin/websearch.ts +196 -0
  579. package/src/tool/plugin/write.ts +72 -0
  580. package/src/tool/read-filesystem.ts +350 -0
  581. package/src/tool/runtime.ts +311 -0
  582. package/src/tool/search.ts +34 -0
  583. package/src/tool/todowrite.txt +7 -0
  584. package/src/tool-output.ts +220 -0
  585. package/src/tool.ts +579 -0
  586. package/src/usage-limits.ts +192 -0
  587. package/src/util/canonical-json.ts +11 -0
  588. package/src/util/error-summary.ts +33 -0
  589. package/src/util/git-executable.ts +59 -0
  590. package/src/util/lazy.ts +11 -0
  591. package/src/util/slug.ts +74 -0
  592. package/src/util/token.ts +5 -0
  593. package/src/util/which.ts +37 -0
  594. package/src/util/wildcard.ts +15 -0
  595. package/src/v1/config/agent.ts +69 -0
  596. package/src/v1/config/command.ts +13 -0
  597. package/src/v1/config/mcp.ts +69 -0
  598. package/src/v1/config/migrate.ts +269 -0
  599. package/src/v1/config/permission.ts +42 -0
  600. package/src/v1/config/plugin.ts +9 -0
  601. package/src/v1/config/provider-options.ts +59 -0
  602. package/src/v1/config/provider.ts +113 -0
  603. package/src/variant.ts +699 -0
  604. package/src/vcs/patch.ts +106 -0
  605. package/src/vcs.ts +262 -0
  606. package/src/video-generation.ts +344 -0
  607. package/src/voice.ts +194 -0
  608. package/src/websearch.ts +239 -0
  609. package/src/wellknown/plugin.ts +36 -0
  610. package/src/wellknown.ts +230 -0
  611. package/src/workspace/driver.ts +89 -0
  612. package/src/workspace/sql.ts +11 -0
  613. package/src/workspace.ts +566 -0
  614. package/src/worktree/directory.ts +16 -0
  615. package/src/worktree/git.ts +39 -0
  616. package/src/worktree/sql.ts +21 -0
  617. package/src/worktree/strategies.ts +74 -0
  618. package/src/worktree.ts +357 -0
  619. package/test/agent.test.ts +224 -0
  620. package/test/aisdk-native.test.ts +590 -0
  621. package/test/aisdk.test.ts +1259 -0
  622. package/test/app.test.ts +6 -0
  623. package/test/artifact.test.ts +216 -0
  624. package/test/automation-event.test.ts +688 -0
  625. package/test/automation-shell.test.ts +293 -0
  626. package/test/automation.test.ts +1950 -0
  627. package/test/blob-store.test.ts +37 -0
  628. package/test/boot-work.test.ts +215 -0
  629. package/test/browser-attach.test.ts +150 -0
  630. package/test/browser-idle.test.ts +107 -0
  631. package/test/bus-session-routing.test.ts +334 -0
  632. package/test/bus-unpersisted.test.ts +50 -0
  633. package/test/bus.test.ts +1347 -0
  634. package/test/catalog.test.ts +704 -0
  635. package/test/codemode/catalog.test.ts +339 -0
  636. package/test/codemode/diffs.test.ts +90 -0
  637. package/test/codemode/instructions.test.ts +123 -0
  638. package/test/codemode-execute-options.test.ts +172 -0
  639. package/test/codemode-script-diffs.test.ts +131 -0
  640. package/test/codemode.test.ts +132 -0
  641. package/test/command.test.ts +71 -0
  642. package/test/config/agent.test.ts +847 -0
  643. package/test/config/command-subagent.test.ts +165 -0
  644. package/test/config/command.test.ts +628 -0
  645. package/test/config/compaction.test.ts +184 -0
  646. package/test/config/config.test.ts +2113 -0
  647. package/test/config/discovery.test.ts +150 -0
  648. package/test/config/entry-observer.test.ts +51 -0
  649. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -0
  650. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -0
  651. package/test/config/image.test.ts +78 -0
  652. package/test/config/markdown.test.ts +129 -0
  653. package/test/config/model.test.ts +28 -0
  654. package/test/config/normalization.test.ts +854 -0
  655. package/test/config/overlay.test.ts +205 -0
  656. package/test/config/policy.test.ts +432 -0
  657. package/test/config/provider-options.test.ts +55 -0
  658. package/test/config/provider.test.ts +1338 -0
  659. package/test/config/reload.test.ts +526 -0
  660. package/test/config/session-search.test.ts +61 -0
  661. package/test/config/shell.test.ts +42 -0
  662. package/test/config/skill.test.ts +602 -0
  663. package/test/config/snapshot.test.ts +61 -0
  664. package/test/config/tool-output.test.ts +59 -0
  665. package/test/config/watch.test.ts +53 -0
  666. package/test/config/websearch.test.ts +45 -0
  667. package/test/credential-refresh.test.ts +113 -0
  668. package/test/credential.test.ts +271 -0
  669. package/test/database-drizzle.test.ts +228 -0
  670. package/test/database-migration.test.ts +783 -0
  671. package/test/database.test.ts +39 -0
  672. package/test/effect/cross-spawn-spawner.test.ts +522 -0
  673. package/test/effect/keyed-mutex.test.ts +73 -0
  674. package/test/effect/layer-node/layer-node-types.test.ts +230 -0
  675. package/test/effect/layer-node/layer-node.test.ts +467 -0
  676. package/test/effect/layer-node/node-build.test.ts +148 -0
  677. package/test/effect/observability.test.ts +141 -0
  678. package/test/effect-app-node-platform.test.ts +86 -0
  679. package/test/effect-simplification-types.test.ts +12 -0
  680. package/test/environment.test.ts +154 -0
  681. package/test/environments.test.ts +406 -0
  682. package/test/event-logger.test.ts +50 -0
  683. package/test/file-access-path.test.ts +336 -0
  684. package/test/file-access.test.ts +178 -0
  685. package/test/file-mutation.test.ts +244 -0
  686. package/test/filesystem/file-watch.test.ts +213 -0
  687. package/test/filesystem/filesystem.test.ts +383 -0
  688. package/test/filesystem/location-watcher-policy.test.ts +70 -0
  689. package/test/filesystem/search.test.ts +385 -0
  690. package/test/filesystem/watcher.test.ts +719 -0
  691. package/test/fixture/app-execution-alias.ts +17 -0
  692. package/test/fixture/codemode.ts +63 -0
  693. package/test/fixture/config-nodes.ts +40 -0
  694. package/test/fixture/durable-object-storage.ts +58 -0
  695. package/test/fixture/effect-flock-worker.ts +60 -0
  696. package/test/fixture/env.ts +22 -0
  697. package/test/fixture/environment.ts +52 -0
  698. package/test/fixture/event-server.ts +65 -0
  699. package/test/fixture/flock-worker.ts +72 -0
  700. package/test/fixture/git.ts +86 -0
  701. package/test/fixture/global.ts +26 -0
  702. package/test/fixture/held-stdio.cjs +36 -0
  703. package/test/fixture/html-markdown.ts +7 -0
  704. package/test/fixture/link-v1-transcript.json +27 -0
  705. package/test/fixture/location.ts +27 -0
  706. package/test/fixture/lock-worker.ts +53 -0
  707. package/test/fixture/machine-v2.json +66 -0
  708. package/test/fixture/machine-worker.ts +284 -0
  709. package/test/fixture/mcp-echo.ts +14 -0
  710. package/test/fixture/mcp-legacy-silent.ts +22 -0
  711. package/test/fixture/mcp-modern-stdio.ts +15 -0
  712. package/test/fixture/mcp-output-schema.ts +63 -0
  713. package/test/fixture/mcp-prompts.ts +29 -0
  714. package/test/fixture/mcp-timeout.ts +32 -0
  715. package/test/fixture/mcp-union-output-schema.ts +41 -0
  716. package/test/fixture/mcp.ts +44 -0
  717. package/test/fixture/models.ts +6 -0
  718. package/test/fixture/native/2.0.14-media.json +22 -0
  719. package/test/fixture/noise-xx-vectors.json +75 -0
  720. package/test/fixture/persistent-pty-daemon.ts +347 -0
  721. package/test/fixture/persistent-pty.ts +9 -0
  722. package/test/fixture/photon-crash-worker.ts +10 -0
  723. package/test/fixture/photon-exit.ts +29 -0
  724. package/test/fixture/photon-hang-worker.ts +2 -0
  725. package/test/fixture/policy.ts +98 -0
  726. package/test/fixture/prompt-location.ts +33 -0
  727. package/test/fixture/pty-windows.ts +69 -0
  728. package/test/fixture/selector.ts +12 -0
  729. package/test/fixture/shell-daemon.ts +122 -0
  730. package/test/fixture/spawn.ts +24 -0
  731. package/test/fixture/sqlite-node-client.ts +100 -0
  732. package/test/fixture/target-environment.ts +58 -0
  733. package/test/fixture/tmpdir.ts +44 -0
  734. package/test/fixture/v1-config/attachment.ts +25 -0
  735. package/test/fixture/v1-config/config.ts +182 -0
  736. package/test/fixture/v1-config/formatter.ts +13 -0
  737. package/test/fixture/v1-config/layout.ts +6 -0
  738. package/test/fixture/v1-config/lsp.ts +80 -0
  739. package/test/fixture/v1-config/server.ts +19 -0
  740. package/test/fixture/v1-config/skills.ts +13 -0
  741. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -0
  742. package/test/flag.test.ts +203 -0
  743. package/test/form.test.ts +357 -0
  744. package/test/formatter-target-environment.test.ts +138 -0
  745. package/test/formatter.test.ts +350 -0
  746. package/test/generate.test.ts +752 -0
  747. package/test/git.test.ts +666 -0
  748. package/test/github-copilot/models.test.ts +167 -0
  749. package/test/image-photon.test.ts +177 -0
  750. package/test/instance-vanilla.test.ts +124 -0
  751. package/test/instruction-discovery.test.ts +804 -0
  752. package/test/instruction-state.test.ts +537 -0
  753. package/test/instructions/builtins.test.ts +83 -0
  754. package/test/instructions/index.test.ts +248 -0
  755. package/test/integration-refresh.test.ts +118 -0
  756. package/test/integration.test.ts +716 -0
  757. package/test/job.test.ts +968 -0
  758. package/test/kv.test.ts +81 -0
  759. package/test/lib/clock.ts +43 -0
  760. package/test/lib/effect.ts +80 -0
  761. package/test/lib/environment-conformance.ts +204 -0
  762. package/test/lib/eventually.ts +20 -0
  763. package/test/lib/image.ts +7 -0
  764. package/test/lib/instructions.ts +47 -0
  765. package/test/lib/permission.ts +12 -0
  766. package/test/lib/project.ts +26 -0
  767. package/test/lib/session-message.ts +26 -0
  768. package/test/lib/tool.ts +102 -0
  769. package/test/lib/websearch.ts +63 -0
  770. package/test/lib/websocket-server.ts +73 -0
  771. package/test/location-activity.test.ts +315 -0
  772. package/test/location-filesystem.test.ts +332 -0
  773. package/test/location-layer.test.ts +784 -0
  774. package/test/location-missing-project.test.ts +71 -0
  775. package/test/location-retain.test.ts +98 -0
  776. package/test/location.test.ts +46 -0
  777. package/test/logging.test.ts +14 -0
  778. package/test/machine-frames.test.ts +768 -0
  779. package/test/machine-instructions.test.ts +135 -0
  780. package/test/machine-join.test.ts +223 -0
  781. package/test/machine-link.test.ts +527 -0
  782. package/test/machine-noise.test.ts +429 -0
  783. package/test/machine-path.test.ts +1202 -0
  784. package/test/machine.test.ts +786 -0
  785. package/test/machines.test.ts +730 -0
  786. package/test/mcp-attach.test.ts +403 -0
  787. package/test/mcp-events.test.ts +299 -0
  788. package/test/mcp-import-boundary.test.ts +44 -0
  789. package/test/mcp-instructions.test.ts +221 -0
  790. package/test/mcp-oauth.test.ts +1289 -0
  791. package/test/mcp-skills.test.ts +274 -0
  792. package/test/mcp-socket-client.test.ts +210 -0
  793. package/test/mcp-stdio.test.ts +145 -0
  794. package/test/mcp.test.ts +4196 -0
  795. package/test/mime.test.ts +80 -0
  796. package/test/modal/models.test.ts +137 -0
  797. package/test/model-free.test.ts +120 -0
  798. package/test/model-plugins.test.ts +469 -0
  799. package/test/model-resolver.test.ts +1695 -0
  800. package/test/model.test.ts +16 -0
  801. package/test/models.test.ts +1404 -0
  802. package/test/network-guard.test.ts +56 -0
  803. package/test/npm-config.test.ts +42 -0
  804. package/test/npm.test.ts +545 -0
  805. package/test/oauth-page.test.ts +15 -0
  806. package/test/opencode-api-skill.test.ts +16 -0
  807. package/test/patch.test.ts +509 -0
  808. package/test/permission.test.ts +1179 -0
  809. package/test/persistent-pty-daemon.test.ts +337 -0
  810. package/test/persistent-pty-session.test.ts +295 -0
  811. package/test/plugin/automation.test.ts +124 -0
  812. package/test/plugin/command.test.ts +137 -0
  813. package/test/plugin/fixture.ts +174 -0
  814. package/test/plugin/fixtures/greeting.ts +14 -0
  815. package/test/plugin/fixtures/models-dev-reasoning.json +811 -0
  816. package/test/plugin/fixtures/models-dev.json +92 -0
  817. package/test/plugin/fixtures/provider-factory.ts +9 -0
  818. package/test/plugin/goal-watchdog.test.ts +212 -0
  819. package/test/plugin/goal.test.ts +609 -0
  820. package/test/plugin/home-memory.test.ts +131 -0
  821. package/test/plugin/host-model.test.ts +34 -0
  822. package/test/plugin/host.ts +540 -0
  823. package/test/plugin/identity.test.ts +60 -0
  824. package/test/plugin/internal-flag.test.ts +101 -0
  825. package/test/plugin/mcp-codemode-defaults.test.ts +124 -0
  826. package/test/plugin/models-dev.test.ts +1406 -0
  827. package/test/plugin/module.test.ts +494 -0
  828. package/test/plugin/optimize.test.ts +343 -0
  829. package/test/plugin/permission-assert.test.ts +94 -0
  830. package/test/plugin/plan.test.ts +162 -0
  831. package/test/plugin/promise-tool-cancel.test.ts +279 -0
  832. package/test/plugin/promise-tool.test.ts +227 -0
  833. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +326 -0
  834. package/test/plugin/provider/claude-agent/claude/branches.test.ts +300 -0
  835. package/test/plugin/provider/claude-agent/claude/probe.test.ts +99 -0
  836. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +19 -0
  837. package/test/plugin/provider/claude-agent/claude/session.test.ts +30 -0
  838. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +490 -0
  839. package/test/plugin/provider/claude-agent/claude/status.test.ts +67 -0
  840. package/test/plugin/provider/claude-agent/claude/sync.test.ts +70 -0
  841. package/test/plugin/provider/claude-agent/claude/tools.test.ts +382 -0
  842. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -0
  843. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -0
  844. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -0
  845. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -0
  846. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -0
  847. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -0
  848. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -0
  849. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -0
  850. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -0
  851. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -0
  852. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -0
  853. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -0
  854. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -0
  855. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -0
  856. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -0
  857. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -0
  858. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -0
  859. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -0
  860. package/test/plugin/provider/claude-agent/fixtures/red.png +0 -0
  861. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +95 -0
  862. package/test/plugin/provider/claude-agent/language-model/error.test.ts +94 -0
  863. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -0
  864. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -0
  865. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -0
  866. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -0
  867. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -0
  868. package/test/plugin/provider/claude-agent/plugin.test.ts +651 -0
  869. package/test/plugin/provider/claude-agent/sync/sync.test.ts +213 -0
  870. package/test/plugin/provider/claude-agent/tools/tools.test.ts +85 -0
  871. package/test/plugin/provider/claude-agent/websearch.test.ts +106 -0
  872. package/test/plugin/provider-amazon-bedrock.test.ts +225 -0
  873. package/test/plugin/provider-azure.test.ts +793 -0
  874. package/test/plugin/provider-cerebras.test.ts +62 -0
  875. package/test/plugin/provider-chatgpt.test.ts +1278 -0
  876. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +160 -0
  877. package/test/plugin/provider-cloudflare-workers-ai.test.ts +158 -0
  878. package/test/plugin/provider-databricks.test.ts +45 -0
  879. package/test/plugin/provider-digitalocean.test.ts +322 -0
  880. package/test/plugin/provider-dynamic.test.ts +179 -0
  881. package/test/plugin/provider-github-copilot.test.ts +806 -0
  882. package/test/plugin/provider-gitlab-oauth.test.ts +407 -0
  883. package/test/plugin/provider-gitlab.test.ts +546 -0
  884. package/test/plugin/provider-google-vertex.test.ts +288 -0
  885. package/test/plugin/provider-kilo.test.ts +66 -0
  886. package/test/plugin/provider-llmgateway.test.ts +72 -0
  887. package/test/plugin/provider-lmstudio.test.ts +487 -0
  888. package/test/plugin/provider-nvidia.test.ts +84 -0
  889. package/test/plugin/provider-ollama.test.ts +312 -0
  890. package/test/plugin/provider-openai-context-caps.test.ts +80 -0
  891. package/test/plugin/provider-openai.test.ts +447 -0
  892. package/test/plugin/provider-opencode-artifacts.test.ts +236 -0
  893. package/test/plugin/provider-opencode-watches.test.ts +1103 -0
  894. package/test/plugin/provider-opencode.test.ts +2590 -0
  895. package/test/plugin/provider-openrouter.test.ts +83 -0
  896. package/test/plugin/provider-poe.test.ts +360 -0
  897. package/test/plugin/provider-sap-ai-core.test.ts +138 -0
  898. package/test/plugin/provider-snowflake-cortex.test.ts +294 -0
  899. package/test/plugin/provider-vllm.test.ts +382 -0
  900. package/test/plugin/provider-xai.test.ts +92 -0
  901. package/test/plugin/provider-zenmux.test.ts +100 -0
  902. package/test/plugin/session-compact.test.ts +52 -0
  903. package/test/plugin/session-instructions.test.ts +197 -0
  904. package/test/plugin/session-list.test.ts +52 -0
  905. package/test/plugin/session-remove.test.ts +61 -0
  906. package/test/plugin/skill.test.ts +81 -0
  907. package/test/plugin/supervisor-reload.test.ts +401 -0
  908. package/test/plugin/supervisor.test.ts +485 -0
  909. package/test/plugin/tool-input-repair-integration.test.ts +296 -0
  910. package/test/plugin/tool-input-repair.test.ts +457 -0
  911. package/test/plugin/vcs-init.test.ts +48 -0
  912. package/test/plugin/verbosity.test.ts +163 -0
  913. package/test/plugin/warming.test.ts +314 -0
  914. package/test/plugin/websearch-fixture.ts +63 -0
  915. package/test/plugin/websearch.test.ts +368 -0
  916. package/test/plugin/worktree.test.ts +52 -0
  917. package/test/plugin-failure.test.ts +305 -0
  918. package/test/plugin.test.ts +756 -0
  919. package/test/preload.test.ts +32 -0
  920. package/test/preload.ts +2 -0
  921. package/test/process/process.test.ts +340 -0
  922. package/test/project-activate.test.ts +144 -0
  923. package/test/project-icon.test.ts +198 -0
  924. package/test/project.test.ts +754 -0
  925. package/test/provider.test.ts +92 -0
  926. package/test/pty/info-schema.test.ts +23 -0
  927. package/test/pty/protocol.test.ts +27 -0
  928. package/test/pty/pty-session.test.ts +224 -0
  929. package/test/pty/pty-windows.test.ts +41 -0
  930. package/test/pty/ticket.test.ts +76 -0
  931. package/test/push-list.test.ts +257 -0
  932. package/test/push-sender.test.ts +235 -0
  933. package/test/push-watcher.test.ts +359 -0
  934. package/test/reference-instructions.test.ts +112 -0
  935. package/test/reference.test.ts +209 -0
  936. package/test/repository-cache.test.ts +235 -0
  937. package/test/repository.test.ts +89 -0
  938. package/test/ripgrep.test.ts +253 -0
  939. package/test/rpc-handler-errors.test.ts +62 -0
  940. package/test/session-activation.test.ts +75 -0
  941. package/test/session-archive.test.ts +81 -0
  942. package/test/session-background.test.ts +97 -0
  943. package/test/session-checkpoint-transport.test.ts +168 -0
  944. package/test/session-compact.test.ts +171 -0
  945. package/test/session-compaction-transport.test.ts +131 -0
  946. package/test/session-compaction.test.ts +1871 -0
  947. package/test/session-create.test.ts +1643 -0
  948. package/test/session-cwd-instructions.test.ts +304 -0
  949. package/test/session-cwd.test.ts +484 -0
  950. package/test/session-diff.test.ts +207 -0
  951. package/test/session-environment.test.ts +30 -0
  952. package/test/session-error.test.ts +434 -0
  953. package/test/session-execution.test.ts +2298 -0
  954. package/test/session-generate.test.ts +502 -0
  955. package/test/session-instructions.test.ts +378 -0
  956. package/test/session-list.test.ts +72 -0
  957. package/test/session-live-tool-metadata.test.ts +43 -0
  958. package/test/session-log.test.ts +123 -0
  959. package/test/session-model-request-hooks.test.ts +270 -0
  960. package/test/session-model-request.test.ts +243 -0
  961. package/test/session-model-transport-live.test.ts +329 -0
  962. package/test/session-model-transport.test.ts +1109 -0
  963. package/test/session-move.test.ts +671 -0
  964. package/test/session-native-compaction.test.ts +425 -0
  965. package/test/session-native.test.ts +359 -0
  966. package/test/session-owned.test.ts +1073 -0
  967. package/test/session-projector.test.ts +2797 -0
  968. package/test/session-prompt.test.ts +1549 -0
  969. package/test/session-remove.test.ts +117 -0
  970. package/test/session-revert.test.ts +121 -0
  971. package/test/session-run-coordinator.test.ts +711 -0
  972. package/test/session-runner-message.test.ts +1574 -0
  973. package/test/session-runner-recorded.test.ts +288 -0
  974. package/test/session-runner-retry.test.ts +130 -0
  975. package/test/session-runner-tool-events.test.ts +662 -0
  976. package/test/session-runner.test.ts +7859 -0
  977. package/test/session-search-build.test.ts +214 -0
  978. package/test/session-search-index.test.ts +524 -0
  979. package/test/session-search.test.ts +375 -0
  980. package/test/session-shell.test.ts +437 -0
  981. package/test/session-skill.test.ts +228 -0
  982. package/test/session-sql.types.ts +25 -0
  983. package/test/session-stats.test.ts +429 -0
  984. package/test/session-step.test.ts +435 -0
  985. package/test/session-store.test.ts +543 -0
  986. package/test/session-system-prompt.test.ts +8 -0
  987. package/test/session-title.test.ts +767 -0
  988. package/test/session-tool-progress.test.ts +159 -0
  989. package/test/session-usage.test.ts +24 -0
  990. package/test/session-view.test.ts +218 -0
  991. package/test/session-wait.test.ts +41 -0
  992. package/test/shared-cache.test.ts +161 -0
  993. package/test/shared-schema.test.ts +187 -0
  994. package/test/shell-cleanup.test.ts +52 -0
  995. package/test/shell-daemon.test.ts +663 -0
  996. package/test/shell-parse-compatibility.test.ts +451 -0
  997. package/test/shell-parse-parity.test.ts +170 -0
  998. package/test/shell-parse-syntax.test.ts +201 -0
  999. package/test/shell-parse.test.ts +251 -0
  1000. package/test/shell-restart.test.ts +268 -0
  1001. package/test/shell-result.test.ts +65 -0
  1002. package/test/shell-retention.test.ts +162 -0
  1003. package/test/shell-scan/adversarial.test.ts +112 -0
  1004. package/test/shell-scan/arithmetic.test.ts +143 -0
  1005. package/test/shell-scan/bash-safety.test.ts +291 -0
  1006. package/test/shell-scan/bash-syntax.test.ts +361 -0
  1007. package/test/shell-scan/closure.test.ts +47 -0
  1008. package/test/shell-scan/compound-parity.test.ts +131 -0
  1009. package/test/shell-scan/generated.test.ts +201 -0
  1010. package/test/shell-scan/oracle.test.ts +762 -0
  1011. package/test/shell-scan/parity-regressions.test.ts +146 -0
  1012. package/test/shell-scan/powershell-runtime.test.ts +604 -0
  1013. package/test/shell-scan/powershell-safety.test.ts +470 -0
  1014. package/test/shell-scan/powershell-syntax.test.ts +177 -0
  1015. package/test/shell-scan/redirect.test.ts +168 -0
  1016. package/test/shell-scan/scan.test.ts +496 -0
  1017. package/test/shell.test.ts +140 -0
  1018. package/test/skill/instructions.test.ts +216 -0
  1019. package/test/skill-discovery.test.ts +154 -0
  1020. package/test/skill.test.ts +297 -0
  1021. package/test/snapshot.test.ts +488 -0
  1022. package/test/sqlite-bundle.test.ts +53 -0
  1023. package/test/sqlite-interrupt.test.ts +86 -0
  1024. package/test/sqlite-node.test.ts +80 -0
  1025. package/test/sqlite-workerd.test.ts +111 -0
  1026. package/test/state-group.test.ts +138 -0
  1027. package/test/state-replay.test.ts +207 -0
  1028. package/test/state.test.ts +679 -0
  1029. package/test/storage-failure.test.ts +88 -0
  1030. package/test/subagent-completion.test.ts +170 -0
  1031. package/test/subagent-idle-e2e.test.ts +825 -0
  1032. package/test/subagent-lifetime.test.ts +146 -0
  1033. package/test/subagent-report.test.ts +834 -0
  1034. package/test/tool/file-diff.test.ts +45 -0
  1035. package/test/tool-automation.test.ts +345 -0
  1036. package/test/tool-cd.test.ts +372 -0
  1037. package/test/tool-edit.test.ts +888 -0
  1038. package/test/tool-execute.test.ts +1077 -0
  1039. package/test/tool-html-markdown-budget.test.ts +68 -0
  1040. package/test/tool-image-generate.test.ts +547 -0
  1041. package/test/tool-machine.test.ts +84 -0
  1042. package/test/tool-mcp-events.test.ts +90 -0
  1043. package/test/tool-media-target-environment.test.ts +213 -0
  1044. package/test/tool-model-policy.test.ts +289 -0
  1045. package/test/tool-opencode.test.ts +303 -0
  1046. package/test/tool-output.test.ts +334 -0
  1047. package/test/tool-patch-target-environment.test.ts +239 -0
  1048. package/test/tool-patch.test.ts +1265 -0
  1049. package/test/tool-question.test.ts +260 -0
  1050. package/test/tool-read-filesystem.test.ts +833 -0
  1051. package/test/tool-read.test.ts +1341 -0
  1052. package/test/tool-registry.test.ts +1662 -0
  1053. package/test/tool-schema.test.ts +538 -0
  1054. package/test/tool-search-target-environment.test.ts +103 -0
  1055. package/test/tool-search.test.ts +411 -0
  1056. package/test/tool-session-search.test.ts +178 -0
  1057. package/test/tool-shell-target-environment.test.ts +193 -0
  1058. package/test/tool-shell.test.ts +2650 -0
  1059. package/test/tool-skill.test.ts +203 -0
  1060. package/test/tool-subagent.test.ts +1046 -0
  1061. package/test/tool-target-environment.test.ts +183 -0
  1062. package/test/tool-todo.test.ts +75 -0
  1063. package/test/tool-video-generate.test.ts +227 -0
  1064. package/test/tool-webfetch.test.ts +737 -0
  1065. package/test/tool-websearch.test.ts +482 -0
  1066. package/test/tool-write.test.ts +440 -0
  1067. package/test/usage-limits.test.ts +210 -0
  1068. package/test/util/effect-flock.test.ts +331 -0
  1069. package/test/util/error-summary.test.ts +19 -0
  1070. package/test/util/flock.test.ts +326 -0
  1071. package/test/util/fs-util.test.ts +50 -0
  1072. package/test/util/git-executable.test.ts +80 -0
  1073. package/test/util/which.test.ts +99 -0
  1074. package/test/v1-migration.test.ts +1508 -0
  1075. package/test/variant.test.ts +575 -0
  1076. package/test/vcs-hg.test.ts +239 -0
  1077. package/test/vcs.test.ts +1396 -0
  1078. package/test/video-generation.test.ts +146 -0
  1079. package/test/voice.test.ts +332 -0
  1080. package/test/websearch.test.ts +593 -0
  1081. package/test/wellknown.test.ts +132 -0
  1082. package/test/worker-client.test.ts +529 -0
  1083. package/test/workspace.test.ts +828 -0
  1084. package/test/worktree.test.ts +944 -0
  1085. package/tsconfig.build.json +11 -0
  1086. package/tsconfig.json +18 -0
  1087. package/tsconfig.tests.json +13 -0
package/src/git.ts ADDED
@@ -0,0 +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
+ }