@phins/engine 0.0.0-stage → 0.1.2

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 (512) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/PROVENANCE.md +28 -0
  4. package/README.md +10 -2
  5. package/THIRD_PARTY.md +40 -0
  6. package/notices/bun-LICENSE.md +74 -0
  7. package/notices/dependency-licenses.json +2314 -0
  8. package/notices/drizzle-LICENSE +201 -0
  9. package/notices/fff-LICENSE +21 -0
  10. package/notices/node-forge-LICENSE +331 -0
  11. package/notices/opentui-spinner-MIT.txt +27 -0
  12. package/notices/packages__http-recorder__LICENSE +21 -0
  13. package/notices/remeda-LICENSE +21 -0
  14. package/notices/runtime-sources.json +7081 -0
  15. package/notices/seq-queue-LICENSE +22 -0
  16. package/notices/supplemental-notices.json +61 -0
  17. package/notices/third-party-source-LICENSE +21 -0
  18. package/package.json +54 -4
  19. package/src/agents/commands.ts +67 -0
  20. package/src/agents/context/builtins.ts +47 -0
  21. package/src/agents/context/instructions.ts +92 -0
  22. package/src/agents/context/registry.ts +53 -0
  23. package/src/agents/context/system.ts +329 -0
  24. package/src/agents/questions.ts +219 -0
  25. package/src/agents/references/guidance.ts +71 -0
  26. package/src/agents/references/registry.ts +122 -0
  27. package/src/agents/registry.ts +108 -0
  28. package/src/agents/resources/client.ts +185 -0
  29. package/src/agents/resources/contract.ts +71 -0
  30. package/src/agents/resources/error.ts +7 -0
  31. package/src/agents/skills/discovery.ts +167 -0
  32. package/src/agents/skills/guidance.ts +76 -0
  33. package/src/agents/skills/registry.ts +131 -0
  34. package/src/contracts/agents/agent.ts +36 -0
  35. package/src/contracts/agents/command.ts +14 -0
  36. package/src/contracts/agents/question-compat.ts +66 -0
  37. package/src/contracts/agents/question.ts +79 -0
  38. package/src/contracts/agents/reference.ts +36 -0
  39. package/src/contracts/agents/skill.ts +54 -0
  40. package/src/contracts/events/durable-manifest.ts +10 -0
  41. package/src/contracts/events/event.ts +125 -0
  42. package/src/contracts/events/filesystem.ts +13 -0
  43. package/src/contracts/events/installation.ts +20 -0
  44. package/src/contracts/events/legacy.ts +18 -0
  45. package/src/contracts/events/manifest.ts +82 -0
  46. package/src/contracts/events/mcp.ts +21 -0
  47. package/src/contracts/events/server.ts +8 -0
  48. package/src/contracts/events/session-compaction.ts +13 -0
  49. package/src/contracts/events/session-status.ts +50 -0
  50. package/src/contracts/events/session.ts +734 -0
  51. package/src/contracts/events/tui.ts +58 -0
  52. package/src/contracts/events/vcs.ts +13 -0
  53. package/src/contracts/events/workspace.ts +32 -0
  54. package/src/contracts/events/worktree.ts +21 -0
  55. package/src/contracts/execution/terminal-ticket.ts +9 -0
  56. package/src/contracts/execution/terminal.ts +55 -0
  57. package/src/contracts/execution/verification-receipt.ts +281 -0
  58. package/src/contracts/extensions/connection.ts +22 -0
  59. package/src/contracts/extensions/integration-id.ts +7 -0
  60. package/src/contracts/extensions/integration.ts +128 -0
  61. package/src/contracts/extensions/plugin.ts +15 -0
  62. package/src/contracts/identifier.ts +30 -0
  63. package/src/contracts/inference/catalog.ts +6 -0
  64. package/src/contracts/inference/llm.ts +23 -0
  65. package/src/contracts/inference/model.ts +103 -0
  66. package/src/contracts/inference/models-dev.ts +9 -0
  67. package/src/contracts/inference/provider.ts +69 -0
  68. package/src/contracts/schema.ts +30 -0
  69. package/src/contracts/security/credential.ts +34 -0
  70. package/src/contracts/security/permission-compat.ts +71 -0
  71. package/src/contracts/security/permission-saved.ts +20 -0
  72. package/src/contracts/security/permission.ts +64 -0
  73. package/src/contracts/session/compat.ts +676 -0
  74. package/src/contracts/session/delivery.ts +6 -0
  75. package/src/contracts/session/id.ts +20 -0
  76. package/src/contracts/session/info.ts +52 -0
  77. package/src/contracts/session/input-origin.ts +43 -0
  78. package/src/contracts/session/input.ts +24 -0
  79. package/src/contracts/session/live.ts +43 -0
  80. package/src/contracts/session/message-id.ts +11 -0
  81. package/src/contracts/session/message.ts +206 -0
  82. package/src/contracts/session/prompt.ts +56 -0
  83. package/src/contracts/session/revert.ts +23 -0
  84. package/src/contracts/session/run-state.ts +109 -0
  85. package/src/contracts/session/todo.ts +24 -0
  86. package/src/contracts/workspace/file-diff.ts +12 -0
  87. package/src/contracts/workspace/filesystem.ts +39 -0
  88. package/src/contracts/workspace/location.ts +30 -0
  89. package/src/contracts/workspace/project-copy.ts +29 -0
  90. package/src/contracts/workspace/project-directories.ts +11 -0
  91. package/src/contracts/workspace/project-id.ts +8 -0
  92. package/src/contracts/workspace/project.ts +41 -0
  93. package/src/contracts/workspace/workspace-id.ts +19 -0
  94. package/src/contracts/workspace/workspace.ts +9 -0
  95. package/src/execution/commands/executor.ts +44 -0
  96. package/src/execution/commands/provider.ts +54 -0
  97. package/src/execution/commands/runner.ts +26 -0
  98. package/src/execution/control/command.ts +55 -0
  99. package/src/execution/control/grant.ts +123 -0
  100. package/src/execution/control/promotion.ts +113 -0
  101. package/src/execution/control/receiver.ts +153 -0
  102. package/src/execution/control/restoration.ts +264 -0
  103. package/src/execution/identity.ts +432 -0
  104. package/src/execution/process/runner.ts +243 -0
  105. package/src/execution/process/sessions.ts +239 -0
  106. package/src/execution/process/spawner.ts +508 -0
  107. package/src/execution/sandbox.ts +143 -0
  108. package/src/execution/shell.ts +226 -0
  109. package/src/execution/terminal/native.ts +26 -0
  110. package/src/execution/terminal/protocol.ts +37 -0
  111. package/src/execution/terminal/schema.ts +1 -0
  112. package/src/execution/terminal/service.ts +318 -0
  113. package/src/execution/terminal/ticket.ts +57 -0
  114. package/src/execution/terminal/types.ts +25 -0
  115. package/src/extensions/agents.ts +211 -0
  116. package/src/extensions/api/agent.ts +14 -0
  117. package/src/extensions/api/catalog.ts +29 -0
  118. package/src/extensions/api/command.ts +13 -0
  119. package/src/extensions/api/context.ts +27 -0
  120. package/src/extensions/api/integration.ts +63 -0
  121. package/src/extensions/api/plugin.ts +17 -0
  122. package/src/extensions/api/reference.ts +12 -0
  123. package/src/extensions/api/registration.ts +16 -0
  124. package/src/extensions/api/skill.ts +11 -0
  125. package/src/extensions/api/tool.ts +58 -0
  126. package/src/extensions/api.ts +6 -0
  127. package/src/extensions/definition.ts +13 -0
  128. package/src/extensions/host.ts +225 -0
  129. package/src/extensions/integrations/service.ts +517 -0
  130. package/src/extensions/internal.ts +117 -0
  131. package/src/extensions/mcp/local.ts +352 -0
  132. package/src/extensions/mcp/schema.ts +21 -0
  133. package/src/extensions/mcp/tool-names.ts +26 -0
  134. package/src/extensions/mcp/tool.ts +149 -0
  135. package/src/extensions/models-dev.ts +135 -0
  136. package/src/extensions/options.ts +1 -0
  137. package/src/extensions/service.ts +152 -0
  138. package/src/extensions/skills/customize-phins.md +106 -0
  139. package/src/extensions/skills.ts +31 -0
  140. package/src/extensions/tools.ts +88 -0
  141. package/src/inference/api.ts +34 -0
  142. package/src/inference/cache-policy.ts +111 -0
  143. package/src/inference/catalog/discovery.ts +163 -0
  144. package/src/inference/catalog/metadata.ts +249 -0
  145. package/src/inference/catalog/model.ts +41 -0
  146. package/src/inference/catalog/provider.ts +25 -0
  147. package/src/inference/catalog/registry.ts +437 -0
  148. package/src/inference/errors.ts +32 -0
  149. package/src/inference/protocols/openai-chat.ts +497 -0
  150. package/src/inference/protocols/openai-compatible-chat.ts +24 -0
  151. package/src/inference/protocols/shared.ts +483 -0
  152. package/src/inference/protocols/utils/lifecycle.ts +102 -0
  153. package/src/inference/protocols/utils/openai-options.ts +93 -0
  154. package/src/inference/protocols/utils/tool-stream.ts +214 -0
  155. package/src/inference/provider.ts +37 -0
  156. package/src/inference/request/api.ts +27 -0
  157. package/src/inference/request/auth-options.ts +57 -0
  158. package/src/inference/request/auth.ts +161 -0
  159. package/src/inference/request/client.ts +490 -0
  160. package/src/inference/request/endpoint.ts +55 -0
  161. package/src/inference/request/execution-boundary.ts +41 -0
  162. package/src/inference/request/executor.ts +478 -0
  163. package/src/inference/request/framing.ts +27 -0
  164. package/src/inference/request/protocol.ts +90 -0
  165. package/src/inference/request/spending.ts +159 -0
  166. package/src/inference/requests.ts +193 -0
  167. package/src/inference/schema/errors.ts +194 -0
  168. package/src/inference/schema/events.ts +372 -0
  169. package/src/inference/schema/ids.ts +43 -0
  170. package/src/inference/schema/messages.ts +312 -0
  171. package/src/inference/schema/options.ts +247 -0
  172. package/src/inference/schema.ts +5 -0
  173. package/src/inference/tools/definition.ts +253 -0
  174. package/src/inference/tools/dispatcher.ts +83 -0
  175. package/src/inference/tools/failure.ts +19 -0
  176. package/src/inference/transports/http.ts +115 -0
  177. package/src/inference/transports/transport.ts +34 -0
  178. package/src/inference/transports/websocket.ts +322 -0
  179. package/src/runtime/effect/keyed-mutex.ts +45 -0
  180. package/src/runtime/effect/platform.ts +12 -0
  181. package/src/runtime/effect/service-access.ts +43 -0
  182. package/src/runtime/effect/service-graph.ts +102 -0
  183. package/src/runtime/events/bus.ts +1222 -0
  184. package/src/runtime/events/session-deltas.ts +128 -0
  185. package/src/runtime/events/verification-publisher.ts +9 -0
  186. package/src/runtime/flags.ts +78 -0
  187. package/src/runtime/markdown.d.ts +4 -0
  188. package/src/runtime/paths.ts +87 -0
  189. package/src/runtime/services.ts +240 -0
  190. package/src/runtime/state.ts +128 -0
  191. package/src/runtime/vendor.d.ts +25 -0
  192. package/src/runtime/version.ts +8 -0
  193. package/src/security/credentials.ts +137 -0
  194. package/src/security/launcher-policy.ts +68 -0
  195. package/src/security/permissions/delegation.ts +32 -0
  196. package/src/security/permissions/origin.ts +70 -0
  197. package/src/security/permissions/saved.ts +78 -0
  198. package/src/security/permissions/service.ts +533 -0
  199. package/src/security/policy.ts +46 -0
  200. package/src/sessions/actions/administration.ts +109 -0
  201. package/src/sessions/actions/command-template.ts +23 -0
  202. package/src/sessions/actions/commands.ts +258 -0
  203. package/src/sessions/actions/errors.ts +16 -0
  204. package/src/sessions/actions/operations.ts +271 -0
  205. package/src/sessions/actions/revert.ts +121 -0
  206. package/src/sessions/context/checkpoint.ts +330 -0
  207. package/src/sessions/context/compaction.ts +268 -0
  208. package/src/sessions/context/epoch.ts +173 -0
  209. package/src/sessions/context/selection.ts +30 -0
  210. package/src/sessions/errors.ts +38 -0
  211. package/src/sessions/identifiers.ts +25 -0
  212. package/src/sessions/info.ts +90 -0
  213. package/src/sessions/input/inbox.ts +514 -0
  214. package/src/sessions/input/origin.ts +131 -0
  215. package/src/sessions/input/turns.ts +125 -0
  216. package/src/sessions/messages/history.ts +101 -0
  217. package/src/sessions/messages/service.ts +2 -0
  218. package/src/sessions/messages/updater.ts +420 -0
  219. package/src/sessions/projector.ts +699 -0
  220. package/src/sessions/run/budget.ts +62 -0
  221. package/src/sessions/run/chat-scope.ts +62 -0
  222. package/src/sessions/run/coding-workflow.ts +82 -0
  223. package/src/sessions/run/coordinator.ts +192 -0
  224. package/src/sessions/run/events.ts +572 -0
  225. package/src/sessions/run/execution.ts +57 -0
  226. package/src/sessions/run/inference.ts +1466 -0
  227. package/src/sessions/run/lifecycle.ts +316 -0
  228. package/src/sessions/run/local-executor.ts +307 -0
  229. package/src/sessions/run/loop.ts +33 -0
  230. package/src/sessions/run/messages.ts +161 -0
  231. package/src/sessions/run/model.ts +232 -0
  232. package/src/sessions/run/state.ts +288 -0
  233. package/src/sessions/run/subtasks.ts +190 -0
  234. package/src/sessions/runtime.ts +40 -0
  235. package/src/sessions/service.ts +686 -0
  236. package/src/sessions/store.ts +129 -0
  237. package/src/sessions/tasks.ts +78 -0
  238. package/src/sessions/title.ts +23 -0
  239. package/src/sessions/usage/contribution-value.ts +48 -0
  240. package/src/sessions/usage/contribution.ts +511 -0
  241. package/src/sessions/usage/cost.ts +21 -0
  242. package/src/sessions/verification/history.ts +79 -0
  243. package/src/sessions/verification/recovery.ts +971 -0
  244. package/src/sessions/verification/service.ts +671 -0
  245. package/src/settings/agents.ts +23 -0
  246. package/src/settings/attachments.ts +15 -0
  247. package/src/settings/commands.ts +12 -0
  248. package/src/settings/compaction.ts +15 -0
  249. package/src/settings/config.ts +234 -0
  250. package/src/settings/experimental.ts +18 -0
  251. package/src/settings/formatters.ts +12 -0
  252. package/src/settings/markdown.ts +36 -0
  253. package/src/settings/mcp.ts +39 -0
  254. package/src/settings/plugins/agent.ts +108 -0
  255. package/src/settings/plugins/command.ts +82 -0
  256. package/src/settings/plugins/provider.ts +113 -0
  257. package/src/settings/plugins/reference.ts +68 -0
  258. package/src/settings/plugins/skill.ts +50 -0
  259. package/src/settings/plugins.ts +13 -0
  260. package/src/settings/providers.ts +71 -0
  261. package/src/settings/references.ts +22 -0
  262. package/src/settings/tool-output.ts +9 -0
  263. package/src/settings/watchers.ts +7 -0
  264. package/src/shared/effect-flock.ts +93 -0
  265. package/src/shared/encode.ts +51 -0
  266. package/src/shared/flock.ts +584 -0
  267. package/src/shared/glob.ts +34 -0
  268. package/src/shared/hash.ts +11 -0
  269. package/src/shared/lazy.ts +26 -0
  270. package/src/shared/prefixed-id.ts +47 -0
  271. package/src/shared/record.ts +3 -0
  272. package/src/shared/schema.ts +87 -0
  273. package/src/shared/slug.ts +74 -0
  274. package/src/shared/token.ts +5 -0
  275. package/src/shared/which.ts +14 -0
  276. package/src/shared/wildcard.ts +48 -0
  277. package/src/storage/database.ts +63 -0
  278. package/src/storage/drizzle/effect-sqlite/driver.ts +77 -0
  279. package/src/storage/drizzle/effect-sqlite/migrator.ts +14 -0
  280. package/src/storage/drizzle/effect-sqlite/session.ts +218 -0
  281. package/src/storage/drizzle/index.ts +10 -0
  282. package/src/storage/drizzle/internal/drizzle-utils.ts +127 -0
  283. package/src/storage/drizzle/sqlite-core/effect/count.ts +58 -0
  284. package/src/storage/drizzle/sqlite-core/effect/db.ts +296 -0
  285. package/src/storage/drizzle/sqlite-core/effect/delete.ts +261 -0
  286. package/src/storage/drizzle/sqlite-core/effect/insert.ts +349 -0
  287. package/src/storage/drizzle/sqlite-core/effect/query.ts +198 -0
  288. package/src/storage/drizzle/sqlite-core/effect/raw.ts +49 -0
  289. package/src/storage/drizzle/sqlite-core/effect/select.ts +279 -0
  290. package/src/storage/drizzle/sqlite-core/effect/session.ts +490 -0
  291. package/src/storage/drizzle/sqlite-core/effect/update.ts +402 -0
  292. package/src/storage/drizzle/up-migrations/effect-sqlite.ts +102 -0
  293. package/src/storage/drizzle/up-migrations/sqlite.ts +253 -0
  294. package/src/storage/drizzle/up-migrations/utils.ts +45 -0
  295. package/src/storage/migration.gen.ts +62 -0
  296. package/src/storage/migration.ts +168 -0
  297. package/src/storage/migrations/20260127222353_familiar_lady_ursula.ts +107 -0
  298. package/src/storage/migrations/20260211171708_add_project_commands.ts +11 -0
  299. package/src/storage/migrations/20260213144116_wakeful_the_professor.ts +23 -0
  300. package/src/storage/migrations/20260225215848_workspace.ts +19 -0
  301. package/src/storage/migrations/20260227213759_add_session_workspace_id.ts +12 -0
  302. package/src/storage/migrations/20260228203230_blue_harpoon.ts +30 -0
  303. package/src/storage/migrations/20260303231226_add_workspace_fields.ts +15 -0
  304. package/src/storage/migrations/20260309230000_move_org_to_state.ts +15 -0
  305. package/src/storage/migrations/20260312043431_session_message_cursor.ts +16 -0
  306. package/src/storage/migrations/20260323234822_events.ts +26 -0
  307. package/src/storage/migrations/20260410174513_workspace-name.ts +29 -0
  308. package/src/storage/migrations/20260413175956_chief_energizer.ts +24 -0
  309. package/src/storage/migrations/20260423070820_add_icon_url_override.ts +14 -0
  310. package/src/storage/migrations/20260427172553_slow_nightmare.ts +30 -0
  311. package/src/storage/migrations/20260428004200_add_session_path.ts +11 -0
  312. package/src/storage/migrations/20260501142318_next_venus.ts +12 -0
  313. package/src/storage/migrations/20260504145000_add_sync_owner.ts +11 -0
  314. package/src/storage/migrations/20260507164347_add_workspace_time.ts +11 -0
  315. package/src/storage/migrations/20260510033149_session_usage.ts +56 -0
  316. package/src/storage/migrations/20260511000411_data_migration_state.ts +16 -0
  317. package/src/storage/migrations/20260511173437_session-metadata.ts +16 -0
  318. package/src/storage/migrations/20260601010001_normalize_storage_paths.ts +22 -0
  319. package/src/storage/migrations/20260601202201_amazing_prowler.ts +11 -0
  320. package/src/storage/migrations/20260602002951_lowly_union_jack.ts +24 -0
  321. package/src/storage/migrations/20260602182828_add_project_directories.ts +20 -0
  322. package/src/storage/migrations/20260603001617_session_message_projection_indexes.ts +19 -0
  323. package/src/storage/migrations/20260603040000_session_message_projection_order.ts +19 -0
  324. package/src/storage/migrations/20260603141458_session_input_inbox.ts +25 -0
  325. package/src/storage/migrations/20260603160727_jittery_ezekiel_stane.ts +20 -0
  326. package/src/storage/migrations/20260604172448_event_sourced_session_input.ts +47 -0
  327. package/src/storage/migrations/20260605003541_add_session_context_snapshot.ts +21 -0
  328. package/src/storage/migrations/20260605042240_add_context_epoch_agent.ts +11 -0
  329. package/src/storage/migrations/20260611035744_credential.ts +25 -0
  330. package/src/storage/migrations/20260611192811_lush_chimera.ts +25 -0
  331. package/src/storage/migrations/20260612174303_project_dir_strategy.ts +29 -0
  332. package/src/storage/migrations/20260622142730_simplify_session_context_epoch.ts +13 -0
  333. package/src/storage/migrations/20260622170816_reset_v2_session_state.ts +17 -0
  334. package/src/storage/migrations/20260622202450_simplify_session_input.ts +17 -0
  335. package/src/storage/migrations/20260722030810_rolling_work_context_epoch.ts +44 -0
  336. package/src/storage/migrations/20260729010558_verification_receipt.ts +45 -0
  337. package/src/storage/migrations/20260729040943_verification_request_outbox.ts +35 -0
  338. package/src/storage/migrations/20260731015112_verification_attempt_lease.ts +16 -0
  339. package/src/storage/migrations/20260731022945_verification_attempt_timeout.ts +11 -0
  340. package/src/storage/migrations/20260731023300_event_owner_generation.ts +11 -0
  341. package/src/storage/migrations/20260731031224_session_warp_outbox.ts +38 -0
  342. package/src/storage/migrations/20260731073410_workspace-mutation-lease.ts +28 -0
  343. package/src/storage/migrations/20260731074831_verification-execution-attestation.ts +11 -0
  344. package/src/storage/migrations/20260731081000_workspace-session-mutation-fences.ts +67 -0
  345. package/src/storage/migrations/20260801155612_session_run_state.ts +33 -0
  346. package/src/storage/migrations/20260801162000_session_usage_contribution.ts +46 -0
  347. package/src/storage/migrations/20260801163000_backfill_session_transcript.ts +551 -0
  348. package/src/storage/migrations/20260913045944_session_tree_budget.ts +20 -0
  349. package/src/storage/migrations/20261005065909_session_input_origin.ts +25 -0
  350. package/src/storage/migrations/20261005143808_session_run_input_owner.ts +13 -0
  351. package/src/storage/migrations/20261006020515_node_command_receipt.ts +19 -0
  352. package/src/storage/migrations/20261009151628_session_command_receipt.ts +21 -0
  353. package/src/storage/offline.ts +34 -0
  354. package/src/storage/path.ts +91 -0
  355. package/src/storage/schema.gen.ts +490 -0
  356. package/src/storage/schema.sql.ts +10 -0
  357. package/src/storage/sqlite.bun.ts +195 -0
  358. package/src/storage/sqlite.ts +8 -0
  359. package/src/storage/tables/commands.ts +19 -0
  360. package/src/storage/tables/credentials.ts +14 -0
  361. package/src/storage/tables/events.ts +26 -0
  362. package/src/storage/tables/permissions.ts +20 -0
  363. package/src/storage/tables/projects.ts +35 -0
  364. package/src/storage/tables/sessions.ts +358 -0
  365. package/src/storage/tables/workspaces.ts +87 -0
  366. package/src/tools/admission.ts +29 -0
  367. package/src/tools/application.ts +54 -0
  368. package/src/tools/builtins.ts +50 -0
  369. package/src/tools/definition.ts +198 -0
  370. package/src/tools/files/edit.ts +200 -0
  371. package/src/tools/files/format.ts +46 -0
  372. package/src/tools/files/glob.ts +102 -0
  373. package/src/tools/files/grep.ts +134 -0
  374. package/src/tools/files/patch.ts +179 -0
  375. package/src/tools/files/read.ts +146 -0
  376. package/src/tools/files/reader.ts +363 -0
  377. package/src/tools/files/write.ts +94 -0
  378. package/src/tools/output-store.ts +217 -0
  379. package/src/tools/planning.ts +56 -0
  380. package/src/tools/process/session.ts +44 -0
  381. package/src/tools/process/shell.ts +271 -0
  382. package/src/tools/question.ts +107 -0
  383. package/src/tools/registration.ts +13 -0
  384. package/src/tools/registry.ts +248 -0
  385. package/src/tools/skill.ts +103 -0
  386. package/src/tools/task.ts +100 -0
  387. package/src/tools/web/body.ts +30 -0
  388. package/src/tools/web/fetch.ts +211 -0
  389. package/src/tools/web/search.ts +253 -0
  390. package/src/transport/api/definition.ts +103 -0
  391. package/src/transport/api/errors.ts +112 -0
  392. package/src/transport/api/middleware/authorization.ts +7 -0
  393. package/src/transport/api/middleware/schema-error.ts +8 -0
  394. package/src/transport/api/middleware/service-admission.ts +8 -0
  395. package/src/transport/api/resources/agent.ts +21 -0
  396. package/src/transport/api/resources/command.ts +28 -0
  397. package/src/transport/api/resources/credential.ts +38 -0
  398. package/src/transport/api/resources/event.ts +61 -0
  399. package/src/transport/api/resources/fs.ts +69 -0
  400. package/src/transport/api/resources/health.ts +65 -0
  401. package/src/transport/api/resources/integration.ts +131 -0
  402. package/src/transport/api/resources/location.ts +43 -0
  403. package/src/transport/api/resources/message.ts +69 -0
  404. package/src/transport/api/resources/model.ts +33 -0
  405. package/src/transport/api/resources/permission.ts +96 -0
  406. package/src/transport/api/resources/project-copy.ts +57 -0
  407. package/src/transport/api/resources/project.ts +19 -0
  408. package/src/transport/api/resources/provider.ts +46 -0
  409. package/src/transport/api/resources/pty.ts +143 -0
  410. package/src/transport/api/resources/question.ts +85 -0
  411. package/src/transport/api/resources/reference.ts +28 -0
  412. package/src/transport/api/resources/service.ts +46 -0
  413. package/src/transport/api/resources/session.ts +477 -0
  414. package/src/transport/api/resources/skill.ts +28 -0
  415. package/src/transport/api/resources/tui.ts +100 -0
  416. package/src/transport/client/connection.ts +389 -0
  417. package/src/transport/client/create.ts +112 -0
  418. package/src/transport/client/errors.ts +51 -0
  419. package/src/transport/client/events.ts +218 -0
  420. package/src/transport/client/generated/client/client.gen.ts +311 -0
  421. package/src/transport/client/generated/client/index.ts +25 -0
  422. package/src/transport/client/generated/client/types.gen.ts +241 -0
  423. package/src/transport/client/generated/client/utils.gen.ts +337 -0
  424. package/src/transport/client/generated/client.gen.ts +25 -0
  425. package/src/transport/client/generated/core/auth.gen.ts +42 -0
  426. package/src/transport/client/generated/core/bodySerializer.gen.ts +100 -0
  427. package/src/transport/client/generated/core/params.gen.ts +176 -0
  428. package/src/transport/client/generated/core/pathSerializer.gen.ts +181 -0
  429. package/src/transport/client/generated/core/queryKeySerializer.gen.ts +136 -0
  430. package/src/transport/client/generated/core/serverSentEvents.gen.ts +266 -0
  431. package/src/transport/client/generated/core/types.gen.ts +118 -0
  432. package/src/transport/client/generated/core/utils.gen.ts +143 -0
  433. package/src/transport/client/generated/sdk.gen.ts +6695 -0
  434. package/src/transport/client/generated/types.gen.ts +16571 -0
  435. package/src/transport/client/session-state.ts +341 -0
  436. package/src/transport/host/api.ts +9 -0
  437. package/src/transport/host/auth.ts +64 -0
  438. package/src/transport/host/cors.ts +35 -0
  439. package/src/transport/host/handlers/agent.ts +14 -0
  440. package/src/transport/host/handlers/command.ts +9 -0
  441. package/src/transport/host/handlers/credential.ts +23 -0
  442. package/src/transport/host/handlers/event.ts +39 -0
  443. package/src/transport/host/handlers/fs.ts +40 -0
  444. package/src/transport/host/handlers/health.ts +11 -0
  445. package/src/transport/host/handlers/integration.ts +105 -0
  446. package/src/transport/host/handlers/location.ts +19 -0
  447. package/src/transport/host/handlers/message.ts +65 -0
  448. package/src/transport/host/handlers/model.ts +25 -0
  449. package/src/transport/host/handlers/permission.ts +68 -0
  450. package/src/transport/host/handlers/project-copy.ts +69 -0
  451. package/src/transport/host/handlers/project.ts +32 -0
  452. package/src/transport/host/handlers/provider.ts +33 -0
  453. package/src/transport/host/handlers/pty.ts +224 -0
  454. package/src/transport/host/handlers/question.ts +63 -0
  455. package/src/transport/host/handlers/reference.ts +9 -0
  456. package/src/transport/host/handlers/service.ts +24 -0
  457. package/src/transport/host/handlers/session.ts +581 -0
  458. package/src/transport/host/handlers/skill.ts +9 -0
  459. package/src/transport/host/handlers/tui.ts +136 -0
  460. package/src/transport/host/handlers.ts +68 -0
  461. package/src/transport/host/location.ts +66 -0
  462. package/src/transport/host/middleware/authorization.ts +59 -0
  463. package/src/transport/host/middleware/schema-error.ts +17 -0
  464. package/src/transport/host/middleware/service-admission.ts +22 -0
  465. package/src/transport/host/middleware/session-location.ts +72 -0
  466. package/src/transport/host/pty-environment.ts +17 -0
  467. package/src/transport/host/routes.ts +67 -0
  468. package/src/transport/host/runtime.ts +22 -0
  469. package/src/transport/host/service-control.ts +143 -0
  470. package/src/transport/host/sse.ts +415 -0
  471. package/src/transport/host/utf8.ts +26 -0
  472. package/src/verification/authority.ts +547 -0
  473. package/src/verification/canonical-signature.ts +145 -0
  474. package/src/verification/containment.ts +197 -0
  475. package/src/verification/enforcement.ts +255 -0
  476. package/src/verification/execution-attestation.ts +321 -0
  477. package/src/verification/key-lifecycle.ts +456 -0
  478. package/src/verification/local.ts +87 -0
  479. package/src/verification/oci/containment.ts +529 -0
  480. package/src/verification/oci/lease.ts +1549 -0
  481. package/src/verification/oci/runtime.ts +309 -0
  482. package/src/verification/oci/supervisor.ts +429 -0
  483. package/src/verification/registry.ts +379 -0
  484. package/src/verification/settlement-admission.ts +322 -0
  485. package/src/verification/trusted-file.ts +372 -0
  486. package/src/workspace/files/access.ts +257 -0
  487. package/src/workspace/files/diff.ts +6 -0
  488. package/src/workspace/files/formatter.ts +130 -0
  489. package/src/workspace/files/ignore.ts +67 -0
  490. package/src/workspace/files/mutation.ts +203 -0
  491. package/src/workspace/files/patch.ts +197 -0
  492. package/src/workspace/files/protected.ts +53 -0
  493. package/src/workspace/files/service.ts +115 -0
  494. package/src/workspace/files/watcher.ts +138 -0
  495. package/src/workspace/location.ts +35 -0
  496. package/src/workspace/media/image.ts +78 -0
  497. package/src/workspace/media/photon.ts +95 -0
  498. package/src/workspace/mutations.ts +158 -0
  499. package/src/workspace/projects/copy-strategies.ts +35 -0
  500. package/src/workspace/projects/copy.ts +282 -0
  501. package/src/workspace/projects/directories.ts +159 -0
  502. package/src/workspace/projects/schema.ts +16 -0
  503. package/src/workspace/projects/service.ts +136 -0
  504. package/src/workspace/repository/cache.ts +261 -0
  505. package/src/workspace/repository/git.ts +4272 -0
  506. package/src/workspace/repository/reference.ts +217 -0
  507. package/src/workspace/repository/retention-barrier.ts +18 -0
  508. package/src/workspace/repository/snapshot.ts +791 -0
  509. package/src/workspace/search/binary.ts +134 -0
  510. package/src/workspace/search/native.ts +140 -0
  511. package/src/workspace/search/ripgrep.ts +282 -0
  512. package/src/workspace/search/service.ts +239 -0
@@ -0,0 +1,4272 @@
1
+ export * as Git from "./git";
2
+
3
+ import path from "path";
4
+ import { randomUUID } from "crypto";
5
+ import { constants, type BigIntStats } from "node:fs";
6
+ import { lstat, open, realpath } from "node:fs/promises";
7
+ import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
8
+ import { ChildProcess } from "effect/unstable/process";
9
+ import { AbsolutePath, RelativePath } from "../../shared/schema";
10
+ import { FileAccess } from "../files/access";
11
+ import { ProcessRunner } from "../../execution/process/runner";
12
+ import { ServiceGraph } from "../../runtime/effect/service-graph";
13
+ import { File } from "../files/diff";
14
+ import { KeyedMutex } from "../../runtime/effect/keyed-mutex";
15
+ import { Flock } from "../../shared/flock";
16
+ import { Hash } from "../../shared/hash";
17
+
18
+ export class Repository extends Schema.Class<Repository>("Git.Repository")({
19
+ worktree: AbsolutePath,
20
+ gitDirectory: AbsolutePath,
21
+ commonDirectory: AbsolutePath,
22
+ }) {}
23
+
24
+ export const ChangeSet = Schema.String.pipe(Schema.brand("Git.ChangeSet"));
25
+ export type ChangeSet = typeof ChangeSet.Type;
26
+
27
+ export const TreeID = Schema.String.pipe(Schema.brand("Git.TreeID"));
28
+ export type TreeID = typeof TreeID.Type;
29
+
30
+ /** Canonical namespace used to retain captured snapshot trees. */
31
+ export const SNAPSHOT_REF_PREFIX = "refs/phins/snapshots";
32
+
33
+ /** Build the content-addressed ref for a captured snapshot tree. */
34
+ export const snapshotRef = (tree: string) => `${SNAPSHOT_REF_PREFIX}/${tree}`;
35
+
36
+ /** Candidate refs keep swept objects reachable until the atomic delete step. */
37
+ export const SNAPSHOT_RECLAIM_REF_PREFIX =
38
+ "refs/phins/snapshot-reclaim-candidates";
39
+
40
+ export const snapshotReclaimRef = (tree: string) =>
41
+ `${SNAPSHOT_RECLAIM_REF_PREFIX}/${tree}`;
42
+
43
+ /** Versioned contract persisted before a snapshot store may retain captures. */
44
+ export const SnapshotStoreDescriptorV1 = Schema.Struct({
45
+ version: Schema.Literal(1),
46
+ snapshotID: Schema.Literal("git-tree-oid"),
47
+ localization: Schema.Literal("reachable-non-thin-pack-v1"),
48
+ coverage: Schema.Literal("captures-after-descriptor"),
49
+ retention: Schema.Literal("content-addressed-ref-v1"),
50
+ reclamation: Schema.Literal("none"),
51
+ });
52
+ export type SnapshotStoreDescriptorV1 = typeof SnapshotStoreDescriptorV1.Type;
53
+
54
+ /** Installed only after an authoritative durable live-set backfill succeeds. */
55
+ export const SnapshotStoreDescriptorV2 = Schema.Struct({
56
+ version: Schema.Literal(2),
57
+ snapshotID: Schema.Literal("git-tree-oid"),
58
+ localization: Schema.Literal("reachable-non-thin-pack-v1"),
59
+ coverage: Schema.Literal("durable-live-set-backfill-v1"),
60
+ retention: Schema.Literal("content-addressed-ref-v1"),
61
+ reclamation: Schema.Literal("two-pass-live-mark-sweep-v1"),
62
+ });
63
+ export type SnapshotStoreDescriptorV2 = typeof SnapshotStoreDescriptorV2.Type;
64
+
65
+ export const SnapshotStoreDescriptor = Schema.Union([
66
+ SnapshotStoreDescriptorV1,
67
+ SnapshotStoreDescriptorV2,
68
+ ]);
69
+ export type SnapshotStoreDescriptor = typeof SnapshotStoreDescriptor.Type;
70
+
71
+ export const SNAPSHOT_STORE_DESCRIPTOR = Object.freeze({
72
+ version: 1,
73
+ snapshotID: "git-tree-oid",
74
+ localization: "reachable-non-thin-pack-v1",
75
+ coverage: "captures-after-descriptor",
76
+ retention: "content-addressed-ref-v1",
77
+ reclamation: "none",
78
+ } as const satisfies SnapshotStoreDescriptor);
79
+
80
+ export const SNAPSHOT_STORE_DESCRIPTOR_V2 = Object.freeze({
81
+ version: 2,
82
+ snapshotID: "git-tree-oid",
83
+ localization: "reachable-non-thin-pack-v1",
84
+ coverage: "durable-live-set-backfill-v1",
85
+ retention: "content-addressed-ref-v1",
86
+ reclamation: "two-pass-live-mark-sweep-v1",
87
+ } as const satisfies SnapshotStoreDescriptor);
88
+
89
+ /** One atomic Git-config value keeps descriptor upgrades fail-closed. */
90
+ export const SNAPSHOT_STORE_DESCRIPTOR_KEY = "phins.snapshot.descriptor";
91
+ export const SNAPSHOT_STORE_DESCRIPTOR_JSON = JSON.stringify(
92
+ SNAPSHOT_STORE_DESCRIPTOR,
93
+ );
94
+ export const SNAPSHOT_STORE_DESCRIPTOR_V2_JSON = JSON.stringify(
95
+ SNAPSHOT_STORE_DESCRIPTOR_V2,
96
+ );
97
+
98
+ /** One exact value records the first pass used to age reclaim candidates. */
99
+ export const SNAPSHOT_RECLAMATION_STATE_KEY =
100
+ "phins.snapshot.reclamation-state";
101
+ export const SNAPSHOT_RECLAMATION_MIN_AGE_MS = 24 * 60 * 60 * 1_000;
102
+ export const MAX_SNAPSHOT_RETENTION_REFS = 100_000;
103
+ export const MAX_SNAPSHOT_RETENTION_MANIFEST_BYTES = 16 * 1024 * 1024;
104
+
105
+ export interface SnapshotRetentionReport {
106
+ readonly live: number;
107
+ readonly retained: number;
108
+ readonly candidates: number;
109
+ readonly reclaimed: number;
110
+ readonly garbageCollected: boolean;
111
+ readonly preparedAt: number;
112
+ readonly eligibleAt: number;
113
+ }
114
+
115
+ /**
116
+ * Snapshot repositories retain captured trees under custom refs. These local
117
+ * settings also prevent automatic maintenance from racing unretained legacy
118
+ * objects while authoritative historical backfill and reclamation are pending.
119
+ */
120
+ export const SNAPSHOT_RETENTION_CONFIG = Object.freeze([
121
+ Object.freeze(["gc.auto", "0"] as const),
122
+ Object.freeze(["gc.autoPackLimit", "0"] as const),
123
+ Object.freeze(["maintenance.auto", "false"] as const),
124
+ Object.freeze(["gc.pruneExpire", "never"] as const),
125
+ ]);
126
+
127
+ /** Maximum in-memory non-thin pack accepted while localizing one capture. */
128
+ export const MAX_SNAPSHOT_LOCALIZATION_PACK_BYTES = 640 * 1024 * 1024;
129
+
130
+ /**
131
+ * Cross-host replay is deliberately narrower than local retention. The
132
+ * transfer stays buffered today, so reject oversized closures before they can
133
+ * become an unbounded JSON/HTTP payload. A later streaming protocol may raise
134
+ * this without weakening the pack contract.
135
+ */
136
+ export const MAX_SNAPSHOT_TRANSFER_PACK_BYTES = 64 * 1024 * 1024;
137
+
138
+ /**
139
+ * Canonical pack arguments. `--no-local` includes objects borrowed through an
140
+ * alternate; disabling deltas makes the installed pack self-contained.
141
+ */
142
+ export const SNAPSHOT_LOCALIZATION_PACK_ARGS = Object.freeze([
143
+ "pack-objects",
144
+ "--stdout",
145
+ "--revs",
146
+ "--no-thin",
147
+ "--no-local",
148
+ "--no-reuse-delta",
149
+ "--no-reuse-object",
150
+ "--window=0",
151
+ "--depth=0",
152
+ "--missing=error",
153
+ "--no-use-bitmap-index",
154
+ ] as const);
155
+
156
+ export interface SnapshotClosureV1 {
157
+ readonly version: 1;
158
+ readonly tree: TreeID;
159
+ readonly objectFormat: "sha1" | "sha256";
160
+ readonly encoding: "git-pack-v1";
161
+ readonly digest: `sha256:${string}`;
162
+ /** Canonical sorted object IDs for the tree's complete reachable closure. */
163
+ readonly objects: readonly string[];
164
+ readonly pack: Uint8Array;
165
+ }
166
+
167
+ export const MAX_MATERIALIZED_ENTRIES = 50_000;
168
+ export const MAX_MATERIALIZED_MANIFEST_BYTES = 16 * 1024 * 1024;
169
+ export const MAX_MATERIALIZED_PATH_BYTES = 4_096;
170
+ export const MAX_MATERIALIZED_SEGMENT_BYTES = 255;
171
+ export const MAX_MATERIALIZED_FILE_BYTES = 64 * 1024 * 1024;
172
+ export const MAX_MATERIALIZED_TOTAL_BYTES = 512 * 1024 * 1024;
173
+
174
+ export interface MaterializedTree {
175
+ readonly tree: TreeID;
176
+ readonly files: number;
177
+ readonly bytes: number;
178
+ }
179
+
180
+ export class OperationError extends Schema.TaggedErrorClass<OperationError>()(
181
+ "Git.OperationError",
182
+ {
183
+ operation: Schema.Literals([
184
+ "clone",
185
+ "fetch",
186
+ "checkout",
187
+ "reset",
188
+ "create",
189
+ "configure",
190
+ "retain",
191
+ "reclaim",
192
+ "refresh",
193
+ "capture",
194
+ "write_tree",
195
+ "list_files",
196
+ "diff",
197
+ "restore",
198
+ "materialize",
199
+ ]),
200
+ message: Schema.String,
201
+ directory: Schema.optional(AbsolutePath),
202
+ cause: Schema.optional(Schema.Defect()),
203
+ },
204
+ ) {}
205
+
206
+ export class Worktree extends Schema.Class<Worktree>("Git.Worktree")({
207
+ directory: AbsolutePath,
208
+ kind: Schema.Literals(["main", "linked"]),
209
+ }) {}
210
+
211
+ export class WorktreeError extends Schema.TaggedErrorClass<WorktreeError>()(
212
+ "Git.WorktreeError",
213
+ {
214
+ operation: Schema.Literals(["create", "remove", "list"]),
215
+ message: Schema.String,
216
+ directory: Schema.optional(AbsolutePath),
217
+ forceRequired: Schema.optional(Schema.Boolean),
218
+ cause: Schema.optional(Schema.Defect()),
219
+ },
220
+ ) {}
221
+
222
+ export class PatchError extends Schema.TaggedErrorClass<PatchError>()(
223
+ "Git.PatchError",
224
+ {
225
+ operation: Schema.Literals(["capture", "apply", "reset"]),
226
+ directory: AbsolutePath,
227
+ message: Schema.String,
228
+ cause: Schema.optional(Schema.Defect()),
229
+ },
230
+ ) {}
231
+
232
+ export interface Interface {
233
+ readonly repo: {
234
+ readonly discover: (
235
+ input: AbsolutePath,
236
+ ) => Effect.Effect<Repository | undefined>;
237
+ readonly clone: (input: {
238
+ remote: string;
239
+ directory: AbsolutePath;
240
+ branch?: string;
241
+ depth?: number;
242
+ }) => Effect.Effect<Repository, OperationError>;
243
+ readonly create: (input: {
244
+ worktree: AbsolutePath;
245
+ gitDirectory: AbsolutePath;
246
+ seed?: Repository;
247
+ }) => Effect.Effect<Repository, OperationError>;
248
+ readonly ensureSnapshotRetention: (
249
+ repository: Repository,
250
+ ) => Effect.Effect<void, OperationError>;
251
+ };
252
+ readonly remote: {
253
+ readonly get: (
254
+ repository: Repository,
255
+ name?: string,
256
+ ) => Effect.Effect<string | undefined>;
257
+ };
258
+ readonly history: {
259
+ readonly head: (
260
+ repository: Repository,
261
+ ) => Effect.Effect<string | undefined>;
262
+ readonly branch: (
263
+ repository: Repository,
264
+ ) => Effect.Effect<string | undefined>;
265
+ readonly defaultRemoteBranch: (
266
+ repository: Repository,
267
+ remote?: string,
268
+ ) => Effect.Effect<string | undefined>;
269
+ readonly rootCommits: (
270
+ repository: Repository,
271
+ ) => Effect.Effect<readonly string[]>;
272
+ };
273
+ readonly sync: {
274
+ readonly fetchRemotes: (
275
+ repository: Repository,
276
+ input?: { prune?: boolean },
277
+ ) => Effect.Effect<void, OperationError>;
278
+ readonly fetchBranch: (
279
+ repository: Repository,
280
+ input: { remote?: string; branch: string; force?: boolean },
281
+ ) => Effect.Effect<void, OperationError>;
282
+ readonly checkoutRemoteBranch: (
283
+ repository: Repository,
284
+ input: { remote?: string; branch: string; reset?: boolean },
285
+ ) => Effect.Effect<void, OperationError>;
286
+ readonly resetHard: (
287
+ repository: Repository,
288
+ revision: string,
289
+ ) => Effect.Effect<void, OperationError>;
290
+ };
291
+ readonly change: {
292
+ readonly capture: (input: {
293
+ repository: Repository;
294
+ path: AbsolutePath;
295
+ }) => Effect.Effect<ChangeSet, PatchError>;
296
+ readonly apply: (input: {
297
+ repository: Repository;
298
+ path: AbsolutePath;
299
+ changes: ChangeSet;
300
+ }) => Effect.Effect<void, PatchError>;
301
+ readonly discard: (input: {
302
+ repository: Repository;
303
+ path: AbsolutePath;
304
+ index: "preserve" | "reset";
305
+ untracked: "preserve" | "remove";
306
+ }) => Effect.Effect<void, PatchError>;
307
+ };
308
+ readonly worktree: {
309
+ readonly create: (input: {
310
+ repository: Repository;
311
+ directory: AbsolutePath;
312
+ }) => Effect.Effect<Repository, WorktreeError>;
313
+ readonly remove: (input: {
314
+ repository: Repository;
315
+ directory: AbsolutePath;
316
+ force: boolean;
317
+ }) => Effect.Effect<void, WorktreeError>;
318
+ readonly list: (
319
+ repository: Repository,
320
+ ) => Effect.Effect<readonly Worktree[], WorktreeError>;
321
+ };
322
+ readonly index: {
323
+ /** Refresh only the requested project-relative scope, preserving all other entries. */
324
+ readonly refresh: (input: {
325
+ repository: Repository;
326
+ scope: RelativePath;
327
+ ignores?: Repository;
328
+ maximumUntrackedFileBytes?: number;
329
+ }) => Effect.Effect<
330
+ { readonly skipped: readonly RelativePath[] },
331
+ OperationError
332
+ >;
333
+ readonly ignored: (input: {
334
+ repository: Repository;
335
+ paths: readonly RelativePath[];
336
+ }) => Effect.Effect<ReadonlySet<RelativePath>, OperationError>;
337
+ };
338
+ readonly tree: {
339
+ readonly capture: (input: {
340
+ repository: Repository;
341
+ scopes: readonly RelativePath[];
342
+ ignores?: Repository;
343
+ maximumUntrackedFileBytes?: number;
344
+ }) => Effect.Effect<TreeID, OperationError>;
345
+ readonly captureExact: (input: {
346
+ repository: Repository;
347
+ scopes: readonly RelativePath[];
348
+ ignores?: Repository;
349
+ maximumUntrackedFileBytes?: number;
350
+ }) => Effect.Effect<TreeID, OperationError>;
351
+ /** Localize and pin one caller-authorized historical or current tree. */
352
+ readonly retain: (input: {
353
+ repository: Repository;
354
+ tree: TreeID;
355
+ }) => Effect.Effect<void, OperationError>;
356
+ /** Return whether a canonical ID names a tree visible to this store. */
357
+ readonly contains: (input: {
358
+ repository: Repository;
359
+ tree: TreeID;
360
+ }) => Effect.Effect<boolean, OperationError>;
361
+ /** Export the exact reachable non-thin closure of one retained tree. */
362
+ readonly exportClosure: (input: {
363
+ repository: Repository;
364
+ tree: TreeID;
365
+ }) => Effect.Effect<SnapshotClosureV1, OperationError>;
366
+ /** Verify, install, localize and pin one cross-host closure. */
367
+ readonly importClosure: (input: {
368
+ repository: Repository;
369
+ expectedTree: TreeID;
370
+ closure: SnapshotClosureV1;
371
+ }) => Effect.Effect<void, OperationError>;
372
+ /** Backfill the complete live set and advance two-pass reclamation safely. */
373
+ readonly reconcileRetention: (input: {
374
+ repository: Repository;
375
+ live: readonly TreeID[];
376
+ reclaim?: boolean;
377
+ nowMs?: number;
378
+ minimumAgeMs?: number;
379
+ }) => Effect.Effect<SnapshotRetentionReport, OperationError>;
380
+ readonly write: (
381
+ repository: Repository,
382
+ ) => Effect.Effect<TreeID, OperationError>;
383
+ readonly files: (input: {
384
+ repository: Repository;
385
+ from: TreeID;
386
+ to: TreeID;
387
+ }) => Effect.Effect<readonly RelativePath[], OperationError>;
388
+ readonly diff: (input: {
389
+ repository: Repository;
390
+ from: TreeID;
391
+ to: TreeID;
392
+ context?: number;
393
+ paths?: readonly RelativePath[];
394
+ }) => Effect.Effect<readonly File.Diff[], OperationError>;
395
+ readonly preview: (input: {
396
+ repository: Repository;
397
+ current: TreeID;
398
+ files: ReadonlyMap<RelativePath, TreeID>;
399
+ context?: number;
400
+ }) => Effect.Effect<readonly File.Diff[], OperationError>;
401
+ readonly restore: (input: {
402
+ repository: Repository;
403
+ files: ReadonlyMap<RelativePath, TreeID>;
404
+ }) => Effect.Effect<void, OperationError>;
405
+ readonly checkout: (input: {
406
+ repository: Repository;
407
+ tree: TreeID;
408
+ }) => Effect.Effect<void, OperationError>;
409
+ /** Materialize raw tree blobs into an existing empty directory without touching the repository worktree. */
410
+ readonly materialize: (input: {
411
+ repository: Repository;
412
+ tree: TreeID;
413
+ directory: AbsolutePath;
414
+ }) => Effect.Effect<MaterializedTree, OperationError>;
415
+ };
416
+ }
417
+
418
+ export class Service extends Context.Service<Service, Interface>()(
419
+ "@phins/GitV2",
420
+ ) {}
421
+
422
+ type MaterializationEntry =
423
+ | {
424
+ readonly kind: "directory";
425
+ readonly path: string;
426
+ readonly object: string;
427
+ }
428
+ | {
429
+ readonly kind: "file";
430
+ readonly path: string;
431
+ readonly object: string;
432
+ readonly executable: boolean;
433
+ readonly size: number;
434
+ };
435
+
436
+ const RESERVED_WINDOWS_SEGMENT =
437
+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
438
+
439
+ const materializationFailure = (message: string) =>
440
+ new globalThis.Error(message);
441
+
442
+ const validateMaterializedPath = (input: string) => {
443
+ const bytes = Buffer.byteLength(input, "utf8");
444
+ if (bytes === 0 || bytes > MAX_MATERIALIZED_PATH_BYTES)
445
+ throw materializationFailure(
446
+ `Tree path must be between 1 and ${MAX_MATERIALIZED_PATH_BYTES} UTF-8 bytes`,
447
+ );
448
+ if (
449
+ /^[A-Za-z]:/.test(input) ||
450
+ path.posix.isAbsolute(input) ||
451
+ path.win32.isAbsolute(input)
452
+ )
453
+ throw materializationFailure(
454
+ `Tree path must be relative: ${JSON.stringify(input)}`,
455
+ );
456
+ if (input.includes("\\") || path.posix.normalize(input) !== input)
457
+ throw materializationFailure(
458
+ `Tree path is not portable and normalized: ${JSON.stringify(input)}`,
459
+ );
460
+ const segments = input.split("/");
461
+ for (const segment of segments) {
462
+ if (
463
+ segment.length === 0 ||
464
+ segment === "." ||
465
+ segment === ".." ||
466
+ segment.toLowerCase() === ".git" ||
467
+ segment.endsWith(".") ||
468
+ segment.endsWith(" ") ||
469
+ RESERVED_WINDOWS_SEGMENT.test(segment) ||
470
+ /[<>:"|?*]/.test(segment) ||
471
+ /[\u0000-\u001f\u007f]/.test(segment) ||
472
+ Buffer.byteLength(segment, "utf8") > MAX_MATERIALIZED_SEGMENT_BYTES
473
+ )
474
+ throw materializationFailure(
475
+ `Tree path contains an unsafe segment: ${JSON.stringify(input)}`,
476
+ );
477
+ }
478
+ };
479
+
480
+ const decodeMaterializationManifest = (
481
+ input: Uint8Array,
482
+ objectBytes: number,
483
+ ): MaterializationEntry[] => {
484
+ if (input.length > 0 && input[input.length - 1] !== 0)
485
+ throw materializationFailure("Git returned an unterminated tree manifest");
486
+ const records = Buffer.from(input)
487
+ .subarray(0, Math.max(0, input.length - 1))
488
+ .toString("latin1");
489
+ const rawRecords = records.length === 0 ? [] : records.split("\0");
490
+ const decoder = new TextDecoder("utf-8", { fatal: true });
491
+ const entries: MaterializationEntry[] = [];
492
+ const exact = new Map<string, MaterializationEntry["kind"]>();
493
+ const portable = new Map<string, string>();
494
+ let totalBytes = 0n;
495
+
496
+ for (const rawRecord of rawRecords) {
497
+ if (entries.length >= MAX_MATERIALIZED_ENTRIES)
498
+ throw materializationFailure(
499
+ `Tree exceeds ${MAX_MATERIALIZED_ENTRIES} materialized entries`,
500
+ );
501
+ const record = decoder.decode(Buffer.from(rawRecord, "latin1"));
502
+ const delimiter = record.indexOf("\t");
503
+ if (delimiter <= 0)
504
+ throw materializationFailure(
505
+ "Git returned a malformed tree manifest entry",
506
+ );
507
+ const metadata = record.slice(0, delimiter);
508
+ const treePath = record.slice(delimiter + 1);
509
+ const match = /^(\d{6}) (blob|tree|commit) ([0-9a-f]+) +(-|\d+)$/.exec(
510
+ metadata,
511
+ );
512
+ if (!match || match[3]?.length !== objectBytes * 2)
513
+ throw materializationFailure(
514
+ "Git returned a malformed tree manifest entry",
515
+ );
516
+ validateMaterializedPath(treePath);
517
+
518
+ const collisionKey = treePath.normalize("NFC").toLowerCase();
519
+ const collision = portable.get(collisionKey);
520
+ if (collision !== undefined)
521
+ throw materializationFailure(
522
+ `Tree contains colliding paths: ${JSON.stringify(collision)} and ${JSON.stringify(treePath)}`,
523
+ );
524
+ if (exact.has(treePath))
525
+ throw materializationFailure(
526
+ `Tree contains a duplicate path: ${JSON.stringify(treePath)}`,
527
+ );
528
+
529
+ const mode = match[1];
530
+ const type = match[2];
531
+ const object = match[3];
532
+ const sizeText = match[4];
533
+ let entry: MaterializationEntry;
534
+ if (mode === "040000" && type === "tree" && sizeText === "-") {
535
+ entry = { kind: "directory", path: treePath, object };
536
+ } else if (
537
+ (mode === "100644" || mode === "100755") &&
538
+ type === "blob" &&
539
+ sizeText !== "-"
540
+ ) {
541
+ const size = BigInt(sizeText);
542
+ if (size > BigInt(MAX_MATERIALIZED_FILE_BYTES))
543
+ throw materializationFailure(
544
+ `Tree blob exceeds ${MAX_MATERIALIZED_FILE_BYTES} bytes: ${JSON.stringify(treePath)}`,
545
+ );
546
+ totalBytes += size;
547
+ if (totalBytes > BigInt(MAX_MATERIALIZED_TOTAL_BYTES))
548
+ throw materializationFailure(
549
+ `Tree exceeds ${MAX_MATERIALIZED_TOTAL_BYTES} materialized bytes`,
550
+ );
551
+ entry = {
552
+ kind: "file",
553
+ path: treePath,
554
+ object,
555
+ executable: mode === "100755",
556
+ size: Number(size),
557
+ };
558
+ } else if (mode === "120000") {
559
+ throw materializationFailure(
560
+ `Tree symlinks are not allowed: ${JSON.stringify(treePath)}`,
561
+ );
562
+ } else if (mode === "160000" || type === "commit") {
563
+ throw materializationFailure(
564
+ `Tree gitlinks are not allowed: ${JSON.stringify(treePath)}`,
565
+ );
566
+ } else {
567
+ throw materializationFailure(
568
+ `Tree entry mode is not allowed: ${JSON.stringify(treePath)}`,
569
+ );
570
+ }
571
+ exact.set(treePath, entry.kind);
572
+ portable.set(collisionKey, treePath);
573
+ entries.push(entry);
574
+ }
575
+
576
+ for (const entry of entries) {
577
+ const segments = entry.path.split("/");
578
+ for (let index = 1; index < segments.length; index++) {
579
+ const ancestor = segments.slice(0, index).join("/");
580
+ const kind = exact.get(ancestor);
581
+ if (kind !== "directory")
582
+ throw materializationFailure(
583
+ `Tree path has an invalid ancestor: ${JSON.stringify(ancestor)}`,
584
+ );
585
+ }
586
+ }
587
+ return entries;
588
+ };
589
+
590
+ const decodeExactCapturePaths = (input: Uint8Array) => {
591
+ if (input.length > 0 && input[input.length - 1] !== 0)
592
+ throw materializationFailure(
593
+ "Git returned an unterminated exact-capture path list",
594
+ );
595
+ const records = Buffer.from(input)
596
+ .subarray(0, Math.max(0, input.length - 1))
597
+ .toString("latin1");
598
+ if (records.length === 0) return [];
599
+ const decoder = new TextDecoder("utf-8", { fatal: true });
600
+ const paths: RelativePath[] = [];
601
+ const portable = new Map<string, string>();
602
+ for (const record of records.split("\0")) {
603
+ if (paths.length >= MAX_MATERIALIZED_ENTRIES)
604
+ throw materializationFailure(
605
+ `Exact capture exceeds ${MAX_MATERIALIZED_ENTRIES} entries`,
606
+ );
607
+ const candidate = decoder.decode(Buffer.from(record, "latin1"));
608
+ validateMaterializedPath(candidate);
609
+ const collisionKey = candidate.normalize("NFC").toLowerCase();
610
+ const collision = portable.get(collisionKey);
611
+ if (collision !== undefined)
612
+ throw materializationFailure(
613
+ `Exact capture contains colliding paths: ${JSON.stringify(collision)} and ${JSON.stringify(candidate)}`,
614
+ );
615
+ portable.set(collisionKey, candidate);
616
+ paths.push(RelativePath.make(candidate));
617
+ }
618
+ return paths;
619
+ };
620
+
621
+ const snapshotStoreLocks = KeyedMutex.makeUnsafe<string>();
622
+
623
+ /** Serialize snapshot-store index, descriptor, alternate, and ref mutations. */
624
+ export const withSnapshotStoreLock = <A, E, R>(
625
+ gitDirectory: string,
626
+ effect: Effect.Effect<A, E, R>,
627
+ ) =>
628
+ snapshotStoreLocks.withLock(gitDirectory)(
629
+ Effect.scoped(
630
+ Effect.gen(function* () {
631
+ yield* Flock.effect(`snapshot-store:${gitDirectory}`, {
632
+ dir: path.join(gitDirectory, "phins-locks"),
633
+ });
634
+ return yield* effect;
635
+ }),
636
+ ),
637
+ );
638
+
639
+ export const layer = Layer.effect(
640
+ Service,
641
+ Effect.gen(function* () {
642
+ const fs = yield* FileAccess.Service;
643
+ const proc = yield* ProcessRunner.Service;
644
+ const retainedSnapshotRepositories = new WeakSet<Repository>();
645
+ const snapshotObjectCharacters = new WeakMap<Repository, 40 | 64>();
646
+ const snapshotRetentionArgs = SNAPSHOT_RETENTION_CONFIG.flatMap(
647
+ ([key, value]) => ["-c", `${key}=${value}`],
648
+ );
649
+ const locked = <A, E, R>(
650
+ repository: Repository,
651
+ effect: Effect.Effect<A, E, R>,
652
+ ) => withSnapshotStoreLock(repository.gitDirectory, effect);
653
+
654
+ const discover = Effect.fn("Git.repo.discover")(function* (
655
+ input: AbsolutePath,
656
+ ) {
657
+ const dotgit = yield* fs.up({ targets: [".git"], start: input }).pipe(
658
+ Effect.map((matches) => matches[0]),
659
+ Effect.catch(() => Effect.succeed(undefined)),
660
+ );
661
+ if (!dotgit) return undefined;
662
+
663
+ const cwd = path.dirname(dotgit);
664
+ const git = run(cwd, proc);
665
+ const topLevel = yield* git(["rev-parse", "--show-toplevel"]);
666
+ const gitDir = yield* git(["rev-parse", "--git-dir"]);
667
+ const commonDir = yield* git(["rev-parse", "--git-common-dir"]);
668
+ if (gitDir.exitCode !== 0 || commonDir.exitCode !== 0) return undefined;
669
+
670
+ return new Repository({
671
+ worktree: AbsolutePath.make(
672
+ topLevel.exitCode === 0 ? resolvePath(cwd, topLevel.text) : cwd,
673
+ ),
674
+ gitDirectory: AbsolutePath.make(resolvePath(cwd, gitDir.text)),
675
+ commonDirectory: AbsolutePath.make(resolvePath(cwd, commonDir.text)),
676
+ });
677
+ });
678
+
679
+ const remote = Effect.fn("Git.remote.get")(function* (
680
+ repository: Repository,
681
+ name = "origin",
682
+ ) {
683
+ const result = yield* run(
684
+ repository.worktree,
685
+ proc,
686
+ )(["remote", "get-url", name]);
687
+ if (result.exitCode !== 0) return undefined;
688
+ return result.text.trim() || undefined;
689
+ });
690
+
691
+ const roots = Effect.fn("Git.history.rootCommits")(function* (
692
+ repository: Repository,
693
+ ) {
694
+ const result = yield* run(
695
+ repository.worktree,
696
+ proc,
697
+ )(["rev-list", "--max-parents=0", "HEAD"]);
698
+ if (result.exitCode !== 0) return [];
699
+ return result.text
700
+ .split("\n")
701
+ .map((item) => item.trim())
702
+ .filter(Boolean)
703
+ .toSorted();
704
+ });
705
+
706
+ const head = Effect.fn("Git.history.head")(function* (
707
+ repository: Repository,
708
+ ) {
709
+ const result = yield* run(
710
+ repository.worktree,
711
+ proc,
712
+ )(["rev-parse", "HEAD"]);
713
+ if (result.exitCode !== 0) return undefined;
714
+ return result.text.trim() || undefined;
715
+ });
716
+
717
+ const branch = Effect.fn("Git.history.branch")(function* (
718
+ repository: Repository,
719
+ ) {
720
+ const result = yield* run(
721
+ repository.worktree,
722
+ proc,
723
+ )(["symbolic-ref", "--quiet", "--short", "HEAD"]);
724
+ if (result.exitCode !== 0) return undefined;
725
+ return result.text.trim() || undefined;
726
+ });
727
+
728
+ const remoteHead = Effect.fn("Git.history.defaultRemoteBranch")(function* (
729
+ repository: Repository,
730
+ remoteName = "origin",
731
+ ) {
732
+ const result = yield* run(
733
+ repository.worktree,
734
+ proc,
735
+ )(["symbolic-ref", `refs/remotes/${remoteName}/HEAD`]);
736
+ if (result.exitCode !== 0) return undefined;
737
+ return (
738
+ result.text
739
+ .trim()
740
+ .replace(new RegExp(`^refs/remotes/${remoteName}/`), "") || undefined
741
+ );
742
+ });
743
+
744
+ const operation = Effect.fnUntraced(function* (
745
+ operation: OperationError["operation"],
746
+ directory: AbsolutePath,
747
+ args: string[],
748
+ ) {
749
+ const result = yield* execute(
750
+ directory,
751
+ proc,
752
+ )(args).pipe(
753
+ Effect.mapError(
754
+ (cause) =>
755
+ new OperationError({
756
+ operation,
757
+ directory,
758
+ message: cause.message,
759
+ cause,
760
+ }),
761
+ ),
762
+ );
763
+ if (result.exitCode === 0) return;
764
+ return yield* new OperationError({
765
+ operation,
766
+ directory,
767
+ message:
768
+ result.stderr.trim() ||
769
+ result.text.trim() ||
770
+ `Git ${operation} failed`,
771
+ });
772
+ });
773
+
774
+ const clone = Effect.fn("Git.repo.clone")(function* (input: {
775
+ remote: string;
776
+ directory: AbsolutePath;
777
+ branch?: string;
778
+ depth?: number;
779
+ }) {
780
+ yield* operation(
781
+ "clone",
782
+ AbsolutePath.make(path.dirname(input.directory)),
783
+ [
784
+ "clone",
785
+ "--depth",
786
+ String(input.depth ?? 100),
787
+ ...(input.branch ? ["--branch", input.branch] : []),
788
+ "--",
789
+ input.remote,
790
+ input.directory,
791
+ ],
792
+ );
793
+ const repository = yield* discover(input.directory);
794
+ if (repository) return repository;
795
+ return yield* new OperationError({
796
+ operation: "clone",
797
+ directory: input.directory,
798
+ message: "Cloned repository could not be opened",
799
+ });
800
+ });
801
+
802
+ const fetch = Effect.fn("Git.sync.fetchRemotes")(function* (
803
+ repository: Repository,
804
+ input: { prune?: boolean } = {},
805
+ ) {
806
+ yield* operation("fetch", repository.worktree, [
807
+ "fetch",
808
+ "--all",
809
+ ...(input.prune === false ? [] : ["--prune"]),
810
+ ]);
811
+ });
812
+
813
+ const fetchBranch = Effect.fn("Git.sync.fetchBranch")(function* (
814
+ repository: Repository,
815
+ input: { remote?: string; branch: string; force?: boolean },
816
+ ) {
817
+ const remoteName = input.remote ?? "origin";
818
+ const spec = `refs/heads/${input.branch}:refs/remotes/${remoteName}/${input.branch}`;
819
+ yield* operation("fetch", repository.worktree, [
820
+ "fetch",
821
+ remoteName,
822
+ input.force === false ? spec : `+${spec}`,
823
+ ]);
824
+ });
825
+
826
+ const checkout = Effect.fn("Git.sync.checkoutRemoteBranch")(function* (
827
+ repository: Repository,
828
+ input: { remote?: string; branch: string; reset?: boolean },
829
+ ) {
830
+ const remoteName = input.remote ?? "origin";
831
+ yield* operation("checkout", repository.worktree, [
832
+ "checkout",
833
+ ...(input.reset === false
834
+ ? [input.branch]
835
+ : ["-B", input.branch, `${remoteName}/${input.branch}`]),
836
+ ]);
837
+ });
838
+
839
+ const reset = Effect.fn("Git.sync.resetHard")(function* (
840
+ repository: Repository,
841
+ revision: string,
842
+ ) {
843
+ yield* operation("reset", repository.worktree, [
844
+ "reset",
845
+ "--hard",
846
+ revision,
847
+ ]);
848
+ });
849
+
850
+ const repositoryArgs = (repository: Repository, args: string[]) => [
851
+ "--git-dir",
852
+ repository.gitDirectory,
853
+ "--work-tree",
854
+ repository.worktree,
855
+ ...(retainedSnapshotRepositories.has(repository)
856
+ ? snapshotRetentionArgs
857
+ : []),
858
+ ...args,
859
+ ];
860
+
861
+ const repositoryOperation = Effect.fnUntraced(function* (
862
+ operationName: OperationError["operation"],
863
+ repository: Repository,
864
+ args: string[],
865
+ options?: { stdin?: string; env?: Record<string, string> },
866
+ ) {
867
+ const result = yield* proc
868
+ .run(
869
+ ChildProcess.make("git", repositoryArgs(repository, args), {
870
+ cwd: repository.worktree,
871
+ env: options?.env,
872
+ extendEnv: true,
873
+ }),
874
+ { stdin: options?.stdin },
875
+ )
876
+ .pipe(
877
+ Effect.mapError(
878
+ (cause) =>
879
+ new OperationError({
880
+ operation: operationName,
881
+ directory: repository.worktree,
882
+ message: cause.message,
883
+ cause,
884
+ }),
885
+ ),
886
+ );
887
+ const text = result.stdout.toString("utf8");
888
+ if (result.exitCode === 0)
889
+ return { text, stderr: result.stderr.toString("utf8") };
890
+ return yield* new OperationError({
891
+ operation: operationName,
892
+ directory: repository.worktree,
893
+ message:
894
+ result.stderr.toString("utf8").trim() ||
895
+ text.trim() ||
896
+ `Git ${operationName} failed`,
897
+ });
898
+ });
899
+
900
+ const localConfigValues = Effect.fnUntraced(function* (
901
+ repository: Repository,
902
+ key: string,
903
+ ) {
904
+ const result = yield* proc
905
+ .run(
906
+ ChildProcess.make(
907
+ "git",
908
+ repositoryArgs(repository, ["config", "--local", "--get-all", key]),
909
+ {
910
+ cwd: repository.worktree,
911
+ env: { LANG: "C", LC_ALL: "C" },
912
+ extendEnv: true,
913
+ },
914
+ ),
915
+ { maxOutputBytes: 64 * 1024, maxErrorBytes: 64 * 1024 },
916
+ )
917
+ .pipe(
918
+ Effect.mapError(
919
+ (cause) =>
920
+ new OperationError({
921
+ operation: "configure",
922
+ directory: repository.gitDirectory,
923
+ message: cause.message,
924
+ cause,
925
+ }),
926
+ ),
927
+ );
928
+ if (
929
+ result.exitCode === 1 &&
930
+ result.stdout.length === 0 &&
931
+ result.stderr.length === 0
932
+ )
933
+ return [];
934
+ if (result.exitCode !== 0)
935
+ return yield* new OperationError({
936
+ operation: "configure",
937
+ directory: repository.gitDirectory,
938
+ message:
939
+ result.stderr.toString("utf8").trim() ||
940
+ "Failed to read snapshot store descriptor",
941
+ });
942
+ if (result.stdoutTruncated || result.stderrTruncated)
943
+ return yield* new OperationError({
944
+ operation: "configure",
945
+ directory: repository.gitDirectory,
946
+ message: "Snapshot store descriptor exceeded its output limit",
947
+ });
948
+ return result.stdout
949
+ .toString("utf8")
950
+ .replaceAll("\r\n", "\n")
951
+ .split("\n")
952
+ .filter((value) => value.length > 0);
953
+ });
954
+
955
+ const persistSnapshotDescriptor = Effect.fnUntraced(function* (
956
+ repository: Repository,
957
+ ) {
958
+ const existing = yield* localConfigValues(
959
+ repository,
960
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
961
+ );
962
+ const compatible = (value: string) =>
963
+ value === SNAPSHOT_STORE_DESCRIPTOR_JSON ||
964
+ value === SNAPSHOT_STORE_DESCRIPTOR_V2_JSON;
965
+ if (
966
+ existing.length > 0 &&
967
+ (existing.length !== 1 || !compatible(existing[0] ?? ""))
968
+ )
969
+ return yield* new OperationError({
970
+ operation: "configure",
971
+ directory: repository.gitDirectory,
972
+ message:
973
+ "Snapshot store descriptor is incompatible with this runtime",
974
+ });
975
+ if (existing.length === 0)
976
+ yield* repositoryOperation(
977
+ "configure",
978
+ repository,
979
+ [
980
+ "config",
981
+ "--local",
982
+ "--replace-all",
983
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
984
+ SNAPSHOT_STORE_DESCRIPTOR_JSON,
985
+ ],
986
+ { env: { LANG: "C", LC_ALL: "C" } },
987
+ );
988
+ const verified = yield* localConfigValues(
989
+ repository,
990
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
991
+ );
992
+ if (verified.length === 1 && compatible(verified[0] ?? "")) return;
993
+ return yield* new OperationError({
994
+ operation: "configure",
995
+ directory: repository.gitDirectory,
996
+ message: "Snapshot store descriptor was not persisted exactly",
997
+ });
998
+ });
999
+
1000
+ const upgradeSnapshotDescriptor = Effect.fnUntraced(function* (
1001
+ repository: Repository,
1002
+ ) {
1003
+ const existing = yield* localConfigValues(
1004
+ repository,
1005
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
1006
+ );
1007
+ if (
1008
+ existing.length !== 1 ||
1009
+ (existing[0] !== SNAPSHOT_STORE_DESCRIPTOR_JSON &&
1010
+ existing[0] !== SNAPSHOT_STORE_DESCRIPTOR_V2_JSON)
1011
+ )
1012
+ return yield* new OperationError({
1013
+ operation: "reclaim",
1014
+ directory: repository.gitDirectory,
1015
+ message:
1016
+ "Snapshot store descriptor cannot be upgraded from an incompatible value",
1017
+ });
1018
+ if (existing[0] !== SNAPSHOT_STORE_DESCRIPTOR_V2_JSON)
1019
+ yield* repositoryOperation(
1020
+ "reclaim",
1021
+ repository,
1022
+ [
1023
+ "config",
1024
+ "--local",
1025
+ "--replace-all",
1026
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
1027
+ SNAPSHOT_STORE_DESCRIPTOR_V2_JSON,
1028
+ ],
1029
+ { env: { LANG: "C", LC_ALL: "C" } },
1030
+ );
1031
+ const verified = yield* localConfigValues(
1032
+ repository,
1033
+ SNAPSHOT_STORE_DESCRIPTOR_KEY,
1034
+ );
1035
+ if (
1036
+ verified.length === 1 &&
1037
+ verified[0] === SNAPSHOT_STORE_DESCRIPTOR_V2_JSON
1038
+ )
1039
+ return;
1040
+ return yield* new OperationError({
1041
+ operation: "reclaim",
1042
+ directory: repository.gitDirectory,
1043
+ message: "Snapshot store descriptor upgrade was not persisted exactly",
1044
+ });
1045
+ });
1046
+
1047
+ const persistSnapshotRetention = Effect.fnUntraced(function* (
1048
+ repository: Repository,
1049
+ ) {
1050
+ const environment = { LANG: "C", LC_ALL: "C" };
1051
+ for (const [key, value] of SNAPSHOT_RETENTION_CONFIG) {
1052
+ yield* repositoryOperation(
1053
+ "configure",
1054
+ repository,
1055
+ ["config", "--local", "--replace-all", key, value],
1056
+ {
1057
+ env: environment,
1058
+ },
1059
+ );
1060
+ }
1061
+ for (const [key, expected] of SNAPSHOT_RETENTION_CONFIG) {
1062
+ const result = yield* repositoryOperation(
1063
+ "configure",
1064
+ repository,
1065
+ ["config", "--local", "--get-all", key],
1066
+ {
1067
+ env: environment,
1068
+ },
1069
+ );
1070
+ const values = result.text
1071
+ .replaceAll("\r\n", "\n")
1072
+ .split("\n")
1073
+ .filter((value) => value.length > 0);
1074
+ if (values.length === 1 && values[0] === expected) continue;
1075
+ return yield* new OperationError({
1076
+ operation: "configure",
1077
+ directory: repository.gitDirectory,
1078
+ message: `Snapshot retention setting ${key} was not persisted exactly`,
1079
+ });
1080
+ }
1081
+ });
1082
+
1083
+ const isConfigLockRace = (cause: OperationError) => {
1084
+ const message = cause.message.toLowerCase();
1085
+ return (
1086
+ message.includes("could not lock config file") &&
1087
+ (message.includes("file exists") || message.includes("already exists"))
1088
+ );
1089
+ };
1090
+
1091
+ const persistSnapshotRetentionWithRetry = (
1092
+ repository: Repository,
1093
+ attempt = 0,
1094
+ ): Effect.Effect<void, OperationError> =>
1095
+ persistSnapshotRetention(repository).pipe(
1096
+ Effect.catch((cause) => {
1097
+ if (attempt >= 4 || !isConfigLockRace(cause))
1098
+ return Effect.fail(cause);
1099
+ return Effect.sleep(Duration.millis(10 * 2 ** attempt)).pipe(
1100
+ Effect.andThen(
1101
+ persistSnapshotRetentionWithRetry(repository, attempt + 1),
1102
+ ),
1103
+ );
1104
+ }),
1105
+ );
1106
+
1107
+ const persistSnapshotDescriptorWithRetry = (
1108
+ repository: Repository,
1109
+ attempt = 0,
1110
+ ): Effect.Effect<void, OperationError> =>
1111
+ persistSnapshotDescriptor(repository).pipe(
1112
+ Effect.catch((cause) => {
1113
+ if (attempt >= 4 || !isConfigLockRace(cause))
1114
+ return Effect.fail(cause);
1115
+ return Effect.sleep(Duration.millis(10 * 2 ** attempt)).pipe(
1116
+ Effect.andThen(
1117
+ persistSnapshotDescriptorWithRetry(repository, attempt + 1),
1118
+ ),
1119
+ );
1120
+ }),
1121
+ );
1122
+
1123
+ const parkedAlternatesPattern =
1124
+ /^alternates\.phins-(?:localization|reclamation)-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1125
+
1126
+ const recoverParkedSnapshotAlternates = Effect.fnUntraced(function* (
1127
+ repository: Repository,
1128
+ ) {
1129
+ const infoDirectory = path.join(
1130
+ repository.gitDirectory,
1131
+ "objects",
1132
+ "info",
1133
+ );
1134
+ if (!(yield* fs.existsSafe(infoDirectory))) return;
1135
+ const entries = yield* fs.readDirectoryEntries(infoDirectory).pipe(
1136
+ Effect.mapError(
1137
+ (cause) =>
1138
+ new OperationError({
1139
+ operation: "retain",
1140
+ directory: repository.gitDirectory,
1141
+ message: "Failed to inspect parked snapshot alternates",
1142
+ cause,
1143
+ }),
1144
+ ),
1145
+ );
1146
+ const suspicious = entries.filter((entry) =>
1147
+ entry.name.startsWith("alternates.phins-"),
1148
+ );
1149
+ if (
1150
+ suspicious.some(
1151
+ (entry) =>
1152
+ entry.type !== "file" || !parkedAlternatesPattern.test(entry.name),
1153
+ ) ||
1154
+ suspicious.length > 1
1155
+ )
1156
+ return yield* new OperationError({
1157
+ operation: "retain",
1158
+ directory: repository.gitDirectory,
1159
+ message: "Snapshot store has ambiguous parked alternates",
1160
+ });
1161
+ if (suspicious.length === 0) return;
1162
+
1163
+ const alternates = path.join(infoDirectory, "alternates");
1164
+ if (yield* fs.existsSafe(alternates))
1165
+ return yield* new OperationError({
1166
+ operation: "retain",
1167
+ directory: repository.gitDirectory,
1168
+ message:
1169
+ "Snapshot store has both active and parked alternates; refusing recovery",
1170
+ });
1171
+ yield* fs
1172
+ .rename(path.join(infoDirectory, suspicious[0]!.name), alternates)
1173
+ .pipe(
1174
+ Effect.mapError(
1175
+ (cause) =>
1176
+ new OperationError({
1177
+ operation: "retain",
1178
+ directory: repository.gitDirectory,
1179
+ message: "Failed to restore parked snapshot alternates",
1180
+ cause,
1181
+ }),
1182
+ ),
1183
+ );
1184
+ });
1185
+
1186
+ const ensureSnapshotRetention = Effect.fn(
1187
+ "Git.repo.ensureSnapshotRetention",
1188
+ )((repository: Repository) =>
1189
+ locked(
1190
+ repository,
1191
+ Effect.gen(function* () {
1192
+ yield* recoverParkedSnapshotAlternates(repository);
1193
+ yield* persistSnapshotDescriptorWithRetry(repository);
1194
+ yield* persistSnapshotRetentionWithRetry(repository);
1195
+ retainedSnapshotRepositories.add(repository);
1196
+ }),
1197
+ ),
1198
+ );
1199
+
1200
+ const objectOperation = Effect.fnUntraced(function* (
1201
+ repository: Repository,
1202
+ args: readonly string[],
1203
+ maximumOutputBytes: number,
1204
+ options: {
1205
+ readonly operation?: "capture" | "materialize" | "retain" | "reclaim";
1206
+ readonly stdin?: Uint8Array;
1207
+ readonly environment?: Readonly<Record<string, string>>;
1208
+ readonly worktree?: boolean;
1209
+ } = {},
1210
+ ) {
1211
+ const operationName = options.operation ?? "materialize";
1212
+ const environment: Record<string, string> = {
1213
+ ...options.environment,
1214
+ PATH:
1215
+ process.env.PATH ??
1216
+ (process.platform === "win32"
1217
+ ? "C:\\Windows\\System32"
1218
+ : "/usr/bin:/bin"),
1219
+ LANG: "C.UTF-8",
1220
+ LC_ALL: "C.UTF-8",
1221
+ GIT_CONFIG_NOSYSTEM: "1",
1222
+ GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null",
1223
+ GIT_ATTR_NOSYSTEM: "1",
1224
+ GIT_NO_LAZY_FETCH: "1",
1225
+ GIT_NO_REPLACE_OBJECTS: "1",
1226
+ GIT_OPTIONAL_LOCKS: "0",
1227
+ };
1228
+ if (process.platform === "win32" && process.env.SystemRoot)
1229
+ environment.SystemRoot = process.env.SystemRoot;
1230
+ const result = yield* proc
1231
+ .run(
1232
+ ChildProcess.make(
1233
+ "git",
1234
+ [
1235
+ "--git-dir",
1236
+ repository.gitDirectory,
1237
+ ...(options.worktree ? ["--work-tree", repository.worktree] : []),
1238
+ ...(retainedSnapshotRepositories.has(repository)
1239
+ ? snapshotRetentionArgs
1240
+ : []),
1241
+ ...args,
1242
+ ],
1243
+ {
1244
+ cwd: options.worktree
1245
+ ? repository.worktree
1246
+ : repository.gitDirectory,
1247
+ env: environment,
1248
+ extendEnv: false,
1249
+ stdin: "ignore",
1250
+ },
1251
+ ),
1252
+ {
1253
+ maxOutputBytes: maximumOutputBytes,
1254
+ maxErrorBytes: 64 * 1024,
1255
+ stdin: options.stdin,
1256
+ },
1257
+ )
1258
+ .pipe(
1259
+ Effect.mapError(
1260
+ (cause) =>
1261
+ new OperationError({
1262
+ operation: operationName,
1263
+ directory: repository.gitDirectory,
1264
+ message: cause.message,
1265
+ cause,
1266
+ }),
1267
+ ),
1268
+ );
1269
+ if (result.exitCode !== 0)
1270
+ return yield* new OperationError({
1271
+ operation: operationName,
1272
+ directory: repository.gitDirectory,
1273
+ message:
1274
+ result.stderr.toString("utf8").trim() ||
1275
+ result.stdout.toString("utf8").trim() ||
1276
+ "Git object operation failed",
1277
+ });
1278
+ if (result.stdoutTruncated || result.stderrTruncated)
1279
+ return yield* new OperationError({
1280
+ operation: operationName,
1281
+ directory: repository.gitDirectory,
1282
+ message: "Git object operation exceeded its output limit",
1283
+ });
1284
+ return result.stdout;
1285
+ });
1286
+
1287
+ const snapshotObjectIDCharacters = Effect.fnUntraced(function* (
1288
+ repository: Repository,
1289
+ ) {
1290
+ const cached = snapshotObjectCharacters.get(repository);
1291
+ if (cached !== undefined) return cached;
1292
+ const format = (yield* objectOperation(
1293
+ repository,
1294
+ ["rev-parse", "--show-object-format"],
1295
+ 32,
1296
+ {
1297
+ operation: "retain",
1298
+ },
1299
+ ))
1300
+ .toString("utf8")
1301
+ .trim();
1302
+ const characters =
1303
+ format === "sha1" ? 40 : format === "sha256" ? 64 : undefined;
1304
+ if (characters === undefined)
1305
+ return yield* new OperationError({
1306
+ operation: "retain",
1307
+ directory: repository.gitDirectory,
1308
+ message: "Snapshot retention requires a supported Git object format",
1309
+ });
1310
+ snapshotObjectCharacters.set(repository, characters);
1311
+ return characters;
1312
+ });
1313
+
1314
+ const snapshotClosureManifest = Effect.fnUntraced(function* (
1315
+ repository: Repository,
1316
+ tree: TreeID,
1317
+ environment?: Readonly<Record<string, string>>,
1318
+ ) {
1319
+ const objects = yield* objectOperation(
1320
+ repository,
1321
+ ["rev-list", "--objects", "--no-object-names", tree],
1322
+ MAX_MATERIALIZED_MANIFEST_BYTES,
1323
+ { operation: "retain", environment },
1324
+ );
1325
+ const characters = yield* snapshotObjectIDCharacters(repository);
1326
+ const ids = objects
1327
+ .toString("utf8")
1328
+ .replaceAll("\r\n", "\n")
1329
+ .split("\n")
1330
+ .filter(Boolean);
1331
+ if (
1332
+ ids.length === 0 ||
1333
+ ids[0] !== tree ||
1334
+ ids.some((id) => !new RegExp(`^[0-9a-f]{${characters}}$`).test(id))
1335
+ )
1336
+ return yield* new OperationError({
1337
+ operation: "retain",
1338
+ directory: repository.gitDirectory,
1339
+ message:
1340
+ "Snapshot localization produced an invalid reachable-object manifest",
1341
+ });
1342
+ const checked = yield* objectOperation(
1343
+ repository,
1344
+ ["cat-file", "--batch-check=%(objectname) %(objecttype)"],
1345
+ MAX_MATERIALIZED_MANIFEST_BYTES,
1346
+ { operation: "retain", stdin: objects, environment },
1347
+ );
1348
+ const results = checked
1349
+ .toString("utf8")
1350
+ .replaceAll("\r\n", "\n")
1351
+ .split("\n")
1352
+ .filter(Boolean);
1353
+ if (
1354
+ results.length !== ids.length ||
1355
+ results.some(
1356
+ (result, index) =>
1357
+ !result.startsWith(`${ids[index]} `) ||
1358
+ result.endsWith(" missing"),
1359
+ )
1360
+ )
1361
+ return yield* new OperationError({
1362
+ operation: "retain",
1363
+ directory: repository.gitDirectory,
1364
+ message:
1365
+ "Snapshot reachable closure is not present in the local object database",
1366
+ });
1367
+ return Object.freeze(ids.toSorted());
1368
+ });
1369
+
1370
+ const verifyLocalizedSnapshotTree = Effect.fnUntraced(function* (
1371
+ repository: Repository,
1372
+ tree: TreeID,
1373
+ ) {
1374
+ const verify = snapshotClosureManifest(repository, tree);
1375
+ const alternates = path.join(
1376
+ repository.gitDirectory,
1377
+ "objects",
1378
+ "info",
1379
+ "alternates",
1380
+ );
1381
+ if (!(yield* fs.existsSafe(alternates))) return yield* verify;
1382
+
1383
+ const parked = `${alternates}.phins-localization-${randomUUID()}`;
1384
+ const move = (from: string, to: string, message: string) =>
1385
+ fs.rename(from, to).pipe(
1386
+ Effect.mapError(
1387
+ (cause) =>
1388
+ new OperationError({
1389
+ operation: "retain",
1390
+ directory: repository.gitDirectory,
1391
+ message,
1392
+ cause,
1393
+ }),
1394
+ ),
1395
+ );
1396
+ return yield* Effect.uninterruptibleMask((restore) =>
1397
+ Effect.gen(function* () {
1398
+ yield* move(
1399
+ alternates,
1400
+ parked,
1401
+ "Failed to disable snapshot alternates for localization verification",
1402
+ );
1403
+ const result = yield* restore(verify).pipe(Effect.exit);
1404
+ yield* move(
1405
+ parked,
1406
+ alternates,
1407
+ "Failed to restore snapshot alternates after localization verification",
1408
+ );
1409
+ if (result._tag === "Success") return result.value;
1410
+ return yield* Effect.failCause(result.cause);
1411
+ }),
1412
+ );
1413
+ });
1414
+
1415
+ const localizeSnapshotTree = Effect.fnUntraced(function* (
1416
+ repository: Repository,
1417
+ tree: TreeID,
1418
+ ) {
1419
+ const alreadyLocal = yield* verifyLocalizedSnapshotTree(
1420
+ repository,
1421
+ tree,
1422
+ ).pipe(
1423
+ Effect.as(true),
1424
+ Effect.catch(() => Effect.succeed(false)),
1425
+ );
1426
+ if (alreadyLocal) return;
1427
+
1428
+ const pack = yield* objectOperation(
1429
+ repository,
1430
+ SNAPSHOT_LOCALIZATION_PACK_ARGS,
1431
+ MAX_SNAPSHOT_LOCALIZATION_PACK_BYTES,
1432
+ { operation: "retain", stdin: Buffer.from(`${tree}\n`, "utf8") },
1433
+ );
1434
+ if (pack.length < 12 || pack.subarray(0, 4).toString("ascii") !== "PACK")
1435
+ return yield* new OperationError({
1436
+ operation: "retain",
1437
+ directory: repository.gitDirectory,
1438
+ message: "Snapshot localization did not produce a canonical pack",
1439
+ });
1440
+
1441
+ const characters = yield* snapshotObjectIDCharacters(repository);
1442
+ const installed = (yield* objectOperation(
1443
+ repository,
1444
+ ["index-pack", "--stdin", "--strict"],
1445
+ characters + 8,
1446
+ {
1447
+ operation: "retain",
1448
+ stdin: pack,
1449
+ },
1450
+ ))
1451
+ .toString("utf8")
1452
+ .trim();
1453
+ if (!new RegExp(`^pack\\s[0-9a-f]{${characters}}$`).test(installed))
1454
+ return yield* new OperationError({
1455
+ operation: "retain",
1456
+ directory: repository.gitDirectory,
1457
+ message: "Snapshot localization pack was not installed exactly",
1458
+ });
1459
+ yield* verifyLocalizedSnapshotTree(repository, tree);
1460
+ });
1461
+
1462
+ const snapshotTreeExists = Effect.fnUntraced(function* (
1463
+ repository: Repository,
1464
+ tree: TreeID,
1465
+ operation: "retain" | "reclaim",
1466
+ ) {
1467
+ const characters = yield* snapshotObjectIDCharacters(repository);
1468
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(tree))
1469
+ return yield* new OperationError({
1470
+ operation,
1471
+ directory: repository.gitDirectory,
1472
+ message: "Snapshot must be a canonical full tree object ID",
1473
+ });
1474
+ if (tree.length !== characters) return false;
1475
+ const output = (yield* objectOperation(
1476
+ repository,
1477
+ ["cat-file", "--batch-check=%(objectname) %(objecttype)"],
1478
+ characters + 16,
1479
+ {
1480
+ operation,
1481
+ stdin: Buffer.from(`${tree}\n`, "utf8"),
1482
+ },
1483
+ ))
1484
+ .toString("utf8")
1485
+ .replaceAll("\r\n", "\n")
1486
+ .trimEnd();
1487
+ if (output === `${tree} missing`) return false;
1488
+ if (output === `${tree} tree`) return true;
1489
+ return yield* new OperationError({
1490
+ operation,
1491
+ directory: repository.gitDirectory,
1492
+ message: "Snapshot ID resolved to an unexpected Git object",
1493
+ });
1494
+ });
1495
+
1496
+ const listRetentionRefs = Effect.fnUntraced(function* (
1497
+ repository: Repository,
1498
+ prefix: string,
1499
+ ) {
1500
+ const characters = yield* snapshotObjectIDCharacters(repository);
1501
+ const output = (yield* objectOperation(
1502
+ repository,
1503
+ ["for-each-ref", "--format=%(refname) %(objectname)", prefix],
1504
+ MAX_SNAPSHOT_RETENTION_MANIFEST_BYTES,
1505
+ { operation: "reclaim" },
1506
+ ))
1507
+ .toString("utf8")
1508
+ .replaceAll("\r\n", "\n");
1509
+ if (/\0|\r/.test(output))
1510
+ return yield* new OperationError({
1511
+ operation: "reclaim",
1512
+ directory: repository.gitDirectory,
1513
+ message: "Snapshot retention ref manifest is not canonical",
1514
+ });
1515
+ const refs = new Map<TreeID, string>();
1516
+ const lines = output.split("\n").filter(Boolean);
1517
+ if (lines.length > MAX_SNAPSHOT_RETENTION_REFS)
1518
+ return yield* new OperationError({
1519
+ operation: "reclaim",
1520
+ directory: repository.gitDirectory,
1521
+ message: `Snapshot retention exceeds ${MAX_SNAPSHOT_RETENTION_REFS} refs`,
1522
+ });
1523
+ for (const line of lines) {
1524
+ const separator = line.indexOf(" ");
1525
+ const ref = separator === -1 ? "" : line.slice(0, separator);
1526
+ const object = separator === -1 ? "" : line.slice(separator + 1);
1527
+ if (!ref.startsWith(`${prefix}/`))
1528
+ return yield* new OperationError({
1529
+ operation: "reclaim",
1530
+ directory: repository.gitDirectory,
1531
+ message: "Snapshot retention ref escaped its namespace",
1532
+ });
1533
+ const suffix = ref.slice(prefix.length + 1);
1534
+ if (
1535
+ !new RegExp(`^[0-9a-f]{${characters}}$`).test(suffix) ||
1536
+ object !== suffix ||
1537
+ refs.has(TreeID.make(suffix))
1538
+ )
1539
+ return yield* new OperationError({
1540
+ operation: "reclaim",
1541
+ directory: repository.gitDirectory,
1542
+ message: "Snapshot retention ref did not match its exact tree",
1543
+ });
1544
+ refs.set(TreeID.make(suffix), object);
1545
+ }
1546
+ return refs;
1547
+ });
1548
+
1549
+ const exactRetentionRefTarget = Effect.fnUntraced(function* (
1550
+ repository: Repository,
1551
+ prefix: string,
1552
+ tree: TreeID,
1553
+ operation: "retain" | "reclaim",
1554
+ ) {
1555
+ const output = (yield* objectOperation(
1556
+ repository,
1557
+ [
1558
+ "for-each-ref",
1559
+ "--format=%(objectname)",
1560
+ "--count=1",
1561
+ `${prefix}/${tree}`,
1562
+ ],
1563
+ tree.length + 2,
1564
+ { operation },
1565
+ ))
1566
+ .toString("utf8")
1567
+ .replaceAll("\r\n", "\n")
1568
+ .trimEnd();
1569
+ if (output === "") return undefined;
1570
+ if (output === tree) return tree;
1571
+ return yield* new OperationError({
1572
+ operation,
1573
+ directory: repository.gitDirectory,
1574
+ message: "Snapshot retention ref did not match its exact tree",
1575
+ });
1576
+ });
1577
+
1578
+ type ReclamationState = {
1579
+ readonly version: 3;
1580
+ readonly digest: string;
1581
+ /** Exact candidate generation aged by this journal entry. */
1582
+ readonly candidatesDigest?: string;
1583
+ readonly preparedAt: number;
1584
+ readonly phase: "prepared" | "gc-pending";
1585
+ };
1586
+
1587
+ const reclamationCandidatesDigest = (
1588
+ candidates: ReadonlyMap<TreeID, string>,
1589
+ ) =>
1590
+ `sha256:${Hash.sha256(
1591
+ JSON.stringify(
1592
+ Array.from(candidates).sort(([left], [right]) =>
1593
+ left.localeCompare(right),
1594
+ ),
1595
+ ),
1596
+ )}`;
1597
+
1598
+ const readReclamationState = Effect.fnUntraced(function* (
1599
+ repository: Repository,
1600
+ ) {
1601
+ const values = yield* localConfigValues(
1602
+ repository,
1603
+ SNAPSHOT_RECLAMATION_STATE_KEY,
1604
+ );
1605
+ if (values.length === 0) return undefined;
1606
+ if (values.length !== 1)
1607
+ return yield* new OperationError({
1608
+ operation: "reclaim",
1609
+ directory: repository.gitDirectory,
1610
+ message: "Snapshot reclamation state is ambiguous",
1611
+ });
1612
+ return yield* Effect.try({
1613
+ try: () => {
1614
+ const parsed: unknown = JSON.parse(values[0] ?? "");
1615
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1616
+ throw new globalThis.Error("state is not an object");
1617
+ const record = parsed as Record<string, unknown>;
1618
+ const keys = Object.keys(record).sort().join("\0");
1619
+ const legacy =
1620
+ record.version === 1 &&
1621
+ keys === ["digest", "preparedAt", "version"].sort().join("\0");
1622
+ const previous =
1623
+ record.version === 2 &&
1624
+ keys ===
1625
+ ["digest", "phase", "preparedAt", "version"].sort().join("\0");
1626
+ const current =
1627
+ record.version === 3 &&
1628
+ keys ===
1629
+ [
1630
+ "candidatesDigest",
1631
+ "digest",
1632
+ "phase",
1633
+ "preparedAt",
1634
+ "version",
1635
+ ]
1636
+ .sort()
1637
+ .join("\0");
1638
+ if (
1639
+ (!legacy && !previous && !current) ||
1640
+ typeof record.digest !== "string" ||
1641
+ !/^sha256:[0-9a-f]{64}$/.test(record.digest) ||
1642
+ (current &&
1643
+ (typeof record.candidatesDigest !== "string" ||
1644
+ !/^sha256:[0-9a-f]{64}$/.test(record.candidatesDigest))) ||
1645
+ typeof record.preparedAt !== "number" ||
1646
+ !Number.isSafeInteger(record.preparedAt) ||
1647
+ record.preparedAt < 0 ||
1648
+ ((previous || current) &&
1649
+ record.phase !== "prepared" &&
1650
+ record.phase !== "gc-pending")
1651
+ )
1652
+ throw new globalThis.Error("state has an invalid shape");
1653
+ return {
1654
+ version: 3,
1655
+ digest: record.digest,
1656
+ ...(current
1657
+ ? { candidatesDigest: record.candidatesDigest as string }
1658
+ : {}),
1659
+ preparedAt: record.preparedAt,
1660
+ phase: previous || current
1661
+ ? (record.phase as ReclamationState["phase"])
1662
+ : "prepared",
1663
+ } satisfies ReclamationState;
1664
+ },
1665
+ catch: (cause) =>
1666
+ new OperationError({
1667
+ operation: "reclaim",
1668
+ directory: repository.gitDirectory,
1669
+ message: "Snapshot reclamation state is invalid",
1670
+ cause,
1671
+ }),
1672
+ });
1673
+ });
1674
+
1675
+ const persistReclamationState = Effect.fnUntraced(function* (
1676
+ repository: Repository,
1677
+ state: ReclamationState,
1678
+ ) {
1679
+ const encoded = JSON.stringify(state);
1680
+ yield* repositoryOperation(
1681
+ "reclaim",
1682
+ repository,
1683
+ [
1684
+ "config",
1685
+ "--local",
1686
+ "--replace-all",
1687
+ SNAPSHOT_RECLAMATION_STATE_KEY,
1688
+ encoded,
1689
+ ],
1690
+ { env: { LANG: "C", LC_ALL: "C" } },
1691
+ );
1692
+ const verified = yield* localConfigValues(
1693
+ repository,
1694
+ SNAPSHOT_RECLAMATION_STATE_KEY,
1695
+ );
1696
+ if (verified.length === 1 && verified[0] === encoded) return;
1697
+ return yield* new OperationError({
1698
+ operation: "reclaim",
1699
+ directory: repository.gitDirectory,
1700
+ message: "Snapshot reclamation state was not persisted exactly",
1701
+ });
1702
+ });
1703
+
1704
+ const updateCandidateRefs = Effect.fnUntraced(function* (
1705
+ repository: Repository,
1706
+ existing: ReadonlyMap<TreeID, string>,
1707
+ desired: ReadonlyMap<TreeID, string>,
1708
+ ) {
1709
+ const commands: string[] = ["start"];
1710
+ for (const [tree, object] of existing) {
1711
+ if (desired.has(tree)) continue;
1712
+ commands.push(`delete ${snapshotReclaimRef(tree)} ${object}`);
1713
+ }
1714
+ for (const [tree, object] of desired) {
1715
+ if (existing.has(tree)) continue;
1716
+ commands.push(`create ${snapshotReclaimRef(tree)} ${object}`);
1717
+ }
1718
+ if (commands.length === 1) return;
1719
+ commands.push("prepare", "commit", "");
1720
+ yield* repositoryOperation(
1721
+ "reclaim",
1722
+ repository,
1723
+ ["update-ref", "--stdin"],
1724
+ { stdin: commands.join("\n") },
1725
+ );
1726
+ });
1727
+
1728
+ const sweepCandidateRefs = Effect.fnUntraced(function* (
1729
+ repository: Repository,
1730
+ snapshotRefs: ReadonlyMap<TreeID, string>,
1731
+ candidates: ReadonlyMap<TreeID, string>,
1732
+ ) {
1733
+ if (candidates.size === 0) return;
1734
+ const commands: string[] = ["start"];
1735
+ for (const [tree, object] of candidates) {
1736
+ const retained = snapshotRefs.get(tree);
1737
+ if (retained !== undefined)
1738
+ commands.push(`delete ${snapshotRef(tree)} ${retained}`);
1739
+ commands.push(`delete ${snapshotReclaimRef(tree)} ${object}`);
1740
+ }
1741
+ commands.push("prepare", "commit", "");
1742
+ yield* repositoryOperation(
1743
+ "reclaim",
1744
+ repository,
1745
+ ["update-ref", "--stdin"],
1746
+ { stdin: commands.join("\n") },
1747
+ );
1748
+ });
1749
+
1750
+ const garbageCollectSnapshotStore = Effect.fnUntraced(function* (
1751
+ repository: Repository,
1752
+ ) {
1753
+ const collect = Effect.gen(function* () {
1754
+ yield* repositoryOperation("reclaim", repository, [
1755
+ "reflog",
1756
+ "expire",
1757
+ "--expire=now",
1758
+ "--expire-unreachable=now",
1759
+ "--all",
1760
+ ]);
1761
+ yield* repositoryOperation("reclaim", repository, [
1762
+ "gc",
1763
+ "--prune=now",
1764
+ ]);
1765
+ });
1766
+ const alternates = path.join(
1767
+ repository.gitDirectory,
1768
+ "objects",
1769
+ "info",
1770
+ "alternates",
1771
+ );
1772
+ if (!(yield* fs.existsSafe(alternates))) return yield* collect;
1773
+ const parked = `${alternates}.phins-reclamation-${randomUUID()}`;
1774
+ const move = (from: string, to: string, message: string) =>
1775
+ fs.rename(from, to).pipe(
1776
+ Effect.mapError(
1777
+ (cause) =>
1778
+ new OperationError({
1779
+ operation: "reclaim",
1780
+ directory: repository.gitDirectory,
1781
+ message,
1782
+ cause,
1783
+ }),
1784
+ ),
1785
+ );
1786
+ return yield* Effect.uninterruptibleMask((restore) =>
1787
+ Effect.gen(function* () {
1788
+ yield* move(
1789
+ alternates,
1790
+ parked,
1791
+ "Failed to disable snapshot alternates before reclamation",
1792
+ );
1793
+ const result = yield* restore(collect).pipe(Effect.exit);
1794
+ yield* move(
1795
+ parked,
1796
+ alternates,
1797
+ "Failed to restore snapshot alternates after reclamation",
1798
+ );
1799
+ if (result._tag === "Success") return result.value;
1800
+ return yield* Effect.failCause(result.cause);
1801
+ }),
1802
+ );
1803
+ });
1804
+
1805
+ const isRefLockRace = (cause: OperationError) => {
1806
+ const message = cause.message.toLowerCase();
1807
+ return (
1808
+ message.includes("cannot lock ref") &&
1809
+ (message.includes("file exists") ||
1810
+ message.includes("another git process"))
1811
+ );
1812
+ };
1813
+
1814
+ const updateSnapshotRef = (
1815
+ repository: Repository,
1816
+ ref: string,
1817
+ tree: TreeID,
1818
+ attempt = 0,
1819
+ ): Effect.Effect<void, OperationError> =>
1820
+ objectOperation(repository, ["update-ref", "--no-deref", ref, tree], 16, {
1821
+ operation: "retain",
1822
+ }).pipe(
1823
+ Effect.asVoid,
1824
+ Effect.catch((cause) => {
1825
+ if (attempt >= 4 || !isRefLockRace(cause)) return Effect.fail(cause);
1826
+ return Effect.sleep(Duration.millis(10 * 2 ** attempt)).pipe(
1827
+ Effect.andThen(
1828
+ updateSnapshotRef(repository, ref, tree, attempt + 1),
1829
+ ),
1830
+ );
1831
+ }),
1832
+ );
1833
+
1834
+ const retainSnapshotTree = Effect.fnUntraced(function* (
1835
+ repository: Repository,
1836
+ tree: TreeID,
1837
+ ) {
1838
+ const characters = yield* snapshotObjectIDCharacters(repository);
1839
+ if (!new RegExp(`^[0-9a-f]{${characters}}$`).test(tree))
1840
+ return yield* new OperationError({
1841
+ operation: "retain",
1842
+ directory: repository.gitDirectory,
1843
+ message: "Snapshot must be a canonical full tree object ID",
1844
+ });
1845
+ const type = (yield* objectOperation(
1846
+ repository,
1847
+ ["cat-file", "-t", tree],
1848
+ 16,
1849
+ {
1850
+ operation: "retain",
1851
+ },
1852
+ ))
1853
+ .toString("utf8")
1854
+ .trim();
1855
+ if (type !== "tree")
1856
+ return yield* new OperationError({
1857
+ operation: "retain",
1858
+ directory: repository.gitDirectory,
1859
+ message: "Snapshot retention target is not a tree",
1860
+ });
1861
+
1862
+ yield* localizeSnapshotTree(repository, tree);
1863
+ const ref = snapshotRef(tree);
1864
+ yield* updateSnapshotRef(repository, ref, tree);
1865
+ // Re-retaining a tree is an authoritative liveness signal. Requiring the
1866
+ // expected old value makes a corrupted candidate fail closed.
1867
+ const reclaimCandidate = yield* exactRetentionRefTarget(
1868
+ repository,
1869
+ SNAPSHOT_RECLAIM_REF_PREFIX,
1870
+ tree,
1871
+ "retain",
1872
+ );
1873
+ if (reclaimCandidate !== undefined)
1874
+ yield* objectOperation(
1875
+ repository,
1876
+ ["update-ref", "-d", snapshotReclaimRef(tree), tree],
1877
+ 16,
1878
+ { operation: "retain" },
1879
+ );
1880
+ const retained = (yield* objectOperation(
1881
+ repository,
1882
+ ["show-ref", "--verify", "--hash", ref],
1883
+ characters + 1,
1884
+ {
1885
+ operation: "retain",
1886
+ },
1887
+ ))
1888
+ .toString("utf8")
1889
+ .trim();
1890
+ if (retained !== tree)
1891
+ return yield* new OperationError({
1892
+ operation: "retain",
1893
+ directory: repository.gitDirectory,
1894
+ message: "Snapshot retention ref did not persist the exact tree",
1895
+ });
1896
+ });
1897
+
1898
+ const snapshotClosureFailure = (
1899
+ repository: Repository,
1900
+ message: string,
1901
+ ) =>
1902
+ new OperationError({
1903
+ operation: "retain",
1904
+ directory: repository.gitDirectory,
1905
+ message,
1906
+ });
1907
+
1908
+ const sameObjectManifest = (
1909
+ left: readonly string[],
1910
+ right: readonly string[],
1911
+ ) =>
1912
+ left.length === right.length &&
1913
+ left.every((object, index) => object === right[index]);
1914
+
1915
+ const validateSnapshotClosure = Effect.fnUntraced(function* (
1916
+ repository: Repository,
1917
+ closure: SnapshotClosureV1,
1918
+ ) {
1919
+ const keys = Object.keys(closure as object).sort();
1920
+ const expectedKeys = [
1921
+ "digest",
1922
+ "encoding",
1923
+ "objectFormat",
1924
+ "objects",
1925
+ "pack",
1926
+ "tree",
1927
+ "version",
1928
+ ];
1929
+ if (!sameObjectManifest(keys, expectedKeys))
1930
+ return yield* snapshotClosureFailure(
1931
+ repository,
1932
+ "Snapshot closure envelope fields are not exact",
1933
+ );
1934
+ const version = closure.version;
1935
+ const tree = closure.tree;
1936
+ const objectFormat = closure.objectFormat;
1937
+ const encoding = closure.encoding;
1938
+ const digest = closure.digest;
1939
+ const sourceObjects = closure.objects;
1940
+ const sourcePack = closure.pack;
1941
+ if (version !== 1 || encoding !== "git-pack-v1")
1942
+ return yield* snapshotClosureFailure(
1943
+ repository,
1944
+ "Snapshot closure protocol is incompatible",
1945
+ );
1946
+ if (!Array.isArray(sourceObjects) || sourceObjects.length === 0)
1947
+ return yield* snapshotClosureFailure(
1948
+ repository,
1949
+ "Snapshot closure object manifest is empty",
1950
+ );
1951
+ const objects = Object.freeze(Array.from(sourceObjects));
1952
+ if (
1953
+ !(sourcePack instanceof Uint8Array) ||
1954
+ sourcePack.byteLength < 12 ||
1955
+ sourcePack.byteLength > MAX_SNAPSHOT_TRANSFER_PACK_BYTES
1956
+ )
1957
+ return yield* snapshotClosureFailure(
1958
+ repository,
1959
+ "Snapshot closure pack exceeded its canonical bounds",
1960
+ );
1961
+ const pack = Buffer.from(sourcePack);
1962
+ const characters = yield* snapshotObjectIDCharacters(repository);
1963
+ const targetObjectFormat = characters === 40 ? "sha1" : "sha256";
1964
+ if (objectFormat !== targetObjectFormat)
1965
+ return yield* snapshotClosureFailure(
1966
+ repository,
1967
+ "Snapshot closure object format does not match the target store",
1968
+ );
1969
+ const objectPattern = new RegExp(`^[0-9a-f]{${characters}}$`);
1970
+ if (!objectPattern.test(tree))
1971
+ return yield* snapshotClosureFailure(
1972
+ repository,
1973
+ "Snapshot closure tree is not a canonical full object ID",
1974
+ );
1975
+ let manifestBytes = 0;
1976
+ let previous: string | undefined;
1977
+ let containsTree = false;
1978
+ for (const object of objects) {
1979
+ if (
1980
+ typeof object !== "string" ||
1981
+ !objectPattern.test(object) ||
1982
+ (previous !== undefined && previous >= object)
1983
+ )
1984
+ return yield* snapshotClosureFailure(
1985
+ repository,
1986
+ "Snapshot closure object manifest is not canonical",
1987
+ );
1988
+ manifestBytes += Buffer.byteLength(object, "utf8") + 1;
1989
+ if (manifestBytes > MAX_SNAPSHOT_RETENTION_MANIFEST_BYTES)
1990
+ return yield* snapshotClosureFailure(
1991
+ repository,
1992
+ "Snapshot closure object manifest exceeded its byte limit",
1993
+ );
1994
+ if (object === tree) containsTree = true;
1995
+ previous = object;
1996
+ }
1997
+ if (!containsTree)
1998
+ return yield* snapshotClosureFailure(
1999
+ repository,
2000
+ "Snapshot closure object manifest does not contain its tree",
2001
+ );
2002
+ if (pack.subarray(0, 4).toString("ascii") !== "PACK")
2003
+ return yield* snapshotClosureFailure(
2004
+ repository,
2005
+ "Snapshot closure did not contain a Git pack",
2006
+ );
2007
+ if (!/^sha256:[0-9a-f]{64}$/.test(digest))
2008
+ return yield* snapshotClosureFailure(
2009
+ repository,
2010
+ "Snapshot closure digest is not canonical",
2011
+ );
2012
+ const actualDigest = `sha256:${Hash.sha256(pack)}`;
2013
+ if (digest !== actualDigest)
2014
+ return yield* snapshotClosureFailure(
2015
+ repository,
2016
+ "Snapshot closure digest does not match its pack",
2017
+ );
2018
+ return { characters, objects, pack, tree };
2019
+ });
2020
+
2021
+ const inspectSnapshotClosurePack = Effect.fnUntraced(function* (
2022
+ repository: Repository,
2023
+ pack: Uint8Array,
2024
+ characters: 40 | 64,
2025
+ objectDirectory: string,
2026
+ environment?: Readonly<Record<string, string>>,
2027
+ ) {
2028
+ const installed = (yield* objectOperation(
2029
+ repository,
2030
+ ["index-pack", "--stdin", "--strict"],
2031
+ characters + 8,
2032
+ {
2033
+ operation: "retain",
2034
+ stdin: pack,
2035
+ environment,
2036
+ },
2037
+ ))
2038
+ .toString("utf8")
2039
+ .trim();
2040
+ const match = new RegExp(
2041
+ `^pack\\s([0-9a-f]{${characters}})$`,
2042
+ ).exec(installed);
2043
+ if (!match)
2044
+ return yield* snapshotClosureFailure(
2045
+ repository,
2046
+ "Snapshot closure pack was not installed exactly",
2047
+ );
2048
+ const packHash = match[1]!;
2049
+ const index = path.join(
2050
+ objectDirectory,
2051
+ "pack",
2052
+ `pack-${packHash}.idx`,
2053
+ );
2054
+ const verified = (yield* objectOperation(
2055
+ repository,
2056
+ ["verify-pack", "-v", index],
2057
+ MAX_SNAPSHOT_RETENTION_MANIFEST_BYTES,
2058
+ { operation: "retain", environment },
2059
+ ))
2060
+ .toString("utf8")
2061
+ .replaceAll("\r\n", "\n")
2062
+ .split("\n")
2063
+ .filter(Boolean);
2064
+ const objectPattern = new RegExp(`^([0-9a-f]{${characters}})\\s`);
2065
+ const packedObjects: string[] = [];
2066
+ for (const line of verified) {
2067
+ const object = objectPattern.exec(line)?.[1];
2068
+ if (object) {
2069
+ packedObjects.push(object);
2070
+ continue;
2071
+ }
2072
+ if (
2073
+ /^non delta: \d+ objects$/.test(line) ||
2074
+ /^chain length = \d+: \d+ objects?$/.test(line) ||
2075
+ (line.endsWith(": ok") && line.includes(`pack-${packHash}.`))
2076
+ )
2077
+ continue;
2078
+ return yield* snapshotClosureFailure(
2079
+ repository,
2080
+ "Snapshot closure pack verification output is not canonical",
2081
+ );
2082
+ }
2083
+ return Object.freeze(packedObjects.toSorted());
2084
+ });
2085
+
2086
+ const exportSnapshotClosure = Effect.fn("Git.tree.exportClosure")(
2087
+ function* (input: { repository: Repository; tree: TreeID }) {
2088
+ yield* ensureSnapshotRetention(input.repository);
2089
+ return yield* locked(
2090
+ input.repository,
2091
+ Effect.gen(function* () {
2092
+ const retained = yield* exactRetentionRefTarget(
2093
+ input.repository,
2094
+ SNAPSHOT_REF_PREFIX,
2095
+ input.tree,
2096
+ "retain",
2097
+ );
2098
+ if (retained !== input.tree)
2099
+ return yield* snapshotClosureFailure(
2100
+ input.repository,
2101
+ "Snapshot closure export requires an exact retained tree",
2102
+ );
2103
+ const objects = yield* verifyLocalizedSnapshotTree(
2104
+ input.repository,
2105
+ input.tree,
2106
+ );
2107
+ const pack = yield* objectOperation(
2108
+ input.repository,
2109
+ SNAPSHOT_LOCALIZATION_PACK_ARGS,
2110
+ MAX_SNAPSHOT_TRANSFER_PACK_BYTES,
2111
+ {
2112
+ operation: "retain",
2113
+ stdin: Buffer.from(`${input.tree}\n`, "utf8"),
2114
+ },
2115
+ );
2116
+ if (
2117
+ pack.length < 12 ||
2118
+ pack.subarray(0, 4).toString("ascii") !== "PACK"
2119
+ )
2120
+ return yield* snapshotClosureFailure(
2121
+ input.repository,
2122
+ "Snapshot closure export did not produce a canonical pack",
2123
+ );
2124
+ const characters = yield* snapshotObjectIDCharacters(
2125
+ input.repository,
2126
+ );
2127
+ return Object.freeze({
2128
+ version: 1,
2129
+ tree: input.tree,
2130
+ objectFormat: characters === 40 ? "sha1" : "sha256",
2131
+ encoding: "git-pack-v1",
2132
+ digest: `sha256:${Hash.sha256(pack)}`,
2133
+ objects,
2134
+ pack: new Uint8Array(pack),
2135
+ }) satisfies SnapshotClosureV1;
2136
+ }),
2137
+ );
2138
+ },
2139
+ );
2140
+
2141
+ const importSnapshotClosure = Effect.fn("Git.tree.importClosure")(
2142
+ function* (input: {
2143
+ repository: Repository;
2144
+ expectedTree: TreeID;
2145
+ closure: SnapshotClosureV1;
2146
+ }) {
2147
+ yield* ensureSnapshotRetention(input.repository);
2148
+ yield* locked(
2149
+ input.repository,
2150
+ Effect.gen(function* () {
2151
+ const validated = yield* validateSnapshotClosure(
2152
+ input.repository,
2153
+ input.closure,
2154
+ );
2155
+ if (validated.tree !== input.expectedTree)
2156
+ return yield* snapshotClosureFailure(
2157
+ input.repository,
2158
+ "Snapshot closure tree does not match the expected replay root",
2159
+ );
2160
+ yield* Effect.acquireUseRelease(
2161
+ fs
2162
+ .makeTempDirectory({ prefix: "phins-snapshot-import-" })
2163
+ .pipe(
2164
+ Effect.mapError(
2165
+ (cause) =>
2166
+ new OperationError({
2167
+ operation: "retain",
2168
+ directory: input.repository.gitDirectory,
2169
+ message:
2170
+ "Failed to create snapshot closure quarantine",
2171
+ cause,
2172
+ }),
2173
+ ),
2174
+ ),
2175
+ (quarantine) =>
2176
+ Effect.gen(function* () {
2177
+ const packDirectory = path.join(quarantine, "pack");
2178
+ yield* fs.ensureDir(packDirectory).pipe(
2179
+ Effect.mapError(
2180
+ (cause) =>
2181
+ new OperationError({
2182
+ operation: "retain",
2183
+ directory: input.repository.gitDirectory,
2184
+ message:
2185
+ "Failed to prepare snapshot closure quarantine",
2186
+ cause,
2187
+ }),
2188
+ ),
2189
+ );
2190
+ const environment = {
2191
+ GIT_OBJECT_DIRECTORY: quarantine,
2192
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: "",
2193
+ };
2194
+ const packedObjects =
2195
+ yield* inspectSnapshotClosurePack(
2196
+ input.repository,
2197
+ validated.pack,
2198
+ validated.characters,
2199
+ quarantine,
2200
+ environment,
2201
+ );
2202
+ if (
2203
+ !sameObjectManifest(
2204
+ packedObjects,
2205
+ validated.objects,
2206
+ )
2207
+ )
2208
+ return yield* snapshotClosureFailure(
2209
+ input.repository,
2210
+ "Snapshot closure pack does not match its exact object manifest",
2211
+ );
2212
+ const reachable = yield* snapshotClosureManifest(
2213
+ input.repository,
2214
+ validated.tree,
2215
+ environment,
2216
+ );
2217
+ if (
2218
+ !sameObjectManifest(reachable, validated.objects)
2219
+ )
2220
+ return yield* snapshotClosureFailure(
2221
+ input.repository,
2222
+ "Snapshot closure manifest does not match the reachable tree",
2223
+ );
2224
+ }),
2225
+ (quarantine) =>
2226
+ fs
2227
+ .remove(quarantine, { recursive: true, force: true })
2228
+ .pipe(
2229
+ Effect.mapError(
2230
+ (cause) =>
2231
+ new OperationError({
2232
+ operation: "retain",
2233
+ directory: input.repository.gitDirectory,
2234
+ message:
2235
+ "Failed to clean snapshot closure quarantine",
2236
+ cause,
2237
+ }),
2238
+ ),
2239
+ ),
2240
+ );
2241
+
2242
+ const packedObjects = yield* inspectSnapshotClosurePack(
2243
+ input.repository,
2244
+ validated.pack,
2245
+ validated.characters,
2246
+ path.join(input.repository.gitDirectory, "objects"),
2247
+ );
2248
+ if (!sameObjectManifest(packedObjects, validated.objects))
2249
+ return yield* snapshotClosureFailure(
2250
+ input.repository,
2251
+ "Installed snapshot closure changed after quarantine",
2252
+ );
2253
+ const reachable = yield* verifyLocalizedSnapshotTree(
2254
+ input.repository,
2255
+ validated.tree,
2256
+ );
2257
+ if (!sameObjectManifest(reachable, validated.objects))
2258
+ return yield* snapshotClosureFailure(
2259
+ input.repository,
2260
+ "Installed snapshot closure does not match its exact manifest",
2261
+ );
2262
+ yield* retainSnapshotTree(
2263
+ input.repository,
2264
+ validated.tree,
2265
+ );
2266
+ }),
2267
+ );
2268
+ },
2269
+ );
2270
+
2271
+ const retainTree = Effect.fn("Git.tree.retain")(function* (input: {
2272
+ repository: Repository;
2273
+ tree: TreeID;
2274
+ }) {
2275
+ yield* ensureSnapshotRetention(input.repository);
2276
+ yield* locked(
2277
+ input.repository,
2278
+ retainSnapshotTree(input.repository, input.tree),
2279
+ );
2280
+ });
2281
+
2282
+ const containsTree = Effect.fn("Git.tree.contains")(function* (input: {
2283
+ repository: Repository;
2284
+ tree: TreeID;
2285
+ }) {
2286
+ yield* ensureSnapshotRetention(input.repository);
2287
+ return yield* locked(
2288
+ input.repository,
2289
+ snapshotTreeExists(input.repository, input.tree, "retain"),
2290
+ );
2291
+ });
2292
+
2293
+ const reconcileRetention = Effect.fn("Git.tree.reconcileRetention")(
2294
+ function* (input: {
2295
+ repository: Repository;
2296
+ live: readonly TreeID[];
2297
+ reclaim?: boolean;
2298
+ nowMs?: number;
2299
+ minimumAgeMs?: number;
2300
+ }) {
2301
+ const nowMs = input.nowMs ?? Date.now();
2302
+ const minimumAgeMs =
2303
+ input.minimumAgeMs ?? SNAPSHOT_RECLAMATION_MIN_AGE_MS;
2304
+ if (
2305
+ !Number.isSafeInteger(nowMs) ||
2306
+ nowMs < 0 ||
2307
+ !Number.isSafeInteger(minimumAgeMs) ||
2308
+ minimumAgeMs < 0
2309
+ )
2310
+ return yield* new OperationError({
2311
+ operation: "reclaim",
2312
+ directory: input.repository.gitDirectory,
2313
+ message: "Snapshot reclamation time bounds are invalid",
2314
+ });
2315
+ if (input.live.length > MAX_SNAPSHOT_RETENTION_REFS)
2316
+ return yield* new OperationError({
2317
+ operation: "reclaim",
2318
+ directory: input.repository.gitDirectory,
2319
+ message: `Snapshot live set exceeds ${MAX_SNAPSHOT_RETENTION_REFS} refs`,
2320
+ });
2321
+ const live = Array.from(new Set(input.live)).sort();
2322
+ yield* ensureSnapshotRetention(input.repository);
2323
+ return yield* locked(
2324
+ input.repository,
2325
+ Effect.gen(function* () {
2326
+ for (const tree of live) {
2327
+ if (
2328
+ !(yield* snapshotTreeExists(input.repository, tree, "reclaim"))
2329
+ )
2330
+ return yield* new OperationError({
2331
+ operation: "reclaim",
2332
+ directory: input.repository.gitDirectory,
2333
+ message: `Authoritative live snapshot is missing: ${tree}`,
2334
+ });
2335
+ yield* retainSnapshotTree(input.repository, tree);
2336
+ }
2337
+
2338
+ const liveSet = new Set(live);
2339
+ let refs = yield* listRetentionRefs(
2340
+ input.repository,
2341
+ SNAPSHOT_REF_PREFIX,
2342
+ );
2343
+ for (const tree of live) {
2344
+ if (refs.get(tree) !== tree)
2345
+ return yield* new OperationError({
2346
+ operation: "reclaim",
2347
+ directory: input.repository.gitDirectory,
2348
+ message:
2349
+ "Authoritative live snapshot was not retained exactly",
2350
+ });
2351
+ }
2352
+ let candidates = yield* listRetentionRefs(
2353
+ input.repository,
2354
+ SNAPSHOT_RECLAIM_REF_PREFIX,
2355
+ );
2356
+ const digest = `sha256:${Hash.sha256(JSON.stringify(live))}`;
2357
+ let state = yield* readReclamationState(input.repository);
2358
+ let reclaimed = 0;
2359
+ let garbageCollected = false;
2360
+
2361
+ const desiredBeforeSweep = new Map<TreeID, string>();
2362
+ for (const [tree, object] of refs) {
2363
+ if (!liveSet.has(tree)) desiredBeforeSweep.set(tree, object);
2364
+ }
2365
+ const candidatesMatch =
2366
+ candidates.size === desiredBeforeSweep.size &&
2367
+ Array.from(desiredBeforeSweep).every(
2368
+ ([tree, object]) => candidates.get(tree) === object,
2369
+ );
2370
+ const candidatesDigest =
2371
+ reclamationCandidatesDigest(candidates);
2372
+ const journalMatchesCandidates =
2373
+ state?.candidatesDigest === candidatesDigest;
2374
+
2375
+ const resumeGc = state?.phase === "gc-pending";
2376
+ const beginGc =
2377
+ state !== undefined &&
2378
+ state.phase === "prepared" &&
2379
+ state.digest === digest &&
2380
+ journalMatchesCandidates &&
2381
+ candidatesMatch &&
2382
+ input.reclaim === true &&
2383
+ candidates.size > 0 &&
2384
+ nowMs >= state.preparedAt + minimumAgeMs;
2385
+
2386
+ if (resumeGc || beginGc) {
2387
+ if (!state)
2388
+ return yield* new OperationError({
2389
+ operation: "reclaim",
2390
+ directory: input.repository.gitDirectory,
2391
+ message: "Snapshot reclamation journal disappeared",
2392
+ });
2393
+ if (!resumeGc) {
2394
+ state = { ...state, version: 3, phase: "gc-pending" };
2395
+ // Journal the destructive phase before the single atomic ref
2396
+ // deletion. A killed process therefore resumes GC even when no
2397
+ // candidate refs remain on the next invocation.
2398
+ yield* persistReclamationState(input.repository, state);
2399
+ }
2400
+ // A retain/capture removes its candidate under this same
2401
+ // cross-process lock. After a restart, only sweep when the live
2402
+ // set and exact candidate generation still match the journal.
2403
+ // An older journal without a candidate digest is ambiguous, as
2404
+ // is a mismatch after a crash, so both paths only finish GC and
2405
+ // restart aging below.
2406
+ const sweep = new Map<TreeID, string>();
2407
+ if (
2408
+ state.digest === digest &&
2409
+ state.candidatesDigest === candidatesDigest &&
2410
+ candidatesMatch
2411
+ ) {
2412
+ for (const [tree, object] of candidates) {
2413
+ if (!liveSet.has(tree)) sweep.set(tree, object);
2414
+ }
2415
+ }
2416
+ yield* sweepCandidateRefs(input.repository, refs, sweep);
2417
+ reclaimed = sweep.size;
2418
+ yield* garbageCollectSnapshotStore(input.repository);
2419
+ garbageCollected = true;
2420
+ for (const tree of live) {
2421
+ yield* verifyLocalizedSnapshotTree(input.repository, tree);
2422
+ }
2423
+ refs = yield* listRetentionRefs(
2424
+ input.repository,
2425
+ SNAPSHOT_REF_PREFIX,
2426
+ );
2427
+ const remainingCandidates = yield* listRetentionRefs(
2428
+ input.repository,
2429
+ SNAPSHOT_RECLAIM_REF_PREFIX,
2430
+ );
2431
+ const desired = new Map<TreeID, string>();
2432
+ for (const [tree, object] of refs) {
2433
+ if (!liveSet.has(tree)) desired.set(tree, object);
2434
+ }
2435
+ state = {
2436
+ version: 3,
2437
+ digest,
2438
+ candidatesDigest: reclamationCandidatesDigest(desired),
2439
+ preparedAt: nowMs,
2440
+ phase: "prepared",
2441
+ };
2442
+ // Persist the generation before publishing its refs. Either
2443
+ // side of a crash then disagrees and must restart the grace
2444
+ // period instead of inheriting an older preparedAt value.
2445
+ yield* persistReclamationState(input.repository, state);
2446
+ yield* updateCandidateRefs(
2447
+ input.repository,
2448
+ remainingCandidates,
2449
+ desired,
2450
+ );
2451
+ candidates = desired;
2452
+ } else if (!state || state.digest !== digest) {
2453
+ state = {
2454
+ version: 3,
2455
+ digest,
2456
+ candidatesDigest:
2457
+ reclamationCandidatesDigest(desiredBeforeSweep),
2458
+ preparedAt: nowMs,
2459
+ phase: "prepared",
2460
+ };
2461
+ yield* persistReclamationState(input.repository, state);
2462
+ yield* updateCandidateRefs(
2463
+ input.repository,
2464
+ candidates,
2465
+ desiredBeforeSweep,
2466
+ );
2467
+ candidates = desiredBeforeSweep;
2468
+ } else if (!candidatesMatch || !journalMatchesCandidates) {
2469
+ // A new unreferenced capture (or a fresh liveness signal that
2470
+ // cleared one candidate), a legacy journal, or either half of a
2471
+ // journal/ref crash starts a new complete aging pass.
2472
+ state = {
2473
+ version: 3,
2474
+ digest,
2475
+ candidatesDigest:
2476
+ reclamationCandidatesDigest(desiredBeforeSweep),
2477
+ preparedAt: nowMs,
2478
+ phase: "prepared",
2479
+ };
2480
+ yield* persistReclamationState(input.repository, state);
2481
+ yield* updateCandidateRefs(
2482
+ input.repository,
2483
+ candidates,
2484
+ desiredBeforeSweep,
2485
+ );
2486
+ candidates = desiredBeforeSweep;
2487
+ }
2488
+
2489
+ yield* upgradeSnapshotDescriptor(input.repository);
2490
+ return Object.freeze({
2491
+ live: live.length,
2492
+ retained: live.length,
2493
+ candidates: candidates.size,
2494
+ reclaimed,
2495
+ garbageCollected,
2496
+ preparedAt: state.preparedAt,
2497
+ eligibleAt: state.preparedAt + minimumAgeMs,
2498
+ }) satisfies SnapshotRetentionReport;
2499
+ }),
2500
+ );
2501
+ },
2502
+ );
2503
+
2504
+ const create = Effect.fn("Git.repo.create")(function* (input: {
2505
+ worktree: AbsolutePath;
2506
+ gitDirectory: AbsolutePath;
2507
+ seed?: Repository;
2508
+ }) {
2509
+ yield* fs.ensureDir(input.gitDirectory).pipe(
2510
+ Effect.mapError(
2511
+ (cause) =>
2512
+ new OperationError({
2513
+ operation: "create",
2514
+ directory: input.gitDirectory,
2515
+ message: "Failed to create Git storage",
2516
+ cause,
2517
+ }),
2518
+ ),
2519
+ );
2520
+ const repository = new Repository({
2521
+ worktree: input.worktree,
2522
+ gitDirectory: input.gitDirectory,
2523
+ commonDirectory: input.gitDirectory,
2524
+ });
2525
+ yield* repositoryOperation("create", repository, ["init"]);
2526
+ yield* Effect.forEach(
2527
+ [
2528
+ ["core.autocrlf", "false"],
2529
+ ["core.longpaths", "true"],
2530
+ ["core.symlinks", "true"],
2531
+ ["core.fsmonitor", "false"],
2532
+ ["feature.manyFiles", "true"],
2533
+ ["index.version", "4"],
2534
+ ["index.threads", "true"],
2535
+ ["core.untrackedCache", "true"],
2536
+ ],
2537
+ ([key, value]) =>
2538
+ repositoryOperation("create", repository, ["config", key, value]),
2539
+ { discard: true },
2540
+ );
2541
+ if (!input.seed) return repository;
2542
+ yield* fs
2543
+ .ensureDir(path.join(input.gitDirectory, "objects", "info"))
2544
+ .pipe(
2545
+ Effect.mapError(
2546
+ (cause) =>
2547
+ new OperationError({
2548
+ operation: "create",
2549
+ directory: input.gitDirectory,
2550
+ message: "Failed to configure shared Git objects",
2551
+ cause,
2552
+ }),
2553
+ ),
2554
+ );
2555
+ yield* fs
2556
+ .writeFileString(
2557
+ path.join(input.gitDirectory, "objects", "info", "alternates"),
2558
+ path.join(input.seed.commonDirectory, "objects") + "\n",
2559
+ )
2560
+ .pipe(
2561
+ Effect.mapError(
2562
+ (cause) =>
2563
+ new OperationError({
2564
+ operation: "create",
2565
+ directory: input.gitDirectory,
2566
+ message: "Failed to configure shared Git objects",
2567
+ cause,
2568
+ }),
2569
+ ),
2570
+ );
2571
+ yield* fs
2572
+ .copyFile(
2573
+ path.join(input.seed.gitDirectory, "index"),
2574
+ path.join(input.gitDirectory, "index"),
2575
+ )
2576
+ .pipe(Effect.catch(() => Effect.void));
2577
+ return repository;
2578
+ });
2579
+
2580
+ const refresh = Effect.fn("Git.index.refresh")(function* (input: {
2581
+ repository: Repository;
2582
+ scope: RelativePath;
2583
+ ignores?: Repository;
2584
+ maximumUntrackedFileBytes?: number;
2585
+ }) {
2586
+ const list = (args: string[]) =>
2587
+ repositoryOperation("refresh", input.repository, args).pipe(
2588
+ Effect.map((result) => result.text.split("\0").filter(Boolean)),
2589
+ );
2590
+ const [tracked, untracked] = yield* Effect.all(
2591
+ [
2592
+ list(["diff-files", "--name-only", "-z", "--", input.scope]),
2593
+ list([
2594
+ "ls-files",
2595
+ "--others",
2596
+ "--exclude-standard",
2597
+ "-z",
2598
+ "--",
2599
+ input.scope,
2600
+ ]),
2601
+ ],
2602
+ { concurrency: 2 },
2603
+ );
2604
+ const candidates = Array.from(new Set([...tracked, ...untracked]));
2605
+ if (!candidates.length) return { skipped: [] };
2606
+ const ignored = input.ignores
2607
+ ? new Set(
2608
+ (yield* repositoryOperation(
2609
+ "refresh",
2610
+ input.ignores,
2611
+ ["check-ignore", "--no-index", "--stdin", "-z"],
2612
+ {
2613
+ stdin: candidates.join("\0") + "\0",
2614
+ },
2615
+ ).pipe(
2616
+ Effect.catch(() => Effect.succeed({ text: "", stderr: "" })),
2617
+ )).text
2618
+ .split("\0")
2619
+ .filter(Boolean),
2620
+ )
2621
+ : new Set<string>();
2622
+ const allowed = candidates.filter((item) => !ignored.has(item));
2623
+ const allowedSet = new Set(allowed);
2624
+ const maximum = input.maximumUntrackedFileBytes;
2625
+ const skipped = maximum
2626
+ ? (yield* Effect.forEach(
2627
+ untracked.filter((item) => allowedSet.has(item)),
2628
+ (item) =>
2629
+ fs.stat(path.join(input.repository.worktree, item)).pipe(
2630
+ Effect.map((info) =>
2631
+ info.type === "File" && Number(info.size) > maximum
2632
+ ? RelativePath.make(item)
2633
+ : undefined,
2634
+ ),
2635
+ Effect.catch(() => Effect.succeed(undefined)),
2636
+ ),
2637
+ { concurrency: 8 },
2638
+ )).filter((item): item is RelativePath => item !== undefined)
2639
+ : [];
2640
+ const skippedSet = new Set<string>(skipped);
2641
+ const stage = allowed.filter((item) => !skippedSet.has(item));
2642
+ const remove = [...ignored, ...skipped];
2643
+ if (remove.length)
2644
+ yield* repositoryOperation(
2645
+ "refresh",
2646
+ input.repository,
2647
+ [
2648
+ "rm",
2649
+ "--cached",
2650
+ "-f",
2651
+ "--ignore-unmatch",
2652
+ "--pathspec-from-file=-",
2653
+ "--pathspec-file-nul",
2654
+ ],
2655
+ { stdin: remove.join("\0") + "\0" },
2656
+ );
2657
+ if (stage.length)
2658
+ yield* repositoryOperation(
2659
+ "refresh",
2660
+ input.repository,
2661
+ [
2662
+ "add",
2663
+ "--all",
2664
+ "--sparse",
2665
+ "--pathspec-from-file=-",
2666
+ "--pathspec-file-nul",
2667
+ ],
2668
+ { stdin: stage.join("\0") + "\0" },
2669
+ );
2670
+ return { skipped };
2671
+ });
2672
+
2673
+ const ignored = Effect.fn("Git.index.ignored")(function* (input: {
2674
+ repository: Repository;
2675
+ paths: readonly RelativePath[];
2676
+ }) {
2677
+ if (!input.paths.length) return new Set<RelativePath>();
2678
+ const result = yield* proc
2679
+ .run(
2680
+ ChildProcess.make(
2681
+ "git",
2682
+ repositoryArgs(input.repository, [
2683
+ "check-ignore",
2684
+ "--no-index",
2685
+ "--stdin",
2686
+ "-z",
2687
+ ]),
2688
+ {
2689
+ cwd: input.repository.worktree,
2690
+ extendEnv: true,
2691
+ },
2692
+ ),
2693
+ { stdin: input.paths.join("\0") + "\0" },
2694
+ )
2695
+ .pipe(
2696
+ Effect.mapError(
2697
+ (cause) =>
2698
+ new OperationError({
2699
+ operation: "list_files",
2700
+ directory: input.repository.worktree,
2701
+ message: cause.message,
2702
+ cause,
2703
+ }),
2704
+ ),
2705
+ );
2706
+ if (result.exitCode !== 0 && result.exitCode !== 1)
2707
+ return yield* new OperationError({
2708
+ operation: "list_files",
2709
+ directory: input.repository.worktree,
2710
+ message:
2711
+ result.stderr.toString("utf8").trim() ||
2712
+ "Failed to check ignored paths",
2713
+ });
2714
+ return new Set(
2715
+ result.stdout
2716
+ .toString("utf8")
2717
+ .split("\0")
2718
+ .filter(Boolean)
2719
+ .map((file) => RelativePath.make(file)),
2720
+ );
2721
+ });
2722
+
2723
+ const writeTree = Effect.fn("Git.tree.write")(function* (
2724
+ repository: Repository,
2725
+ ) {
2726
+ return TreeID.make(
2727
+ (yield* repositoryOperation("write_tree", repository, [
2728
+ "write-tree",
2729
+ ])).text.trim(),
2730
+ );
2731
+ });
2732
+
2733
+ type CaptureTreeInput = {
2734
+ readonly repository: Repository;
2735
+ readonly scopes: readonly RelativePath[];
2736
+ readonly ignores?: Repository;
2737
+ readonly maximumUntrackedFileBytes?: number;
2738
+ };
2739
+
2740
+ const captureTree = Effect.fn("Git.tree.capture")(
2741
+ (input: CaptureTreeInput) =>
2742
+ ensureSnapshotRetention(input.repository).pipe(
2743
+ Effect.andThen(
2744
+ locked(
2745
+ input.repository,
2746
+ Effect.gen(function* () {
2747
+ yield* Effect.forEach(
2748
+ input.scopes,
2749
+ (scope) => refresh({ ...input, scope }),
2750
+ { discard: true },
2751
+ );
2752
+ const tree = yield* writeTree(input.repository);
2753
+ yield* retainSnapshotTree(input.repository, tree);
2754
+ return tree;
2755
+ }),
2756
+ ),
2757
+ ),
2758
+ ),
2759
+ );
2760
+
2761
+ const captureExactTree = Effect.fn("Git.tree.captureExact")(
2762
+ (input: CaptureTreeInput) =>
2763
+ ensureSnapshotRetention(input.repository).pipe(
2764
+ Effect.andThen(
2765
+ locked(
2766
+ input.repository,
2767
+ Effect.gen(function* () {
2768
+ const exactScope = input.scopes[0];
2769
+ const normalizedScope =
2770
+ exactScope === undefined
2771
+ ? undefined
2772
+ : path.posix.normalize(exactScope.replaceAll("\\", "/"));
2773
+ if (
2774
+ input.scopes.length !== 1 ||
2775
+ exactScope === undefined ||
2776
+ !input.ignores ||
2777
+ exactScope.includes("\0") ||
2778
+ exactScope !== normalizedScope ||
2779
+ path.posix.isAbsolute(exactScope) ||
2780
+ exactScope === ".." ||
2781
+ exactScope.startsWith("../") ||
2782
+ Buffer.byteLength(exactScope, "utf8") >
2783
+ MAX_MATERIALIZED_PATH_BYTES
2784
+ )
2785
+ return yield* new OperationError({
2786
+ operation: "capture",
2787
+ directory: input.repository.worktree,
2788
+ message:
2789
+ "Exact capture requires one normalized project-relative scope and the source repository",
2790
+ });
2791
+
2792
+ const source = input.ignores;
2793
+ const maximumUntrackedFileBytes =
2794
+ input.maximumUntrackedFileBytes ??
2795
+ MAX_MATERIALIZED_FILE_BYTES;
2796
+ if (
2797
+ !Number.isSafeInteger(maximumUntrackedFileBytes) ||
2798
+ maximumUntrackedFileBytes < 0
2799
+ )
2800
+ return yield* new OperationError({
2801
+ operation: "capture",
2802
+ directory: input.repository.worktree,
2803
+ message:
2804
+ "Exact capture requires a non-negative, safe untracked-file byte limit",
2805
+ });
2806
+ const projectWorktree = yield* Effect.tryPromise({
2807
+ try: async () => {
2808
+ const [repositoryWorktree, sourceWorktree] =
2809
+ await Promise.all([
2810
+ realpath(input.repository.worktree),
2811
+ realpath(source.worktree),
2812
+ ]);
2813
+ if (repositoryWorktree !== sourceWorktree)
2814
+ throw materializationFailure(
2815
+ "Exact-capture repositories do not share one canonical worktree",
2816
+ );
2817
+ return repositoryWorktree;
2818
+ },
2819
+ catch: (cause) =>
2820
+ new OperationError({
2821
+ operation: "capture",
2822
+ directory: input.repository.worktree,
2823
+ message:
2824
+ cause instanceof globalThis.Error
2825
+ ? cause.message
2826
+ : "Failed to resolve the exact-capture worktree",
2827
+ cause,
2828
+ }),
2829
+ });
2830
+ const gitOptions = [
2831
+ "-c",
2832
+ "core.fsmonitor=false",
2833
+ "-c",
2834
+ "core.untrackedCache=false",
2835
+ "-c",
2836
+ `core.excludesFile=${process.platform === "win32" ? "NUL" : "/dev/null"}`,
2837
+ ];
2838
+ const operationOptions = {
2839
+ operation: "capture" as const,
2840
+ worktree: true,
2841
+ };
2842
+ const [
2843
+ trackedOutput,
2844
+ untrackedOutput,
2845
+ sparseOutput,
2846
+ unmergedOutput,
2847
+ ] = yield* Effect.all(
2848
+ [
2849
+ objectOperation(
2850
+ source,
2851
+ [
2852
+ ...gitOptions,
2853
+ "ls-files",
2854
+ "-z",
2855
+ "--cached",
2856
+ "--deduplicate",
2857
+ "--",
2858
+ exactScope,
2859
+ ],
2860
+ MAX_MATERIALIZED_MANIFEST_BYTES,
2861
+ operationOptions,
2862
+ ),
2863
+ objectOperation(
2864
+ source,
2865
+ [
2866
+ ...gitOptions,
2867
+ "ls-files",
2868
+ "-z",
2869
+ "--others",
2870
+ "--exclude-standard",
2871
+ "--",
2872
+ exactScope,
2873
+ ],
2874
+ MAX_MATERIALIZED_MANIFEST_BYTES,
2875
+ operationOptions,
2876
+ ),
2877
+ objectOperation(
2878
+ source,
2879
+ [
2880
+ ...gitOptions,
2881
+ "ls-files",
2882
+ "-t",
2883
+ "-z",
2884
+ "--cached",
2885
+ "--",
2886
+ exactScope,
2887
+ ],
2888
+ MAX_MATERIALIZED_MANIFEST_BYTES,
2889
+ operationOptions,
2890
+ ),
2891
+ objectOperation(
2892
+ source,
2893
+ [
2894
+ ...gitOptions,
2895
+ "ls-files",
2896
+ "-z",
2897
+ "--unmerged",
2898
+ "--",
2899
+ exactScope,
2900
+ ],
2901
+ MAX_MATERIALIZED_MANIFEST_BYTES,
2902
+ operationOptions,
2903
+ ),
2904
+ ],
2905
+ { concurrency: 4 },
2906
+ );
2907
+ if (unmergedOutput.length > 0)
2908
+ return yield* new OperationError({
2909
+ operation: "capture",
2910
+ directory: input.repository.worktree,
2911
+ message:
2912
+ "Exact capture does not support an unmerged Git index",
2913
+ });
2914
+ if (
2915
+ Buffer.from(sparseOutput)
2916
+ .toString("latin1")
2917
+ .split("\0")
2918
+ .some((entry) => entry.startsWith("S "))
2919
+ )
2920
+ return yield* new OperationError({
2921
+ operation: "capture",
2922
+ directory: input.repository.worktree,
2923
+ message:
2924
+ "Exact capture does not support skip-worktree entries",
2925
+ });
2926
+
2927
+ const [tracked, untracked] = yield* Effect.try({
2928
+ try: () =>
2929
+ [
2930
+ decodeExactCapturePaths(trackedOutput),
2931
+ decodeExactCapturePaths(untrackedOutput),
2932
+ ] as const,
2933
+ catch: (cause) =>
2934
+ new OperationError({
2935
+ operation: "capture",
2936
+ directory: input.repository.worktree,
2937
+ message:
2938
+ cause instanceof globalThis.Error
2939
+ ? cause.message
2940
+ : "Exact-capture paths are invalid",
2941
+ cause,
2942
+ }),
2943
+ });
2944
+ const candidates = [
2945
+ ...tracked.map((file) => ({ file, tracked: true }) as const),
2946
+ ...untracked.map(
2947
+ (file) => ({ file, tracked: false }) as const,
2948
+ ),
2949
+ ];
2950
+ if (candidates.length > MAX_MATERIALIZED_ENTRIES)
2951
+ return yield* new OperationError({
2952
+ operation: "capture",
2953
+ directory: input.repository.worktree,
2954
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_ENTRIES} entries`,
2955
+ });
2956
+ const candidateBytes = candidates.reduce(
2957
+ (total, candidate) =>
2958
+ total + Buffer.byteLength(candidate.file, "utf8") + 1,
2959
+ 0,
2960
+ );
2961
+ if (candidateBytes > MAX_MATERIALIZED_MANIFEST_BYTES)
2962
+ return yield* new OperationError({
2963
+ operation: "capture",
2964
+ directory: input.repository.worktree,
2965
+ message: `Exact-capture paths exceed ${MAX_MATERIALIZED_MANIFEST_BYTES} bytes`,
2966
+ });
2967
+ const candidatePaths = new Set<string>();
2968
+ for (const { file } of candidates) {
2969
+ if (candidatePaths.has(file))
2970
+ return yield* new OperationError({
2971
+ operation: "capture",
2972
+ directory: input.repository.worktree,
2973
+ message: `Exact capture contains a duplicate path: ${JSON.stringify(file)}`,
2974
+ });
2975
+ candidatePaths.add(file);
2976
+ }
2977
+ const candidateDirectories = new Set<string>();
2978
+ for (const { file } of candidates) {
2979
+ const segments = file.split("/");
2980
+ for (let index = 1; index < segments.length; index++) {
2981
+ candidateDirectories.add(
2982
+ segments.slice(0, index).join("/"),
2983
+ );
2984
+ if (
2985
+ candidatePaths.size + candidateDirectories.size >
2986
+ MAX_MATERIALIZED_ENTRIES
2987
+ )
2988
+ return yield* new OperationError({
2989
+ operation: "capture",
2990
+ directory: input.repository.worktree,
2991
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_ENTRIES} materialized entries`,
2992
+ });
2993
+ }
2994
+ }
2995
+ for (const directory of candidateDirectories) {
2996
+ if (candidatePaths.has(directory))
2997
+ return yield* new OperationError({
2998
+ operation: "capture",
2999
+ directory: input.repository.worktree,
3000
+ message: `Exact capture contains a file/directory prefix collision: ${JSON.stringify(directory)}`,
3001
+ });
3002
+ }
3003
+ const portable = new Map<string, string>();
3004
+ for (const capturePath of [
3005
+ ...candidateDirectories,
3006
+ ...candidatePaths,
3007
+ ]) {
3008
+ const collisionKey = capturePath
3009
+ .normalize("NFC")
3010
+ .toLowerCase();
3011
+ const collision = portable.get(collisionKey);
3012
+ if (collision !== undefined)
3013
+ return yield* new OperationError({
3014
+ operation: "capture",
3015
+ directory: input.repository.worktree,
3016
+ message: `Exact capture contains colliding paths: ${JSON.stringify(collision)} and ${JSON.stringify(capturePath)}`,
3017
+ });
3018
+ portable.set(collisionKey, capturePath);
3019
+ }
3020
+
3021
+ const objectFormat = (yield* objectOperation(
3022
+ input.repository,
3023
+ ["rev-parse", "--show-object-format"],
3024
+ 32,
3025
+ {
3026
+ operation: "capture",
3027
+ },
3028
+ ))
3029
+ .toString("utf8")
3030
+ .trim();
3031
+ const objectCharacters =
3032
+ objectFormat === "sha1"
3033
+ ? 40
3034
+ : objectFormat === "sha256"
3035
+ ? 64
3036
+ : undefined;
3037
+ if (objectCharacters === undefined)
3038
+ return yield* new OperationError({
3039
+ operation: "capture",
3040
+ directory: input.repository.gitDirectory,
3041
+ message:
3042
+ "Exact capture requires a supported Git object format",
3043
+ });
3044
+ snapshotObjectCharacters.set(
3045
+ input.repository,
3046
+ objectCharacters,
3047
+ );
3048
+
3049
+ const captureCandidates: Array<
3050
+ (typeof candidates)[number] & {
3051
+ readonly target: string;
3052
+ readonly initial: BigIntStats;
3053
+ }
3054
+ > = [];
3055
+ let preflightBytes = 0n;
3056
+ for (const candidate of candidates) {
3057
+ const target = path.join(
3058
+ projectWorktree,
3059
+ ...candidate.file.split("/"),
3060
+ );
3061
+ const initial = yield* Effect.tryPromise({
3062
+ try: async () => {
3063
+ try {
3064
+ return await lstat(target, { bigint: true });
3065
+ } catch (cause) {
3066
+ if ((cause as NodeJS.ErrnoException).code === "ENOENT")
3067
+ return undefined;
3068
+ throw cause;
3069
+ }
3070
+ },
3071
+ catch: (cause) =>
3072
+ new OperationError({
3073
+ operation: "capture",
3074
+ directory: input.repository.worktree,
3075
+ message: `Failed to inspect raw file: ${JSON.stringify(candidate.file)}`,
3076
+ cause,
3077
+ }),
3078
+ });
3079
+ if (!initial) continue;
3080
+ if (!initial.isFile())
3081
+ return yield* new OperationError({
3082
+ operation: "capture",
3083
+ directory: input.repository.worktree,
3084
+ message: `Exact capture only supports regular files: ${JSON.stringify(candidate.file)}`,
3085
+ });
3086
+ const canonical = yield* Effect.tryPromise({
3087
+ try: () => realpath(target),
3088
+ catch: (cause) =>
3089
+ new OperationError({
3090
+ operation: "capture",
3091
+ directory: input.repository.worktree,
3092
+ message: `Failed to resolve raw file: ${JSON.stringify(candidate.file)}`,
3093
+ cause,
3094
+ }),
3095
+ });
3096
+ if (
3097
+ canonical !== target ||
3098
+ !FileAccess.contains(projectWorktree, canonical)
3099
+ )
3100
+ return yield* new OperationError({
3101
+ operation: "capture",
3102
+ directory: input.repository.worktree,
3103
+ message: `Exact-capture file resolves outside the canonical project tree: ${JSON.stringify(candidate.file)}`,
3104
+ });
3105
+ const maximum = candidate.tracked
3106
+ ? MAX_MATERIALIZED_FILE_BYTES
3107
+ : Math.min(
3108
+ maximumUntrackedFileBytes,
3109
+ MAX_MATERIALIZED_FILE_BYTES,
3110
+ );
3111
+ if (initial.size > BigInt(maximum))
3112
+ return yield* new OperationError({
3113
+ operation: "capture",
3114
+ directory: input.repository.worktree,
3115
+ message: `Exact-capture file exceeds ${maximum} bytes: ${JSON.stringify(candidate.file)}`,
3116
+ });
3117
+ preflightBytes += initial.size;
3118
+ if (preflightBytes > BigInt(MAX_MATERIALIZED_TOTAL_BYTES))
3119
+ return yield* new OperationError({
3120
+ operation: "capture",
3121
+ directory: input.repository.worktree,
3122
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_TOTAL_BYTES} bytes`,
3123
+ });
3124
+ captureCandidates.push({ ...candidate, target, initial });
3125
+ }
3126
+
3127
+ const capturedPaths = new Set(
3128
+ captureCandidates.map(
3129
+ (candidate) => candidate.file as string,
3130
+ ),
3131
+ );
3132
+ const capturedDirectories = new Set<string>();
3133
+ for (const candidate of captureCandidates) {
3134
+ const segments = candidate.file.split("/");
3135
+ for (let index = 1; index < segments.length; index++) {
3136
+ capturedDirectories.add(segments.slice(0, index).join("/"));
3137
+ if (
3138
+ capturedPaths.size + capturedDirectories.size >
3139
+ MAX_MATERIALIZED_ENTRIES
3140
+ )
3141
+ return yield* new OperationError({
3142
+ operation: "capture",
3143
+ directory: input.repository.worktree,
3144
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_ENTRIES} materialized entries`,
3145
+ });
3146
+ }
3147
+ }
3148
+ const capturedEntries =
3149
+ capturedPaths.size + capturedDirectories.size;
3150
+ if (capturedEntries > MAX_MATERIALIZED_ENTRIES)
3151
+ return yield* new OperationError({
3152
+ operation: "capture",
3153
+ directory: input.repository.worktree,
3154
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_ENTRIES} materialized entries`,
3155
+ });
3156
+ const manifestRecordBytes = (
3157
+ capturePath: string,
3158
+ size?: bigint,
3159
+ ) =>
3160
+ 6 +
3161
+ 1 +
3162
+ 4 +
3163
+ 1 +
3164
+ objectCharacters +
3165
+ 1 +
3166
+ Math.max(7, size === undefined ? 1 : size.toString().length) +
3167
+ 1 +
3168
+ Buffer.byteLength(capturePath, "utf8") +
3169
+ 1;
3170
+ const capturedManifestBytes =
3171
+ Array.from(capturedDirectories).reduce(
3172
+ (total, directory) =>
3173
+ total + manifestRecordBytes(directory),
3174
+ 0,
3175
+ ) +
3176
+ captureCandidates.reduce(
3177
+ (total, candidate) =>
3178
+ total +
3179
+ manifestRecordBytes(
3180
+ candidate.file,
3181
+ candidate.initial.size,
3182
+ ),
3183
+ 0,
3184
+ );
3185
+ if (capturedManifestBytes > MAX_MATERIALIZED_MANIFEST_BYTES)
3186
+ return yield* new OperationError({
3187
+ operation: "capture",
3188
+ directory: input.repository.worktree,
3189
+ message: `Exact-capture tree manifest exceeds ${MAX_MATERIALIZED_MANIFEST_BYTES} bytes`,
3190
+ });
3191
+
3192
+ const index = path.join(
3193
+ input.repository.gitDirectory,
3194
+ `capture-${randomUUID()}.index`,
3195
+ );
3196
+ const indexEnvironment = { GIT_INDEX_FILE: index };
3197
+ const exact = Effect.gen(function* () {
3198
+ yield* objectOperation(
3199
+ input.repository,
3200
+ ["read-tree", "--empty"],
3201
+ 16,
3202
+ {
3203
+ operation: "capture",
3204
+ environment: indexEnvironment,
3205
+ },
3206
+ );
3207
+ const staged: Buffer[] = [];
3208
+ let totalBytes = 0;
3209
+ for (const candidate of captureCandidates) {
3210
+ const captured = yield* Effect.tryPromise({
3211
+ try: async () => {
3212
+ const initial = await lstat(candidate.target, {
3213
+ bigint: true,
3214
+ });
3215
+ if (!initial.isFile())
3216
+ throw materializationFailure(
3217
+ "Entry is not a regular file",
3218
+ );
3219
+ if (
3220
+ initial.dev !== candidate.initial.dev ||
3221
+ initial.ino !== candidate.initial.ino ||
3222
+ initial.mode !== candidate.initial.mode ||
3223
+ initial.size !== candidate.initial.size ||
3224
+ initial.mtimeNs !== candidate.initial.mtimeNs ||
3225
+ initial.ctimeNs !== candidate.initial.ctimeNs
3226
+ )
3227
+ throw materializationFailure(
3228
+ "Entry changed after exact-capture preflight",
3229
+ );
3230
+ const canonical = await realpath(candidate.target);
3231
+ if (
3232
+ canonical !== candidate.target ||
3233
+ !FileAccess.contains(projectWorktree, canonical)
3234
+ )
3235
+ throw materializationFailure(
3236
+ "Entry resolves outside the canonical project tree",
3237
+ );
3238
+ const handle = await open(
3239
+ candidate.target,
3240
+ constants.O_RDONLY | constants.O_NOFOLLOW,
3241
+ );
3242
+ try {
3243
+ const before = await handle.stat({ bigint: true });
3244
+ if (
3245
+ !before.isFile() ||
3246
+ before.dev !== initial.dev ||
3247
+ before.ino !== initial.ino ||
3248
+ before.mode !== initial.mode ||
3249
+ before.size !== initial.size ||
3250
+ before.mtimeNs !== initial.mtimeNs ||
3251
+ before.ctimeNs !== initial.ctimeNs
3252
+ )
3253
+ throw materializationFailure(
3254
+ "Entry identity changed while opening",
3255
+ );
3256
+ const maximum = candidate.tracked
3257
+ ? MAX_MATERIALIZED_FILE_BYTES
3258
+ : Math.min(
3259
+ maximumUntrackedFileBytes,
3260
+ MAX_MATERIALIZED_FILE_BYTES,
3261
+ );
3262
+ if (before.size > BigInt(maximum))
3263
+ throw materializationFailure(
3264
+ `Entry exceeds ${maximum} bytes`,
3265
+ );
3266
+ const expected = Number(before.size);
3267
+ const buffer = Buffer.alloc(expected + 1);
3268
+ let offset = 0;
3269
+ while (offset < buffer.length) {
3270
+ const { bytesRead } = await handle.read(
3271
+ buffer,
3272
+ offset,
3273
+ buffer.length - offset,
3274
+ null,
3275
+ );
3276
+ if (bytesRead === 0) break;
3277
+ offset += bytesRead;
3278
+ }
3279
+ const after = await handle.stat({ bigint: true });
3280
+ if (
3281
+ offset !== expected ||
3282
+ after.dev !== before.dev ||
3283
+ after.ino !== before.ino ||
3284
+ after.mode !== before.mode ||
3285
+ after.size !== before.size ||
3286
+ after.mtimeNs !== before.mtimeNs ||
3287
+ after.ctimeNs !== before.ctimeNs
3288
+ )
3289
+ throw materializationFailure(
3290
+ "Entry changed while reading",
3291
+ );
3292
+ return {
3293
+ bytes: buffer.subarray(0, expected),
3294
+ mode:
3295
+ (before.mode & 0o111n) === 0n
3296
+ ? "100644"
3297
+ : "100755",
3298
+ };
3299
+ } finally {
3300
+ await handle.close();
3301
+ }
3302
+ },
3303
+ catch: (cause) =>
3304
+ new OperationError({
3305
+ operation: "capture",
3306
+ directory: input.repository.worktree,
3307
+ message: `Failed to capture raw file: ${JSON.stringify(candidate.file)}${
3308
+ cause instanceof globalThis.Error
3309
+ ? `: ${cause.message}`
3310
+ : ""
3311
+ }`,
3312
+ cause,
3313
+ }),
3314
+ });
3315
+ totalBytes += captured.bytes.length;
3316
+ if (totalBytes > MAX_MATERIALIZED_TOTAL_BYTES)
3317
+ return yield* new OperationError({
3318
+ operation: "capture",
3319
+ directory: input.repository.worktree,
3320
+ message: `Exact capture exceeds ${MAX_MATERIALIZED_TOTAL_BYTES} bytes`,
3321
+ });
3322
+ const object = (yield* objectOperation(
3323
+ input.repository,
3324
+ ["hash-object", "-w", "--no-filters", "--stdin"],
3325
+ 128,
3326
+ { operation: "capture", stdin: captured.bytes },
3327
+ ))
3328
+ .toString("utf8")
3329
+ .trim();
3330
+ if (
3331
+ !new RegExp(`^[0-9a-f]{${objectCharacters}}$`).test(
3332
+ object,
3333
+ )
3334
+ )
3335
+ return yield* new OperationError({
3336
+ operation: "capture",
3337
+ directory: input.repository.gitDirectory,
3338
+ message: "Git returned an invalid raw blob object ID",
3339
+ });
3340
+ staged.push(
3341
+ Buffer.from(
3342
+ `${captured.mode} blob ${object}\t${candidate.file}\0`,
3343
+ "utf8",
3344
+ ),
3345
+ );
3346
+ }
3347
+ if (staged.length > 0)
3348
+ yield* objectOperation(
3349
+ input.repository,
3350
+ ["update-index", "-z", "--index-info"],
3351
+ 16,
3352
+ {
3353
+ operation: "capture",
3354
+ stdin: Buffer.concat(staged),
3355
+ environment: indexEnvironment,
3356
+ },
3357
+ );
3358
+ const tree = (yield* objectOperation(
3359
+ input.repository,
3360
+ ["write-tree"],
3361
+ 128,
3362
+ {
3363
+ operation: "capture",
3364
+ environment: indexEnvironment,
3365
+ },
3366
+ ))
3367
+ .toString("utf8")
3368
+ .trim();
3369
+ if (!new RegExp(`^[0-9a-f]{${objectCharacters}}$`).test(tree))
3370
+ return yield* new OperationError({
3371
+ operation: "capture",
3372
+ directory: input.repository.gitDirectory,
3373
+ message: "Git returned an invalid exact tree object ID",
3374
+ });
3375
+ const retained = TreeID.make(tree);
3376
+ yield* retainSnapshotTree(input.repository, retained);
3377
+ return retained;
3378
+ });
3379
+ const cleanupIndex = Effect.all(
3380
+ [
3381
+ fs.remove(index, { force: true }),
3382
+ fs.remove(`${index}.lock`, { force: true }),
3383
+ ],
3384
+ { discard: true },
3385
+ ).pipe(
3386
+ Effect.mapError(
3387
+ (cause) =>
3388
+ new OperationError({
3389
+ operation: "capture",
3390
+ directory: input.repository.gitDirectory,
3391
+ message:
3392
+ "Failed to remove the isolated exact-capture index",
3393
+ cause,
3394
+ }),
3395
+ ),
3396
+ Effect.uninterruptible,
3397
+ );
3398
+ return yield* exact.pipe(
3399
+ Effect.matchCauseEffect({
3400
+ onSuccess: (tree) => cleanupIndex.pipe(Effect.as(tree)),
3401
+ onFailure: (cause) =>
3402
+ Effect.gen(function* () {
3403
+ yield* cleanupIndex;
3404
+ return yield* Effect.failCause(cause);
3405
+ }),
3406
+ }),
3407
+ );
3408
+ }),
3409
+ ),
3410
+ ),
3411
+ ),
3412
+ );
3413
+
3414
+ const treeFiles = Effect.fn("Git.tree.files")(function* (input: {
3415
+ repository: Repository;
3416
+ from: TreeID;
3417
+ to: TreeID;
3418
+ }) {
3419
+ return (yield* repositoryOperation("list_files", input.repository, [
3420
+ "diff",
3421
+ "--name-only",
3422
+ "-z",
3423
+ input.from,
3424
+ input.to,
3425
+ ])).text
3426
+ .split("\0")
3427
+ .filter(Boolean)
3428
+ .map((file) => RelativePath.make(file));
3429
+ });
3430
+
3431
+ const treeDiff = Effect.fn("Git.tree.diff")(function* (input: {
3432
+ repository: Repository;
3433
+ from: TreeID;
3434
+ to: TreeID;
3435
+ context?: number;
3436
+ paths?: readonly RelativePath[];
3437
+ }) {
3438
+ const paths = input.paths ?? (yield* treeFiles(input));
3439
+ return yield* Effect.forEach(paths, (file) =>
3440
+ Effect.gen(function* () {
3441
+ const statusText = (yield* repositoryOperation(
3442
+ "diff",
3443
+ input.repository,
3444
+ [
3445
+ "diff",
3446
+ "--name-status",
3447
+ "--no-renames",
3448
+ input.from,
3449
+ input.to,
3450
+ "--",
3451
+ file,
3452
+ ],
3453
+ )).text.trim();
3454
+ const status = statusText.startsWith("A")
3455
+ ? "added"
3456
+ : statusText.startsWith("D")
3457
+ ? "deleted"
3458
+ : "modified";
3459
+ const stats = (yield* repositoryOperation("diff", input.repository, [
3460
+ "diff",
3461
+ "--numstat",
3462
+ "--no-renames",
3463
+ input.from,
3464
+ input.to,
3465
+ "--",
3466
+ file,
3467
+ ])).text.split("\t");
3468
+ const binary = stats[0] === "-" || stats[1] === "-";
3469
+ const patch = binary
3470
+ ? ""
3471
+ : (yield* repositoryOperation("diff", input.repository, [
3472
+ "diff",
3473
+ `--unified=${input.context ?? 3}`,
3474
+ "--no-renames",
3475
+ input.from,
3476
+ input.to,
3477
+ "--",
3478
+ file,
3479
+ ])).text;
3480
+ return {
3481
+ path: file,
3482
+ status,
3483
+ additions: binary ? 0 : Number(stats[0] ?? 0),
3484
+ deletions: binary ? 0 : Number(stats[1] ?? 0),
3485
+ patch,
3486
+ } satisfies File.Diff;
3487
+ }),
3488
+ );
3489
+ });
3490
+
3491
+ const entry = Effect.fnUntraced(function* (
3492
+ repository: Repository,
3493
+ tree: TreeID,
3494
+ file: RelativePath,
3495
+ ) {
3496
+ const text = (yield* repositoryOperation("restore", repository, [
3497
+ "ls-tree",
3498
+ "-z",
3499
+ tree,
3500
+ "--",
3501
+ file,
3502
+ ])).text.replace(/\0$/, "");
3503
+ if (!text) return;
3504
+ const match = text.match(/^(\d+)\s+\w+\s+([0-9a-f]+)\t/);
3505
+ if (!match)
3506
+ return yield* new OperationError({
3507
+ operation: "restore",
3508
+ directory: repository.worktree,
3509
+ message: `Invalid tree entry for ${file}`,
3510
+ });
3511
+ return { mode: match[1], object: match[2] };
3512
+ });
3513
+
3514
+ const preview = Effect.fn("Git.tree.preview")(
3515
+ (input: {
3516
+ repository: Repository;
3517
+ current: TreeID;
3518
+ files: ReadonlyMap<RelativePath, TreeID>;
3519
+ context?: number;
3520
+ }) =>
3521
+ locked(
3522
+ input.repository,
3523
+ Effect.gen(function* () {
3524
+ const index = path.join(
3525
+ input.repository.gitDirectory,
3526
+ `preview-${randomUUID()}.index`,
3527
+ );
3528
+ const env = { GIT_INDEX_FILE: index };
3529
+ return yield* Effect.gen(function* () {
3530
+ yield* repositoryOperation(
3531
+ "diff",
3532
+ input.repository,
3533
+ ["read-tree", input.current],
3534
+ { env },
3535
+ );
3536
+ yield* Effect.forEach(
3537
+ input.files,
3538
+ ([file, tree]) =>
3539
+ Effect.gen(function* () {
3540
+ const source = yield* entry(input.repository, tree, file);
3541
+ if (!source) {
3542
+ yield* repositoryOperation(
3543
+ "diff",
3544
+ input.repository,
3545
+ ["update-index", "--force-remove", "--", file],
3546
+ { env },
3547
+ );
3548
+ return;
3549
+ }
3550
+ yield* repositoryOperation(
3551
+ "diff",
3552
+ input.repository,
3553
+ [
3554
+ "update-index",
3555
+ "--add",
3556
+ "--cacheinfo",
3557
+ source.mode,
3558
+ source.object,
3559
+ file,
3560
+ ],
3561
+ { env },
3562
+ );
3563
+ }),
3564
+ { discard: true },
3565
+ );
3566
+ const target = TreeID.make(
3567
+ (yield* repositoryOperation(
3568
+ "diff",
3569
+ input.repository,
3570
+ ["write-tree"],
3571
+ { env },
3572
+ )).text.trim(),
3573
+ );
3574
+ return yield* treeDiff({
3575
+ repository: input.repository,
3576
+ from: input.current,
3577
+ to: target,
3578
+ context: input.context,
3579
+ paths: Array.from(input.files.keys()),
3580
+ });
3581
+ }).pipe(
3582
+ Effect.ensuring(
3583
+ fs.remove(index).pipe(Effect.catch(() => Effect.void)),
3584
+ ),
3585
+ );
3586
+ }),
3587
+ ),
3588
+ );
3589
+
3590
+ const restore = Effect.fn("Git.tree.restore")(
3591
+ (input: {
3592
+ repository: Repository;
3593
+ files: ReadonlyMap<RelativePath, TreeID>;
3594
+ }) =>
3595
+ locked(
3596
+ input.repository,
3597
+ Effect.forEach(
3598
+ input.files,
3599
+ ([file, tree]) =>
3600
+ Effect.gen(function* () {
3601
+ if (yield* entry(input.repository, tree, file)) {
3602
+ yield* repositoryOperation("restore", input.repository, [
3603
+ "checkout",
3604
+ tree,
3605
+ "--",
3606
+ file,
3607
+ ]);
3608
+ return;
3609
+ }
3610
+ yield* fs
3611
+ .remove(path.join(input.repository.worktree, file), {
3612
+ recursive: true,
3613
+ force: true,
3614
+ })
3615
+ .pipe(
3616
+ Effect.mapError(
3617
+ (cause) =>
3618
+ new OperationError({
3619
+ operation: "restore",
3620
+ directory: input.repository.worktree,
3621
+ message: `Failed to remove ${file}`,
3622
+ cause,
3623
+ }),
3624
+ ),
3625
+ );
3626
+ }),
3627
+ { discard: true },
3628
+ ),
3629
+ ),
3630
+ );
3631
+
3632
+ const checkoutTree = Effect.fn("Git.tree.checkout")(
3633
+ (input: { repository: Repository; tree: TreeID }) =>
3634
+ locked(
3635
+ input.repository,
3636
+ Effect.gen(function* () {
3637
+ yield* repositoryOperation("restore", input.repository, [
3638
+ "read-tree",
3639
+ input.tree,
3640
+ ]);
3641
+ yield* repositoryOperation("restore", input.repository, [
3642
+ "checkout-index",
3643
+ "--all",
3644
+ "--force",
3645
+ ]);
3646
+ }),
3647
+ ),
3648
+ );
3649
+
3650
+ const materializeTree = Effect.fn("Git.tree.materialize")(
3651
+ function* (input: {
3652
+ repository: Repository;
3653
+ tree: TreeID;
3654
+ directory: AbsolutePath;
3655
+ }) {
3656
+ const directory = path.normalize(input.directory);
3657
+ if (
3658
+ !path.isAbsolute(input.directory) ||
3659
+ path.resolve(input.directory) !== input.directory ||
3660
+ directory !== input.directory
3661
+ )
3662
+ return yield* new OperationError({
3663
+ operation: "materialize",
3664
+ directory: input.directory,
3665
+ message:
3666
+ "Materialization directory must be an absolute normalized path",
3667
+ });
3668
+ const canonicalDirectory = yield* fs.realPath(input.directory).pipe(
3669
+ Effect.mapError(
3670
+ (cause) =>
3671
+ new OperationError({
3672
+ operation: "materialize",
3673
+ directory: input.directory,
3674
+ message: "Failed to resolve materialization directory",
3675
+ cause,
3676
+ }),
3677
+ ),
3678
+ );
3679
+ if (
3680
+ canonicalDirectory !== input.directory ||
3681
+ FileAccess.overlaps(input.repository.worktree, input.directory)
3682
+ )
3683
+ return yield* new OperationError({
3684
+ operation: "materialize",
3685
+ directory: input.directory,
3686
+ message:
3687
+ "Materialization directory must be canonical and outside the repository worktree",
3688
+ });
3689
+ const info = yield* fs.stat(input.directory).pipe(
3690
+ Effect.mapError(
3691
+ (cause) =>
3692
+ new OperationError({
3693
+ operation: "materialize",
3694
+ directory: input.directory,
3695
+ message: "Failed to inspect materialization directory",
3696
+ cause,
3697
+ }),
3698
+ ),
3699
+ );
3700
+ const contents = yield* fs.readDirectory(input.directory).pipe(
3701
+ Effect.mapError(
3702
+ (cause) =>
3703
+ new OperationError({
3704
+ operation: "materialize",
3705
+ directory: input.directory,
3706
+ message: "Failed to list materialization directory",
3707
+ cause,
3708
+ }),
3709
+ ),
3710
+ );
3711
+ if (info.type !== "Directory" || contents.length !== 0)
3712
+ return yield* new OperationError({
3713
+ operation: "materialize",
3714
+ directory: input.directory,
3715
+ message: "Materialization directory must be an empty directory",
3716
+ });
3717
+
3718
+ const objectFormat = (yield* objectOperation(
3719
+ input.repository,
3720
+ ["rev-parse", "--show-object-format"],
3721
+ 32,
3722
+ ))
3723
+ .toString("utf8")
3724
+ .trim();
3725
+ const objectCharacters =
3726
+ objectFormat === "sha1"
3727
+ ? 40
3728
+ : objectFormat === "sha256"
3729
+ ? 64
3730
+ : undefined;
3731
+ if (
3732
+ objectCharacters === undefined ||
3733
+ !new RegExp(`^[0-9a-f]{${objectCharacters}}$`).test(input.tree)
3734
+ )
3735
+ return yield* new OperationError({
3736
+ operation: "materialize",
3737
+ directory: input.directory,
3738
+ message: "Snapshot must be a canonical full tree object ID",
3739
+ });
3740
+ const objectType = (yield* objectOperation(
3741
+ input.repository,
3742
+ ["cat-file", "-t", input.tree],
3743
+ 16,
3744
+ ))
3745
+ .toString("utf8")
3746
+ .trim();
3747
+ if (objectType !== "tree")
3748
+ return yield* new OperationError({
3749
+ operation: "materialize",
3750
+ directory: input.directory,
3751
+ message: "Snapshot object is not a tree",
3752
+ });
3753
+
3754
+ const manifest = yield* objectOperation(
3755
+ input.repository,
3756
+ [
3757
+ "ls-tree",
3758
+ "-r",
3759
+ "-t",
3760
+ "-z",
3761
+ "--full-tree",
3762
+ "--long",
3763
+ input.tree,
3764
+ "--",
3765
+ ],
3766
+ MAX_MATERIALIZED_MANIFEST_BYTES,
3767
+ );
3768
+ const entries = yield* Effect.try({
3769
+ try: () =>
3770
+ decodeMaterializationManifest(manifest, objectCharacters / 2),
3771
+ catch: (cause) =>
3772
+ new OperationError({
3773
+ operation: "materialize",
3774
+ directory: input.directory,
3775
+ message:
3776
+ cause instanceof globalThis.Error
3777
+ ? cause.message
3778
+ : "Tree manifest is invalid",
3779
+ cause,
3780
+ }),
3781
+ });
3782
+
3783
+ yield* fs.chmod(input.directory, 0o700).pipe(
3784
+ Effect.mapError(
3785
+ (cause) =>
3786
+ new OperationError({
3787
+ operation: "materialize",
3788
+ directory: input.directory,
3789
+ message: "Failed to secure materialization directory",
3790
+ cause,
3791
+ }),
3792
+ ),
3793
+ );
3794
+ const directories = entries
3795
+ .filter(
3796
+ (
3797
+ entry,
3798
+ ): entry is Extract<MaterializationEntry, { kind: "directory" }> =>
3799
+ entry.kind === "directory",
3800
+ )
3801
+ .toSorted(
3802
+ (left, right) =>
3803
+ left.path.split("/").length - right.path.split("/").length,
3804
+ );
3805
+ for (const entry of directories)
3806
+ yield* fs
3807
+ .makeDirectory(
3808
+ path.join(input.directory, ...entry.path.split("/")),
3809
+ {
3810
+ recursive: true,
3811
+ mode: 0o700,
3812
+ },
3813
+ )
3814
+ .pipe(
3815
+ Effect.mapError(
3816
+ (cause) =>
3817
+ new OperationError({
3818
+ operation: "materialize",
3819
+ directory: input.directory,
3820
+ message: `Failed to create tree directory: ${JSON.stringify(entry.path)}`,
3821
+ cause,
3822
+ }),
3823
+ ),
3824
+ );
3825
+
3826
+ const files = entries.filter(
3827
+ (entry): entry is Extract<MaterializationEntry, { kind: "file" }> =>
3828
+ entry.kind === "file",
3829
+ );
3830
+ let bytes = 0;
3831
+ for (const entry of files) {
3832
+ const target = path.join(input.directory, ...entry.path.split("/"));
3833
+ yield* fs
3834
+ .makeDirectory(path.dirname(target), {
3835
+ recursive: true,
3836
+ mode: 0o700,
3837
+ })
3838
+ .pipe(
3839
+ Effect.mapError(
3840
+ (cause) =>
3841
+ new OperationError({
3842
+ operation: "materialize",
3843
+ directory: input.directory,
3844
+ message: `Failed to create tree parent: ${JSON.stringify(entry.path)}`,
3845
+ cause,
3846
+ }),
3847
+ ),
3848
+ );
3849
+ const blob = yield* objectOperation(
3850
+ input.repository,
3851
+ ["cat-file", "blob", entry.object],
3852
+ entry.size + 1,
3853
+ );
3854
+ if (blob.length !== entry.size)
3855
+ return yield* new OperationError({
3856
+ operation: "materialize",
3857
+ directory: input.directory,
3858
+ message: `Tree blob size did not match its manifest: ${JSON.stringify(entry.path)}`,
3859
+ });
3860
+ yield* fs.writeFile(target, blob, { flag: "wx", mode: 0o600 }).pipe(
3861
+ Effect.andThen(fs.chmod(target, entry.executable ? 0o755 : 0o644)),
3862
+ Effect.mapError(
3863
+ (cause) =>
3864
+ new OperationError({
3865
+ operation: "materialize",
3866
+ directory: input.directory,
3867
+ message: `Failed to write tree blob: ${JSON.stringify(entry.path)}`,
3868
+ cause,
3869
+ }),
3870
+ ),
3871
+ );
3872
+ bytes += entry.size;
3873
+ }
3874
+ return {
3875
+ tree: input.tree,
3876
+ files: files.length,
3877
+ bytes,
3878
+ } satisfies MaterializedTree;
3879
+ },
3880
+ );
3881
+
3882
+ const capture = Effect.fn("Git.change.capture")(function* (input: {
3883
+ repository: Repository;
3884
+ path: AbsolutePath;
3885
+ }) {
3886
+ const scope =
3887
+ path
3888
+ .relative(input.repository.worktree, input.path)
3889
+ .replaceAll("\\", "/") || ".";
3890
+ const tracked = yield* execute(
3891
+ input.repository.worktree,
3892
+ proc,
3893
+ )(["diff", "--binary", "HEAD", "--", scope]).pipe(
3894
+ Effect.mapError(
3895
+ (cause) =>
3896
+ new PatchError({
3897
+ operation: "capture",
3898
+ directory: input.path,
3899
+ message: cause.message,
3900
+ cause,
3901
+ }),
3902
+ ),
3903
+ );
3904
+ if (tracked.exitCode !== 0) {
3905
+ return yield* new PatchError({
3906
+ operation: "capture",
3907
+ directory: input.path,
3908
+ message:
3909
+ tracked.stderr.trim() ||
3910
+ tracked.text.trim() ||
3911
+ "Failed to capture tracked changes",
3912
+ });
3913
+ }
3914
+
3915
+ const untracked = yield* execute(
3916
+ input.repository.worktree,
3917
+ proc,
3918
+ )(["ls-files", "--others", "--exclude-standard", "-z", "--", scope]).pipe(
3919
+ Effect.mapError(
3920
+ (cause) =>
3921
+ new PatchError({
3922
+ operation: "capture",
3923
+ directory: input.path,
3924
+ message: cause.message,
3925
+ cause,
3926
+ }),
3927
+ ),
3928
+ );
3929
+ if (untracked.exitCode !== 0) {
3930
+ return yield* new PatchError({
3931
+ operation: "capture",
3932
+ directory: input.path,
3933
+ message:
3934
+ untracked.stderr.trim() ||
3935
+ untracked.text.trim() ||
3936
+ "Failed to list untracked changes",
3937
+ });
3938
+ }
3939
+
3940
+ const created = yield* Effect.forEach(
3941
+ untracked.text.split("\0").filter(Boolean),
3942
+ (file) =>
3943
+ execute(
3944
+ input.repository.worktree,
3945
+ proc,
3946
+ )(["diff", "--binary", "--no-index", "--", "/dev/null", file]).pipe(
3947
+ Effect.mapError(
3948
+ (cause) =>
3949
+ new PatchError({
3950
+ operation: "capture",
3951
+ directory: input.path,
3952
+ message: cause.message,
3953
+ cause,
3954
+ }),
3955
+ ),
3956
+ Effect.flatMap((result) =>
3957
+ // git diff --no-index returns 1 when differences were found.
3958
+ result.exitCode === 0 || result.exitCode === 1
3959
+ ? Effect.succeed(result.text)
3960
+ : Effect.fail(
3961
+ new PatchError({
3962
+ operation: "capture",
3963
+ directory: input.path,
3964
+ message:
3965
+ result.stderr.trim() ||
3966
+ result.text.trim() ||
3967
+ `Failed to capture untracked change: ${file}`,
3968
+ }),
3969
+ ),
3970
+ ),
3971
+ ),
3972
+ );
3973
+ return ChangeSet.make(
3974
+ [tracked.text, ...created].filter(Boolean).join("\n"),
3975
+ );
3976
+ });
3977
+
3978
+ const apply = Effect.fn("Git.change.apply")(function* (input: {
3979
+ repository: Repository;
3980
+ path: AbsolutePath;
3981
+ changes: ChangeSet;
3982
+ }) {
3983
+ const result = yield* proc
3984
+ .run(
3985
+ ChildProcess.make("git", ["apply", "-"], {
3986
+ cwd: input.path,
3987
+ extendEnv: true,
3988
+ stdin: Stream.make(new TextEncoder().encode(input.changes)),
3989
+ }),
3990
+ )
3991
+ .pipe(
3992
+ Effect.mapError(
3993
+ (cause) =>
3994
+ new PatchError({
3995
+ operation: "apply",
3996
+ directory: input.path,
3997
+ message: cause.message,
3998
+ cause,
3999
+ }),
4000
+ ),
4001
+ );
4002
+ if (result.exitCode === 0) return;
4003
+ return yield* new PatchError({
4004
+ operation: "apply",
4005
+ directory: input.path,
4006
+ message:
4007
+ result.stderr.toString("utf8").trim() ||
4008
+ result.stdout.toString("utf8").trim() ||
4009
+ "Failed to apply changes",
4010
+ });
4011
+ });
4012
+
4013
+ const discard = Effect.fn("Git.change.discard")(function* (input: {
4014
+ repository: Repository;
4015
+ path: AbsolutePath;
4016
+ index: "preserve" | "reset";
4017
+ untracked: "preserve" | "remove";
4018
+ }) {
4019
+ const scope =
4020
+ path
4021
+ .relative(input.repository.worktree, input.path)
4022
+ .replaceAll("\\", "/") || ".";
4023
+ const restore = yield* execute(
4024
+ input.repository.worktree,
4025
+ proc,
4026
+ )(
4027
+ input.index === "reset"
4028
+ ? ["checkout", "HEAD", "--", scope]
4029
+ : ["checkout", "--", scope],
4030
+ ).pipe(
4031
+ Effect.mapError(
4032
+ (cause) =>
4033
+ new PatchError({
4034
+ operation: "reset",
4035
+ directory: input.path,
4036
+ message: cause.message,
4037
+ cause,
4038
+ }),
4039
+ ),
4040
+ );
4041
+ if (restore.exitCode !== 0) {
4042
+ return yield* new PatchError({
4043
+ operation: "reset",
4044
+ directory: input.path,
4045
+ message:
4046
+ restore.stderr.trim() ||
4047
+ restore.text.trim() ||
4048
+ "Failed to restore tracked changes",
4049
+ });
4050
+ }
4051
+ if (input.untracked === "preserve") return;
4052
+ const clean = yield* execute(
4053
+ input.repository.worktree,
4054
+ proc,
4055
+ )(["clean", "-fd", "--", scope]).pipe(
4056
+ Effect.mapError(
4057
+ (cause) =>
4058
+ new PatchError({
4059
+ operation: "reset",
4060
+ directory: input.path,
4061
+ message: cause.message,
4062
+ cause,
4063
+ }),
4064
+ ),
4065
+ );
4066
+ if (clean.exitCode === 0) return;
4067
+ return yield* new PatchError({
4068
+ operation: "reset",
4069
+ directory: input.path,
4070
+ message:
4071
+ clean.stderr.trim() ||
4072
+ clean.text.trim() ||
4073
+ "Failed to clean untracked changes",
4074
+ });
4075
+ });
4076
+
4077
+ const worktreeRun = Effect.fnUntraced(function* (
4078
+ operation: "create" | "remove" | "list",
4079
+ repository: Repository,
4080
+ args: string[],
4081
+ worktreeDirectory?: AbsolutePath,
4082
+ cwd = repository.worktree,
4083
+ ) {
4084
+ const result = yield* proc
4085
+ .run(
4086
+ ChildProcess.make("git", args, {
4087
+ cwd,
4088
+ extendEnv: true,
4089
+ stdin: "ignore",
4090
+ }),
4091
+ )
4092
+ .pipe(
4093
+ Effect.mapError(
4094
+ (cause) =>
4095
+ new WorktreeError({
4096
+ operation,
4097
+ directory: worktreeDirectory,
4098
+ message: cause.message,
4099
+ cause,
4100
+ }),
4101
+ ),
4102
+ );
4103
+ if (result.exitCode === 0) return result.stdout.toString("utf8");
4104
+ const message =
4105
+ result.stderr.toString("utf8").trim() ||
4106
+ result.stdout.toString("utf8").trim() ||
4107
+ "Git failed";
4108
+ return yield* new WorktreeError({
4109
+ operation,
4110
+ directory: worktreeDirectory,
4111
+ message,
4112
+ forceRequired:
4113
+ operation === "remove" &&
4114
+ /contains modified or untracked files|is dirty/i.test(message),
4115
+ });
4116
+ });
4117
+
4118
+ const worktreeCreate = Effect.fn("Git.worktree.create")(function* (input: {
4119
+ repository: Repository;
4120
+ directory: AbsolutePath;
4121
+ }) {
4122
+ yield* worktreeRun(
4123
+ "create",
4124
+ input.repository,
4125
+ ["worktree", "add", "--detach", input.directory, "HEAD"],
4126
+ input.directory,
4127
+ );
4128
+ const repository = yield* discover(input.directory);
4129
+ if (repository) return repository;
4130
+ return yield* new WorktreeError({
4131
+ operation: "create",
4132
+ directory: input.directory,
4133
+ message: "Created worktree could not be opened",
4134
+ });
4135
+ });
4136
+
4137
+ const worktreeRemove = Effect.fn("Git.worktree.remove")(function* (input: {
4138
+ repository: Repository;
4139
+ directory: AbsolutePath;
4140
+ force: boolean;
4141
+ }) {
4142
+ yield* worktreeRun(
4143
+ "remove",
4144
+ input.repository,
4145
+ [
4146
+ "worktree",
4147
+ "remove",
4148
+ ...(input.force ? ["--force"] : []),
4149
+ input.directory,
4150
+ ],
4151
+ input.directory,
4152
+ input.repository.commonDirectory,
4153
+ );
4154
+ });
4155
+
4156
+ const worktreeList = Effect.fn("Git.worktree.list")(function* (
4157
+ repository: Repository,
4158
+ ) {
4159
+ return (yield* worktreeRun("list", repository, [
4160
+ "worktree",
4161
+ "list",
4162
+ "--porcelain",
4163
+ ]))
4164
+ .split("\n")
4165
+ .filter((line) => line.startsWith("worktree "))
4166
+ .map(
4167
+ (line, index) =>
4168
+ new Worktree({
4169
+ directory: AbsolutePath.make(
4170
+ resolvePath(
4171
+ repository.worktree,
4172
+ line.slice("worktree ".length).trim(),
4173
+ ),
4174
+ ),
4175
+ kind: index === 0 ? "main" : "linked",
4176
+ }),
4177
+ );
4178
+ });
4179
+
4180
+ return Service.of({
4181
+ repo: { discover, clone, create, ensureSnapshotRetention },
4182
+ remote: { get: remote },
4183
+ history: {
4184
+ head,
4185
+ branch,
4186
+ defaultRemoteBranch: remoteHead,
4187
+ rootCommits: roots,
4188
+ },
4189
+ sync: {
4190
+ fetchRemotes: fetch,
4191
+ fetchBranch,
4192
+ checkoutRemoteBranch: checkout,
4193
+ resetHard: reset,
4194
+ },
4195
+ change: { capture, apply, discard },
4196
+ worktree: {
4197
+ create: worktreeCreate,
4198
+ remove: worktreeRemove,
4199
+ list: worktreeList,
4200
+ },
4201
+ index: { refresh, ignored },
4202
+ tree: {
4203
+ capture: captureTree,
4204
+ captureExact: captureExactTree,
4205
+ retain: retainTree,
4206
+ contains: containsTree,
4207
+ exportClosure: exportSnapshotClosure,
4208
+ importClosure: importSnapshotClosure,
4209
+ reconcileRetention,
4210
+ write: writeTree,
4211
+ files: treeFiles,
4212
+ diff: treeDiff,
4213
+ preview,
4214
+ restore,
4215
+ checkout: checkoutTree,
4216
+ materialize: materializeTree,
4217
+ },
4218
+ });
4219
+ }),
4220
+ );
4221
+
4222
+ export const defaultLayer = layer.pipe(
4223
+ Layer.provide(FileAccess.defaultLayer),
4224
+ Layer.provide(ProcessRunner.defaultLayer),
4225
+ );
4226
+ export const node = ServiceGraph.node(layer, [FileAccess.node, ProcessRunner.node]);
4227
+
4228
+ interface Result {
4229
+ readonly exitCode: number;
4230
+ readonly text: string;
4231
+ readonly stderr: string;
4232
+ }
4233
+
4234
+ function run(cwd: string, proc: ProcessRunner.Interface) {
4235
+ return (args: string[]) =>
4236
+ execute(
4237
+ cwd,
4238
+ proc,
4239
+ )(args).pipe(
4240
+ Effect.catch(() => Effect.succeed({ exitCode: 1, text: "", stderr: "" })),
4241
+ );
4242
+ }
4243
+
4244
+ function execute(cwd: string, proc: ProcessRunner.Interface) {
4245
+ return (args: string[]) =>
4246
+ proc
4247
+ .run(
4248
+ ChildProcess.make("git", args, {
4249
+ cwd,
4250
+ extendEnv: true,
4251
+ stdin: "ignore",
4252
+ }),
4253
+ )
4254
+ .pipe(
4255
+ Effect.map(
4256
+ (result) =>
4257
+ ({
4258
+ exitCode: result.exitCode,
4259
+ text: result.stdout.toString("utf8"),
4260
+ stderr: result.stderr.toString("utf8"),
4261
+ }) satisfies Result,
4262
+ ),
4263
+ );
4264
+ }
4265
+
4266
+ function resolvePath(cwd: string, value: string) {
4267
+ const trimmed = value.replace(/[\r\n]+$/, "");
4268
+ if (!trimmed) return cwd;
4269
+ const normalized = FileAccess.windowsPath(trimmed);
4270
+ if (path.isAbsolute(normalized)) return path.normalize(normalized);
4271
+ return path.resolve(cwd, normalized);
4272
+ }