@1agh/maude 1.0.9 → 1.2.0

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 (506) hide show
  1. package/apps/studio/acp/bridge.ts +18 -13
  2. package/apps/studio/acp/probe.ts +268 -16
  3. package/apps/studio/acp/transcript-io.ts +394 -0
  4. package/apps/studio/acp/transcript.ts +103 -38
  5. package/apps/studio/api.ts +139 -26
  6. package/apps/studio/bin/_import-figma.mjs +57 -11
  7. package/apps/studio/bin/_seed-fixture.mjs +163 -0
  8. package/apps/studio/canvas-imports.ts +89 -0
  9. package/apps/studio/client/app.jsx +257 -7
  10. package/apps/studio/client/export-center.jsx +15 -7
  11. package/apps/studio/client/panels/ReadinessList.jsx +7 -1
  12. package/apps/studio/client/panels/SyncPanel.jsx +125 -4
  13. package/apps/studio/client/report-bug.jsx +19 -1
  14. package/apps/studio/client/styles/3-shell-maude.css +34 -0
  15. package/apps/studio/client/styles/4-components.css +26 -0
  16. package/apps/studio/collab/persistence.ts +132 -16
  17. package/apps/studio/collab/registry.ts +10 -18
  18. package/apps/studio/debug-bundle.ts +13 -0
  19. package/apps/studio/dist/client.bundle.js +1128 -1128
  20. package/apps/studio/dist/styles.css +1 -1
  21. package/apps/studio/export-dialog.tsx +54 -0
  22. package/apps/studio/exporters/degraded.ts +19 -3
  23. package/apps/studio/exporters/ghostscript.ts +194 -0
  24. package/apps/studio/exporters/pdf-fonts.ts +261 -0
  25. package/apps/studio/exporters/pdf.ts +152 -3
  26. package/apps/studio/exporters/remote.ts +36 -1
  27. package/apps/studio/fs-watch.ts +45 -1
  28. package/apps/studio/http.ts +7 -1
  29. package/apps/studio/mem.ts +45 -9
  30. package/apps/studio/readiness.ts +42 -7
  31. package/apps/studio/server.ts +11 -4
  32. package/apps/studio/sync/agent.ts +136 -29
  33. package/apps/studio/sync/asset-push.ts +1 -47
  34. package/apps/studio/sync/codec.ts +122 -31
  35. package/apps/studio/sync/cold-start-apply.ts +7 -0
  36. package/apps/studio/sync/cold-start.ts +118 -22
  37. package/apps/studio/sync/comment-identity.ts +68 -0
  38. package/apps/studio/sync/connection-state.ts +15 -1
  39. package/apps/studio/sync/file-ledger.ts +117 -0
  40. package/apps/studio/sync/file-plane.ts +623 -27
  41. package/apps/studio/sync/index.ts +711 -20
  42. package/apps/studio/sync/journal-client.ts +13 -1
  43. package/apps/studio/sync/migrate-seed.ts +40 -3
  44. package/apps/studio/sync/presentation.ts +26 -3
  45. package/apps/studio/sync/retry-after.ts +169 -0
  46. package/apps/studio/sync/seed-progress.ts +218 -0
  47. package/apps/studio/sync/status.ts +122 -5
  48. package/apps/studio/sync/transport-error.ts +111 -0
  49. package/apps/studio/whats-new.json +91 -0
  50. package/cli/bin/maude.mjs +2 -0
  51. package/cli/commands/codex.mjs +191 -0
  52. package/cli/commands/harness.mjs +1051 -0
  53. package/cli/commands/help.mjs +13 -0
  54. package/cli/lib/design-link.mjs +190 -2
  55. package/cli/lib/harness/capabilities.mjs +302 -0
  56. package/cli/lib/harness/codex-runtime.mjs +889 -0
  57. package/cli/lib/harness/compatibility.mjs +27 -0
  58. package/cli/lib/harness/discover-claude.mjs +1393 -0
  59. package/cli/lib/harness/managed-state.mjs +1296 -0
  60. package/cli/lib/harness/model.mjs +86 -0
  61. package/cli/lib/harness/secrets.mjs +390 -0
  62. package/cli/lib/harness/targets/codex.mjs +1141 -0
  63. package/cli/lib/harness/targets/opencode.mjs +807 -0
  64. package/cli/lib/harness/transaction.mjs +1099 -0
  65. package/cli/lib/hubs-config.mjs +35 -8
  66. package/cli/templates/harness/opencode/maude-projector.ts +58 -0
  67. package/docs/harness-capability-matrix.md +125 -0
  68. package/docs/harness-environment-projection.md +95 -0
  69. package/package.json +32 -9
  70. package/plugins/flow/.claude-plugin/config.schema.json +8 -0
  71. package/apps/studio/.ai/cache/_stats.json +0 -7
  72. package/apps/studio/bin/_agent-browser-safe.test.mjs +0 -165
  73. package/apps/studio/bin/_curl-local.test.mjs +0 -280
  74. package/apps/studio/bin/_pw-launch.test.mjs +0 -90
  75. package/apps/studio/bin/_smart-frames.test.mjs +0 -195
  76. package/apps/studio/bin/_transcribe.test.mjs +0 -80
  77. package/apps/studio/bun.lock +0 -928
  78. package/apps/studio/draw/test/animate.test.ts +0 -172
  79. package/apps/studio/draw/test/brush.test.ts +0 -213
  80. package/apps/studio/draw/test/composition.test.ts +0 -141
  81. package/apps/studio/draw/test/geometry.test.ts +0 -199
  82. package/apps/studio/draw/test/gradient.test.ts +0 -167
  83. package/apps/studio/draw/test/layout.test.ts +0 -120
  84. package/apps/studio/draw/test/morph.test.ts +0 -107
  85. package/apps/studio/draw/test/optimize.test.ts +0 -40
  86. package/apps/studio/draw/test/palette.test.ts +0 -123
  87. package/apps/studio/draw/test/primitives.test.ts +0 -129
  88. package/apps/studio/draw/test/serialize-animate.test.ts +0 -142
  89. package/apps/studio/draw/test/serialize.test.ts +0 -105
  90. package/apps/studio/figma/assets.test.ts +0 -464
  91. package/apps/studio/figma/client.test.ts +0 -395
  92. package/apps/studio/figma/codegen-client.test.ts +0 -276
  93. package/apps/studio/figma/codegen-fonts.test.ts +0 -103
  94. package/apps/studio/figma/codegen-values.test.ts +0 -179
  95. package/apps/studio/figma/comments-to-strokes.test.ts +0 -194
  96. package/apps/studio/figma/fig-decode.test.ts +0 -788
  97. package/apps/studio/figma/fig-differential.test.ts +0 -182
  98. package/apps/studio/figma/fig-translator.test.ts +0 -192
  99. package/apps/studio/figma/fig-vector.test.ts +0 -113
  100. package/apps/studio/figma/from-codegen.test.ts +0 -408
  101. package/apps/studio/figma/sanitize.test.ts +0 -325
  102. package/apps/studio/figma/tailwind-map.test.ts +0 -142
  103. package/apps/studio/figma/to-artboard.test.ts +0 -808
  104. package/apps/studio/figma/to-render.test.ts +0 -180
  105. package/apps/studio/figma/to-strokes-roundtrip.test.ts +0 -152
  106. package/apps/studio/figma/to-strokes.test.ts +0 -705
  107. package/apps/studio/figma/to-tokens.test.ts +0 -321
  108. package/apps/studio/figma/url.test.ts +0 -167
  109. package/apps/studio/footage/schema.test.ts +0 -287
  110. package/apps/studio/generation/adapters/groq.test.ts +0 -80
  111. package/apps/studio/generation/audio-library.test.ts +0 -95
  112. package/apps/studio/generation/captions.test.ts +0 -78
  113. package/apps/studio/generation/elevenlabs.test.ts +0 -223
  114. package/apps/studio/generation/gemini.test.ts +0 -350
  115. package/apps/studio/generation/jobs.test.ts +0 -128
  116. package/apps/studio/generation/keys.test.ts +0 -75
  117. package/apps/studio/generation/prefs.test.ts +0 -95
  118. package/apps/studio/generation/types.test.ts +0 -123
  119. package/apps/studio/generation/whisper-models.test.ts +0 -179
  120. package/apps/studio/test/_helpers.ts +0 -108
  121. package/apps/studio/test/acp-activity-endpoint.test.ts +0 -183
  122. package/apps/studio/test/acp-activity.test.ts +0 -154
  123. package/apps/studio/test/acp-ai-activity.test.ts +0 -182
  124. package/apps/studio/test/acp-attachment-serve.test.ts +0 -74
  125. package/apps/studio/test/acp-bootstrap-brief.test.ts +0 -178
  126. package/apps/studio/test/acp-branch-guard.test.ts +0 -123
  127. package/apps/studio/test/acp-bridge-lifetime.test.ts +0 -475
  128. package/apps/studio/test/acp-bridge.test.ts +0 -301
  129. package/apps/studio/test/acp-capabilities.test.ts +0 -123
  130. package/apps/studio/test/acp-caps-bridge.test.ts +0 -279
  131. package/apps/studio/test/acp-commands.test.ts +0 -119
  132. package/apps/studio/test/acp-elicitation-bridge.test.ts +0 -480
  133. package/apps/studio/test/acp-elicitation.test.ts +0 -251
  134. package/apps/studio/test/acp-env.test.ts +0 -95
  135. package/apps/studio/test/acp-mode-banner.test.ts +0 -45
  136. package/apps/studio/test/acp-origin-gate.test.ts +0 -160
  137. package/apps/studio/test/acp-permission-prompt.test.ts +0 -251
  138. package/apps/studio/test/acp-permission.test.ts +0 -278
  139. package/apps/studio/test/acp-plugin-bootstrap.test.ts +0 -89
  140. package/apps/studio/test/acp-session-allowed-tools.test.ts +0 -235
  141. package/apps/studio/test/acp-session-plugins.test.ts +0 -209
  142. package/apps/studio/test/acp-toolgroup.test.ts +0 -76
  143. package/apps/studio/test/acp-transcript-view.test.ts +0 -71
  144. package/apps/studio/test/acp-transcript.test.ts +0 -238
  145. package/apps/studio/test/acp-usage-bridge.test.ts +0 -141
  146. package/apps/studio/test/acp-usage.test.ts +0 -143
  147. package/apps/studio/test/acp-write-gate.test.ts +0 -323
  148. package/apps/studio/test/acp-write-scope.test.ts +0 -533
  149. package/apps/studio/test/active-state.test.ts +0 -186
  150. package/apps/studio/test/activity.test.ts +0 -189
  151. package/apps/studio/test/ai-activity.test.ts +0 -113
  152. package/apps/studio/test/annotate-write.test.ts +0 -1074
  153. package/apps/studio/test/annotation-strokes-command.test.ts +0 -166
  154. package/apps/studio/test/annotations-align.test.ts +0 -88
  155. package/apps/studio/test/annotations-api.test.ts +0 -145
  156. package/apps/studio/test/annotations-bindings.test.ts +0 -262
  157. package/apps/studio/test/annotations-draw-modifiers.test.ts +0 -206
  158. package/apps/studio/test/annotations-groups.test.ts +0 -231
  159. package/apps/studio/test/annotations-layer.test.ts +0 -1011
  160. package/apps/studio/test/annotations-roundtrip.test.ts +0 -663
  161. package/apps/studio/test/annotations-snap.test.ts +0 -135
  162. package/apps/studio/test/annotations-text-format.test.ts +0 -396
  163. package/apps/studio/test/artboard-activity-overlay.test.tsx +0 -56
  164. package/apps/studio/test/artboard-guides-overlay.test.tsx +0 -152
  165. package/apps/studio/test/artboard-hug-commit.test.ts +0 -36
  166. package/apps/studio/test/artboard-kinds.test.tsx +0 -83
  167. package/apps/studio/test/artboard-selection-attrs.test.ts +0 -69
  168. package/apps/studio/test/asset-api.test.ts +0 -149
  169. package/apps/studio/test/assets-s3.test.ts +0 -249
  170. package/apps/studio/test/binary-smoke.test.ts +0 -47
  171. package/apps/studio/test/boot-self-heal.test.ts +0 -87
  172. package/apps/studio/test/browse-posture.test.tsx +0 -107
  173. package/apps/studio/test/bundle-smoke.test.ts +0 -46
  174. package/apps/studio/test/camera-reveal.test.tsx +0 -173
  175. package/apps/studio/test/canvas-artifacts.test.ts +0 -125
  176. package/apps/studio/test/canvas-build-sandbox.test.ts +0 -69
  177. package/apps/studio/test/canvas-build.test.ts +0 -141
  178. package/apps/studio/test/canvas-create-api.test.ts +0 -676
  179. package/apps/studio/test/canvas-cursors.test.ts +0 -164
  180. package/apps/studio/test/canvas-edit.test.ts +0 -470
  181. package/apps/studio/test/canvas-freshness-deps.test.ts +0 -64
  182. package/apps/studio/test/canvas-header.test.ts +0 -127
  183. package/apps/studio/test/canvas-hide-chrome.test.ts +0 -88
  184. package/apps/studio/test/canvas-hmr-runtime.test.tsx +0 -114
  185. package/apps/studio/test/canvas-lib-inline.test.ts +0 -146
  186. package/apps/studio/test/canvas-lib-motion.test.ts +0 -131
  187. package/apps/studio/test/canvas-lib-resolver.test.ts +0 -111
  188. package/apps/studio/test/canvas-list-watch.test.ts +0 -388
  189. package/apps/studio/test/canvas-media-drop.test.ts +0 -187
  190. package/apps/studio/test/canvas-meta-api.test.ts +0 -707
  191. package/apps/studio/test/canvas-move-api.test.ts +0 -587
  192. package/apps/studio/test/canvas-origin-gate.test.ts +0 -417
  193. package/apps/studio/test/canvas-pipeline.test.ts +0 -180
  194. package/apps/studio/test/canvas-rects.test.ts +0 -198
  195. package/apps/studio/test/canvas-reorder.test.ts +0 -211
  196. package/apps/studio/test/canvas-route.test.ts +0 -179
  197. package/apps/studio/test/canvas-shell-base.test.ts +0 -107
  198. package/apps/studio/test/canvas-shell-build-error.test.ts +0 -52
  199. package/apps/studio/test/canvas-url.test.ts +0 -138
  200. package/apps/studio/test/canvas-wheel-delta.test.ts +0 -42
  201. package/apps/studio/test/canvas-zoom-floor.test.ts +0 -73
  202. package/apps/studio/test/capture-core.test.ts +0 -32
  203. package/apps/studio/test/capture-determinism-shape.test.ts +0 -135
  204. package/apps/studio/test/chat-attachments.test.ts +0 -117
  205. package/apps/studio/test/chat-context.test.ts +0 -129
  206. package/apps/studio/test/chat-markdown.test.tsx +0 -58
  207. package/apps/studio/test/clip-addressing.test.ts +0 -738
  208. package/apps/studio/test/clip-ops.test.ts +0 -922
  209. package/apps/studio/test/cloud-build.test.ts +0 -95
  210. package/apps/studio/test/cloud-connect-note.test.ts +0 -135
  211. package/apps/studio/test/cloud-endpoints.test.ts +0 -590
  212. package/apps/studio/test/cloud-history-hardening.test.ts +0 -165
  213. package/apps/studio/test/cloud-history-posture.test.ts +0 -230
  214. package/apps/studio/test/cloud-managed-save-surfaces.test.ts +0 -90
  215. package/apps/studio/test/cloud-renew.test.ts +0 -205
  216. package/apps/studio/test/cloud-session-role.test.ts +0 -161
  217. package/apps/studio/test/cloud-shell-surfaces.test.ts +0 -170
  218. package/apps/studio/test/cold-start-apply.test.ts +0 -303
  219. package/apps/studio/test/collab-annotations-bridge.test.ts +0 -55
  220. package/apps/studio/test/collab-awareness-bridge.test.ts +0 -223
  221. package/apps/studio/test/collab-bridge.test.ts +0 -79
  222. package/apps/studio/test/collab-loopback.test.ts +0 -63
  223. package/apps/studio/test/collab-origin-gate.test.ts +0 -323
  224. package/apps/studio/test/collab-protocol.test.ts +0 -146
  225. package/apps/studio/test/collab-readonly-gate.test.ts +0 -194
  226. package/apps/studio/test/collab-reseed-guard.test.ts +0 -78
  227. package/apps/studio/test/collab-room.test.ts +0 -188
  228. package/apps/studio/test/collab-session-survival.test.tsx +0 -176
  229. package/apps/studio/test/collab-stress.test.ts +0 -129
  230. package/apps/studio/test/comment-mount.test.ts +0 -97
  231. package/apps/studio/test/comment-relay-origin-gate.test.ts +0 -117
  232. package/apps/studio/test/comments-api.test.ts +0 -277
  233. package/apps/studio/test/comments-fs-rebroadcast.test.ts +0 -155
  234. package/apps/studio/test/comments-overlay.test.ts +0 -117
  235. package/apps/studio/test/compile-entry.test.ts +0 -133
  236. package/apps/studio/test/component-map.test.ts +0 -48
  237. package/apps/studio/test/config-projection.test.ts +0 -104
  238. package/apps/studio/test/config-reload.test.ts +0 -230
  239. package/apps/studio/test/config-version.test.ts +0 -88
  240. package/apps/studio/test/context-resolve-tokens.test.ts +0 -97
  241. package/apps/studio/test/convert-to-absolute.test.ts +0 -333
  242. package/apps/studio/test/credential-grammar.test.ts +0 -107
  243. package/apps/studio/test/csp-canvas-shell.test.ts +0 -62
  244. package/apps/studio/test/csrf-write-guard.test.ts +0 -141
  245. package/apps/studio/test/debug-bundle.test.ts +0 -105
  246. package/apps/studio/test/design-setup-readiness.test.ts +0 -155
  247. package/apps/studio/test/detach-component.test.ts +0 -94
  248. package/apps/studio/test/dns-rebinding-guard.test.ts +0 -101
  249. package/apps/studio/test/dom-selection.test.ts +0 -198
  250. package/apps/studio/test/dynamic-text-edit.test.ts +0 -162
  251. package/apps/studio/test/edit-css-occurrence.test.ts +0 -81
  252. package/apps/studio/test/edit-persistence.test.ts +0 -91
  253. package/apps/studio/test/edit-scope-api.test.ts +0 -119
  254. package/apps/studio/test/edit-source-command.test.ts +0 -142
  255. package/apps/studio/test/edit-suppress.test.ts +0 -170
  256. package/apps/studio/test/editing-presence.test.ts +0 -103
  257. package/apps/studio/test/element-resize.test.ts +0 -136
  258. package/apps/studio/test/element-structural-api.test.ts +0 -434
  259. package/apps/studio/test/element-structural-edit.test.ts +0 -750
  260. package/apps/studio/test/ensure-browser.test.ts +0 -92
  261. package/apps/studio/test/equal-spacing-detector.test.ts +0 -257
  262. package/apps/studio/test/export-assemble.test.ts +0 -53
  263. package/apps/studio/test/export-browser-lane.test.ts +0 -126
  264. package/apps/studio/test/export-capture-fidelity.test.ts +0 -146
  265. package/apps/studio/test/export-capture-hygiene.test.ts +0 -675
  266. package/apps/studio/test/export-center.test.tsx +0 -287
  267. package/apps/studio/test/export-e2e-lanes.test.ts +0 -857
  268. package/apps/studio/test/export-format-scope-coherence.test.ts +0 -89
  269. package/apps/studio/test/export-lane.test.ts +0 -245
  270. package/apps/studio/test/export-shim-multi-capture.test.ts +0 -83
  271. package/apps/studio/test/exporters/canva.test.ts +0 -63
  272. package/apps/studio/test/exporters/degraded-propagation.test.ts +0 -123
  273. package/apps/studio/test/exporters/endpoint.test.ts +0 -121
  274. package/apps/studio/test/exporters/history.test.ts +0 -107
  275. package/apps/studio/test/exporters/html.test.ts +0 -26
  276. package/apps/studio/test/exporters/jobs.test.ts +0 -342
  277. package/apps/studio/test/exporters/pdf.test.ts +0 -85
  278. package/apps/studio/test/exporters/png.test.ts +0 -103
  279. package/apps/studio/test/exporters/pptx-deck.test.ts +0 -112
  280. package/apps/studio/test/exporters/pptx.test.ts +0 -31
  281. package/apps/studio/test/exporters/pw-launch.test.ts +0 -49
  282. package/apps/studio/test/exporters/runtime.test.ts +0 -59
  283. package/apps/studio/test/exporters/scope.test.ts +0 -292
  284. package/apps/studio/test/exporters/svg.test.ts +0 -29
  285. package/apps/studio/test/exporters/unsupported-media.test.ts +0 -123
  286. package/apps/studio/test/exporters/zip.test.ts +0 -104
  287. package/apps/studio/test/fetch-asset-gate.test.ts +0 -189
  288. package/apps/studio/test/figjam-v3-model.test.ts +0 -342
  289. package/apps/studio/test/figma-explode.test.ts +0 -438
  290. package/apps/studio/test/figma-provenance.test.ts +0 -108
  291. package/apps/studio/test/figma-routes.test.ts +0 -294
  292. package/apps/studio/test/file-lock.test.ts +0 -84
  293. package/apps/studio/test/fixtures/fake-claude-auth.mjs +0 -13
  294. package/apps/studio/test/fixtures/figjam-v3-groups-bindings.svg +0 -1
  295. package/apps/studio/test/fixtures/mock-acp-agent-caps.mjs +0 -158
  296. package/apps/studio/test/fixtures/mock-acp-agent-commands.mjs +0 -44
  297. package/apps/studio/test/fixtures/mock-acp-agent-elicit-flood.mjs +0 -46
  298. package/apps/studio/test/fixtures/mock-acp-agent-elicit-url.mjs +0 -42
  299. package/apps/studio/test/fixtures/mock-acp-agent-elicit.mjs +0 -63
  300. package/apps/studio/test/fixtures/mock-acp-agent-permission-flood.mjs +0 -51
  301. package/apps/studio/test/fixtures/mock-acp-agent-permission.mjs +0 -50
  302. package/apps/studio/test/fixtures/mock-acp-agent-slow.mjs +0 -45
  303. package/apps/studio/test/fixtures/mock-acp-agent-usage.mjs +0 -56
  304. package/apps/studio/test/fixtures/mock-acp-agent-wedged.mjs +0 -37
  305. package/apps/studio/test/fixtures/mock-acp-agent-write.mjs +0 -118
  306. package/apps/studio/test/fixtures/mock-acp-agent.mjs +0 -69
  307. package/apps/studio/test/fixtures/perf-canvas.mjs +0 -201
  308. package/apps/studio/test/fixtures/phase-20-annotations.svg +0 -1
  309. package/apps/studio/test/fixtures/phase-21-annotations.svg +0 -1
  310. package/apps/studio/test/fixtures/tiny-subset.woff2 +0 -0
  311. package/apps/studio/test/fixtures/video-comp-fixture.tsx +0 -82
  312. package/apps/studio/test/footage-store.test.ts +0 -100
  313. package/apps/studio/test/fs-mkdir-api.test.ts +0 -248
  314. package/apps/studio/test/fs-watch.test.ts +0 -41
  315. package/apps/studio/test/gemma-models.test.ts +0 -245
  316. package/apps/studio/test/generate-route.test.ts +0 -106
  317. package/apps/studio/test/git-api.test.ts +0 -0
  318. package/apps/studio/test/git-branches.test.ts +0 -341
  319. package/apps/studio/test/git-cloud-posture.test.ts +0 -59
  320. package/apps/studio/test/git-grouping.test.ts +0 -106
  321. package/apps/studio/test/git-lifecycle.test.ts +0 -100
  322. package/apps/studio/test/git-log-format.test.ts +0 -95
  323. package/apps/studio/test/git-safe-rel.test.ts +0 -132
  324. package/apps/studio/test/git-system-engine.test.ts +0 -135
  325. package/apps/studio/test/git-watch.test.ts +0 -97
  326. package/apps/studio/test/github-api.test.ts +0 -577
  327. package/apps/studio/test/grid-track-handles.test.ts +0 -160
  328. package/apps/studio/test/handoff-static-frames.test.ts +0 -215
  329. package/apps/studio/test/handoff.test.ts +0 -329
  330. package/apps/studio/test/history-rollback.test.ts +0 -88
  331. package/apps/studio/test/hmr-broadcast.test.ts +0 -236
  332. package/apps/studio/test/hmr-classify.test.ts +0 -87
  333. package/apps/studio/test/hub-link.test.ts +0 -80
  334. package/apps/studio/test/identity-cache.test.ts +0 -83
  335. package/apps/studio/test/import-asset-browser.test.ts +0 -64
  336. package/apps/studio/test/import-asset-route.test.ts +0 -71
  337. package/apps/studio/test/import-asset.test.ts +0 -427
  338. package/apps/studio/test/import-brand-browser.test.ts +0 -88
  339. package/apps/studio/test/import-brand-route.test.ts +0 -120
  340. package/apps/studio/test/import-brand.test.ts +0 -206
  341. package/apps/studio/test/import-figma.test.ts +0 -667
  342. package/apps/studio/test/import-tokens.test.ts +0 -722
  343. package/apps/studio/test/index-data-canvas-ds.test.ts +0 -97
  344. package/apps/studio/test/input-router.test.ts +0 -757
  345. package/apps/studio/test/inspect-script-syntax.test.ts +0 -53
  346. package/apps/studio/test/inspect-selections.test.ts +0 -219
  347. package/apps/studio/test/knob-props-authored.test.ts +0 -87
  348. package/apps/studio/test/layers-synthetic-groups.test.ts +0 -96
  349. package/apps/studio/test/locator.test.ts +0 -214
  350. package/apps/studio/test/marquee-overlay.test.ts +0 -94
  351. package/apps/studio/test/media-commit-chain.test.ts +0 -210
  352. package/apps/studio/test/mode-toggle.test.tsx +0 -226
  353. package/apps/studio/test/motion-sample.test.ts +0 -35
  354. package/apps/studio/test/move-artboards-command.test.ts +0 -108
  355. package/apps/studio/test/participants-chrome.test.ts +0 -65
  356. package/apps/studio/test/paths.test.ts +0 -88
  357. package/apps/studio/test/pdf-print-boxes.test.ts +0 -359
  358. package/apps/studio/test/peer-selection-follows-camera.test.tsx +0 -131
  359. package/apps/studio/test/perf-harness.ts +0 -193
  360. package/apps/studio/test/phase-3.6-smoke.test.ts +0 -79
  361. package/apps/studio/test/photo-bg-remove-validation.test.ts +0 -71
  362. package/apps/studio/test/photo-canvas-bundle.test.ts +0 -79
  363. package/apps/studio/test/photo-edit-api.test.ts +0 -201
  364. package/apps/studio/test/photo-filters.test.ts +0 -149
  365. package/apps/studio/test/photo-pipeline.test.ts +0 -106
  366. package/apps/studio/test/photo-taxonomy.test.ts +0 -96
  367. package/apps/studio/test/print-marks.test.ts +0 -113
  368. package/apps/studio/test/print-units.test.ts +0 -173
  369. package/apps/studio/test/read-annotations.test.ts +0 -727
  370. package/apps/studio/test/read-only-gate.test.ts +0 -188
  371. package/apps/studio/test/read-only-role.test.ts +0 -95
  372. package/apps/studio/test/readiness.test.ts +0 -226
  373. package/apps/studio/test/remote-ahead-behind-cache.test.ts +0 -89
  374. package/apps/studio/test/reorder-api.test.ts +0 -210
  375. package/apps/studio/test/repo-concurrency.test.ts +0 -146
  376. package/apps/studio/test/repo-lock.test.ts +0 -350
  377. package/apps/studio/test/report-proxy.test.ts +0 -125
  378. package/apps/studio/test/ripple.test.ts +0 -197
  379. package/apps/studio/test/runtime-bundle-error-mapping.test.ts +0 -43
  380. package/apps/studio/test/runtime-bundle.test.ts +0 -69
  381. package/apps/studio/test/sanitize-annotation-svg.test.ts +0 -238
  382. package/apps/studio/test/scaffold-design.test.ts +0 -122
  383. package/apps/studio/test/server-lifecycle.test.ts +0 -38
  384. package/apps/studio/test/session-runtime-state.test.ts +0 -226
  385. package/apps/studio/test/session-scope.test.ts +0 -100
  386. package/apps/studio/test/shared-doc-cell-pairing.test.ts +0 -642
  387. package/apps/studio/test/shared-doc-convergence.test.ts +0 -265
  388. package/apps/studio/test/shared-doc-foundation.test.ts +0 -63
  389. package/apps/studio/test/shared-doc-migrate.test.ts +0 -369
  390. package/apps/studio/test/shared-doc-projection.test.ts +0 -238
  391. package/apps/studio/test/shell-importmap.test.ts +0 -56
  392. package/apps/studio/test/sizing-mode.test.ts +0 -102
  393. package/apps/studio/test/slash-commands.test.ts +0 -117
  394. package/apps/studio/test/snap-distance-pill.test.ts +0 -68
  395. package/apps/studio/test/spacing-handles.test.ts +0 -138
  396. package/apps/studio/test/specimen-select.test.ts +0 -88
  397. package/apps/studio/test/sync-agent.test.ts +0 -660
  398. package/apps/studio/test/sync-annotations-cold-start.test.ts +0 -302
  399. package/apps/studio/test/sync-asset-push.test.ts +0 -931
  400. package/apps/studio/test/sync-atomic-write.test.ts +0 -62
  401. package/apps/studio/test/sync-attach-incremental.test.ts +0 -527
  402. package/apps/studio/test/sync-autocommit.test.ts +0 -537
  403. package/apps/studio/test/sync-canvas-path.test.ts +0 -200
  404. package/apps/studio/test/sync-cell-write-nudge.test.ts +0 -346
  405. package/apps/studio/test/sync-codec.test.ts +0 -230
  406. package/apps/studio/test/sync-cold-seed-dedup.test.ts +0 -187
  407. package/apps/studio/test/sync-cold-start.test.ts +0 -304
  408. package/apps/studio/test/sync-connect-honesty.test.ts +0 -114
  409. package/apps/studio/test/sync-connection-state.test.ts +0 -337
  410. package/apps/studio/test/sync-ctl-channel.test.ts +0 -508
  411. package/apps/studio/test/sync-decide-file.test.ts +0 -420
  412. package/apps/studio/test/sync-doc-name.test.ts +0 -281
  413. package/apps/studio/test/sync-echo-guard.test.ts +0 -96
  414. package/apps/studio/test/sync-file-ledger.test.ts +0 -334
  415. package/apps/studio/test/sync-file-membership.test.ts +0 -347
  416. package/apps/studio/test/sync-file-plane.test.ts +0 -976
  417. package/apps/studio/test/sync-file-pull.test.ts +0 -333
  418. package/apps/studio/test/sync-fresh-link-parity.test.ts +0 -267
  419. package/apps/studio/test/sync-fs-mirror.test.ts +0 -181
  420. package/apps/studio/test/sync-hardening.test.ts +0 -586
  421. package/apps/studio/test/sync-hub-listing.test.ts +0 -46
  422. package/apps/studio/test/sync-hubs-config.test.ts +0 -133
  423. package/apps/studio/test/sync-incident-replay.test.ts +0 -211
  424. package/apps/studio/test/sync-journal.test.ts +0 -176
  425. package/apps/studio/test/sync-meta-codec.test.ts +0 -199
  426. package/apps/studio/test/sync-migrate-flat-fallback.test.ts +0 -98
  427. package/apps/studio/test/sync-move-retirement.test.ts +0 -231
  428. package/apps/studio/test/sync-panel-surface.test.ts +0 -153
  429. package/apps/studio/test/sync-path-pull.test.ts +0 -531
  430. package/apps/studio/test/sync-presentation.test.ts +0 -262
  431. package/apps/studio/test/sync-pull-budget.test.ts +0 -169
  432. package/apps/studio/test/sync-remote-docs.test.ts +0 -333
  433. package/apps/studio/test/sync-resync-routes.test.ts +0 -168
  434. package/apps/studio/test/sync-runtime.test.ts +0 -1675
  435. package/apps/studio/test/sync-seed-defers-to-hub.test.ts +0 -83
  436. package/apps/studio/test/sync-settings-routes.test.ts +0 -195
  437. package/apps/studio/test/sync-settings.test.ts +0 -151
  438. package/apps/studio/test/sync-status.test.ts +0 -261
  439. package/apps/studio/test/sync-supervisor.test.ts +0 -262
  440. package/apps/studio/test/sync-tombstone-apply.test.ts +0 -111
  441. package/apps/studio/test/sync-trash.test.ts +0 -132
  442. package/apps/studio/test/sync-two-peer-discovery.test.ts +0 -343
  443. package/apps/studio/test/sync-untrusted.test.ts +0 -103
  444. package/apps/studio/test/system-endpoint.test.ts +0 -144
  445. package/apps/studio/test/text-editability-stamp.test.ts +0 -131
  446. package/apps/studio/test/timeline-comp-target.test.ts +0 -139
  447. package/apps/studio/test/timeline-media-cache.test.ts +0 -41
  448. package/apps/studio/test/timeline-parse.test.ts +0 -184
  449. package/apps/studio/test/timeline-scale.test.ts +0 -65
  450. package/apps/studio/test/timeline-snap.test.ts +0 -85
  451. package/apps/studio/test/tool-palette-insert-anchor.test.ts +0 -86
  452. package/apps/studio/test/tool-palette.test.tsx +0 -55
  453. package/apps/studio/test/tour-overlay.test.tsx +0 -90
  454. package/apps/studio/test/trusted-request-host.test.ts +0 -66
  455. package/apps/studio/test/undo-sequence-byte-compare.test.ts +0 -211
  456. package/apps/studio/test/undo-stack.test.ts +0 -244
  457. package/apps/studio/test/use-agent-presence.test.tsx +0 -117
  458. package/apps/studio/test/use-annotation-resize.test.ts +0 -402
  459. package/apps/studio/test/use-annotation-selection.test.tsx +0 -77
  460. package/apps/studio/test/use-artboard-drag.test.ts +0 -324
  461. package/apps/studio/test/use-canvas-activity.test.tsx +0 -206
  462. package/apps/studio/test/use-collab.test.ts +0 -0
  463. package/apps/studio/test/use-cursor-modifiers.test.ts +0 -59
  464. package/apps/studio/test/use-keyboard-discipline.test.ts +0 -27
  465. package/apps/studio/test/use-selection-set.test.tsx +0 -166
  466. package/apps/studio/test/use-snap-guides.test.ts +0 -271
  467. package/apps/studio/test/use-tool-mode.test.tsx +0 -186
  468. package/apps/studio/test/use-undo-stack.test.tsx +0 -223
  469. package/apps/studio/test/video-asset.test.ts +0 -163
  470. package/apps/studio/test/video-comp-fixture.test.ts +0 -50
  471. package/apps/studio/test/video-comp.test.ts +0 -270
  472. package/apps/studio/test/video-encode-lib.test.ts +0 -63
  473. package/apps/studio/test/video-render-bridge.test.ts +0 -171
  474. package/apps/studio/test/whats-new.test.ts +0 -113
  475. package/apps/studio/test/whisper-setup.test.ts +0 -97
  476. package/apps/studio/test/workspace-containment.test.ts +0 -382
  477. package/apps/studio/test/workspace-signin.test.ts +0 -292
  478. package/apps/studio/test/ws-handshake.test.ts +0 -33
  479. package/cli/commands/cache.test.mjs +0 -166
  480. package/cli/commands/design-link.test.mjs +0 -419
  481. package/cli/commands/design.test.mjs +0 -240
  482. package/cli/commands/doctor.test.mjs +0 -237
  483. package/cli/commands/hub-workspace.test.mjs +0 -275
  484. package/cli/commands/hub.test.mjs +0 -225
  485. package/cli/commands/kg.test.mjs +0 -142
  486. package/cli/commands/preflight.test.mjs +0 -46
  487. package/cli/lib/argv.test.mjs +0 -46
  488. package/cli/lib/cache.test.mjs +0 -303
  489. package/cli/lib/cell-plan.test.mjs +0 -225
  490. package/cli/lib/config-lint.test.mjs +0 -117
  491. package/cli/lib/ddr-to-kgai.test.mjs +0 -118
  492. package/cli/lib/design-ownership.test.mjs +0 -329
  493. package/cli/lib/fetch-asset.test.mjs +0 -213
  494. package/cli/lib/figma-codegen-reachability.test.mjs +0 -104
  495. package/cli/lib/figma-import-controls.test.mjs +0 -70
  496. package/cli/lib/flow-design-integration.test.mjs +0 -165
  497. package/cli/lib/gitignore-block.test.mjs +0 -136
  498. package/cli/lib/gitignore-drift.test.mjs +0 -156
  499. package/cli/lib/hubs-config.test.mjs +0 -165
  500. package/cli/lib/pkg-root.test.mjs +0 -111
  501. package/cli/lib/plugin-cli-reachability.test.mjs +0 -57
  502. package/cli/lib/plugin-name-namespace.test.mjs +0 -71
  503. package/cli/lib/reconstruct-toolset.test.mjs +0 -194
  504. package/cli/lib/stack-detect.test.mjs +0 -121
  505. package/cli/lib/update-check.test.mjs +0 -32
  506. package/cli/lib/workspace-plan.test.mjs +0 -699
@@ -0,0 +1,1296 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import {
4
+ chmod,
5
+ link,
6
+ lstat,
7
+ mkdir,
8
+ open,
9
+ readdir,
10
+ realpath,
11
+ rename,
12
+ rm,
13
+ stat,
14
+ unlink,
15
+ } from 'node:fs/promises';
16
+ import { homedir } from 'node:os';
17
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
18
+
19
+ import { parse as parseToml } from '@decimalturn/toml-patch';
20
+
21
+ import {
22
+ HARNESS_MANIFEST_SCHEMA_VERSION,
23
+ unsupportedManifestSchemaMessage,
24
+ } from './compatibility.mjs';
25
+ import { classifyCredential, sanitizeUntrustedText } from './secrets.mjs';
26
+
27
+ export const MANIFEST_SCHEMA_VERSION = HARNESS_MANIFEST_SCHEMA_VERSION;
28
+ const JOURNAL_SCHEMA_VERSION = 1;
29
+ const SAFE_TARGETS = new Set(['codex', 'opencode']);
30
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
31
+ const HASH = /^sha256:[a-f0-9]{64}$/;
32
+
33
+ export class ScopeLockError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = 'LockError';
37
+ }
38
+ }
39
+
40
+ export class RemovalInterruptedError extends Error {
41
+ constructor(failpoint) {
42
+ super(`simulated removal interruption at ${failpoint}`);
43
+ this.name = 'RemovalInterruptedError';
44
+ }
45
+ }
46
+
47
+ export function removalInterruptionFailpoint(expected) {
48
+ return async (actual) => {
49
+ if (actual === expected) throw new RemovalInterruptedError(actual);
50
+ };
51
+ }
52
+
53
+ export async function manifestPaths({
54
+ projectRoot,
55
+ scope,
56
+ stateRoot = join(homedir(), '.config', 'maude', 'harness'),
57
+ }) {
58
+ if (scope !== 'global' && scope !== 'project') throw new Error(`invalid harness scope: ${scope}`);
59
+ const canonicalStateRoot = await ensureCanonicalDirectoryTree(stateRoot, 'harness state root');
60
+ const canonicalRoot =
61
+ scope === 'project' ? await canonicalExistingDirectory(projectRoot, 'project root') : null;
62
+ const rootHash = hashBytes(canonicalRoot ?? 'global');
63
+ const scopeDir = join(canonicalStateRoot, scope === 'global' ? 'global' : rootHash.slice(7));
64
+ return {
65
+ backupDir: join(scopeDir, 'backups'),
66
+ canonicalRoot,
67
+ lockPath: join(scopeDir, 'transaction.lock'),
68
+ manifestPath: join(scopeDir, 'manifest.json'),
69
+ rootHash,
70
+ scopeDir,
71
+ stateRoot: canonicalStateRoot,
72
+ };
73
+ }
74
+
75
+ export function createManifest({
76
+ capabilitySummary = {},
77
+ generationId,
78
+ outputs,
79
+ rootHash,
80
+ sourceHashes = {},
81
+ targetVersions = {},
82
+ }) {
83
+ if (!generationId || !rootHash || !Array.isArray(outputs)) {
84
+ throw new Error('manifest requires generationId, rootHash, and outputs');
85
+ }
86
+ return {
87
+ schemaVersion: MANIFEST_SCHEMA_VERSION,
88
+ generationId,
89
+ rootHash,
90
+ sourceHashes: sortObject(sourceHashes),
91
+ outputs: [...outputs].sort((left, right) => left.path.localeCompare(right.path)),
92
+ targetVersions: sortObject(targetVersions),
93
+ capabilitySummary: sortObject(capabilitySummary),
94
+ };
95
+ }
96
+
97
+ export async function readManifest(paths) {
98
+ try {
99
+ await assertCanonicalPrivateScope(paths.scopeDir, { create: false });
100
+ } catch (error) {
101
+ if (error.code === 'ENOENT') return null;
102
+ throw error;
103
+ }
104
+ let bytes;
105
+ try {
106
+ bytes = (await readFileNoFollow(paths.manifestPath)).toString('utf8');
107
+ } catch (error) {
108
+ if (error.code === 'ENOENT') return null;
109
+ throw error;
110
+ }
111
+ let manifest;
112
+ try {
113
+ manifest = JSON.parse(bytes);
114
+ } catch (error) {
115
+ throw new Error(`invalid harness manifest ${paths.manifestPath}: ${error.message}`);
116
+ }
117
+ if (manifest?.schemaVersion !== MANIFEST_SCHEMA_VERSION) {
118
+ throw new Error(
119
+ unsupportedManifestSchemaMessage(paths.manifestPath, manifest?.schemaVersion ?? 'missing')
120
+ );
121
+ }
122
+ if (!Array.isArray(manifest.outputs)) {
123
+ throw new Error(`invalid harness manifest outputs in ${paths.manifestPath}`);
124
+ }
125
+ return manifest;
126
+ }
127
+
128
+ export async function writeManifest(paths, manifest) {
129
+ await assertCanonicalPrivateScope(paths.scopeDir, { create: true });
130
+ await atomicWrite(paths.manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 0o600);
131
+ }
132
+
133
+ export async function hashFile(path) {
134
+ return hashBytes(await readNoFollow(path));
135
+ }
136
+
137
+ export async function adoptManagedPath({ allowRoots, confirm = false, path, paths, target }) {
138
+ if (!SAFE_TARGETS.has(target)) throw new Error(`invalid harness target identifier: ${target}`);
139
+ const checkedPath = await assertAllowedPath(path, allowRoots, { mustExist: true });
140
+ const info = await lstat(checkedPath);
141
+ if (!info.isFile()) throw new Error(`adoption requires a regular file: ${checkedPath}`);
142
+ const bytes = await readNoFollow(checkedPath);
143
+ if (containsRawCredential(bytes.toString('utf8'), checkedPath)) {
144
+ throw new Error(`refusing to back up a literal credential from ${checkedPath}`);
145
+ }
146
+ const hash = hashBytes(bytes);
147
+ if (!confirm) return { action: 'preview', hash, path: checkedPath, target };
148
+
149
+ await assertCanonicalPrivateScope(paths.scopeDir, { create: true });
150
+ await ensurePrivateChildDirectory(paths.backupDir, paths.scopeDir, 'machine-local backup');
151
+ const backupPath = join(
152
+ paths.backupDir,
153
+ `${target}-${createHash('sha256').update(checkedPath).digest('hex')}.backup`
154
+ );
155
+ let createdBackup = false;
156
+ try {
157
+ const existingHash = await hashFile(backupPath);
158
+ if (existingHash !== hash) throw new Error(`adoption backup already exists: ${backupPath}`);
159
+ } catch (error) {
160
+ if (error.code !== 'ENOENT') throw error;
161
+ try {
162
+ await writeExclusive(backupPath, bytes, 0o600);
163
+ await syncDirectory(paths.backupDir);
164
+ createdBackup = true;
165
+ } catch (writeError) {
166
+ if (writeError.code !== 'EEXIST' || (await hashFile(backupPath)) !== hash) throw writeError;
167
+ }
168
+ }
169
+ if ((await hashFile(checkedPath)) !== hash) {
170
+ if (createdBackup) await unlink(backupPath);
171
+ throw new Error(`adoption target changed while being backed up: ${checkedPath}`);
172
+ }
173
+ return {
174
+ action: 'adopted',
175
+ backupHash: hash,
176
+ backupPath,
177
+ hash,
178
+ ownership: 'adopted',
179
+ originalMode: info.mode & 0o777,
180
+ path: checkedPath,
181
+ target,
182
+ };
183
+ }
184
+
185
+ export async function assertManagedOutputsUnmodified(outputs, { allowRoots } = {}) {
186
+ for (const output of outputs) {
187
+ if (allowRoots) await assertAllowedPath(output.path, allowRoots, { mustExist: true });
188
+ let currentHash;
189
+ try {
190
+ currentHash = await hashFile(output.path);
191
+ } catch (error) {
192
+ if (error.code === 'ENOENT') throw new Error(`managed output is missing: ${output.path}`);
193
+ throw error;
194
+ }
195
+ if (currentHash !== output.hash) {
196
+ throw new Error(`managed output was externally modified: ${output.path}`);
197
+ }
198
+ }
199
+ }
200
+
201
+ export async function removeManagedOutputs({
202
+ allowRoots,
203
+ backupRoots,
204
+ failpoint = async () => {},
205
+ outputs,
206
+ scopeDir,
207
+ }) {
208
+ await assertCanonicalPrivateScope(scopeDir, { create: true });
209
+ const releaseLock = await acquireScopeLock(scopeDir);
210
+ const parentPins = new Map();
211
+ let journal;
212
+ try {
213
+ await recoverRemovalJournal({ allowRoots, backupRoots, parentPins, scopeDir });
214
+ await assertManagedOutputsUnmodified(outputs, { allowRoots });
215
+ const transactionId = randomUUID();
216
+ const entries = [];
217
+ for (let index = 0; index < outputs.length; index += 1) {
218
+ const output = outputs[index];
219
+ const parent = dirname(output.path);
220
+ if (!parentPins.has(parent)) {
221
+ parentPins.set(parent, await pinAllowedParent(output.path, allowRoots));
222
+ }
223
+ const parentPin = parentPins.get(parent);
224
+ await failpoint(`after-remove-parent-pin:${index}`);
225
+ await failpoint(`before-remove-inspect:${index}`);
226
+ const current = await inspectRegularFile(pinnedChildPath(parentPin, output.path));
227
+ if (current.hash !== output.hash) {
228
+ throw new Error(`managed output was externally modified during removal: ${output.path}`);
229
+ }
230
+ if (output.ownership !== 'generated' && output.ownership !== 'adopted') {
231
+ throw new Error(`invalid managed ownership for ${output.path}`);
232
+ }
233
+ let stagePath = null;
234
+ let restoreHash = null;
235
+ if (output.ownership === 'adopted') {
236
+ await assertBackup(output, backupRoots);
237
+ stagePath = artifactPath(output.path, 'remove-stage', transactionId, index);
238
+ const backup = await readNoFollow(output.backupPath);
239
+ await writeExclusive(pinnedChildPath(parentPin, stagePath), backup, 0o600);
240
+ restoreHash = output.backupHash;
241
+ }
242
+ entries.push({
243
+ claimPath: artifactPath(output.path, 'remove-claim', transactionId, index),
244
+ backupPath: output.ownership === 'adopted' ? output.backupPath : null,
245
+ claimed: false,
246
+ claiming: false,
247
+ discardPath: artifactPath(output.path, 'remove-discard', transactionId, index),
248
+ index,
249
+ installed: false,
250
+ installing: false,
251
+ originalHash: current.hash,
252
+ originalMode: current.mode,
253
+ ownership: output.ownership,
254
+ path: output.path,
255
+ restoreHash,
256
+ restoreMode: output.originalMode ?? 0o600,
257
+ stagePath,
258
+ });
259
+ }
260
+ journal = {
261
+ entries,
262
+ phase: 'prepared',
263
+ schemaVersion: JOURNAL_SCHEMA_VERSION,
264
+ transactionId,
265
+ };
266
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
267
+ journal.phase = 'removing';
268
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
269
+ for (const entry of entries) {
270
+ entry.claiming = true;
271
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
272
+ const parentPin = parentPins.get(dirname(entry.path));
273
+ await claimExistingFile(entry, allowRoots, parentPin);
274
+ entry.claimed = true;
275
+ entry.claiming = false;
276
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
277
+ if (entry.ownership === 'adopted') {
278
+ entry.installing = true;
279
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
280
+ await installNoClobber(
281
+ entry.stagePath,
282
+ entry.path,
283
+ entry.restoreHash,
284
+ allowRoots,
285
+ entry.restoreMode,
286
+ parentPin
287
+ );
288
+ entry.installed = true;
289
+ entry.installing = false;
290
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
291
+ }
292
+ await failpoint(`after-remove:${entry.index}`);
293
+ }
294
+ for (const pin of parentPins.values()) await revalidatePinnedParent(pin);
295
+ journal.phase = 'committed';
296
+ await writeDurableJson(join(scopeDir, 'removal.json'), journal);
297
+ await cleanupRemoval(entries, allowRoots, backupRoots, parentPins);
298
+ await unlink(join(scopeDir, 'removal.json'));
299
+ await syncDirectory(scopeDir);
300
+ return { removed: entries.map((entry) => entry.path) };
301
+ } catch (error) {
302
+ if (error instanceof RemovalInterruptedError) throw error;
303
+ let rollbackError;
304
+ try {
305
+ if (journal?.phase === 'committed') {
306
+ await cleanupRemoval(journal.entries, allowRoots, backupRoots, parentPins);
307
+ } else if (journal) {
308
+ await rollbackRemoval(journal.entries, allowRoots, parentPins);
309
+ } else {
310
+ await recoverRemovalJournal({ allowRoots, backupRoots, parentPins, scopeDir });
311
+ }
312
+ if (journal) {
313
+ await unlink(join(scopeDir, 'removal.json'));
314
+ await syncDirectory(scopeDir);
315
+ }
316
+ } catch (recoveryError) {
317
+ rollbackError = recoveryError;
318
+ }
319
+ if (rollbackError) {
320
+ throw new AggregateError(
321
+ [error, rollbackError],
322
+ 'managed removal failed and rollback was incomplete'
323
+ );
324
+ }
325
+ throw error;
326
+ } finally {
327
+ try {
328
+ await closeParentPins(parentPins);
329
+ } finally {
330
+ await releaseLock();
331
+ }
332
+ }
333
+ }
334
+
335
+ export async function recoverManagedRemoval({ allowRoots, backupRoots = [], scopeDir }) {
336
+ await assertCanonicalPrivateScope(scopeDir, { create: false });
337
+ const releaseLock = await acquireScopeLock(scopeDir);
338
+ const parentPins = new Map();
339
+ try {
340
+ return await recoverRemovalJournal({ allowRoots, backupRoots, parentPins, scopeDir });
341
+ } finally {
342
+ try {
343
+ await closeParentPins(parentPins);
344
+ } finally {
345
+ await releaseLock();
346
+ }
347
+ }
348
+ }
349
+
350
+ async function recoverRemovalJournal({ allowRoots, backupRoots = [], parentPins, scopeDir }) {
351
+ const journalPath = join(scopeDir, 'removal.json');
352
+ let journal;
353
+ try {
354
+ journal = JSON.parse((await readFileNoFollow(journalPath)).toString('utf8'));
355
+ } catch (error) {
356
+ if (error.code === 'ENOENT') return { recovered: false };
357
+ throw new Error(`invalid removal journal ${journalPath}: ${error.message}`);
358
+ }
359
+ await validateRemovalJournal(journal, allowRoots, backupRoots, journalPath);
360
+ for (const entry of journal.entries) await removalPinForEntry(entry, allowRoots, parentPins);
361
+ if (journal.phase === 'committed') {
362
+ await cleanupRemoval(journal.entries, allowRoots, backupRoots, parentPins);
363
+ } else {
364
+ await rollbackRemoval(journal.entries, allowRoots, parentPins);
365
+ }
366
+ await unlink(journalPath);
367
+ await syncDirectory(scopeDir);
368
+ return { recovered: true };
369
+ }
370
+
371
+ async function rollbackRemoval(entries, allowRoots, parentPins) {
372
+ for (const entry of [...entries].reverse()) {
373
+ const pin = await removalPinForEntry(entry, allowRoots, parentPins);
374
+ await normalizeInterruptedRemoval(entry, allowRoots, pin);
375
+ if (entry.installed) {
376
+ await removeInstalledNoClobber(entry, entry.restoreHash, allowRoots, pin);
377
+ entry.installed = false;
378
+ }
379
+ if (entry.claimed) {
380
+ await restoreClaimNoClobber(entry, allowRoots, pin);
381
+ entry.claimed = false;
382
+ }
383
+ await cleanupRemovalEntry(entry, allowRoots, pin);
384
+ }
385
+ }
386
+
387
+ async function normalizeInterruptedRemoval(entry, allowRoots, pin) {
388
+ if (entry.claiming && !entry.claimed) {
389
+ const [claim, target] = await Promise.all([
390
+ inspectOptionalFile(pinnedChildPath(pin, entry.claimPath)),
391
+ inspectOptionalFile(pinnedChildPath(pin, entry.path)),
392
+ ]);
393
+ if (claim?.hash === entry.originalHash && target === null) entry.claimed = true;
394
+ else if (claim?.hash === entry.originalHash && target?.hash === entry.originalHash) {
395
+ await unlinkOwnedArtifact(entry.claimPath, allowRoots, pin);
396
+ } else if (claim || target?.hash !== entry.originalHash) {
397
+ throw new Error(`cannot resolve interrupted removal claim: ${entry.path}`);
398
+ }
399
+ entry.claiming = false;
400
+ }
401
+ if (entry.installing && !entry.installed) {
402
+ const target = await inspectOptionalFile(pinnedChildPath(pin, entry.path));
403
+ if (target?.hash === entry.restoreHash) entry.installed = true;
404
+ else if (target !== null)
405
+ throw new Error(`cannot resolve interrupted removal install: ${entry.path}`);
406
+ entry.installing = false;
407
+ }
408
+ }
409
+
410
+ async function cleanupRemoval(entries, allowRoots, backupRoots, parentPins) {
411
+ for (const entry of entries) {
412
+ const pin = await removalPinForEntry(entry, allowRoots, parentPins);
413
+ await cleanupRemovalEntry(entry, allowRoots, pin);
414
+ if (entry.backupPath) await securelyDeleteBackup(entry.backupPath, backupRoots);
415
+ }
416
+ }
417
+
418
+ async function cleanupRemovalEntry(entry, allowRoots, pin) {
419
+ for (const path of [entry.stagePath, entry.claimPath, entry.discardPath].filter(Boolean)) {
420
+ await unlinkOwnedArtifact(path, allowRoots, pin);
421
+ }
422
+ }
423
+
424
+ async function removalPinForEntry(entry, allowRoots, parentPins) {
425
+ const parent = dirname(entry.path);
426
+ if (!parentPins.has(parent)) {
427
+ parentPins.set(parent, await pinAllowedParent(entry.path, allowRoots));
428
+ }
429
+ return parentPins.get(parent);
430
+ }
431
+
432
+ async function validateRemovalJournal(journal, allowRoots, backupRoots, journalPath) {
433
+ if (
434
+ !isPlainObject(journal) ||
435
+ journal.schemaVersion !== JOURNAL_SCHEMA_VERSION ||
436
+ !UUID.test(journal.transactionId) ||
437
+ !exactKeys(journal, ['entries', 'phase', 'schemaVersion', 'transactionId']) ||
438
+ !['prepared', 'removing', 'committed'].includes(journal.phase) ||
439
+ !Array.isArray(journal.entries)
440
+ ) {
441
+ throw new Error(`invalid removal journal ${journalPath}`);
442
+ }
443
+ const paths = new Set();
444
+ for (let index = 0; index < journal.entries.length; index += 1) {
445
+ const entry = journal.entries[index];
446
+ const prefix = `${journal.transactionId}-${index}`;
447
+ if (
448
+ !isPlainObject(entry) ||
449
+ !exactKeys(entry, [
450
+ 'claimPath',
451
+ 'backupPath',
452
+ 'claimed',
453
+ 'claiming',
454
+ 'discardPath',
455
+ 'index',
456
+ 'installed',
457
+ 'installing',
458
+ 'originalHash',
459
+ 'originalMode',
460
+ 'ownership',
461
+ 'path',
462
+ 'restoreHash',
463
+ 'restoreMode',
464
+ 'stagePath',
465
+ ]) ||
466
+ entry.index !== index ||
467
+ typeof entry.claimed !== 'boolean' ||
468
+ typeof entry.claiming !== 'boolean' ||
469
+ typeof entry.installed !== 'boolean' ||
470
+ typeof entry.installing !== 'boolean' ||
471
+ !['generated', 'adopted'].includes(entry.ownership) ||
472
+ !validMode(entry.originalMode) ||
473
+ !validMode(entry.restoreMode) ||
474
+ !HASH.test(entry.originalHash) ||
475
+ (entry.restoreHash !== null && !HASH.test(entry.restoreHash)) ||
476
+ typeof entry.path !== 'string' ||
477
+ paths.has(entry.path)
478
+ ) {
479
+ throw new Error(`invalid removal journal ${journalPath}`);
480
+ }
481
+ paths.add(entry.path);
482
+ if (
483
+ (journal.phase === 'prepared' &&
484
+ (entry.claimed || entry.claiming || entry.installed || entry.installing)) ||
485
+ (journal.phase === 'committed' &&
486
+ (!entry.claimed || (entry.ownership === 'adopted' && !entry.installed))) ||
487
+ (entry.ownership === 'generated' && (entry.installed || entry.installing))
488
+ ) {
489
+ throw new Error(`invalid removal journal state in ${journalPath}`);
490
+ }
491
+ await assertAllowedPath(entry.path, allowRoots);
492
+ validateArtifact(entry.claimPath, entry.path, `remove-claim-${prefix}`, journalPath);
493
+ validateArtifact(entry.discardPath, entry.path, `remove-discard-${prefix}`, journalPath);
494
+ if (entry.ownership === 'adopted') {
495
+ if (typeof entry.backupPath !== 'string') {
496
+ throw new Error(`invalid removal journal ${journalPath}`);
497
+ }
498
+ await assertAllowedPath(entry.backupPath, backupRoots, {
499
+ mustExist: journal.phase !== 'committed',
500
+ });
501
+ validateArtifact(entry.stagePath, entry.path, `remove-stage-${prefix}`, journalPath);
502
+ } else if (
503
+ entry.backupPath !== null ||
504
+ entry.stagePath !== null ||
505
+ entry.restoreHash !== null
506
+ ) {
507
+ throw new Error(`invalid removal journal ${journalPath}`);
508
+ }
509
+ }
510
+ }
511
+
512
+ export async function assertCanonicalPrivateScope(scopeDir, { create }) {
513
+ if (!isAbsolute(scopeDir)) throw new Error(`machine-local scope must be absolute: ${scopeDir}`);
514
+ const expected = resolve(scopeDir);
515
+ if (create) {
516
+ const parent = dirname(expected);
517
+ const canonicalParent = await realpath(parent);
518
+ if (canonicalParent !== parent)
519
+ throw new Error(`machine-local scope parent is not canonical: ${parent}`);
520
+ try {
521
+ await mkdir(expected, { mode: 0o700 });
522
+ } catch (error) {
523
+ if (error.code !== 'EEXIST') throw error;
524
+ }
525
+ }
526
+ const info = await lstat(expected);
527
+ if (info.isSymbolicLink())
528
+ throw new Error(`machine-local scope directory may not be a symlink: ${expected}`);
529
+ if (!info.isDirectory())
530
+ throw new Error(`machine-local scope path is not a directory: ${expected}`);
531
+ if ((info.mode & 0o077) !== 0)
532
+ throw new Error(`machine-local scope directory is not private: ${expected}`);
533
+ if ((await realpath(expected)) !== expected) {
534
+ throw new Error(`machine-local scope directory is not canonical: ${expected}`);
535
+ }
536
+ return expected;
537
+ }
538
+
539
+ export async function assertAllowedPath(
540
+ path,
541
+ allowRoots,
542
+ { allowMissingRoots = false, mustExist = false } = {}
543
+ ) {
544
+ if (!isAbsolute(path)) throw new Error(`managed path must be absolute: ${path}`);
545
+ if (!Array.isArray(allowRoots) || allowRoots.length === 0) {
546
+ throw new Error('at least one allowlisted target root is required');
547
+ }
548
+ const candidate = resolve(path);
549
+ let selectedRoot;
550
+ let validationRoot;
551
+ for (const root of allowRoots) {
552
+ const absoluteRoot = resolve(root);
553
+ let info;
554
+ try {
555
+ info = await lstat(absoluteRoot);
556
+ } catch (error) {
557
+ if (error.code !== 'ENOENT' || !allowMissingRoots) throw error;
558
+ validationRoot = await nearestCanonicalDirectory(absoluteRoot);
559
+ }
560
+ if (
561
+ info &&
562
+ (info.isSymbolicLink() ||
563
+ !info.isDirectory() ||
564
+ (await realpath(absoluteRoot)) !== absoluteRoot)
565
+ ) {
566
+ throw new Error(`allowlisted target root is not a canonical directory: ${absoluteRoot}`);
567
+ }
568
+ const nested = relative(absoluteRoot, candidate);
569
+ if (
570
+ nested === '' ||
571
+ (!nested.startsWith(`..${sep}`) && nested !== '..' && !isAbsolute(nested))
572
+ ) {
573
+ selectedRoot = absoluteRoot;
574
+ validationRoot ??= absoluteRoot;
575
+ break;
576
+ }
577
+ validationRoot = undefined;
578
+ }
579
+ if (!selectedRoot) throw new Error(`path is outside every allowlisted target root: ${candidate}`);
580
+ await rejectSymlinkSegments(validationRoot, candidate, { mustExist });
581
+ return candidate;
582
+ }
583
+
584
+ async function nearestCanonicalDirectory(path) {
585
+ let current = dirname(path);
586
+ while (true) {
587
+ try {
588
+ const info = await lstat(current);
589
+ if (info.isSymbolicLink() || !info.isDirectory() || (await realpath(current)) !== current) {
590
+ throw new Error(`allowlisted target ancestor is not a canonical directory: ${current}`);
591
+ }
592
+ return current;
593
+ } catch (error) {
594
+ if (error.code !== 'ENOENT') throw error;
595
+ const parent = dirname(current);
596
+ if (parent === current) throw error;
597
+ current = parent;
598
+ }
599
+ }
600
+ }
601
+
602
+ export async function ensureAllowedParent(path, allowRoots) {
603
+ const checked = await assertAllowedPath(path, allowRoots);
604
+ const root = allowRoots
605
+ .map((candidate) => resolve(candidate))
606
+ .find((candidate) => isWithin(candidate, checked));
607
+ const nestedParent = relative(root, dirname(checked));
608
+ let current = root;
609
+ for (const segment of nestedParent.split(sep).filter(Boolean)) {
610
+ current = join(current, segment);
611
+ try {
612
+ const info = await lstat(current);
613
+ if (info.isSymbolicLink())
614
+ throw new Error(`symlink is not allowed in managed path: ${current}`);
615
+ if (!info.isDirectory()) throw new Error(`managed parent is not a directory: ${current}`);
616
+ } catch (error) {
617
+ if (error.code !== 'ENOENT') throw error;
618
+ await mkdir(current, { mode: 0o700 });
619
+ }
620
+ }
621
+ await revalidateAllowedParent(checked, allowRoots);
622
+ return checked;
623
+ }
624
+
625
+ export async function revalidateAllowedParent(path, allowRoots) {
626
+ await assertAllowedPath(path, allowRoots);
627
+ const parent = dirname(path);
628
+ const info = await lstat(parent);
629
+ if (!info.isDirectory() || info.isSymbolicLink() || (await realpath(parent)) !== parent) {
630
+ throw new Error(`managed parent is not a canonical directory: ${parent}`);
631
+ }
632
+ }
633
+
634
+ export async function pinAllowedParent(path, allowRoots) {
635
+ const checked = await assertAllowedPath(path, allowRoots);
636
+ const parent = dirname(checked);
637
+ const handle = await open(
638
+ parent,
639
+ constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0)
640
+ );
641
+ try {
642
+ const identity = await handle.stat();
643
+ if (!identity.isDirectory()) throw new Error(`managed parent is not a directory: ${parent}`);
644
+ let descriptorPath;
645
+ if (process.platform === 'linux') {
646
+ descriptorPath = `/proc/self/fd/${handle.fd}`;
647
+ } else if (process.platform === 'darwin') {
648
+ descriptorPath = `/.vol/${identity.dev}/${identity.ino}`;
649
+ } else {
650
+ throw new Error(
651
+ `platform cannot safely mutate managed files descriptor-relative: ${process.platform}`
652
+ );
653
+ }
654
+ const descriptorIdentity = await stat(descriptorPath);
655
+ if (
656
+ !descriptorIdentity.isDirectory() ||
657
+ descriptorIdentity.dev !== identity.dev ||
658
+ descriptorIdentity.ino !== identity.ino
659
+ ) {
660
+ throw new Error(`platform cannot safely resolve pinned managed parent: ${parent}`);
661
+ }
662
+ return { descriptorPath, handle, identity, parent };
663
+ } catch (error) {
664
+ await handle.close();
665
+ throw error;
666
+ }
667
+ }
668
+
669
+ export async function revalidatePinnedParent(pin) {
670
+ const handleIdentity = await pin.handle.stat();
671
+ if (
672
+ handleIdentity.dev !== pin.identity.dev ||
673
+ handleIdentity.ino !== pin.identity.ino ||
674
+ !handleIdentity.isDirectory()
675
+ ) {
676
+ throw new Error(`pinned managed parent identity changed: ${pin.parent}`);
677
+ }
678
+ const pathIdentity = await lstat(pin.parent);
679
+ if (
680
+ pathIdentity.isSymbolicLink() ||
681
+ !pathIdentity.isDirectory() ||
682
+ pathIdentity.dev !== pin.identity.dev ||
683
+ pathIdentity.ino !== pin.identity.ino
684
+ ) {
685
+ throw new Error(`managed parent identity changed while pinned: ${pin.parent}`);
686
+ }
687
+ }
688
+
689
+ export async function closeParentPins(pins) {
690
+ await Promise.all([...pins.values()].map((pin) => pin.handle.close()));
691
+ }
692
+
693
+ export function pinnedChildPath(pin, path) {
694
+ if (
695
+ !pin ||
696
+ dirname(path) !== pin.parent ||
697
+ basename(path) !== path.slice(pin.parent.length + 1)
698
+ ) {
699
+ throw new Error(`managed mutation path does not belong to its pinned parent: ${path}`);
700
+ }
701
+ return join(pin.descriptorPath, basename(path));
702
+ }
703
+
704
+ export async function acquireScopeLock(
705
+ scopeDir,
706
+ { afterLink = async () => {}, afterTempSync = async () => {} } = {}
707
+ ) {
708
+ await assertCanonicalPrivateScope(scopeDir, { create: false });
709
+ const lockPath = join(scopeDir, 'transaction.lock');
710
+ for (let attempt = 0; attempt < 2; attempt += 1) {
711
+ const token = randomUUID();
712
+ const tempPath = join(scopeDir, `.maude-lock-stage-${token}`);
713
+ try {
714
+ await writeExclusive(
715
+ tempPath,
716
+ `${JSON.stringify({ pid: process.pid, schemaVersion: 1, token })}\n`,
717
+ 0o600
718
+ );
719
+ await afterTempSync();
720
+ await linkNoClobber(tempPath, lockPath);
721
+ await afterLink();
722
+ await unlink(tempPath);
723
+ await syncDirectory(scopeDir);
724
+ const handle = await open(lockPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
725
+ const published = await readLockHandle(handle, lockPath);
726
+ if (published.token !== token) {
727
+ await handle.close();
728
+ throw lockError(`lock ownership token changed during publication: ${lockPath}`);
729
+ }
730
+ await cleanupLockStages(scopeDir);
731
+ return async () => releaseScopeLock({ handle, lockPath, scopeDir, token });
732
+ } catch (error) {
733
+ await unlink(tempPath).catch((cleanupError) => {
734
+ if (cleanupError.code !== 'ENOENT') throw cleanupError;
735
+ });
736
+ if (error.code !== 'EEXIST' && !/no-clobber destination exists/.test(error.message))
737
+ throw error;
738
+ const observed = await readLock(lockPath);
739
+ if (!isDeadPid(observed.pid) || attempt > 0) {
740
+ throw lockError(`harness scope is locked: ${lockPath}`);
741
+ }
742
+ const quarantine = join(scopeDir, `.maude-lock-quarantine-${observed.token}-${randomUUID()}`);
743
+ try {
744
+ await rename(lockPath, quarantine);
745
+ } catch (renameError) {
746
+ if (renameError.code === 'ENOENT') continue;
747
+ throw renameError;
748
+ }
749
+ const quarantined = await readLock(quarantine);
750
+ if (quarantined.token !== observed.token || !isDeadPid(quarantined.pid)) {
751
+ await linkNoClobber(quarantine, lockPath);
752
+ await unlink(quarantine);
753
+ throw lockError(`stale lock changed during takeover: ${lockPath}`);
754
+ }
755
+ await unlink(quarantine);
756
+ await syncDirectory(scopeDir);
757
+ }
758
+ }
759
+ throw lockError(`harness scope is locked: ${lockPath}`);
760
+ }
761
+
762
+ async function cleanupLockStages(scopeDir) {
763
+ for (const name of await readdir(scopeDir)) {
764
+ if (!/^\.maude-lock-stage-[0-9a-f-]{36}$/i.test(name)) continue;
765
+ const path = join(scopeDir, name);
766
+ const info = await lstat(path);
767
+ if (info.isFile() && !info.isSymbolicLink()) await unlink(path);
768
+ }
769
+ await syncDirectory(scopeDir);
770
+ }
771
+
772
+ async function releaseScopeLock({ handle, lockPath, scopeDir, token }) {
773
+ await handle.close();
774
+ const quarantine = join(scopeDir, `.maude-lock-release-${token}-${randomUUID()}`);
775
+ try {
776
+ await rename(lockPath, quarantine);
777
+ } catch (error) {
778
+ if (error.code === 'ENOENT') throw lockError(`lock ownership was lost: ${lockPath}`);
779
+ throw error;
780
+ }
781
+ const observed = await readLock(quarantine);
782
+ if (observed.token !== token) {
783
+ await linkNoClobber(quarantine, lockPath).catch(() => {});
784
+ await unlink(quarantine);
785
+ throw lockError(`lock ownership token changed: ${lockPath}`);
786
+ }
787
+ await unlink(quarantine);
788
+ await syncDirectory(scopeDir);
789
+ }
790
+
791
+ export async function inspectRegularFile(path) {
792
+ const info = await lstat(path);
793
+ if (info.isSymbolicLink()) throw new Error(`symlink is not allowed for managed file: ${path}`);
794
+ if (!info.isFile()) throw new Error(`managed path is not a regular file: ${path}`);
795
+ return { hash: hashBytes(await readNoFollow(path)), mode: info.mode & 0o777 };
796
+ }
797
+
798
+ export async function claimExistingFile(entry, allowRoots, parentPin) {
799
+ const pin = parentPin ?? (await pinAllowedParent(entry.path, allowRoots));
800
+ const ownedPin = !parentPin;
801
+ const targetPath = pinnedChildPath(pin, entry.path);
802
+ const claimPath = pinnedChildPath(pin, entry.claimPath);
803
+ const discardPath = pinnedChildPath(pin, entry.discardPath);
804
+ try {
805
+ await assertArtifactAbsent(claimPath);
806
+ await link(targetPath, claimPath);
807
+ const claim = await inspectRegularFile(claimPath);
808
+ if (claim.hash !== entry.originalHash)
809
+ throw new Error(`managed target changed before claim: ${entry.path}`);
810
+ await assertArtifactAbsent(discardPath);
811
+ await rename(targetPath, discardPath);
812
+ const discarded = await inspectRegularFile(discardPath);
813
+ if (discarded.hash !== entry.originalHash) {
814
+ await linkNoClobber(discardPath, targetPath);
815
+ throw new Error(`managed target changed while being claimed: ${entry.path}`);
816
+ }
817
+ await unlink(discardPath);
818
+ await pin.handle.sync();
819
+ } finally {
820
+ if (ownedPin) await pin.handle.close();
821
+ }
822
+ }
823
+
824
+ export async function installNoClobber(
825
+ stagePath,
826
+ path,
827
+ expectedHash,
828
+ allowRoots,
829
+ mode = 0o600,
830
+ parentPin
831
+ ) {
832
+ const pin = parentPin ?? (await pinAllowedParent(path, allowRoots));
833
+ const ownedPin = !parentPin;
834
+ const pinnedStage = pinnedChildPath(pin, stagePath);
835
+ const pinnedTarget = pinnedChildPath(pin, path);
836
+ try {
837
+ try {
838
+ await link(pinnedStage, pinnedTarget);
839
+ } catch (error) {
840
+ if (error.code === 'EEXIST') throw new Error(`managed target appeared or collided: ${path}`);
841
+ if (['EXDEV', 'ENOTSUP', 'EPERM'].includes(error.code)) {
842
+ throw new Error(
843
+ `platform cannot safely install managed target without clobbering: ${path}`
844
+ );
845
+ }
846
+ throw error;
847
+ }
848
+ await verifyAndChmodNoFollow(pinnedTarget, expectedHash, mode);
849
+ await pin.handle.sync();
850
+ } finally {
851
+ if (ownedPin) await pin.handle.close();
852
+ }
853
+ }
854
+
855
+ export async function removeInstalledNoClobber(entry, expectedHash, allowRoots, parentPin) {
856
+ const pin = parentPin ?? (await pinAllowedParent(entry.path, allowRoots));
857
+ const ownedPin = !parentPin;
858
+ const targetPath = pinnedChildPath(pin, entry.path);
859
+ const discardPath = pinnedChildPath(pin, entry.discardPath);
860
+ try {
861
+ await assertArtifactAbsent(discardPath);
862
+ await rename(targetPath, discardPath);
863
+ const discarded = await inspectRegularFile(discardPath);
864
+ if (discarded.hash !== expectedHash) {
865
+ await linkNoClobber(discardPath, targetPath);
866
+ throw new Error(`concurrent edit detected during rollback: ${entry.path}`);
867
+ }
868
+ await unlink(discardPath);
869
+ await pin.handle.sync();
870
+ } finally {
871
+ if (ownedPin) await pin.handle.close();
872
+ }
873
+ }
874
+
875
+ export async function restoreClaimNoClobber(entry, allowRoots, parentPin) {
876
+ const pin = parentPin ?? (await pinAllowedParent(entry.path, allowRoots));
877
+ const ownedPin = !parentPin;
878
+ const targetPath = pinnedChildPath(pin, entry.path);
879
+ const claimPath = pinnedChildPath(pin, entry.claimPath);
880
+ try {
881
+ try {
882
+ await link(claimPath, targetPath);
883
+ } catch (error) {
884
+ if (error.code === 'EEXIST')
885
+ throw new Error(`concurrent edit blocks rollback: ${entry.path}`);
886
+ throw error;
887
+ }
888
+ await verifyAndChmodNoFollow(targetPath, entry.originalHash, entry.originalMode);
889
+ await pin.handle.sync();
890
+ } finally {
891
+ if (ownedPin) await pin.handle.close();
892
+ }
893
+ }
894
+
895
+ export async function unlinkOwnedArtifact(path, allowRoots, parentPin) {
896
+ if (!path) return;
897
+ const pin = parentPin ?? (await pinAllowedParent(path, allowRoots));
898
+ const ownedPin = !parentPin;
899
+ const descriptorPath = pinnedChildPath(pin, path);
900
+ try {
901
+ const info = await lstat(descriptorPath);
902
+ if (!info.isFile() || info.isSymbolicLink())
903
+ throw new Error(`owned artifact is not a file: ${path}`);
904
+ await unlink(descriptorPath);
905
+ } catch (error) {
906
+ if (error.code !== 'ENOENT') throw error;
907
+ } finally {
908
+ if (ownedPin) await pin.handle.close();
909
+ }
910
+ }
911
+
912
+ export async function writeExclusive(path, contents, mode = 0o600) {
913
+ const handle = await open(path, 'wx', mode);
914
+ try {
915
+ await handle.writeFile(contents);
916
+ await handle.sync();
917
+ } finally {
918
+ await handle.close();
919
+ }
920
+ }
921
+
922
+ export async function writeDurableJson(path, value) {
923
+ await atomicWrite(path, `${JSON.stringify(value)}\n`, 0o600);
924
+ }
925
+
926
+ export async function syncDirectory(path) {
927
+ const handle = await open(path, 'r');
928
+ try {
929
+ await handle.sync();
930
+ } finally {
931
+ await handle.close();
932
+ }
933
+ }
934
+
935
+ function artifactPath(path, kind, transactionId, index) {
936
+ return join(dirname(path), `.maude-${kind}-${transactionId}-${index}`);
937
+ }
938
+
939
+ function validateArtifact(path, targetPath, expectedName, journalPath) {
940
+ if (
941
+ typeof path !== 'string' ||
942
+ dirname(path) !== dirname(targetPath) ||
943
+ basename(path) !== `.maude-${expectedName}`
944
+ ) {
945
+ throw new Error(`invalid removal journal artifact in ${journalPath}`);
946
+ }
947
+ }
948
+
949
+ async function assertBackup(output, backupRoots) {
950
+ if (!output.backupPath || !HASH.test(output.backupHash ?? '')) {
951
+ throw new Error(`adopted output has no valid backup metadata: ${output.path}`);
952
+ }
953
+ await assertAllowedPath(output.backupPath, backupRoots, { mustExist: true });
954
+ if ((await hashFile(output.backupPath)) !== output.backupHash) {
955
+ throw new Error(`adoption backup was modified: ${output.backupPath}`);
956
+ }
957
+ }
958
+
959
+ async function atomicWrite(path, contents, mode) {
960
+ const tempPath = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
961
+ try {
962
+ await writeExclusive(tempPath, contents, mode);
963
+ await rename(tempPath, path);
964
+ await chmod(path, mode);
965
+ await syncDirectory(dirname(path));
966
+ } finally {
967
+ await rm(tempPath, { force: true }).catch(() => {});
968
+ }
969
+ }
970
+
971
+ export async function readFileNoFollow(path) {
972
+ const pathInfo = await lstat(path);
973
+ if (pathInfo.isSymbolicLink())
974
+ throw new Error(`symlink is not allowed for managed file: ${path}`);
975
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
976
+ try {
977
+ const info = await handle.stat();
978
+ if (!info.isFile()) throw new Error(`managed path is not a regular file: ${path}`);
979
+ return await handle.readFile();
980
+ } finally {
981
+ await handle.close();
982
+ }
983
+ }
984
+
985
+ const readNoFollow = readFileNoFollow;
986
+
987
+ async function canonicalExistingDirectory(path, label) {
988
+ if (!path) throw new Error(`${label} is required`);
989
+ const canonical = await realpath(path);
990
+ const info = await stat(canonical);
991
+ if (!info.isDirectory()) throw new Error(`${label} is not a directory: ${path}`);
992
+ return canonical;
993
+ }
994
+
995
+ async function ensureCanonicalDirectoryTree(path, label) {
996
+ const target = resolve(path);
997
+ const missing = [];
998
+ let current = target;
999
+ while (true) {
1000
+ try {
1001
+ const info = await lstat(current);
1002
+ if (info.isSymbolicLink() || !info.isDirectory() || (await realpath(current)) !== current) {
1003
+ throw new Error(`${label} crosses a non-canonical directory: ${current}`);
1004
+ }
1005
+ break;
1006
+ } catch (error) {
1007
+ if (error.code !== 'ENOENT') throw error;
1008
+ const parent = dirname(current);
1009
+ if (parent === current) throw error;
1010
+ missing.unshift(basename(current));
1011
+ current = parent;
1012
+ }
1013
+ }
1014
+ for (const segment of missing) {
1015
+ current = join(current, segment);
1016
+ await mkdir(current, { mode: 0o700 });
1017
+ const info = await lstat(current);
1018
+ if (info.isSymbolicLink() || !info.isDirectory() || (await realpath(current)) !== current) {
1019
+ throw new Error(`${label} could not be created safely: ${current}`);
1020
+ }
1021
+ }
1022
+ return target;
1023
+ }
1024
+
1025
+ async function ensurePrivateChildDirectory(path, parent, label) {
1026
+ await assertCanonicalPrivateScope(parent, { create: false });
1027
+ if (dirname(path) !== parent) throw new Error(`${label} escapes its parent: ${path}`);
1028
+ try {
1029
+ await mkdir(path, { mode: 0o700 });
1030
+ } catch (error) {
1031
+ if (error.code !== 'EEXIST') throw error;
1032
+ }
1033
+ const info = await lstat(path);
1034
+ if (
1035
+ !info.isDirectory() ||
1036
+ info.isSymbolicLink() ||
1037
+ (info.mode & 0o077) !== 0 ||
1038
+ (await realpath(path)) !== path
1039
+ ) {
1040
+ throw new Error(`${label} is not a canonical private directory: ${path}`);
1041
+ }
1042
+ }
1043
+
1044
+ async function rejectSymlinkSegments(root, candidate, { mustExist }) {
1045
+ const nested = relative(root, candidate);
1046
+ let current = root;
1047
+ const segments = nested.split(sep).filter(Boolean);
1048
+ for (let index = 0; index < segments.length; index += 1) {
1049
+ current = join(current, segments[index]);
1050
+ try {
1051
+ const info = await lstat(current);
1052
+ if (info.isSymbolicLink())
1053
+ throw new Error(`symlink is not allowed in managed path: ${current}`);
1054
+ if (index < segments.length - 1 && !info.isDirectory()) {
1055
+ throw new Error(`managed path parent is not a directory: ${current}`);
1056
+ }
1057
+ } catch (error) {
1058
+ if (error.code !== 'ENOENT') throw error;
1059
+ if (mustExist) throw error;
1060
+ return;
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ async function assertArtifactAbsent(path) {
1066
+ try {
1067
+ await lstat(path);
1068
+ throw new Error(`transaction artifact already exists: ${path}`);
1069
+ } catch (error) {
1070
+ if (error.code !== 'ENOENT') throw error;
1071
+ }
1072
+ }
1073
+
1074
+ async function linkNoClobber(source, destination) {
1075
+ try {
1076
+ await link(source, destination);
1077
+ } catch (error) {
1078
+ if (error.code === 'EEXIST') throw new Error(`no-clobber destination exists: ${destination}`);
1079
+ throw error;
1080
+ }
1081
+ }
1082
+
1083
+ async function readLock(path) {
1084
+ let handle;
1085
+ try {
1086
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
1087
+ return await readLockHandle(handle, path);
1088
+ } catch (error) {
1089
+ if (error instanceof ScopeLockError) throw error;
1090
+ throw lockError(`invalid scope lock ${path}: ${error.message}`);
1091
+ } finally {
1092
+ await handle?.close();
1093
+ }
1094
+ }
1095
+
1096
+ async function readLockHandle(handle, path) {
1097
+ let value;
1098
+ try {
1099
+ const info = await handle.stat();
1100
+ if (!info.isFile()) throw new Error('lock is not a regular file');
1101
+ value = JSON.parse((await handle.readFile()).toString('utf8'));
1102
+ } catch (error) {
1103
+ throw lockError(`invalid scope lock ${path}: ${error.message}`);
1104
+ }
1105
+ if (
1106
+ !isPlainObject(value) ||
1107
+ !exactKeys(value, ['pid', 'schemaVersion', 'token']) ||
1108
+ value.schemaVersion !== 1 ||
1109
+ !UUID.test(value.token) ||
1110
+ !Number.isSafeInteger(value.pid) ||
1111
+ value.pid <= 0
1112
+ ) {
1113
+ throw lockError(`invalid scope lock ${path}`);
1114
+ }
1115
+ return value;
1116
+ }
1117
+
1118
+ function isDeadPid(pid) {
1119
+ try {
1120
+ process.kill(pid, 0);
1121
+ return false;
1122
+ } catch (error) {
1123
+ return error.code === 'ESRCH';
1124
+ }
1125
+ }
1126
+
1127
+ function lockError(message) {
1128
+ return new ScopeLockError(message);
1129
+ }
1130
+
1131
+ function hashBytes(bytes) {
1132
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
1133
+ }
1134
+
1135
+ async function verifyAndChmodNoFollow(path, expectedHash, mode) {
1136
+ const handle = await open(path, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
1137
+ try {
1138
+ const info = await handle.stat();
1139
+ if (!info.isFile()) throw new Error(`managed path is not a regular file: ${path}`);
1140
+ const bytes = await handle.readFile();
1141
+ if (hashBytes(bytes) !== expectedHash) throw new Error(`managed target hash mismatch: ${path}`);
1142
+ await handle.chmod(mode);
1143
+ await handle.sync();
1144
+ } finally {
1145
+ await handle.close();
1146
+ }
1147
+ }
1148
+
1149
+ async function inspectOptionalFile(path) {
1150
+ try {
1151
+ return await inspectRegularFile(path);
1152
+ } catch (error) {
1153
+ if (error.code === 'ENOENT') return null;
1154
+ throw error;
1155
+ }
1156
+ }
1157
+
1158
+ function containsRawCredential(text, path) {
1159
+ if (classifyCredential(text)) return true;
1160
+ if (sanitizeUntrustedText(text).findings.length > 0) return true;
1161
+ if (extname(path).toLowerCase() === '.json') {
1162
+ try {
1163
+ if (containsCredentialValue(JSON.parse(text))) return true;
1164
+ } catch {
1165
+ // Invalid JSON still falls through to assignment scanning.
1166
+ }
1167
+ }
1168
+ if (extname(path).toLowerCase() === '.toml' && containsTomlCredential(text)) return true;
1169
+ return containsCredentialAssignment(text);
1170
+ }
1171
+
1172
+ function containsCredentialValue(value, key = '', sensitiveKey = '') {
1173
+ if (Array.isArray(value)) {
1174
+ return value.some((entry) => containsCredentialValue(entry, key, sensitiveKey));
1175
+ }
1176
+ if (!value || typeof value !== 'object') {
1177
+ return Boolean(classifyCredential(String(value), { key: sensitiveKey || key }));
1178
+ }
1179
+ return Object.entries(value).some(([nestedKey, nested]) => {
1180
+ const nestedSensitiveKey = classifyCredential('literal', { key: nestedKey })
1181
+ ? nestedKey
1182
+ : sensitiveKey;
1183
+ return containsCredentialValue(nested, nestedKey, nestedSensitiveKey);
1184
+ });
1185
+ }
1186
+
1187
+ function containsTomlCredential(text) {
1188
+ try {
1189
+ return containsCredentialValue(parseToml(text));
1190
+ } catch {
1191
+ // Invalid TOML still receives conservative assignment scanning below.
1192
+ }
1193
+ for (const rawLine of text.split(/\r?\n/)) {
1194
+ const line = rawLine.replace(/\s+#.*$/, '').trim();
1195
+ if (!line || /^\[.*\]$/.test(line)) continue;
1196
+ const separator = line.indexOf('=');
1197
+ const candidateKey = (separator < 0 ? line : line.slice(0, separator))
1198
+ .trim()
1199
+ .split('.')
1200
+ .at(-1)
1201
+ ?.replace(/^['"]|['"]$/g, '');
1202
+ if (
1203
+ !classifyCredential('literal', { key: candidateKey ?? '' }) &&
1204
+ !containsCredentialAssignment(line)
1205
+ ) {
1206
+ continue;
1207
+ }
1208
+ if (separator < 0) return true;
1209
+ const candidate = line
1210
+ .slice(separator + 1)
1211
+ .trim()
1212
+ .replace(/^['"]|['"]$/g, '');
1213
+ if (
1214
+ classifyCredential(candidate, { key: candidateKey ?? '' }) ||
1215
+ containsCredentialAssignment(line)
1216
+ ) {
1217
+ return true;
1218
+ }
1219
+ }
1220
+ return false;
1221
+ }
1222
+
1223
+ function containsCredentialAssignment(value) {
1224
+ const assignment =
1225
+ /(?=(?:^|[{,\s;])["']?([A-Za-z_][A-Za-z0-9_-]*)["']?\s*[:=]\s*(?:(\$\{[A-Z_][A-Z0-9_]*\}|\{env:[A-Z_][A-Z0-9_]*\}|keychain:[A-Za-z0-9._/-]+)|"([^"]*)"|'([^']*)'|([^\r\n,}\s]+)))/g;
1226
+ return [...value.matchAll(assignment)].some((match) => {
1227
+ if (!classifyCredential('literal', { key: match[1] })) return false;
1228
+ const candidate = (match[2] ?? match[3] ?? match[4] ?? match[5]).trim();
1229
+ return Boolean(classifyCredential(candidate, { key: match[1] }));
1230
+ });
1231
+ }
1232
+
1233
+ async function securelyDeleteBackup(path, backupRoots) {
1234
+ await assertAllowedPath(path, backupRoots);
1235
+ const pin = await pinAllowedParent(path, backupRoots);
1236
+ const descriptorPath = pinnedChildPath(pin, path);
1237
+ try {
1238
+ await revalidatePinnedParent(pin);
1239
+ let handle;
1240
+ try {
1241
+ handle = await open(descriptorPath, constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0));
1242
+ } catch (error) {
1243
+ if (error.code === 'ENOENT') return;
1244
+ throw error;
1245
+ }
1246
+ try {
1247
+ const info = await handle.stat();
1248
+ if (!info.isFile()) throw new Error(`adoption backup is not a regular file: ${path}`);
1249
+ const zeroes = Buffer.alloc(Math.min(info.size, 64 * 1024));
1250
+ for (let offset = 0; offset < info.size; offset += zeroes.length) {
1251
+ await handle.write(zeroes, 0, Math.min(zeroes.length, info.size - offset), offset);
1252
+ }
1253
+ await handle.truncate(0);
1254
+ await handle.sync();
1255
+ } finally {
1256
+ await handle.close();
1257
+ }
1258
+ await unlink(descriptorPath);
1259
+ await pin.handle.sync();
1260
+ await revalidatePinnedParent(pin);
1261
+ } finally {
1262
+ await pin.handle.close();
1263
+ }
1264
+ }
1265
+
1266
+ function validMode(mode) {
1267
+ return Number.isInteger(mode) && mode >= 0 && mode <= 0o777;
1268
+ }
1269
+
1270
+ function isPlainObject(value) {
1271
+ return (
1272
+ value !== null &&
1273
+ typeof value === 'object' &&
1274
+ !Array.isArray(value) &&
1275
+ Object.getPrototypeOf(value) === Object.prototype
1276
+ );
1277
+ }
1278
+
1279
+ function exactKeys(value, expected) {
1280
+ const actual = Object.keys(value).sort();
1281
+ const wanted = [...expected].sort();
1282
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
1283
+ }
1284
+
1285
+ function isWithin(root, path) {
1286
+ const nested = relative(root, path);
1287
+ return (
1288
+ nested === '' || (!nested.startsWith(`..${sep}`) && nested !== '..' && !isAbsolute(nested))
1289
+ );
1290
+ }
1291
+
1292
+ function sortObject(value) {
1293
+ return Object.fromEntries(
1294
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right))
1295
+ );
1296
+ }