@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,1549 @@
1
+ export * as VerifierOciLease from "./lease"
2
+
3
+ import { constants as FsConstants, type BigIntStats } from "node:fs"
4
+ import * as fs from "node:fs/promises"
5
+ import { randomBytes, randomUUID } from "node:crypto"
6
+ import path from "node:path"
7
+ import { Effect, Schema } from "effect"
8
+ import { AppPaths } from "../../runtime/paths"
9
+ import { AbsolutePath } from "../../shared/schema"
10
+ import { Snapshot } from "../../workspace/repository/snapshot"
11
+ import { withSnapshotRetentionBarrier } from "../../workspace/repository/retention-barrier"
12
+ import { VerifierRegistry } from "../registry"
13
+
14
+ const VERSION = 1 as const
15
+ const DIRECTORY_MODE = 0o700
16
+ const FILE_MODE = 0o600
17
+ const MAX_INTENT_BYTES = 4 * 1024
18
+ const CONTAINER_ID_BYTES = 64
19
+ const NO_START_BOUNDARY = "no-start"
20
+ const PENDING_BOUNDARY_PATTERN = /^container-id\.pending-[a-f0-9]{16}$/
21
+ const MAX_PENDING_BOUNDARIES = 16
22
+ const ABSENCE_OBSERVATION_PATTERN = /^absence-([12])\.json$/
23
+ const MAX_ABSENCE_OBSERVATION_BYTES = 256
24
+ const LEASE_ID_PATTERN = /^[a-f0-9]{32}$/
25
+ const TRASH_DIRECTORY_PATTERN = /^[a-f0-9]{32}-[a-f0-9]{16}$/
26
+ const GENERATION_PATTERN = /^[a-f0-9]{32}$/
27
+ const STAGING_DIRECTORY_PATTERN =
28
+ /^s-([a-f0-9]{32})-([0-9]{16})-([a-f0-9]{32})$/
29
+ const STAGING_TRASH_DIRECTORY_PATTERN =
30
+ /^cancel-([a-f0-9]{32})-([0-9]{16})-([a-f0-9]{32})-([a-f0-9]{32})$/
31
+ const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/
32
+ const EXECUTION_HASH_PATTERN = /^sha256:[a-f0-9]{64}$/
33
+ const OWNER_PATTERN =
34
+ /^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/
35
+
36
+ /**
37
+ * Fixed safety limits for crash-artifact and no-start retirement. They are
38
+ * intentionally not environment-tunable: reducing the retention window must
39
+ * require a reviewed code change, not an accidental deployment setting.
40
+ */
41
+ export const RETIREMENT_POLICY = Object.freeze({
42
+ expiredStagingPerRead: 32,
43
+ expiredLeasesPerReap: 64,
44
+ noStartRetirementsPerReap: 16,
45
+ absenceObservationsRequired: 2,
46
+ absenceObservationSpacingMs: 60_000,
47
+ tombstoneMinimumAgeMs: 24 * 60 * 60 * 1_000,
48
+ })
49
+
50
+ const STRICT_OPTIONS = {
51
+ errors: "all",
52
+ onExcessProperty: "error",
53
+ } as const
54
+
55
+ export const LeaseID = Schema.String.check(
56
+ Schema.isPattern(LEASE_ID_PATTERN),
57
+ ).pipe(Schema.brand("VerifierOciLease.LeaseID"))
58
+
59
+ export type LeaseID = typeof LeaseID.Type
60
+
61
+ export const ContainerID = Schema.String.check(
62
+ Schema.isPattern(CONTAINER_ID_PATTERN),
63
+ ).pipe(Schema.brand("VerifierOciLease.ContainerID"))
64
+
65
+ export type ContainerID = typeof ContainerID.Type
66
+
67
+ const Owner = Schema.String.check(Schema.isPattern(OWNER_PATTERN))
68
+ const ExecutionHash = Schema.String.check(
69
+ Schema.isPattern(EXECUTION_HASH_PATTERN),
70
+ )
71
+ const SnapshotID = Snapshot.ID.check(
72
+ Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),
73
+ )
74
+ const ReapAfterMs = Schema.Number.check(
75
+ Schema.makeFilter((value) =>
76
+ Number.isSafeInteger(value) && value >= 0
77
+ ? undefined
78
+ : "reapAfterMs must be a non-negative safe integer",
79
+ ),
80
+ )
81
+
82
+ export const Intent = Schema.Struct({
83
+ version: Schema.Literal(VERSION),
84
+ leaseID: LeaseID,
85
+ owner: Owner,
86
+ executionHash: ExecutionHash,
87
+ snapshot: SnapshotID,
88
+ image: VerifierRegistry.OciImage,
89
+ reapAfterMs: ReapAfterMs,
90
+ }).annotate({ identifier: "VerifierOciLease.Intent" })
91
+
92
+ export type Intent = typeof Intent.Type
93
+
94
+ const AbsenceObservation = Schema.Struct({
95
+ version: Schema.Literal(VERSION),
96
+ leaseID: LeaseID,
97
+ sequence: Schema.Literals([1, 2]),
98
+ observedAtMs: ReapAfterMs,
99
+ })
100
+ type AbsenceObservation = typeof AbsenceObservation.Type
101
+
102
+ export interface RetirementEvidence {
103
+ readonly observations: number
104
+ readonly firstObservedAtMs?: number
105
+ readonly lastObservedAtMs?: number
106
+ readonly eligible: boolean
107
+ }
108
+
109
+ export type Lease = Readonly<
110
+ Intent & {
111
+ readonly subject: AbsolutePath
112
+ readonly containerID?: ContainerID
113
+ readonly startDisabled?: true
114
+ }
115
+ >
116
+
117
+ export interface PrepareInput {
118
+ readonly executionHash: string
119
+ readonly snapshot: Snapshot.ID
120
+ readonly image: VerifierRegistry.OciImage
121
+ readonly reapAfterMs: number
122
+ }
123
+
124
+ export interface Options {
125
+ readonly leaseID?: () => string
126
+ readonly owner?: () => string
127
+ readonly stagingGeneration?: () => string
128
+ readonly now?: () => number
129
+ }
130
+
131
+ export const Operation = Schema.Literals([
132
+ "prepare",
133
+ "commit-container-id",
134
+ "read",
135
+ "remove-subject",
136
+ "observe-no-start",
137
+ "reset-no-start",
138
+ "retire-no-start",
139
+ "remove",
140
+ ])
141
+ export type Operation = typeof Operation.Type
142
+
143
+ export class Error extends Schema.TaggedErrorClass<Error>()(
144
+ "VerifierOciLease.Error",
145
+ {
146
+ operation: Operation,
147
+ message: Schema.String,
148
+ cause: Schema.optional(Schema.Defect()),
149
+ },
150
+ ) {}
151
+
152
+ export interface Interface {
153
+ /**
154
+ * Durably publishes an immutable intent and returns a derived subject path.
155
+ * The subject does not exist yet; the materializer must create it exclusively.
156
+ * Callers must first validate, localize, and pin the canonical tree in its
157
+ * project snapshot store. Production code satisfies this precondition through
158
+ * `Snapshot.retain` in `VerifierOciContainment`.
159
+ */
160
+ readonly prepare: (input: PrepareInput) => Effect.Effect<Lease, Error>
161
+ /**
162
+ * Durably publishes the immutable container ID. A caller must not issue any
163
+ * start request until this effect succeeds.
164
+ */
165
+ readonly commitContainerID: (
166
+ leaseID: string,
167
+ containerID: string,
168
+ ) => Effect.Effect<Lease, Error>
169
+ /**
170
+ * Reconciles recognized terminal trash, then strictly reads every durable
171
+ * lease or fails closed on any unsafe entry.
172
+ */
173
+ readonly readAll: (nowMs?: number) => Effect.Effect<readonly Lease[], Error>
174
+ /**
175
+ * Removes only the derived materialization while retaining the durable
176
+ * intent tombstone for late-create reconciliation.
177
+ */
178
+ readonly removeSubject: (leaseID: string) => Effect.Effect<void, Error>
179
+ /** Record one durable exact-label absence observation for a fenced lease. */
180
+ readonly observeNoStartAbsence: (
181
+ leaseID: string,
182
+ nowMs: number,
183
+ ) => Effect.Effect<RetirementEvidence, Error>
184
+ /** Reset absence history after any matching late container is discovered. */
185
+ readonly resetNoStartAbsence: (leaseID: string) => Effect.Effect<void, Error>
186
+ /**
187
+ * Retire an aged no-start tombstone. The caller must perform a final trusted
188
+ * exact-label runtime scan immediately before invoking this operation.
189
+ */
190
+ readonly retireNoStart: (
191
+ leaseID: string,
192
+ nowMs: number,
193
+ ) => Effect.Effect<void, Error>
194
+ /**
195
+ * Idempotently removes only paths derived from a canonical lease ID. The
196
+ * supervisor must prove the corresponding container absent before calling it.
197
+ */
198
+ readonly remove: (leaseID: string) => Effect.Effect<void, Error>
199
+ }
200
+
201
+ interface Roots {
202
+ readonly state: string
203
+ readonly temporary: string
204
+ readonly leases: string
205
+ readonly staging: string
206
+ readonly stagingTrash: string
207
+ readonly trash: string
208
+ readonly subjects: string
209
+ }
210
+
211
+ const failure = (operation: Operation, message: string, cause?: unknown) =>
212
+ new Error({
213
+ operation,
214
+ message,
215
+ ...(cause === undefined ? {} : { cause }),
216
+ })
217
+
218
+ const attempt = <A>(
219
+ operation: Operation,
220
+ message: string,
221
+ run: () => Promise<A>,
222
+ ) =>
223
+ Effect.tryPromise({
224
+ try: run,
225
+ catch: (cause) =>
226
+ cause instanceof Error ? cause : failure(operation, message, cause),
227
+ })
228
+
229
+ const errorCode = (cause: unknown) =>
230
+ cause && typeof cause === "object" && "code" in cause
231
+ ? String(cause.code)
232
+ : undefined
233
+
234
+ const mode = (value: number) => value & 0o777
235
+
236
+ const decodeLeaseID = (value: unknown): LeaseID =>
237
+ Schema.decodeUnknownSync(LeaseID)(value, STRICT_OPTIONS)
238
+
239
+ const decodeContainerID = (value: unknown): ContainerID =>
240
+ Schema.decodeUnknownSync(ContainerID)(value, STRICT_OPTIONS)
241
+
242
+ const freezeIntent = (intent: Intent): Intent =>
243
+ Object.freeze({
244
+ version: intent.version,
245
+ leaseID: intent.leaseID,
246
+ owner: intent.owner,
247
+ executionHash: intent.executionHash,
248
+ snapshot: intent.snapshot,
249
+ image: Object.freeze({
250
+ reference: intent.image.reference,
251
+ platform: intent.image.platform,
252
+ }),
253
+ reapAfterMs: intent.reapAfterMs,
254
+ })
255
+
256
+ const encodeIntent = (intent: Intent) =>
257
+ JSON.stringify({
258
+ version: intent.version,
259
+ leaseID: intent.leaseID,
260
+ owner: intent.owner,
261
+ executionHash: intent.executionHash,
262
+ snapshot: intent.snapshot,
263
+ image: {
264
+ reference: intent.image.reference,
265
+ platform: intent.image.platform,
266
+ },
267
+ reapAfterMs: intent.reapAfterMs,
268
+ })
269
+
270
+ const absenceObservationName = (sequence: 1 | 2) => `absence-${sequence}.json`
271
+
272
+ const encodeAbsenceObservation = (observation: AbsenceObservation) =>
273
+ JSON.stringify({
274
+ version: observation.version,
275
+ leaseID: observation.leaseID,
276
+ sequence: observation.sequence,
277
+ observedAtMs: observation.observedAtMs,
278
+ })
279
+
280
+ const makeLease = (
281
+ roots: Roots,
282
+ intent: Intent,
283
+ containerID?: ContainerID,
284
+ startDisabled = false,
285
+ ): Lease =>
286
+ Object.freeze({
287
+ ...intent,
288
+ image: intent.image,
289
+ subject: AbsolutePath.make(path.join(roots.subjects, intent.leaseID)),
290
+ ...(containerID === undefined ? {} : { containerID }),
291
+ ...(startDisabled ? { startDisabled: true as const } : {}),
292
+ })
293
+
294
+ const lstatOptional = async (target: string) => {
295
+ try {
296
+ return await fs.lstat(target)
297
+ } catch (cause) {
298
+ if (errorCode(cause) === "ENOENT") return undefined
299
+ throw cause
300
+ }
301
+ }
302
+
303
+ const assertBaseDirectory = async (target: string) => {
304
+ if (
305
+ !path.isAbsolute(target) ||
306
+ path.resolve(target) !== target ||
307
+ path.normalize(target) !== target
308
+ ) {
309
+ throw new globalThis.Error(
310
+ "Global lease root is not absolute and normalized",
311
+ )
312
+ }
313
+ const info = await lstatOptional(target)
314
+ if (!info || info.isSymbolicLink() || !info.isDirectory()) {
315
+ throw new globalThis.Error("Global lease root is not a real directory")
316
+ }
317
+ }
318
+
319
+ const assertPrivateDirectory = async (target: string) => {
320
+ const info = await lstatOptional(target)
321
+ if (
322
+ !info ||
323
+ info.isSymbolicLink() ||
324
+ !info.isDirectory() ||
325
+ mode(info.mode) !== DIRECTORY_MODE
326
+ ) {
327
+ throw new globalThis.Error("OCI lease directory is missing or insecure")
328
+ }
329
+ }
330
+
331
+ const fsyncDirectory = async (target: string) => {
332
+ const handle = await fs.open(
333
+ target,
334
+ FsConstants.O_RDONLY | FsConstants.O_DIRECTORY | FsConstants.O_NOFOLLOW,
335
+ )
336
+ try {
337
+ const info = await handle.stat()
338
+ if (!info.isDirectory()) {
339
+ throw new globalThis.Error("OCI lease directory changed during fsync")
340
+ }
341
+ await handle.sync()
342
+ } finally {
343
+ await handle.close()
344
+ }
345
+ }
346
+
347
+ const ensurePrivateChild = async (parent: string, name: string) => {
348
+ const target = path.join(parent, name)
349
+ try {
350
+ await fs.mkdir(target, { mode: DIRECTORY_MODE })
351
+ } catch (cause) {
352
+ if (errorCode(cause) !== "EEXIST") throw cause
353
+ }
354
+ await assertPrivateDirectory(target)
355
+ // A concurrent creator may not have fsynced the parent yet. Every caller
356
+ // that relies on the child must establish parent-entry durability itself.
357
+ await fsyncDirectory(parent)
358
+ return target
359
+ }
360
+
361
+ const ensureRoots = async (roots: Roots) => {
362
+ await assertBaseDirectory(roots.state)
363
+ await assertBaseDirectory(roots.temporary)
364
+
365
+ const stateProduct = await ensurePrivateChild(roots.state, "verifier-oci")
366
+ const stateVersion = await ensurePrivateChild(stateProduct, `v${VERSION}`)
367
+ const leases = await ensurePrivateChild(stateVersion, "leases")
368
+ const staging = await ensurePrivateChild(stateVersion, "staging")
369
+ const stagingTrash = await ensurePrivateChild(stateVersion, "staging-trash")
370
+ const trash = await ensurePrivateChild(stateVersion, "trash")
371
+ const temporaryProduct = await ensurePrivateChild(
372
+ roots.temporary,
373
+ "verifier-oci",
374
+ )
375
+ const temporaryVersion = await ensurePrivateChild(
376
+ temporaryProduct,
377
+ `v${VERSION}`,
378
+ )
379
+ const subjects = await ensurePrivateChild(temporaryVersion, "subjects")
380
+
381
+ if (
382
+ leases !== roots.leases ||
383
+ staging !== roots.staging ||
384
+ stagingTrash !== roots.stagingTrash ||
385
+ trash !== roots.trash ||
386
+ subjects !== roots.subjects
387
+ ) {
388
+ throw new globalThis.Error("OCI lease roots did not resolve as expected")
389
+ }
390
+ }
391
+
392
+ const writeExclusive = async (target: string, content: string) => {
393
+ const handle = await fs.open(
394
+ target,
395
+ FsConstants.O_WRONLY |
396
+ FsConstants.O_CREAT |
397
+ FsConstants.O_EXCL |
398
+ FsConstants.O_NOFOLLOW,
399
+ FILE_MODE,
400
+ )
401
+ try {
402
+ await handle.writeFile(content, "utf8")
403
+ const info = await handle.stat()
404
+ if (!info.isFile() || info.nlink !== 1 || mode(info.mode) !== FILE_MODE) {
405
+ throw new globalThis.Error("OCI lease file was not created securely")
406
+ }
407
+ await handle.sync()
408
+ } finally {
409
+ await handle.close()
410
+ }
411
+ await fsyncDirectory(path.dirname(target))
412
+ }
413
+
414
+ const readStrictFile = async (target: string, maximumBytes: number) => {
415
+ const handle = await fs.open(
416
+ target,
417
+ FsConstants.O_RDONLY | FsConstants.O_NOFOLLOW,
418
+ )
419
+ try {
420
+ const info = await handle.stat()
421
+ if (
422
+ !info.isFile() ||
423
+ info.nlink !== 1 ||
424
+ mode(info.mode) !== FILE_MODE ||
425
+ info.size <= 0 ||
426
+ info.size > maximumBytes
427
+ ) {
428
+ throw new globalThis.Error("OCI lease file is missing or insecure")
429
+ }
430
+ return await handle.readFile("utf8")
431
+ } finally {
432
+ await handle.close()
433
+ }
434
+ }
435
+
436
+ const readStartBoundary = async (
437
+ leaseDirectory: string,
438
+ pendingNames: readonly string[],
439
+ ) => {
440
+ const target = path.join(leaseDirectory, "container-id")
441
+ const handle = await fs.open(
442
+ target,
443
+ FsConstants.O_RDONLY | FsConstants.O_NOFOLLOW,
444
+ )
445
+ try {
446
+ const info = await handle.stat()
447
+ if (
448
+ !info.isFile() ||
449
+ mode(info.mode) !== FILE_MODE ||
450
+ info.size <= 0 ||
451
+ info.size > CONTAINER_ID_BYTES ||
452
+ info.nlink < 1 ||
453
+ info.nlink > 2
454
+ )
455
+ throw new globalThis.Error("OCI start boundary is missing or insecure")
456
+ if (info.nlink === 2) {
457
+ let matchingPending = 0
458
+ for (const pendingName of pendingNames) {
459
+ const pending = await fs.lstat(path.join(leaseDirectory, pendingName))
460
+ if (pending.dev === info.dev && pending.ino === info.ino)
461
+ matchingPending++
462
+ }
463
+ if (matchingPending !== 1)
464
+ throw new globalThis.Error(
465
+ "OCI start boundary has an unexplained hard link",
466
+ )
467
+ }
468
+ return await handle.readFile("utf8")
469
+ } finally {
470
+ await handle.close()
471
+ }
472
+ }
473
+
474
+ const decodeIntent = (raw: string, expectedLeaseID: LeaseID): Intent => {
475
+ const parsed = JSON.parse(raw) as unknown
476
+ const decoded = Schema.decodeUnknownSync(Intent)(parsed, STRICT_OPTIONS)
477
+ const intent = freezeIntent(decoded)
478
+ if (intent.leaseID !== expectedLeaseID || raw !== encodeIntent(intent)) {
479
+ throw new globalThis.Error("OCI lease intent is not canonical")
480
+ }
481
+ return intent
482
+ }
483
+
484
+ const decodeAbsenceObservation = (
485
+ raw: string,
486
+ expectedLeaseID: LeaseID,
487
+ expectedSequence: 1 | 2,
488
+ ) => {
489
+ const decoded = Schema.decodeUnknownSync(AbsenceObservation)(
490
+ JSON.parse(raw) as unknown,
491
+ STRICT_OPTIONS,
492
+ )
493
+ if (
494
+ decoded.leaseID !== expectedLeaseID ||
495
+ decoded.sequence !== expectedSequence ||
496
+ raw !== encodeAbsenceObservation(decoded)
497
+ ) {
498
+ throw new globalThis.Error(
499
+ "OCI no-start absence observation is not canonical",
500
+ )
501
+ }
502
+ return decoded
503
+ }
504
+
505
+ const readAbsenceObservations = async (
506
+ leaseDirectory: string,
507
+ intent: Intent,
508
+ ) => {
509
+ const observations: AbsenceObservation[] = []
510
+ for (const sequence of [1, 2] as const) {
511
+ const target = path.join(leaseDirectory, absenceObservationName(sequence))
512
+ const info = await lstatOptional(target)
513
+ if (!info) {
514
+ if (
515
+ sequence === 1 &&
516
+ (await lstatOptional(
517
+ path.join(leaseDirectory, absenceObservationName(2)),
518
+ ))
519
+ ) {
520
+ throw new globalThis.Error(
521
+ "OCI no-start absence observation chain is incomplete",
522
+ )
523
+ }
524
+ break
525
+ }
526
+ const observation = decodeAbsenceObservation(
527
+ await readStrictFile(target, MAX_ABSENCE_OBSERVATION_BYTES),
528
+ intent.leaseID,
529
+ sequence,
530
+ )
531
+ if (
532
+ observation.observedAtMs < intent.reapAfterMs ||
533
+ (sequence === 2 &&
534
+ observation.observedAtMs <
535
+ observations[0]!.observedAtMs +
536
+ RETIREMENT_POLICY.absenceObservationSpacingMs)
537
+ ) {
538
+ throw new globalThis.Error(
539
+ "OCI no-start absence observation timing is invalid",
540
+ )
541
+ }
542
+ observations.push(observation)
543
+ }
544
+ return observations
545
+ }
546
+
547
+ const retirementEvidence = (
548
+ observations: readonly AbsenceObservation[],
549
+ nowMs: number,
550
+ ): RetirementEvidence => {
551
+ const first = observations[0]?.observedAtMs
552
+ const last = observations.at(-1)?.observedAtMs
553
+ if (last !== undefined && last > nowMs)
554
+ throw new globalThis.Error(
555
+ "OCI no-start absence observation is in the future",
556
+ )
557
+ return Object.freeze({
558
+ observations: observations.length,
559
+ ...(first === undefined ? {} : { firstObservedAtMs: first }),
560
+ ...(last === undefined ? {} : { lastObservedAtMs: last }),
561
+ eligible:
562
+ observations.length >= RETIREMENT_POLICY.absenceObservationsRequired &&
563
+ first !== undefined &&
564
+ nowMs >= first + RETIREMENT_POLICY.tombstoneMinimumAgeMs,
565
+ })
566
+ }
567
+
568
+ const assertNoPendingStartBoundary = async (leaseDirectory: string) => {
569
+ const names = await fs.readdir(leaseDirectory)
570
+ if (names.some((name) => PENDING_BOUNDARY_PATTERN.test(name)))
571
+ throw new globalThis.Error(
572
+ "OCI no-start lease still contains a pending start request",
573
+ )
574
+ }
575
+
576
+ const publishStartBoundary = async (
577
+ leaseDirectory: string,
578
+ content: ContainerID | typeof NO_START_BOUNDARY,
579
+ ) => {
580
+ const pendingPath = path.join(
581
+ leaseDirectory,
582
+ `container-id.pending-${randomBytes(8).toString("hex")}`,
583
+ )
584
+ const finalPath = path.join(leaseDirectory, "container-id")
585
+ await writeExclusive(pendingPath, content)
586
+ try {
587
+ await fs.link(pendingPath, finalPath)
588
+ await fsyncDirectory(leaseDirectory)
589
+ await fs.unlink(pendingPath)
590
+ await fsyncDirectory(leaseDirectory)
591
+ if ((await readStrictFile(finalPath, CONTAINER_ID_BYTES)) !== content)
592
+ throw new globalThis.Error(
593
+ "Committed OCI start boundary did not round-trip",
594
+ )
595
+ } catch (cause) {
596
+ try {
597
+ await fs.unlink(pendingPath)
598
+ await fsyncDirectory(leaseDirectory)
599
+ } catch (cleanupCause) {
600
+ if (errorCode(cleanupCause) !== "ENOENT") throw cleanupCause
601
+ }
602
+ throw cause
603
+ }
604
+ }
605
+
606
+ const readLease = async (roots: Roots, leaseID: LeaseID) => {
607
+ const leaseDirectory = path.join(roots.leases, leaseID)
608
+ await assertPrivateDirectory(leaseDirectory)
609
+ const entries = await fs.readdir(leaseDirectory, { withFileTypes: true })
610
+ const names = entries.map((entry) => entry.name).sort()
611
+ const pendingNames = names.filter((name) =>
612
+ PENDING_BOUNDARY_PATTERN.test(name),
613
+ )
614
+ const absenceNames = names.filter((name) =>
615
+ ABSENCE_OBSERVATION_PATTERN.test(name),
616
+ )
617
+ if (
618
+ names.length < 1 ||
619
+ pendingNames.length > MAX_PENDING_BOUNDARIES ||
620
+ absenceNames.length > RETIREMENT_POLICY.absenceObservationsRequired ||
621
+ !names.includes("intent.json") ||
622
+ names.some(
623
+ (name) =>
624
+ name !== "intent.json" &&
625
+ name !== "container-id" &&
626
+ !ABSENCE_OBSERVATION_PATTERN.test(name) &&
627
+ !PENDING_BOUNDARY_PATTERN.test(name),
628
+ ) ||
629
+ entries.some((entry) => entry.isSymbolicLink() || !entry.isFile())
630
+ ) {
631
+ throw new globalThis.Error(
632
+ "OCI lease directory contains unexpected entries",
633
+ )
634
+ }
635
+
636
+ const intentRaw = await readStrictFile(
637
+ path.join(leaseDirectory, "intent.json"),
638
+ MAX_INTENT_BYTES,
639
+ )
640
+ const intent = decodeIntent(intentRaw, leaseID)
641
+ const absenceObservations = await readAbsenceObservations(
642
+ leaseDirectory,
643
+ intent,
644
+ )
645
+ for (const pendingName of pendingNames) {
646
+ const info = await fs.lstat(path.join(leaseDirectory, pendingName))
647
+ if (
648
+ !info.isFile() ||
649
+ info.isSymbolicLink() ||
650
+ mode(info.mode) !== FILE_MODE ||
651
+ info.size <= 0 ||
652
+ info.size > CONTAINER_ID_BYTES ||
653
+ info.nlink < 1 ||
654
+ info.nlink > 2
655
+ )
656
+ throw new globalThis.Error("OCI pending start boundary is insecure")
657
+ }
658
+ if (!names.includes("container-id")) {
659
+ if (absenceObservations.length > 0)
660
+ throw new globalThis.Error(
661
+ "OCI absence observations require a no-start boundary",
662
+ )
663
+ return makeLease(roots, intent)
664
+ }
665
+ const boundary = await readStartBoundary(leaseDirectory, pendingNames)
666
+ if (boundary !== NO_START_BOUNDARY && absenceObservations.length > 0) {
667
+ throw new globalThis.Error(
668
+ "OCI absence observations are attached to a container lease",
669
+ )
670
+ }
671
+ return boundary === NO_START_BOUNDARY
672
+ ? makeLease(roots, intent, undefined, true)
673
+ : makeLease(roots, intent, decodeContainerID(boundary))
674
+ }
675
+
676
+ const assertSubjectDirectory = async (roots: Roots, leaseID: LeaseID) => {
677
+ const subject = path.join(roots.subjects, leaseID)
678
+ await assertPrivateDirectory(subject)
679
+ return subject
680
+ }
681
+
682
+ const removeDerivedDirectory = async (target: string) => {
683
+ const info = await lstatOptional(target)
684
+ if (!info) return
685
+ if (
686
+ info.isSymbolicLink() ||
687
+ !info.isDirectory() ||
688
+ mode(info.mode) !== DIRECTORY_MODE
689
+ ) {
690
+ throw new globalThis.Error("Refusing to remove an insecure OCI lease path")
691
+ }
692
+ try {
693
+ await fs.rm(target, { recursive: true })
694
+ } catch (cause) {
695
+ if (errorCode(cause) !== "ENOENT") throw cause
696
+ }
697
+ }
698
+
699
+ const removeTerminalTrashDirectory = async (target: string) => {
700
+ const directory = await lstatOptional(target)
701
+ if (!directory) return
702
+ const uid = process.getuid?.()
703
+ if (
704
+ directory.isSymbolicLink() ||
705
+ !directory.isDirectory() ||
706
+ mode(directory.mode) !== DIRECTORY_MODE ||
707
+ (uid !== undefined && directory.uid !== uid)
708
+ ) {
709
+ throw new globalThis.Error("Refusing to remove insecure OCI terminal trash")
710
+ }
711
+
712
+ const entries = await fs
713
+ .readdir(target, { withFileTypes: true })
714
+ .catch((cause) => {
715
+ if (errorCode(cause) === "ENOENT") return undefined
716
+ throw cause
717
+ })
718
+ if (!entries) return
719
+ entries.sort((left, right) => left.name.localeCompare(right.name))
720
+ for (const entry of entries) {
721
+ const boundary =
722
+ entry.name === "container-id" || PENDING_BOUNDARY_PATTERN.test(entry.name)
723
+ const absence = ABSENCE_OBSERVATION_PATTERN.test(entry.name)
724
+ if (
725
+ (entry.name !== "intent.json" && !boundary && !absence) ||
726
+ entry.isSymbolicLink() ||
727
+ !entry.isFile()
728
+ ) {
729
+ throw new globalThis.Error("OCI terminal trash contains an unsafe entry")
730
+ }
731
+ const info = await lstatOptional(path.join(target, entry.name))
732
+ if (!info) continue
733
+ const maximum = boundary
734
+ ? CONTAINER_ID_BYTES
735
+ : absence
736
+ ? MAX_ABSENCE_OBSERVATION_BYTES
737
+ : MAX_INTENT_BYTES
738
+ const maximumLinks = boundary ? 2 : 1
739
+ if (
740
+ info.isSymbolicLink() ||
741
+ !info.isFile() ||
742
+ mode(info.mode) !== FILE_MODE ||
743
+ info.size <= 0 ||
744
+ info.size > maximum ||
745
+ info.nlink < 1 ||
746
+ info.nlink > maximumLinks ||
747
+ (uid !== undefined && info.uid !== uid)
748
+ ) {
749
+ throw new globalThis.Error(
750
+ "OCI terminal trash file is missing or insecure",
751
+ )
752
+ }
753
+ }
754
+
755
+ // A committed lease contains files only. Unlink exact validated names and
756
+ // then remove the empty directory; never recursively traverse trash.
757
+ for (const entry of entries) {
758
+ try {
759
+ await fs.unlink(path.join(target, entry.name))
760
+ } catch (cause) {
761
+ if (errorCode(cause) !== "ENOENT") throw cause
762
+ }
763
+ }
764
+ try {
765
+ await fs.rmdir(target)
766
+ } catch (cause) {
767
+ if (errorCode(cause) !== "ENOENT") throw cause
768
+ }
769
+ }
770
+
771
+ const stagingDeadline = (name: string) => {
772
+ const match = STAGING_DIRECTORY_PATTERN.exec(name)
773
+ if (!match) return undefined
774
+ const value = Number(match[2])
775
+ return Number.isSafeInteger(value) &&
776
+ value >= 0 &&
777
+ String(value).padStart(16, "0") === match[2]
778
+ ? value
779
+ : undefined
780
+ }
781
+
782
+ const canceledStagingSource = (name: string) => {
783
+ const match = STAGING_TRASH_DIRECTORY_PATTERN.exec(name)
784
+ if (!match) return undefined
785
+ const source = `s-${match[1]}-${match[2]}-${match[3]}`
786
+ return stagingDeadline(source) === undefined ? undefined : source
787
+ }
788
+
789
+ interface DirectoryIdentity {
790
+ readonly dev: bigint
791
+ readonly ino: bigint
792
+ }
793
+
794
+ const privateDirectoryIdentityOptional = async (
795
+ target: string,
796
+ ): Promise<DirectoryIdentity | undefined> => {
797
+ let info: BigIntStats
798
+ try {
799
+ info = await fs.lstat(target, { bigint: true })
800
+ } catch (cause) {
801
+ if (errorCode(cause) === "ENOENT") return undefined
802
+ throw cause
803
+ }
804
+ const uid = process.getuid?.()
805
+ if (
806
+ info.isSymbolicLink() ||
807
+ !info.isDirectory() ||
808
+ Number(info.mode & 0o777n) !== DIRECTORY_MODE ||
809
+ (uid !== undefined && info.uid !== BigInt(uid))
810
+ ) {
811
+ throw new globalThis.Error("OCI staging directory is missing or insecure")
812
+ }
813
+ return Object.freeze({ dev: info.dev, ino: info.ino })
814
+ }
815
+
816
+ const sameDirectory = (left: DirectoryIdentity, right: DirectoryIdentity) =>
817
+ left.dev === right.dev && left.ino === right.ino
818
+
819
+ const removeStagingTrashEnvelope = async (
820
+ roots: Roots,
821
+ target: string,
822
+ retry = 0,
823
+ ) => {
824
+ if (!(await privateDirectoryIdentityOptional(target))) return
825
+ const name = path.basename(target)
826
+ const sourceName = canceledStagingSource(name)
827
+ if (!sourceName || path.dirname(target) !== roots.stagingTrash) {
828
+ throw new globalThis.Error("OCI staging trash name is invalid")
829
+ }
830
+ const source = path.join(roots.staging, sourceName)
831
+
832
+ let envelopeEntries
833
+ try {
834
+ envelopeEntries = await fs.readdir(target, { withFileTypes: true })
835
+ } catch (cause) {
836
+ if (errorCode(cause) === "ENOENT") return
837
+ throw cause
838
+ }
839
+ if (
840
+ envelopeEntries.length > 1 ||
841
+ envelopeEntries.some(
842
+ (entry) =>
843
+ entry.name !== "payload" ||
844
+ entry.isSymbolicLink() ||
845
+ !entry.isDirectory(),
846
+ )
847
+ ) {
848
+ throw new globalThis.Error("OCI staging trash contains an unsafe entry")
849
+ }
850
+
851
+ if (envelopeEntries.length === 0) {
852
+ // An empty envelope is published before its owner attempts the fencing
853
+ // rename. Do not remove its destination parent while the exact source still
854
+ // exists; a crashed envelope will become removable after the source is
855
+ // published or canceled by this scan.
856
+ if (await lstatOptional(source)) return
857
+ try {
858
+ await fs.rmdir(target)
859
+ } catch (cause) {
860
+ if (errorCode(cause) === "ENOENT") return
861
+ if (errorCode(cause) === "ENOTEMPTY" && retry < 3) {
862
+ return removeStagingTrashEnvelope(roots, target, retry + 1)
863
+ }
864
+ throw cause
865
+ }
866
+ return
867
+ }
868
+
869
+ const payload = path.join(target, "payload")
870
+ if (!(await privateDirectoryIdentityOptional(payload))) return
871
+ if (await lstatOptional(source)) {
872
+ throw new globalThis.Error(
873
+ "OCI staging source still exists beside canceled payload",
874
+ )
875
+ }
876
+ // A cleaner may observe the payload before the canceling process fsyncs its
877
+ // rename. Establish destination-then-source durability itself before
878
+ // unlinking either side of the fence.
879
+ try {
880
+ await fsyncDirectory(target)
881
+ await fsyncDirectory(roots.staging)
882
+ } catch (cause) {
883
+ if (errorCode(cause) === "ENOENT") return
884
+ throw cause
885
+ }
886
+ let payloadEntries
887
+ try {
888
+ payloadEntries = await fs.readdir(payload, { withFileTypes: true })
889
+ } catch (cause) {
890
+ if (errorCode(cause) === "ENOENT") return
891
+ throw cause
892
+ }
893
+ if (
894
+ payloadEntries.length > 1 ||
895
+ payloadEntries.some(
896
+ (entry) =>
897
+ entry.name !== "intent.json" ||
898
+ entry.isSymbolicLink() ||
899
+ !entry.isFile(),
900
+ )
901
+ ) {
902
+ throw new globalThis.Error(
903
+ "OCI staging trash payload contains an unsafe entry",
904
+ )
905
+ }
906
+ if (payloadEntries.length === 1) {
907
+ const targetFile = path.join(payload, "intent.json")
908
+ const info = await lstatOptional(targetFile)
909
+ const uid = process.getuid?.()
910
+ if (info) {
911
+ if (
912
+ info.isSymbolicLink() ||
913
+ !info.isFile() ||
914
+ mode(info.mode) !== FILE_MODE ||
915
+ info.size > MAX_INTENT_BYTES ||
916
+ info.nlink !== 1 ||
917
+ (uid !== undefined && info.uid !== uid)
918
+ ) {
919
+ throw new globalThis.Error(
920
+ "OCI staging trash file is missing or insecure",
921
+ )
922
+ }
923
+ try {
924
+ await fs.unlink(targetFile)
925
+ } catch (cause) {
926
+ if (errorCode(cause) !== "ENOENT") throw cause
927
+ }
928
+ }
929
+ }
930
+ try {
931
+ await fs.rmdir(payload)
932
+ } catch (cause) {
933
+ if (errorCode(cause) !== "ENOENT") throw cause
934
+ }
935
+ try {
936
+ await fs.rmdir(target)
937
+ } catch (cause) {
938
+ if (errorCode(cause) !== "ENOENT") throw cause
939
+ }
940
+ }
941
+
942
+ const terminalizeStagingDirectory = async (
943
+ roots: Roots,
944
+ stagingName: string,
945
+ expected?: DirectoryIdentity,
946
+ retry = 0,
947
+ ) => {
948
+ const source = path.join(roots.staging, stagingName)
949
+ const sourceIdentity = await privateDirectoryIdentityOptional(source)
950
+ if (!sourceIdentity) return undefined
951
+ if (expected && !sameDirectory(sourceIdentity, expected)) {
952
+ throw new globalThis.Error("OCI staging generation changed before fence")
953
+ }
954
+ const match = STAGING_DIRECTORY_PATTERN.exec(stagingName)
955
+ if (!match || stagingDeadline(stagingName) === undefined) {
956
+ throw new globalThis.Error("OCI staging generation name is invalid")
957
+ }
958
+ const envelope = path.join(
959
+ roots.stagingTrash,
960
+ `cancel-${match[1]}-${match[2]}-${match[3]}-${randomBytes(16).toString("hex")}`,
961
+ )
962
+ await fs.mkdir(envelope, { mode: DIRECTORY_MODE })
963
+ await privateDirectoryIdentityOptional(envelope)
964
+ await fsyncDirectory(roots.stagingTrash)
965
+ const payload = path.join(envelope, "payload")
966
+ try {
967
+ await fs.rename(source, payload)
968
+ } catch (cause) {
969
+ if (errorCode(cause) === "ENOENT" || errorCode(cause) === "EINVAL") {
970
+ await removeStagingTrashEnvelope(roots, envelope)
971
+ await fsyncDirectory(roots.stagingTrash)
972
+ const remaining = await privateDirectoryIdentityOptional(source)
973
+ if (remaining) {
974
+ if (!sameDirectory(sourceIdentity, remaining)) {
975
+ throw new globalThis.Error(
976
+ "OCI staging generation changed after a failed fence",
977
+ )
978
+ }
979
+ if (retry >= 3) {
980
+ throw new globalThis.Error(
981
+ "OCI staging generation could not be fenced",
982
+ )
983
+ }
984
+ return terminalizeStagingDirectory(
985
+ roots,
986
+ stagingName,
987
+ sourceIdentity,
988
+ retry + 1,
989
+ )
990
+ }
991
+ return undefined
992
+ }
993
+ throw cause
994
+ }
995
+ const payloadIdentity = await privateDirectoryIdentityOptional(payload)
996
+ if (!payloadIdentity || !sameDirectory(sourceIdentity, payloadIdentity)) {
997
+ throw new globalThis.Error("OCI staging generation changed during fence")
998
+ }
999
+ // The cross-directory rename is the generation fence. A writer that lost
1000
+ // this race cannot later publish a replacement generation through its old
1001
+ // pathname.
1002
+ await fsyncDirectory(envelope)
1003
+ await fsyncDirectory(roots.staging)
1004
+ return envelope
1005
+ }
1006
+
1007
+ const reconcileStagingTrash = async (roots: Roots) => {
1008
+ const entries = await fs.readdir(roots.stagingTrash, {
1009
+ withFileTypes: true,
1010
+ })
1011
+ entries.sort((left, right) => left.name.localeCompare(right.name))
1012
+ const failures: unknown[] = []
1013
+ for (const entry of entries) {
1014
+ if (
1015
+ !canceledStagingSource(entry.name) ||
1016
+ entry.isSymbolicLink() ||
1017
+ !entry.isDirectory()
1018
+ ) {
1019
+ failures.push(
1020
+ new globalThis.Error("OCI staging trash contains an unsafe entry"),
1021
+ )
1022
+ continue
1023
+ }
1024
+ try {
1025
+ await removeStagingTrashEnvelope(
1026
+ roots,
1027
+ path.join(roots.stagingTrash, entry.name),
1028
+ )
1029
+ } catch (cause) {
1030
+ failures.push(cause)
1031
+ }
1032
+ }
1033
+ await fsyncDirectory(roots.stagingTrash)
1034
+ if (failures.length > 0) {
1035
+ throw new AggregateError(
1036
+ failures,
1037
+ "OCI staging trash reconciliation was incomplete",
1038
+ )
1039
+ }
1040
+ }
1041
+
1042
+ const reconcileExpiredStaging = async (roots: Roots, nowMs: number) => {
1043
+ const entries = await fs.readdir(roots.staging, { withFileTypes: true })
1044
+ entries.sort((left, right) => left.name.localeCompare(right.name))
1045
+ const failures: unknown[] = []
1046
+ let retired = 0
1047
+ for (const entry of entries) {
1048
+ const deadline = stagingDeadline(entry.name)
1049
+ let identity: DirectoryIdentity | undefined
1050
+ try {
1051
+ identity = await privateDirectoryIdentityOptional(
1052
+ path.join(roots.staging, entry.name),
1053
+ )
1054
+ } catch (cause) {
1055
+ failures.push(cause)
1056
+ continue
1057
+ }
1058
+ if (!identity) continue
1059
+ if (
1060
+ deadline === undefined ||
1061
+ entry.isSymbolicLink() ||
1062
+ !entry.isDirectory()
1063
+ ) {
1064
+ failures.push(
1065
+ new globalThis.Error("OCI staging contains an unsafe entry"),
1066
+ )
1067
+ continue
1068
+ }
1069
+ if (deadline > nowMs) continue
1070
+ if (retired >= RETIREMENT_POLICY.expiredStagingPerRead) continue
1071
+ retired++
1072
+ try {
1073
+ const terminal = await terminalizeStagingDirectory(
1074
+ roots,
1075
+ entry.name,
1076
+ identity,
1077
+ )
1078
+ if (terminal) await removeStagingTrashEnvelope(roots, terminal)
1079
+ } catch (cause) {
1080
+ failures.push(cause)
1081
+ }
1082
+ }
1083
+ // Persist every successful fence and cleanup before surfacing malformed
1084
+ // siblings. Safe entries therefore converge even during a fail-closed scan.
1085
+ await fsyncDirectory(roots.staging)
1086
+ await fsyncDirectory(roots.stagingTrash)
1087
+ if (failures.length > 0) {
1088
+ throw new AggregateError(
1089
+ failures,
1090
+ "OCI staging reconciliation was incomplete",
1091
+ )
1092
+ }
1093
+ }
1094
+
1095
+ const reconcileTerminalTrash = async (roots: Roots) => {
1096
+ const entries = await fs.readdir(roots.trash, { withFileTypes: true })
1097
+ entries.sort((left, right) => left.name.localeCompare(right.name))
1098
+ const failures: unknown[] = []
1099
+ for (const entry of entries) {
1100
+ if (
1101
+ !TRASH_DIRECTORY_PATTERN.test(entry.name) ||
1102
+ entry.isSymbolicLink() ||
1103
+ !entry.isDirectory()
1104
+ ) {
1105
+ failures.push(new globalThis.Error("OCI trash contains an unsafe entry"))
1106
+ continue
1107
+ }
1108
+ try {
1109
+ // Visibility in trash means the live lease was already atomically
1110
+ // terminalized. Concurrent removers may race here; ENOENT is success.
1111
+ await removeTerminalTrashDirectory(path.join(roots.trash, entry.name))
1112
+ } catch (cause) {
1113
+ failures.push(cause)
1114
+ }
1115
+ }
1116
+ // Make successful removals durable even when another malformed entry makes
1117
+ // this reconciliation fail closed after processing the complete scan.
1118
+ await fsyncDirectory(roots.trash)
1119
+ if (failures.length > 0) {
1120
+ throw new AggregateError(
1121
+ failures,
1122
+ "OCI terminal trash reconciliation was incomplete",
1123
+ )
1124
+ }
1125
+ }
1126
+
1127
+ const terminalizeLease = async (
1128
+ roots: Roots,
1129
+ leaseID: LeaseID,
1130
+ removeSubject = true,
1131
+ ) => {
1132
+ if (removeSubject) {
1133
+ await removeDerivedDirectory(path.join(roots.subjects, leaseID))
1134
+ await fsyncDirectory(roots.subjects)
1135
+ }
1136
+ const leaseDirectory = path.join(roots.leases, leaseID)
1137
+ const leaseInfo = await lstatOptional(leaseDirectory)
1138
+ if (!leaseInfo) {
1139
+ await fsyncDirectory(roots.leases)
1140
+ return
1141
+ }
1142
+ await assertPrivateDirectory(leaseDirectory)
1143
+ const trashDirectory = path.join(
1144
+ roots.trash,
1145
+ `${leaseID}-${randomBytes(8).toString("hex")}`,
1146
+ )
1147
+ try {
1148
+ await fs.rename(leaseDirectory, trashDirectory)
1149
+ } catch (cause) {
1150
+ if (errorCode(cause) === "ENOENT") {
1151
+ await fsyncDirectory(roots.leases)
1152
+ return
1153
+ }
1154
+ throw cause
1155
+ }
1156
+ await fsyncDirectory(roots.leases)
1157
+ await fsyncDirectory(roots.trash)
1158
+ await removeTerminalTrashDirectory(trashDirectory)
1159
+ await fsyncDirectory(roots.trash)
1160
+ }
1161
+
1162
+ export const make = (
1163
+ global: Pick<AppPaths.Interface, "state" | "tmp">,
1164
+ options: Options = {},
1165
+ ): Interface => {
1166
+ const roots = Object.freeze({
1167
+ state: global.state,
1168
+ temporary: global.tmp,
1169
+ leases: path.join(global.state, "verifier-oci", `v${VERSION}`, "leases"),
1170
+ staging: path.join(global.state, "verifier-oci", `v${VERSION}`, "staging"),
1171
+ stagingTrash: path.join(
1172
+ global.state,
1173
+ "verifier-oci",
1174
+ `v${VERSION}`,
1175
+ "staging-trash",
1176
+ ),
1177
+ trash: path.join(global.state, "verifier-oci", `v${VERSION}`, "trash"),
1178
+ subjects: path.join(global.tmp, "verifier-oci", `v${VERSION}`, "subjects"),
1179
+ })
1180
+ const nextLeaseID = options.leaseID ?? (() => randomBytes(16).toString("hex"))
1181
+ const nextOwner = options.owner ?? randomUUID
1182
+ const nextStagingGeneration =
1183
+ options.stagingGeneration ?? (() => randomBytes(16).toString("hex"))
1184
+ const now = options.now ?? Date.now
1185
+
1186
+ const prepare = Effect.fn("VerifierOciLease.prepare")((input: PrepareInput) =>
1187
+ withSnapshotRetentionBarrier(
1188
+ global.state,
1189
+ attempt("prepare", "Failed to prepare durable OCI lease", async () => {
1190
+ const leaseID = decodeLeaseID(nextLeaseID())
1191
+ const intent = freezeIntent(
1192
+ Schema.decodeUnknownSync(Intent)(
1193
+ {
1194
+ version: VERSION,
1195
+ leaseID,
1196
+ owner: nextOwner(),
1197
+ executionHash: input.executionHash,
1198
+ snapshot: input.snapshot,
1199
+ image: input.image,
1200
+ reapAfterMs: input.reapAfterMs,
1201
+ },
1202
+ STRICT_OPTIONS,
1203
+ ),
1204
+ )
1205
+
1206
+ await ensureRoots(roots)
1207
+ const generation = nextStagingGeneration()
1208
+ if (!GENERATION_PATTERN.test(generation)) {
1209
+ throw new globalThis.Error("OCI staging generation is not canonical")
1210
+ }
1211
+ const deadline = String(intent.reapAfterMs).padStart(16, "0")
1212
+ const stagingName = `s-${leaseID}-${deadline}-${generation}`
1213
+ const stagingDirectory = path.join(roots.staging, stagingName)
1214
+ const leaseDirectory = path.join(roots.leases, leaseID)
1215
+ await fs.mkdir(stagingDirectory, { mode: DIRECTORY_MODE })
1216
+ let stagingIdentity: DirectoryIdentity | undefined
1217
+ try {
1218
+ stagingIdentity =
1219
+ await privateDirectoryIdentityOptional(stagingDirectory)
1220
+ if (!stagingIdentity) {
1221
+ throw new globalThis.Error("OCI staging generation disappeared")
1222
+ }
1223
+ await fsyncDirectory(roots.staging)
1224
+ const encodedIntent = encodeIntent(intent)
1225
+ await writeExclusive(
1226
+ path.join(stagingDirectory, "intent.json"),
1227
+ encodedIntent,
1228
+ )
1229
+ const beforePublish =
1230
+ await privateDirectoryIdentityOptional(stagingDirectory)
1231
+ if (
1232
+ !beforePublish ||
1233
+ !sameDirectory(stagingIdentity, beforePublish)
1234
+ ) {
1235
+ throw new globalThis.Error(
1236
+ "OCI staging generation changed before publish",
1237
+ )
1238
+ }
1239
+ const stagingEntries = await fs.readdir(stagingDirectory, {
1240
+ withFileTypes: true,
1241
+ })
1242
+ if (
1243
+ stagingEntries.length !== 1 ||
1244
+ stagingEntries[0]?.name !== "intent.json" ||
1245
+ stagingEntries[0].isSymbolicLink() ||
1246
+ !stagingEntries[0].isFile() ||
1247
+ (await readStrictFile(
1248
+ path.join(stagingDirectory, "intent.json"),
1249
+ MAX_INTENT_BYTES,
1250
+ )) !== encodedIntent
1251
+ ) {
1252
+ throw new globalThis.Error(
1253
+ "OCI staging intent changed before publish",
1254
+ )
1255
+ }
1256
+ await fs.rename(stagingDirectory, leaseDirectory)
1257
+ const publishedIdentity =
1258
+ await privateDirectoryIdentityOptional(leaseDirectory)
1259
+ if (
1260
+ !publishedIdentity ||
1261
+ !sameDirectory(stagingIdentity, publishedIdentity)
1262
+ ) {
1263
+ throw new globalThis.Error(
1264
+ "OCI staging generation changed during publish",
1265
+ )
1266
+ }
1267
+ await fsyncDirectory(roots.leases)
1268
+ await fsyncDirectory(roots.staging)
1269
+ } catch (cause) {
1270
+ const terminal = await terminalizeStagingDirectory(
1271
+ roots,
1272
+ stagingName,
1273
+ stagingIdentity,
1274
+ )
1275
+ if (terminal) {
1276
+ await removeStagingTrashEnvelope(roots, terminal)
1277
+ await fsyncDirectory(roots.stagingTrash)
1278
+ }
1279
+ throw cause
1280
+ }
1281
+ await assertPrivateDirectory(leaseDirectory)
1282
+ return makeLease(roots, intent)
1283
+ }).pipe(Effect.uninterruptible),
1284
+ ),
1285
+ )
1286
+
1287
+ const commitContainerID = Effect.fn("VerifierOciLease.commitContainerID")(
1288
+ (leaseIDInput: string, containerIDInput: string) =>
1289
+ attempt(
1290
+ "commit-container-id",
1291
+ "Failed to commit durable OCI container ID",
1292
+ async () => {
1293
+ const leaseID = decodeLeaseID(leaseIDInput)
1294
+ const containerID = decodeContainerID(containerIDInput)
1295
+ await ensureRoots(roots)
1296
+ const lease = await readLease(roots, leaseID)
1297
+ if (lease.startDisabled)
1298
+ throw new globalThis.Error(
1299
+ "OCI lease start boundary has been permanently disabled",
1300
+ )
1301
+ await assertSubjectDirectory(roots, leaseID)
1302
+ await publishStartBoundary(
1303
+ path.join(roots.leases, leaseID),
1304
+ containerID,
1305
+ )
1306
+ return Object.freeze({ ...lease, containerID })
1307
+ },
1308
+ ).pipe(Effect.uninterruptible),
1309
+ )
1310
+
1311
+ const readAll = Effect.fn("VerifierOciLease.readAll")((nowInput?: number) =>
1312
+ attempt("read", "Failed to read durable OCI leases", async () => {
1313
+ await ensureRoots(roots)
1314
+ const nowMs = nowInput ?? now()
1315
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0) {
1316
+ throw new globalThis.Error("OCI staging reconciliation time is invalid")
1317
+ }
1318
+ await reconcileTerminalTrash(roots)
1319
+ await reconcileStagingTrash(roots)
1320
+ await reconcileExpiredStaging(roots, nowMs)
1321
+ await reconcileStagingTrash(roots)
1322
+ const stateEntries = await fs.readdir(roots.leases, {
1323
+ withFileTypes: true,
1324
+ })
1325
+ stateEntries.sort((left, right) => left.name.localeCompare(right.name))
1326
+ const stateIDs = new Set<string>()
1327
+ const leases: Lease[] = []
1328
+ for (const entry of stateEntries) {
1329
+ if (
1330
+ !LEASE_ID_PATTERN.test(entry.name) ||
1331
+ entry.isSymbolicLink() ||
1332
+ !entry.isDirectory()
1333
+ ) {
1334
+ throw new globalThis.Error("OCI lease list contains an unsafe entry")
1335
+ }
1336
+ const leaseID = decodeLeaseID(entry.name)
1337
+ stateIDs.add(leaseID)
1338
+ leases.push(await readLease(roots, leaseID))
1339
+ }
1340
+
1341
+ const subjectEntries = await fs.readdir(roots.subjects, {
1342
+ withFileTypes: true,
1343
+ })
1344
+ for (const entry of subjectEntries) {
1345
+ if (
1346
+ !LEASE_ID_PATTERN.test(entry.name) ||
1347
+ entry.isSymbolicLink() ||
1348
+ !entry.isDirectory() ||
1349
+ !stateIDs.has(entry.name)
1350
+ ) {
1351
+ throw new globalThis.Error(
1352
+ "OCI subject list contains an orphan or unsafe entry",
1353
+ )
1354
+ }
1355
+ await assertPrivateDirectory(path.join(roots.subjects, entry.name))
1356
+ }
1357
+ return Object.freeze(leases)
1358
+ }),
1359
+ )
1360
+
1361
+ const removeSubject = Effect.fn("VerifierOciLease.removeSubject")(
1362
+ (leaseIDInput: string) =>
1363
+ attempt(
1364
+ "remove-subject",
1365
+ "Failed to remove durable OCI lease subject",
1366
+ async () => {
1367
+ const leaseID = decodeLeaseID(leaseIDInput)
1368
+ await ensureRoots(roots)
1369
+ let lease = await readLease(roots, leaseID)
1370
+ if (lease.containerID)
1371
+ throw new globalThis.Error(
1372
+ "Refusing to remove a subject after container identity commit",
1373
+ )
1374
+ if (!lease.startDisabled) {
1375
+ try {
1376
+ await publishStartBoundary(
1377
+ path.join(roots.leases, leaseID),
1378
+ NO_START_BOUNDARY,
1379
+ )
1380
+ } catch (cause) {
1381
+ lease = await readLease(roots, leaseID)
1382
+ if (!lease.startDisabled) throw cause
1383
+ }
1384
+ }
1385
+ await removeDerivedDirectory(path.join(roots.subjects, leaseID))
1386
+ await fsyncDirectory(roots.subjects)
1387
+ },
1388
+ ).pipe(Effect.uninterruptible),
1389
+ )
1390
+
1391
+ const observeNoStartAbsence = Effect.fn(
1392
+ "VerifierOciLease.observeNoStartAbsence",
1393
+ )((leaseIDInput: string, nowMs: number) =>
1394
+ attempt(
1395
+ "observe-no-start",
1396
+ "Failed to record OCI no-start absence observation",
1397
+ async () => {
1398
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0)
1399
+ throw new globalThis.Error("OCI no-start observation time is invalid")
1400
+ const leaseID = decodeLeaseID(leaseIDInput)
1401
+ await ensureRoots(roots)
1402
+ const lease = await readLease(roots, leaseID)
1403
+ if (!lease.startDisabled || lease.containerID)
1404
+ throw new globalThis.Error(
1405
+ "OCI absence can only be observed for a no-start lease",
1406
+ )
1407
+ if (nowMs < lease.reapAfterMs)
1408
+ throw new globalThis.Error(
1409
+ "OCI no-start lease has not reached its hard deadline",
1410
+ )
1411
+ const leaseDirectory = path.join(roots.leases, leaseID)
1412
+ await assertNoPendingStartBoundary(leaseDirectory)
1413
+ if (await lstatOptional(path.join(roots.subjects, leaseID)))
1414
+ throw new globalThis.Error(
1415
+ "OCI no-start subject is still materialized",
1416
+ )
1417
+
1418
+ let observations = await readAbsenceObservations(leaseDirectory, lease)
1419
+ const last = observations.at(-1)?.observedAtMs
1420
+ if (last !== undefined && nowMs < last)
1421
+ throw new globalThis.Error(
1422
+ "OCI no-start observation time moved backwards",
1423
+ )
1424
+ if (
1425
+ observations.length < RETIREMENT_POLICY.absenceObservationsRequired &&
1426
+ (last === undefined ||
1427
+ nowMs >= last + RETIREMENT_POLICY.absenceObservationSpacingMs)
1428
+ ) {
1429
+ const sequence = (observations.length + 1) as 1 | 2
1430
+ const observation = Schema.decodeUnknownSync(AbsenceObservation)(
1431
+ {
1432
+ version: VERSION,
1433
+ leaseID,
1434
+ sequence,
1435
+ observedAtMs: nowMs,
1436
+ },
1437
+ STRICT_OPTIONS,
1438
+ )
1439
+ try {
1440
+ await writeExclusive(
1441
+ path.join(leaseDirectory, absenceObservationName(sequence)),
1442
+ encodeAbsenceObservation(observation),
1443
+ )
1444
+ } catch (cause) {
1445
+ // Concurrent observers converge on the single fixed sequence slot.
1446
+ if (errorCode(cause) !== "EEXIST") throw cause
1447
+ }
1448
+ const confirmed = await readLease(roots, leaseID)
1449
+ if (!confirmed.startDisabled || confirmed.containerID)
1450
+ throw new globalThis.Error(
1451
+ "OCI no-start boundary changed during observation",
1452
+ )
1453
+ observations = await readAbsenceObservations(
1454
+ leaseDirectory,
1455
+ confirmed,
1456
+ )
1457
+ }
1458
+ return retirementEvidence(observations, nowMs)
1459
+ },
1460
+ ).pipe(Effect.uninterruptible),
1461
+ )
1462
+
1463
+ const resetNoStartAbsence = Effect.fn("VerifierOciLease.resetNoStartAbsence")(
1464
+ (leaseIDInput: string) =>
1465
+ attempt(
1466
+ "reset-no-start",
1467
+ "Failed to reset OCI no-start absence observations",
1468
+ async () => {
1469
+ const leaseID = decodeLeaseID(leaseIDInput)
1470
+ await ensureRoots(roots)
1471
+ const lease = await readLease(roots, leaseID)
1472
+ if (!lease.startDisabled || lease.containerID)
1473
+ throw new globalThis.Error(
1474
+ "OCI absence history belongs only to a no-start lease",
1475
+ )
1476
+ const leaseDirectory = path.join(roots.leases, leaseID)
1477
+ // Delete newest-first so an interrupted reset cannot leave a valid
1478
+ // two-observation chain that predates the late-container sighting.
1479
+ for (const sequence of [2, 1] as const) {
1480
+ try {
1481
+ await fs.unlink(
1482
+ path.join(leaseDirectory, absenceObservationName(sequence)),
1483
+ )
1484
+ } catch (cause) {
1485
+ if (errorCode(cause) !== "ENOENT") throw cause
1486
+ }
1487
+ }
1488
+ await fsyncDirectory(leaseDirectory)
1489
+ },
1490
+ ).pipe(Effect.uninterruptible),
1491
+ )
1492
+
1493
+ const retireNoStart = Effect.fn("VerifierOciLease.retireNoStart")(
1494
+ (leaseIDInput: string, nowMs: number) =>
1495
+ attempt(
1496
+ "retire-no-start",
1497
+ "Failed to retire OCI no-start tombstone",
1498
+ async () => {
1499
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0)
1500
+ throw new globalThis.Error(
1501
+ "OCI no-start retirement time is invalid",
1502
+ )
1503
+ const leaseID = decodeLeaseID(leaseIDInput)
1504
+ await ensureRoots(roots)
1505
+ const lease = await readLease(roots, leaseID)
1506
+ if (!lease.startDisabled || lease.containerID)
1507
+ throw new globalThis.Error(
1508
+ "Only a no-start tombstone may be retired",
1509
+ )
1510
+ const leaseDirectory = path.join(roots.leases, leaseID)
1511
+ await assertNoPendingStartBoundary(leaseDirectory)
1512
+ if (await lstatOptional(path.join(roots.subjects, leaseID)))
1513
+ throw new globalThis.Error(
1514
+ "Refusing to retire a materialized no-start subject",
1515
+ )
1516
+ const evidence = retirementEvidence(
1517
+ await readAbsenceObservations(leaseDirectory, lease),
1518
+ nowMs,
1519
+ )
1520
+ if (!evidence.eligible)
1521
+ throw new globalThis.Error(
1522
+ "OCI no-start tombstone has insufficient aged absence evidence",
1523
+ )
1524
+ // Do not recursively remove the subject here: absence is a required
1525
+ // precondition, not cleanup delegated to this destructive boundary.
1526
+ await terminalizeLease(roots, leaseID, false)
1527
+ },
1528
+ ).pipe(Effect.uninterruptible),
1529
+ )
1530
+
1531
+ const remove = Effect.fn("VerifierOciLease.remove")((leaseIDInput: string) =>
1532
+ attempt("remove", "Failed to remove durable OCI lease", async () => {
1533
+ const leaseID = decodeLeaseID(leaseIDInput)
1534
+ await ensureRoots(roots)
1535
+ await terminalizeLease(roots, leaseID)
1536
+ }).pipe(Effect.uninterruptible),
1537
+ )
1538
+
1539
+ return Object.freeze({
1540
+ prepare,
1541
+ commitContainerID,
1542
+ readAll,
1543
+ removeSubject,
1544
+ observeNoStartAbsence,
1545
+ resetNoStartAbsence,
1546
+ retireNoStart,
1547
+ remove,
1548
+ })
1549
+ }