@1agh/maude 1.0.11 → 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/transcript-io.ts +394 -0
  3. package/apps/studio/acp/transcript.ts +103 -38
  4. package/apps/studio/api.ts +139 -26
  5. package/apps/studio/bin/_import-figma.mjs +57 -11
  6. package/apps/studio/bin/_seed-fixture.mjs +163 -0
  7. package/apps/studio/canvas-imports.ts +89 -0
  8. package/apps/studio/client/app.jsx +257 -7
  9. package/apps/studio/client/export-center.jsx +15 -7
  10. package/apps/studio/client/panels/SyncPanel.jsx +125 -4
  11. package/apps/studio/client/report-bug.jsx +19 -1
  12. package/apps/studio/client/styles/3-shell-maude.css +34 -0
  13. package/apps/studio/client/styles/4-components.css +26 -0
  14. package/apps/studio/collab/persistence.ts +132 -16
  15. package/apps/studio/collab/registry.ts +10 -18
  16. package/apps/studio/debug-bundle.ts +13 -0
  17. package/apps/studio/dist/client.bundle.js +1128 -1128
  18. package/apps/studio/dist/styles.css +1 -1
  19. package/apps/studio/export-dialog.tsx +54 -0
  20. package/apps/studio/exporters/degraded.ts +19 -3
  21. package/apps/studio/exporters/ghostscript.ts +194 -0
  22. package/apps/studio/exporters/pdf-fonts.ts +261 -0
  23. package/apps/studio/exporters/pdf.ts +152 -3
  24. package/apps/studio/exporters/remote.ts +36 -1
  25. package/apps/studio/fs-watch.ts +45 -1
  26. package/apps/studio/http.ts +7 -1
  27. package/apps/studio/mem.ts +45 -9
  28. package/apps/studio/server.ts +11 -4
  29. package/apps/studio/sync/agent.ts +136 -29
  30. package/apps/studio/sync/asset-push.ts +1 -47
  31. package/apps/studio/sync/codec.ts +122 -31
  32. package/apps/studio/sync/cold-start-apply.ts +7 -0
  33. package/apps/studio/sync/cold-start.ts +118 -22
  34. package/apps/studio/sync/comment-identity.ts +68 -0
  35. package/apps/studio/sync/connection-state.ts +15 -1
  36. package/apps/studio/sync/file-ledger.ts +117 -0
  37. package/apps/studio/sync/file-plane.ts +623 -27
  38. package/apps/studio/sync/index.ts +711 -20
  39. package/apps/studio/sync/journal-client.ts +13 -1
  40. package/apps/studio/sync/migrate-seed.ts +40 -3
  41. package/apps/studio/sync/presentation.ts +26 -3
  42. package/apps/studio/sync/retry-after.ts +169 -0
  43. package/apps/studio/sync/seed-progress.ts +218 -0
  44. package/apps/studio/sync/status.ts +122 -5
  45. package/apps/studio/sync/transport-error.ts +111 -0
  46. package/apps/studio/whats-new.json +72 -0
  47. package/cli/bin/maude.mjs +2 -0
  48. package/cli/commands/codex.mjs +191 -0
  49. package/cli/commands/harness.mjs +1051 -0
  50. package/cli/commands/help.mjs +13 -0
  51. package/cli/lib/design-link.mjs +190 -2
  52. package/cli/lib/harness/capabilities.mjs +302 -0
  53. package/cli/lib/harness/codex-runtime.mjs +889 -0
  54. package/cli/lib/harness/compatibility.mjs +27 -0
  55. package/cli/lib/harness/discover-claude.mjs +1393 -0
  56. package/cli/lib/harness/managed-state.mjs +1296 -0
  57. package/cli/lib/harness/model.mjs +86 -0
  58. package/cli/lib/harness/secrets.mjs +390 -0
  59. package/cli/lib/harness/targets/codex.mjs +1141 -0
  60. package/cli/lib/harness/targets/opencode.mjs +807 -0
  61. package/cli/lib/harness/transaction.mjs +1099 -0
  62. package/cli/lib/hubs-config.mjs +35 -8
  63. package/cli/templates/harness/opencode/maude-projector.ts +58 -0
  64. package/docs/harness-capability-matrix.md +125 -0
  65. package/docs/harness-environment-projection.md +95 -0
  66. package/package.json +32 -9
  67. package/plugins/flow/.claude-plugin/config.schema.json +8 -0
  68. package/apps/studio/.ai/cache/_stats.json +0 -7
  69. package/apps/studio/bin/_agent-browser-safe.test.mjs +0 -165
  70. package/apps/studio/bin/_curl-local.test.mjs +0 -280
  71. package/apps/studio/bin/_pw-launch.test.mjs +0 -90
  72. package/apps/studio/bin/_smart-frames.test.mjs +0 -195
  73. package/apps/studio/bin/_transcribe.test.mjs +0 -80
  74. package/apps/studio/bun.lock +0 -928
  75. package/apps/studio/draw/test/animate.test.ts +0 -172
  76. package/apps/studio/draw/test/brush.test.ts +0 -213
  77. package/apps/studio/draw/test/composition.test.ts +0 -141
  78. package/apps/studio/draw/test/geometry.test.ts +0 -199
  79. package/apps/studio/draw/test/gradient.test.ts +0 -167
  80. package/apps/studio/draw/test/layout.test.ts +0 -120
  81. package/apps/studio/draw/test/morph.test.ts +0 -107
  82. package/apps/studio/draw/test/optimize.test.ts +0 -40
  83. package/apps/studio/draw/test/palette.test.ts +0 -123
  84. package/apps/studio/draw/test/primitives.test.ts +0 -129
  85. package/apps/studio/draw/test/serialize-animate.test.ts +0 -142
  86. package/apps/studio/draw/test/serialize.test.ts +0 -105
  87. package/apps/studio/figma/assets.test.ts +0 -464
  88. package/apps/studio/figma/client.test.ts +0 -395
  89. package/apps/studio/figma/codegen-client.test.ts +0 -276
  90. package/apps/studio/figma/codegen-fonts.test.ts +0 -103
  91. package/apps/studio/figma/codegen-values.test.ts +0 -179
  92. package/apps/studio/figma/comments-to-strokes.test.ts +0 -194
  93. package/apps/studio/figma/fig-decode.test.ts +0 -788
  94. package/apps/studio/figma/fig-differential.test.ts +0 -182
  95. package/apps/studio/figma/fig-translator.test.ts +0 -192
  96. package/apps/studio/figma/fig-vector.test.ts +0 -113
  97. package/apps/studio/figma/from-codegen.test.ts +0 -408
  98. package/apps/studio/figma/sanitize.test.ts +0 -325
  99. package/apps/studio/figma/tailwind-map.test.ts +0 -142
  100. package/apps/studio/figma/to-artboard.test.ts +0 -808
  101. package/apps/studio/figma/to-render.test.ts +0 -180
  102. package/apps/studio/figma/to-strokes-roundtrip.test.ts +0 -152
  103. package/apps/studio/figma/to-strokes.test.ts +0 -705
  104. package/apps/studio/figma/to-tokens.test.ts +0 -321
  105. package/apps/studio/figma/url.test.ts +0 -167
  106. package/apps/studio/footage/schema.test.ts +0 -287
  107. package/apps/studio/generation/adapters/groq.test.ts +0 -80
  108. package/apps/studio/generation/audio-library.test.ts +0 -95
  109. package/apps/studio/generation/captions.test.ts +0 -78
  110. package/apps/studio/generation/elevenlabs.test.ts +0 -223
  111. package/apps/studio/generation/gemini.test.ts +0 -350
  112. package/apps/studio/generation/jobs.test.ts +0 -128
  113. package/apps/studio/generation/keys.test.ts +0 -75
  114. package/apps/studio/generation/prefs.test.ts +0 -95
  115. package/apps/studio/generation/types.test.ts +0 -123
  116. package/apps/studio/generation/whisper-models.test.ts +0 -179
  117. package/apps/studio/test/_helpers.ts +0 -108
  118. package/apps/studio/test/acp-activity-endpoint.test.ts +0 -183
  119. package/apps/studio/test/acp-activity.test.ts +0 -154
  120. package/apps/studio/test/acp-ai-activity.test.ts +0 -182
  121. package/apps/studio/test/acp-attachment-serve.test.ts +0 -74
  122. package/apps/studio/test/acp-bootstrap-brief.test.ts +0 -178
  123. package/apps/studio/test/acp-branch-guard.test.ts +0 -123
  124. package/apps/studio/test/acp-bridge-lifetime.test.ts +0 -475
  125. package/apps/studio/test/acp-bridge.test.ts +0 -545
  126. package/apps/studio/test/acp-capabilities.test.ts +0 -123
  127. package/apps/studio/test/acp-caps-bridge.test.ts +0 -279
  128. package/apps/studio/test/acp-commands.test.ts +0 -119
  129. package/apps/studio/test/acp-elicitation-bridge.test.ts +0 -480
  130. package/apps/studio/test/acp-elicitation.test.ts +0 -251
  131. package/apps/studio/test/acp-env.test.ts +0 -95
  132. package/apps/studio/test/acp-mode-banner.test.ts +0 -45
  133. package/apps/studio/test/acp-origin-gate.test.ts +0 -160
  134. package/apps/studio/test/acp-permission-prompt.test.ts +0 -251
  135. package/apps/studio/test/acp-permission.test.ts +0 -278
  136. package/apps/studio/test/acp-plugin-bootstrap.test.ts +0 -89
  137. package/apps/studio/test/acp-session-allowed-tools.test.ts +0 -235
  138. package/apps/studio/test/acp-session-plugins.test.ts +0 -209
  139. package/apps/studio/test/acp-toolgroup.test.ts +0 -76
  140. package/apps/studio/test/acp-transcript-view.test.ts +0 -71
  141. package/apps/studio/test/acp-transcript.test.ts +0 -238
  142. package/apps/studio/test/acp-usage-bridge.test.ts +0 -141
  143. package/apps/studio/test/acp-usage.test.ts +0 -143
  144. package/apps/studio/test/acp-write-gate.test.ts +0 -323
  145. package/apps/studio/test/acp-write-scope.test.ts +0 -533
  146. package/apps/studio/test/active-state.test.ts +0 -186
  147. package/apps/studio/test/activity.test.ts +0 -189
  148. package/apps/studio/test/ai-activity.test.ts +0 -113
  149. package/apps/studio/test/annotate-write.test.ts +0 -1074
  150. package/apps/studio/test/annotation-strokes-command.test.ts +0 -166
  151. package/apps/studio/test/annotations-align.test.ts +0 -88
  152. package/apps/studio/test/annotations-api.test.ts +0 -145
  153. package/apps/studio/test/annotations-bindings.test.ts +0 -262
  154. package/apps/studio/test/annotations-draw-modifiers.test.ts +0 -206
  155. package/apps/studio/test/annotations-groups.test.ts +0 -231
  156. package/apps/studio/test/annotations-layer.test.ts +0 -1011
  157. package/apps/studio/test/annotations-roundtrip.test.ts +0 -663
  158. package/apps/studio/test/annotations-snap.test.ts +0 -135
  159. package/apps/studio/test/annotations-text-format.test.ts +0 -396
  160. package/apps/studio/test/artboard-activity-overlay.test.tsx +0 -56
  161. package/apps/studio/test/artboard-guides-overlay.test.tsx +0 -152
  162. package/apps/studio/test/artboard-hug-commit.test.ts +0 -36
  163. package/apps/studio/test/artboard-kinds.test.tsx +0 -83
  164. package/apps/studio/test/artboard-selection-attrs.test.ts +0 -69
  165. package/apps/studio/test/asset-api.test.ts +0 -149
  166. package/apps/studio/test/assets-s3.test.ts +0 -249
  167. package/apps/studio/test/binary-smoke.test.ts +0 -47
  168. package/apps/studio/test/boot-self-heal.test.ts +0 -87
  169. package/apps/studio/test/browse-posture.test.tsx +0 -107
  170. package/apps/studio/test/bundle-smoke.test.ts +0 -46
  171. package/apps/studio/test/camera-reveal.test.tsx +0 -173
  172. package/apps/studio/test/canvas-artifacts.test.ts +0 -125
  173. package/apps/studio/test/canvas-build-sandbox.test.ts +0 -69
  174. package/apps/studio/test/canvas-build.test.ts +0 -141
  175. package/apps/studio/test/canvas-create-api.test.ts +0 -676
  176. package/apps/studio/test/canvas-cursors.test.ts +0 -164
  177. package/apps/studio/test/canvas-edit.test.ts +0 -470
  178. package/apps/studio/test/canvas-freshness-deps.test.ts +0 -64
  179. package/apps/studio/test/canvas-header.test.ts +0 -127
  180. package/apps/studio/test/canvas-hide-chrome.test.ts +0 -88
  181. package/apps/studio/test/canvas-hmr-runtime.test.tsx +0 -114
  182. package/apps/studio/test/canvas-lib-inline.test.ts +0 -146
  183. package/apps/studio/test/canvas-lib-motion.test.ts +0 -131
  184. package/apps/studio/test/canvas-lib-resolver.test.ts +0 -111
  185. package/apps/studio/test/canvas-list-watch.test.ts +0 -388
  186. package/apps/studio/test/canvas-media-drop.test.ts +0 -187
  187. package/apps/studio/test/canvas-meta-api.test.ts +0 -707
  188. package/apps/studio/test/canvas-move-api.test.ts +0 -587
  189. package/apps/studio/test/canvas-origin-gate.test.ts +0 -417
  190. package/apps/studio/test/canvas-pipeline.test.ts +0 -180
  191. package/apps/studio/test/canvas-rects.test.ts +0 -198
  192. package/apps/studio/test/canvas-reorder.test.ts +0 -211
  193. package/apps/studio/test/canvas-route.test.ts +0 -179
  194. package/apps/studio/test/canvas-shell-base.test.ts +0 -107
  195. package/apps/studio/test/canvas-shell-build-error.test.ts +0 -52
  196. package/apps/studio/test/canvas-url.test.ts +0 -138
  197. package/apps/studio/test/canvas-wheel-delta.test.ts +0 -42
  198. package/apps/studio/test/canvas-zoom-floor.test.ts +0 -73
  199. package/apps/studio/test/capture-core.test.ts +0 -32
  200. package/apps/studio/test/capture-determinism-shape.test.ts +0 -135
  201. package/apps/studio/test/chat-attachments.test.ts +0 -117
  202. package/apps/studio/test/chat-context.test.ts +0 -129
  203. package/apps/studio/test/chat-markdown.test.tsx +0 -58
  204. package/apps/studio/test/clip-addressing.test.ts +0 -738
  205. package/apps/studio/test/clip-ops.test.ts +0 -922
  206. package/apps/studio/test/cloud-build.test.ts +0 -95
  207. package/apps/studio/test/cloud-connect-note.test.ts +0 -135
  208. package/apps/studio/test/cloud-endpoints.test.ts +0 -590
  209. package/apps/studio/test/cloud-history-hardening.test.ts +0 -165
  210. package/apps/studio/test/cloud-history-posture.test.ts +0 -230
  211. package/apps/studio/test/cloud-managed-save-surfaces.test.ts +0 -90
  212. package/apps/studio/test/cloud-renew.test.ts +0 -205
  213. package/apps/studio/test/cloud-session-role.test.ts +0 -161
  214. package/apps/studio/test/cloud-shell-surfaces.test.ts +0 -170
  215. package/apps/studio/test/cold-start-apply.test.ts +0 -303
  216. package/apps/studio/test/collab-annotations-bridge.test.ts +0 -55
  217. package/apps/studio/test/collab-awareness-bridge.test.ts +0 -223
  218. package/apps/studio/test/collab-bridge.test.ts +0 -79
  219. package/apps/studio/test/collab-loopback.test.ts +0 -63
  220. package/apps/studio/test/collab-origin-gate.test.ts +0 -323
  221. package/apps/studio/test/collab-protocol.test.ts +0 -146
  222. package/apps/studio/test/collab-readonly-gate.test.ts +0 -194
  223. package/apps/studio/test/collab-reseed-guard.test.ts +0 -78
  224. package/apps/studio/test/collab-room.test.ts +0 -188
  225. package/apps/studio/test/collab-session-survival.test.tsx +0 -176
  226. package/apps/studio/test/collab-stress.test.ts +0 -129
  227. package/apps/studio/test/comment-mount.test.ts +0 -97
  228. package/apps/studio/test/comment-relay-origin-gate.test.ts +0 -117
  229. package/apps/studio/test/comments-api.test.ts +0 -277
  230. package/apps/studio/test/comments-fs-rebroadcast.test.ts +0 -155
  231. package/apps/studio/test/comments-overlay.test.ts +0 -117
  232. package/apps/studio/test/compile-entry.test.ts +0 -133
  233. package/apps/studio/test/component-map.test.ts +0 -48
  234. package/apps/studio/test/config-projection.test.ts +0 -104
  235. package/apps/studio/test/config-reload.test.ts +0 -230
  236. package/apps/studio/test/config-version.test.ts +0 -88
  237. package/apps/studio/test/context-resolve-tokens.test.ts +0 -97
  238. package/apps/studio/test/convert-to-absolute.test.ts +0 -333
  239. package/apps/studio/test/credential-grammar.test.ts +0 -107
  240. package/apps/studio/test/csp-canvas-shell.test.ts +0 -62
  241. package/apps/studio/test/csrf-write-guard.test.ts +0 -141
  242. package/apps/studio/test/debug-bundle.test.ts +0 -105
  243. package/apps/studio/test/design-setup-readiness.test.ts +0 -155
  244. package/apps/studio/test/detach-component.test.ts +0 -94
  245. package/apps/studio/test/dns-rebinding-guard.test.ts +0 -101
  246. package/apps/studio/test/dom-selection.test.ts +0 -198
  247. package/apps/studio/test/dynamic-text-edit.test.ts +0 -162
  248. package/apps/studio/test/edit-css-occurrence.test.ts +0 -81
  249. package/apps/studio/test/edit-persistence.test.ts +0 -91
  250. package/apps/studio/test/edit-scope-api.test.ts +0 -119
  251. package/apps/studio/test/edit-source-command.test.ts +0 -142
  252. package/apps/studio/test/edit-suppress.test.ts +0 -170
  253. package/apps/studio/test/editing-presence.test.ts +0 -103
  254. package/apps/studio/test/element-resize.test.ts +0 -136
  255. package/apps/studio/test/element-structural-api.test.ts +0 -434
  256. package/apps/studio/test/element-structural-edit.test.ts +0 -750
  257. package/apps/studio/test/ensure-browser.test.ts +0 -92
  258. package/apps/studio/test/equal-spacing-detector.test.ts +0 -257
  259. package/apps/studio/test/export-assemble.test.ts +0 -53
  260. package/apps/studio/test/export-browser-lane.test.ts +0 -126
  261. package/apps/studio/test/export-capture-fidelity.test.ts +0 -146
  262. package/apps/studio/test/export-capture-hygiene.test.ts +0 -675
  263. package/apps/studio/test/export-center.test.tsx +0 -287
  264. package/apps/studio/test/export-e2e-lanes.test.ts +0 -857
  265. package/apps/studio/test/export-format-scope-coherence.test.ts +0 -89
  266. package/apps/studio/test/export-lane.test.ts +0 -245
  267. package/apps/studio/test/export-shim-multi-capture.test.ts +0 -83
  268. package/apps/studio/test/exporters/canva.test.ts +0 -63
  269. package/apps/studio/test/exporters/degraded-propagation.test.ts +0 -123
  270. package/apps/studio/test/exporters/endpoint.test.ts +0 -121
  271. package/apps/studio/test/exporters/history.test.ts +0 -107
  272. package/apps/studio/test/exporters/html.test.ts +0 -26
  273. package/apps/studio/test/exporters/jobs.test.ts +0 -342
  274. package/apps/studio/test/exporters/pdf.test.ts +0 -85
  275. package/apps/studio/test/exporters/png.test.ts +0 -103
  276. package/apps/studio/test/exporters/pptx-deck.test.ts +0 -112
  277. package/apps/studio/test/exporters/pptx.test.ts +0 -31
  278. package/apps/studio/test/exporters/pw-launch.test.ts +0 -49
  279. package/apps/studio/test/exporters/runtime.test.ts +0 -59
  280. package/apps/studio/test/exporters/scope.test.ts +0 -292
  281. package/apps/studio/test/exporters/svg.test.ts +0 -29
  282. package/apps/studio/test/exporters/unsupported-media.test.ts +0 -123
  283. package/apps/studio/test/exporters/zip.test.ts +0 -104
  284. package/apps/studio/test/fetch-asset-gate.test.ts +0 -189
  285. package/apps/studio/test/figjam-v3-model.test.ts +0 -342
  286. package/apps/studio/test/figma-explode.test.ts +0 -438
  287. package/apps/studio/test/figma-provenance.test.ts +0 -108
  288. package/apps/studio/test/figma-routes.test.ts +0 -294
  289. package/apps/studio/test/file-lock.test.ts +0 -84
  290. package/apps/studio/test/fixtures/backgrounding-claude-auth.sh +0 -12
  291. package/apps/studio/test/fixtures/fake-claude-auth.mjs +0 -23
  292. package/apps/studio/test/fixtures/figjam-v3-groups-bindings.svg +0 -1
  293. package/apps/studio/test/fixtures/mock-acp-agent-caps.mjs +0 -158
  294. package/apps/studio/test/fixtures/mock-acp-agent-commands.mjs +0 -44
  295. package/apps/studio/test/fixtures/mock-acp-agent-elicit-flood.mjs +0 -46
  296. package/apps/studio/test/fixtures/mock-acp-agent-elicit-url.mjs +0 -42
  297. package/apps/studio/test/fixtures/mock-acp-agent-elicit.mjs +0 -63
  298. package/apps/studio/test/fixtures/mock-acp-agent-permission-flood.mjs +0 -51
  299. package/apps/studio/test/fixtures/mock-acp-agent-permission.mjs +0 -50
  300. package/apps/studio/test/fixtures/mock-acp-agent-slow.mjs +0 -45
  301. package/apps/studio/test/fixtures/mock-acp-agent-usage.mjs +0 -56
  302. package/apps/studio/test/fixtures/mock-acp-agent-wedged.mjs +0 -37
  303. package/apps/studio/test/fixtures/mock-acp-agent-write.mjs +0 -118
  304. package/apps/studio/test/fixtures/mock-acp-agent.mjs +0 -69
  305. package/apps/studio/test/fixtures/noisy-claude-auth.mjs +0 -27
  306. package/apps/studio/test/fixtures/perf-canvas.mjs +0 -201
  307. package/apps/studio/test/fixtures/phase-20-annotations.svg +0 -1
  308. package/apps/studio/test/fixtures/phase-21-annotations.svg +0 -1
  309. package/apps/studio/test/fixtures/tiny-subset.woff2 +0 -0
  310. package/apps/studio/test/fixtures/video-comp-fixture.tsx +0 -82
  311. package/apps/studio/test/fixtures/wedged-claude-auth.sh +0 -11
  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 -337
  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,1393 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { parseDocument } from 'yaml';
6
+
7
+ import { createEnvironmentIR, sha256 } from './model.mjs';
8
+ import {
9
+ classifyCredential,
10
+ isCredentialReference,
11
+ sanitizeConfiguredEnvironmentValue,
12
+ sanitizeUntrustedText,
13
+ sanitizeUntrustedValue,
14
+ } from './secrets.mjs';
15
+
16
+ const DEFAULT_LIMITS = {
17
+ maxDepth: 8,
18
+ maxEntries: 50_000,
19
+ maxFileBytes: 1024 * 1024,
20
+ maxFiles: 10_000,
21
+ maxFrontmatterBytes: 64 * 1024,
22
+ maxItems: 10_000,
23
+ maxStructureDepth: 32,
24
+ maxStructureNodes: 50_000,
25
+ maxTotalBytes: 25 * 1024 * 1024,
26
+ };
27
+
28
+ export async function discoverClaude({
29
+ home = homedir(),
30
+ projectRoot = process.cwd(),
31
+ allowedPluginRoots = [],
32
+ discoveryFailpoint = async () => {},
33
+ limits = {},
34
+ profile = 'full',
35
+ includeProjectSettings = true,
36
+ } = {}) {
37
+ if (!['full', 'plugins', 'runtime'].includes(profile))
38
+ throw new Error(`unknown Claude discovery profile ${profile}`);
39
+ const bounded = { ...DEFAULT_LIMITS, ...limits };
40
+ const canonicalHome = await canonicalDirectory(home, 'home');
41
+ const canonicalProject = await canonicalDirectory(projectRoot, 'project root');
42
+ const claudeHome = join(canonicalHome, '.claude');
43
+ const context = {
44
+ entries: 0,
45
+ failpoint: discoveryFailpoint,
46
+ files: 0,
47
+ items: [],
48
+ limits: bounded,
49
+ totalBytes: 0,
50
+ };
51
+ const approvedPluginRoots = await existingCanonicalDirectories([
52
+ join(claudeHome, 'plugins'),
53
+ ...(includeProjectSettings ? [canonicalProject] : []),
54
+ ...allowedPluginRoots,
55
+ ]);
56
+
57
+ const settingsLayers = await readSettingsLayers(
58
+ context,
59
+ claudeHome,
60
+ canonicalProject,
61
+ includeProjectSettings
62
+ );
63
+ addEffectiveSettings(context, settingsLayers);
64
+ addSettingsCapabilities(context, settingsLayers);
65
+
66
+ const plugins = await discoverPlugins(
67
+ context,
68
+ claudeHome,
69
+ canonicalProject,
70
+ settingsLayers,
71
+ approvedPluginRoots,
72
+ includeProjectSettings
73
+ );
74
+ if (profile === 'plugins') {
75
+ return createEnvironmentIR(context.items.filter((item) => item.category === 'plugins'));
76
+ }
77
+ if (profile === 'runtime') {
78
+ return createEnvironmentIR(
79
+ context.items.filter(
80
+ (item) =>
81
+ item.category === 'plugins' ||
82
+ item.category === 'permission-mode' ||
83
+ item.category.startsWith('permissions-')
84
+ )
85
+ );
86
+ }
87
+ await discoverInstructions(context, claudeHome, canonicalHome, canonicalProject);
88
+ await discoverAssetRoot(context, claudeHome, 'global', 'global', 10, canonicalHome, false);
89
+ for (const plugin of plugins) {
90
+ await discoverAssetRoot(
91
+ context,
92
+ plugin.root,
93
+ plugin.namespace,
94
+ plugin.scope,
95
+ plugin.precedence,
96
+ plugin.root,
97
+ true
98
+ );
99
+ }
100
+ await discoverAssetRoot(
101
+ context,
102
+ join(canonicalProject, '.claude'),
103
+ 'project',
104
+ 'project',
105
+ 40,
106
+ canonicalProject,
107
+ false
108
+ );
109
+
110
+ await discoverMcp(context, join(canonicalHome, '.claude.json'), 'global', 'global', 10);
111
+ for (const plugin of plugins) {
112
+ await discoverMcp(
113
+ context,
114
+ join(plugin.root, '.mcp.json'),
115
+ plugin.namespace,
116
+ plugin.scope,
117
+ plugin.precedence
118
+ );
119
+ await discoverHookFile(context, plugin);
120
+ }
121
+ await discoverMcp(context, join(canonicalProject, '.mcp.json'), 'project', 'project', 40);
122
+ await discoverProjectState(context, canonicalProject);
123
+
124
+ return createEnvironmentIR(context.items);
125
+ }
126
+
127
+ async function readSettingsLayers(context, claudeHome, projectRoot, includeProjectSettings) {
128
+ const candidates = [
129
+ {
130
+ path: join(claudeHome, 'settings.json'),
131
+ allowedRoot: dirname(claudeHome),
132
+ precedence: 10,
133
+ scope: 'global',
134
+ },
135
+ {
136
+ path: join(projectRoot, '.claude', 'settings.json'),
137
+ allowedRoot: projectRoot,
138
+ precedence: 40,
139
+ scope: 'project',
140
+ },
141
+ {
142
+ path: join(projectRoot, '.claude', 'settings.local.json'),
143
+ allowedRoot: projectRoot,
144
+ precedence: 50,
145
+ scope: 'project',
146
+ },
147
+ ].filter((candidate) => includeProjectSettings || candidate.scope !== 'project');
148
+ const layers = [];
149
+ for (const candidate of candidates) {
150
+ const source = await readJsonIfPresent(context, candidate.path, candidate.allowedRoot);
151
+ if (source) layers.push({ ...candidate, ...source });
152
+ }
153
+ return layers;
154
+ }
155
+
156
+ function addEffectiveSettings(context, layers) {
157
+ const keys = new Set(layers.flatMap((layer) => Object.keys(layer.value)));
158
+ for (const key of [...keys].sort()) {
159
+ if (['enabledPlugins', 'env', 'hooks', 'permissions'].includes(key)) continue;
160
+ const contributors = layers.filter((layer) => layer.value[key] !== undefined);
161
+ const values = contributors.map((layer) => layer.value[key]);
162
+ const value = key === 'permissions' ? mergePermissions(values) : mergeSettingValues(values);
163
+ const winner = contributors.at(-1);
164
+ addItem(context, {
165
+ category: 'settings',
166
+ name: key,
167
+ scope: winner.scope,
168
+ sourcePath: winner.path,
169
+ precedence: winner.precedence,
170
+ value,
171
+ sourceHash: sha256(JSON.stringify(value)),
172
+ contributors: contributors.map(toContributor),
173
+ });
174
+ }
175
+ }
176
+
177
+ function addSettingsCapabilities(context, layers) {
178
+ for (const layer of layers) {
179
+ const permissions = layer.value.permissions ?? {};
180
+ for (const kind of ['allow', 'ask', 'deny']) {
181
+ for (const [index, rule] of (permissions[kind] ?? []).entries()) {
182
+ addItem(
183
+ context,
184
+ sourceItem(layer, `permissions-${kind}`, `${layer.scope}:${index}:${rule}`, rule)
185
+ );
186
+ }
187
+ }
188
+ if (permissions.defaultMode) {
189
+ addItem(
190
+ context,
191
+ sourceItem(layer, 'permission-mode', `${layer.scope}:default`, permissions.defaultMode)
192
+ );
193
+ }
194
+ addHooks(
195
+ context,
196
+ layer.value.hooks,
197
+ layer.scope,
198
+ layer.scope,
199
+ layer.path,
200
+ layer.precedence,
201
+ layer.hash
202
+ );
203
+ }
204
+ const environmentNames = new Set(layers.flatMap((layer) => Object.keys(layer.value.env ?? {})));
205
+ for (const name of [...environmentNames].sort()) {
206
+ const contributors = layers.filter((layer) => layer.value.env?.[name] !== undefined);
207
+ const winner = contributors.at(-1);
208
+ const sanitized = sanitizeConfiguredEnvironmentValue(name, winner.value.env[name]);
209
+ const value = {
210
+ name,
211
+ value: sanitized.value,
212
+ ...(sanitized.rejected ? { secretStatus: { $maudeSecret: 'literal-rejected' } } : {}),
213
+ };
214
+ addItem(context, {
215
+ category: 'environment',
216
+ name: `${winner.scope}:${name}`,
217
+ scope: winner.scope,
218
+ sourcePath: winner.path,
219
+ precedence: winner.precedence,
220
+ value,
221
+ sourceHash: sha256(JSON.stringify(value)),
222
+ contributors: contributors.map(toContributor),
223
+ });
224
+ }
225
+ }
226
+
227
+ async function discoverPlugins(
228
+ context,
229
+ claudeHome,
230
+ projectRoot,
231
+ settingsLayers,
232
+ approvedPluginRoots,
233
+ includeProjectInstalls
234
+ ) {
235
+ const enabled = new Map();
236
+ for (const layer of settingsLayers) {
237
+ for (const [name, value] of Object.entries(layer.value.enabledPlugins ?? {})) {
238
+ if (typeof value !== 'boolean') {
239
+ throw new Error(`enabledPlugins.${name} in ${layer.path} must be boolean`);
240
+ }
241
+ enabled.set(name, value);
242
+ }
243
+ }
244
+ const installedPath = join(claudeHome, 'plugins', 'installed_plugins.json');
245
+ const installed = await readJsonIfPresent(context, installedPath, claudeHome);
246
+ const plugins = [];
247
+ for (const [pluginName, isEnabled] of [...enabled].sort(([a], [b]) => a.localeCompare(b))) {
248
+ if (!isEnabled) continue;
249
+ const installs = installed?.value?.plugins?.[pluginName] ?? [];
250
+ const selected = await selectPluginInstall(installs, projectRoot, includeProjectInstalls);
251
+ if (!selected) {
252
+ const sourceLayer = settingsLayers.findLast(
253
+ (layer) => layer.value.enabledPlugins?.[pluginName] !== undefined
254
+ );
255
+ const value = { enabled: true, missing: true, pluginName };
256
+ addItem(context, {
257
+ category: 'plugins',
258
+ name: pluginName,
259
+ scope: sourceLayer.scope,
260
+ sourcePath: sourceLayer.path,
261
+ precedence: sourceLayer.precedence,
262
+ value,
263
+ sourceHash: sha256(JSON.stringify(value)),
264
+ contributors: [toContributor(sourceLayer)],
265
+ });
266
+ continue;
267
+ }
268
+ const root = await canonicalDirectory(selected.installPath, `plugin ${pluginName}`);
269
+ if (!includeProjectInstalls && isWithin(root, projectRoot)) {
270
+ throw new Error(`plugin ${pluginName} resolves inside an untrusted project: ${root}`);
271
+ }
272
+ if (!approvedPluginRoots.some((approvedRoot) => isWithin(root, approvedRoot))) {
273
+ throw new Error(`plugin ${pluginName} is outside approved roots: ${root}`);
274
+ }
275
+ const scope = selected.projectPath ? 'project' : 'global';
276
+ const precedence = selected.projectPath ? 45 : 20;
277
+ const namespace = pluginName.split('@')[0];
278
+ const value = {
279
+ gitCommitSha: selected.gitCommitSha,
280
+ installPath: root,
281
+ lastUpdated: selected.lastUpdated,
282
+ pluginName,
283
+ scope,
284
+ version: selected.version,
285
+ };
286
+ addItem(context, {
287
+ category: 'plugins',
288
+ name: pluginName,
289
+ scope,
290
+ sourcePath: installedPath,
291
+ precedence,
292
+ value,
293
+ sourceHash: sha256(JSON.stringify(value)),
294
+ contributors: installed
295
+ ? [toContributor({ ...installed, path: installedPath, precedence, scope })]
296
+ : [],
297
+ });
298
+ plugins.push({ namespace, pluginName, precedence, root, scope });
299
+ }
300
+ return plugins;
301
+ }
302
+
303
+ async function selectPluginInstall(installs, projectRoot, includeProjectInstalls = true) {
304
+ if (includeProjectInstalls) {
305
+ for (const entry of installs) {
306
+ if (!entry.projectPath) continue;
307
+ try {
308
+ if ((await realpath(resolve(entry.projectPath))) === projectRoot) return entry;
309
+ } catch (error) {
310
+ if (error.code !== 'ENOENT') throw error;
311
+ }
312
+ }
313
+ }
314
+ return installs.find((entry) => entry.scope === 'user');
315
+ }
316
+
317
+ async function discoverInstructions(context, claudeHome, home, projectRoot) {
318
+ const candidates = [
319
+ {
320
+ path: join(claudeHome, 'CLAUDE.md'),
321
+ allowedRoot: home,
322
+ importRoot: claudeHome,
323
+ name: 'global:CLAUDE.md',
324
+ scope: 'global',
325
+ precedence: 10,
326
+ },
327
+ {
328
+ path: join(projectRoot, 'CLAUDE.md'),
329
+ allowedRoot: projectRoot,
330
+ name: 'project:CLAUDE.md',
331
+ scope: 'project',
332
+ precedence: 40,
333
+ },
334
+ {
335
+ path: join(projectRoot, '.claude', 'CLAUDE.md'),
336
+ allowedRoot: projectRoot,
337
+ name: 'project:.claude/CLAUDE.md',
338
+ scope: 'project',
339
+ precedence: 41,
340
+ },
341
+ ];
342
+ for (const candidate of candidates) {
343
+ const source = await readTextIfPresent(context, candidate.path, candidate.allowedRoot);
344
+ if (!source) continue;
345
+ const imports = instructionImports(source.value);
346
+ const instructionBody = source.value
347
+ .split(/\r?\n/)
348
+ .filter((line) => !/^\s*@[^\s]+\s*$/.test(line))
349
+ .join('\n');
350
+ const sanitized = sanitizeUntrustedText(instructionBody);
351
+ addItem(context, {
352
+ ...textItem(candidate, 'instructions', source),
353
+ value: {
354
+ body: sanitized.value,
355
+ ...(sanitized.findings.length > 0
356
+ ? { secretStatus: { $maudeSecret: 'literal-rejected' } }
357
+ : {}),
358
+ },
359
+ });
360
+ for (const [index, importPath] of imports.entries()) {
361
+ const imported = await inspectInstructionImport(
362
+ context,
363
+ importPath,
364
+ candidate.path,
365
+ candidate.importRoot ?? candidate.allowedRoot
366
+ );
367
+ const value = {
368
+ ...imported.value,
369
+ reference: importPath,
370
+ };
371
+ addItem(context, {
372
+ category: 'instruction-imports',
373
+ name: `${candidate.name}:import:${index}`,
374
+ scope: candidate.scope,
375
+ sourcePath: imported.path ?? candidate.path,
376
+ precedence: candidate.precedence,
377
+ value,
378
+ sourceHash: imported.sourceHash ?? sha256(importPath),
379
+ contributors: imported.contributor
380
+ ? [
381
+ contributor(candidate.path, candidate.scope, candidate.precedence, source.hash),
382
+ imported.contributor,
383
+ ]
384
+ : [contributor(candidate.path, candidate.scope, candidate.precedence, source.hash)],
385
+ });
386
+ }
387
+ }
388
+ }
389
+
390
+ async function discoverAssetRoot(
391
+ context,
392
+ root,
393
+ namespace,
394
+ scope,
395
+ precedence,
396
+ allowedRoot,
397
+ pluginOrigin
398
+ ) {
399
+ if (!(await pathExists(root))) return;
400
+ const roots = [
401
+ { category: 'commands', directory: join(root, 'commands'), recursive: false },
402
+ { category: 'agents', directory: join(root, 'agents'), recursive: false },
403
+ { category: 'rules', directory: join(root, 'rules'), recursive: true },
404
+ ];
405
+ for (const asset of roots) {
406
+ for (const file of await markdownFiles(
407
+ context,
408
+ asset.directory,
409
+ allowedRoot,
410
+ asset.recursive
411
+ )) {
412
+ const source = await readText(context, file, allowedRoot);
413
+ const parsed = parseMarkdown(source.value, context.limits.maxFrontmatterBytes, file);
414
+ const slug = asset.recursive
415
+ ? relative(asset.directory, file).replaceAll(sep, '/').replace(/\.md$/, '')
416
+ : basename(file, '.md');
417
+ addItem(context, {
418
+ category: asset.category,
419
+ origin: pluginOrigin ? 'plugin' : 'direct',
420
+ name: `${namespace}:${slug}`,
421
+ scope,
422
+ sourcePath: file,
423
+ precedence,
424
+ value: parsed,
425
+ sourceHash: source.hash,
426
+ contributors: [contributor(file, scope, precedence, source.hash)],
427
+ });
428
+ }
429
+ }
430
+
431
+ const skillsRoot = join(root, 'skills');
432
+ for (const file of await namedFiles(context, skillsRoot, allowedRoot, 'SKILL.md')) {
433
+ const inventory = await inventorySkillDirectory(context, dirname(file), allowedRoot);
434
+ const skillFile = inventory.files.find((entry) => entry.path === 'SKILL.md');
435
+ if (!skillFile) throw new Error(`skill directory has no regular SKILL.md: ${dirname(file)}`);
436
+ const parsed = parseMarkdown(
437
+ skillFile.bytes.toString('utf8'),
438
+ context.limits.maxFrontmatterBytes,
439
+ file
440
+ );
441
+ const slug = parsed.frontmatter.name || basename(dirname(file));
442
+ const sourceClosure = inventory.files.map(({ path, hash, bytes }) => {
443
+ let content;
444
+ try {
445
+ content = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
446
+ } catch {
447
+ throw new Error(`skill supporting file must be UTF-8 text: ${join(dirname(file), path)}`);
448
+ }
449
+ const sanitized = sanitizeUntrustedText(content);
450
+ return {
451
+ content: sanitized.value,
452
+ hash,
453
+ path,
454
+ ...(sanitized.findings.length > 0
455
+ ? { rejected: { $maudeSecret: 'literal-rejected' } }
456
+ : {}),
457
+ };
458
+ });
459
+ addItem(context, {
460
+ category: 'skills',
461
+ origin: pluginOrigin ? 'plugin' : 'direct',
462
+ name: `${namespace}:${slug}`,
463
+ scope,
464
+ sourcePath: file,
465
+ precedence,
466
+ value: { ...parsed, sourceClosure },
467
+ sourceHash: inventory.treeHash,
468
+ contributors: [contributor(file, scope, precedence, inventory.treeHash)],
469
+ });
470
+ }
471
+ }
472
+
473
+ async function discoverMcp(context, path, namespace, scope, precedence) {
474
+ const source = await readJsonIfPresent(context, path, dirname(path));
475
+ if (!source) return;
476
+ for (const [name, server] of Object.entries(source.value.mcpServers ?? {}).sort(([a], [b]) =>
477
+ a.localeCompare(b)
478
+ )) {
479
+ sanitizeMcpServer(server);
480
+ validateMcpServer(server, path, name);
481
+ const category = server.disabled
482
+ ? 'mcp-disabled'
483
+ : server.type === 'http'
484
+ ? 'mcp-http'
485
+ : server.type === 'sse'
486
+ ? 'mcp-sse'
487
+ : 'mcp-stdio';
488
+ addItem(context, {
489
+ category,
490
+ name: `${namespace}:${name}`,
491
+ scope,
492
+ sourcePath: path,
493
+ precedence,
494
+ value: server,
495
+ sourceHash: sha256(JSON.stringify(server)),
496
+ contributors: [toContributor({ ...source, path, precedence, scope })],
497
+ });
498
+ if (server.oauth) {
499
+ addItem(
500
+ context,
501
+ sourceItem(
502
+ { ...source, path, precedence, scope },
503
+ 'mcp-oauth',
504
+ `${namespace}:${name}`,
505
+ server.oauth
506
+ )
507
+ );
508
+ }
509
+ if (server.env || server.headers) {
510
+ addItem(
511
+ context,
512
+ sourceItem(
513
+ { ...source, path, precedence, scope },
514
+ 'mcp-environment',
515
+ `${namespace}:${name}`,
516
+ { env: server.env ?? {}, headers: server.headers ?? {} }
517
+ )
518
+ );
519
+ }
520
+ }
521
+ }
522
+
523
+ async function discoverHookFile(context, plugin) {
524
+ const path = join(plugin.root, 'hooks', 'hooks.json');
525
+ const source = await readJsonIfPresent(context, path, plugin.root);
526
+ if (!source) return;
527
+ addHooks(
528
+ context,
529
+ source.value.hooks,
530
+ plugin.namespace,
531
+ plugin.scope,
532
+ path,
533
+ plugin.precedence,
534
+ source.hash
535
+ );
536
+ }
537
+
538
+ function addHooks(context, hooks, namespace, scope, sourcePath, precedence, sourceHash) {
539
+ for (const [event, groups] of Object.entries(hooks ?? {}).sort(([a], [b]) =>
540
+ a.localeCompare(b)
541
+ )) {
542
+ for (const [groupIndex, group] of groups.entries()) {
543
+ for (const [hookIndex, hook] of (group.hooks ?? []).entries()) {
544
+ const type = hook.type ?? (hook.command ? 'command' : 'unknown');
545
+ const category = ['command', 'http', 'prompt', 'agent'].includes(type)
546
+ ? `hooks-${type}`
547
+ : 'hooks-unknown';
548
+ addItem(context, {
549
+ category,
550
+ name: `${namespace}:${event}:${precedence}:${groupIndex}:${hookIndex}`,
551
+ scope,
552
+ sourcePath,
553
+ precedence,
554
+ value: { event, matcher: group.matcher, ...hook },
555
+ sourceHash: sha256(JSON.stringify({ event, matcher: group.matcher, ...hook })),
556
+ contributors: [contributor(sourcePath, scope, precedence, sourceHash)],
557
+ });
558
+ }
559
+ }
560
+ }
561
+ }
562
+
563
+ async function discoverProjectState(context, projectRoot) {
564
+ for (const [directory, category] of [
565
+ ['.ai', 'ai-state'],
566
+ ['.design', 'design-state'],
567
+ ]) {
568
+ const path = join(projectRoot, directory);
569
+ if (!(await pathExists(path))) continue;
570
+ const pathInfo = await lstat(path);
571
+ const canonical = await realpath(path);
572
+ assertWithin(
573
+ canonical,
574
+ projectRoot,
575
+ pathInfo.isSymbolicLink() ? `symlink ${directory}` : directory
576
+ );
577
+ const canonicalInfo = pathInfo.isSymbolicLink() ? await stat(canonical) : pathInfo;
578
+ if (!canonicalInfo.isDirectory()) throw new Error(`${path} is not a directory`);
579
+ const value = { path, mode: 'reference' };
580
+ addItem(context, {
581
+ category,
582
+ name: `project:${directory}`,
583
+ scope: 'project',
584
+ sourcePath: path,
585
+ precedence: 40,
586
+ value,
587
+ sourceHash: sha256(path),
588
+ contributors: [contributor(path, 'project', 40, sha256(path))],
589
+ });
590
+ }
591
+ const configPath = join(projectRoot, '.ai', 'workflows.config.json');
592
+ const source = await readJsonIfPresent(context, configPath, join(projectRoot, '.ai'));
593
+ if (source?.value?.knowledgeGraph) {
594
+ addItem(context, {
595
+ category: 'kgai',
596
+ name: 'project:kgai',
597
+ scope: 'project',
598
+ sourcePath: configPath,
599
+ precedence: 40,
600
+ value: source.value.knowledgeGraph,
601
+ sourceHash: sha256(JSON.stringify(source.value.knowledgeGraph)),
602
+ contributors: [contributor(configPath, 'project', 40, source.hash)],
603
+ });
604
+ }
605
+ }
606
+
607
+ function addItem(context, item) {
608
+ context.items.push(item);
609
+ if (context.items.length > context.limits.maxItems) {
610
+ throw new Error(`Claude inventory exceeds ${context.limits.maxItems} items`);
611
+ }
612
+ }
613
+
614
+ function sourceItem(layer, category, name, value) {
615
+ return {
616
+ category,
617
+ name,
618
+ scope: layer.scope,
619
+ sourcePath: layer.path,
620
+ precedence: layer.precedence,
621
+ value,
622
+ sourceHash: sha256(JSON.stringify(value)),
623
+ contributors: [toContributor(layer)],
624
+ };
625
+ }
626
+
627
+ function textItem(candidate, category, source) {
628
+ return {
629
+ category,
630
+ name: candidate.name,
631
+ scope: candidate.scope,
632
+ sourcePath: candidate.path,
633
+ precedence: candidate.precedence,
634
+ value: source.value,
635
+ sourceHash: source.hash,
636
+ contributors: [contributor(candidate.path, candidate.scope, candidate.precedence, source.hash)],
637
+ };
638
+ }
639
+
640
+ function contributor(sourcePath, scope, precedence, sourceHash) {
641
+ return { sourcePath, scope, precedence, sourceHash };
642
+ }
643
+
644
+ function toContributor(layer) {
645
+ return contributor(layer.path, layer.scope, layer.precedence, layer.hash);
646
+ }
647
+
648
+ function mergeSettingValues(values) {
649
+ if (values.every(isPlainObject)) {
650
+ return values.reduce((result, value) => deepMerge(result, value), {});
651
+ }
652
+ if (values.every(Array.isArray)) return unique(values.flat());
653
+ return structuredClone(values.at(-1));
654
+ }
655
+
656
+ function mergePermissions(values) {
657
+ const result = {};
658
+ for (const value of values) {
659
+ for (const kind of ['allow', 'ask', 'deny']) {
660
+ if (value?.[kind]) result[kind] = unique([...(result[kind] ?? []), ...value[kind]]);
661
+ }
662
+ if (value?.defaultMode !== undefined) result.defaultMode = value.defaultMode;
663
+ }
664
+ return result;
665
+ }
666
+
667
+ function deepMerge(left, right) {
668
+ const result = structuredClone(left);
669
+ for (const [key, value] of Object.entries(right)) {
670
+ result[key] =
671
+ isPlainObject(value) && isPlainObject(result[key])
672
+ ? deepMerge(result[key], value)
673
+ : structuredClone(value);
674
+ }
675
+ return result;
676
+ }
677
+
678
+ function isPlainObject(value) {
679
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
680
+ }
681
+
682
+ function unique(values) {
683
+ return [...new Set(values)];
684
+ }
685
+
686
+ function instructionImports(content) {
687
+ return content
688
+ .split(/\r?\n/)
689
+ .map((line) => /^\s*@([^\s]+)\s*$/.exec(line)?.[1])
690
+ .filter(Boolean);
691
+ }
692
+
693
+ function parseMarkdown(content, maxFrontmatterBytes, path) {
694
+ if (!content.startsWith('---\n') && !content.startsWith('---\r\n')) {
695
+ return safeMarkdown({ body: content, frontmatter: {}, frontmatterMode: 'none' });
696
+ }
697
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
698
+ if (!match) throw new Error(`invalid Markdown frontmatter in ${path}`);
699
+ if (Buffer.byteLength(match[1]) > maxFrontmatterBytes) {
700
+ throw new Error(`frontmatter in ${path} exceeds ${maxFrontmatterBytes} bytes`);
701
+ }
702
+ const document = parseDocument(match[1], {
703
+ logLevel: 'silent',
704
+ prettyErrors: true,
705
+ strict: true,
706
+ uniqueKeys: true,
707
+ });
708
+ if (document.errors.length === 0) {
709
+ let parsed;
710
+ try {
711
+ parsed = document.toJS({ maxAliasCount: 0 }) ?? {};
712
+ } catch (error) {
713
+ throw new Error(`invalid Markdown frontmatter in ${path}: ${stableYamlDiagnostic(error)}`);
714
+ }
715
+ if (!isPlainObject(parsed))
716
+ throw new Error(`Markdown frontmatter in ${path} must be an object`);
717
+ const frontmatter = sanitizeUntrustedValue(parsed).value;
718
+ return safeMarkdown({
719
+ body: content.slice(match[0].length),
720
+ frontmatter,
721
+ frontmatterMode: 'yaml',
722
+ });
723
+ }
724
+ if (document.errors.some((error) => /duplicate|unique/i.test(error.message))) {
725
+ throw new Error(
726
+ `invalid Markdown frontmatter in ${path}: ${stableYamlDiagnostic(document.errors[0])}`
727
+ );
728
+ }
729
+ const frontmatter = sanitizeUntrustedValue(parseLooseFrontmatter(match[1], path)).value;
730
+ return safeMarkdown({
731
+ body: content.slice(match[0].length),
732
+ frontmatter,
733
+ frontmatterMode: 'claude-loose',
734
+ frontmatterWarning: stableYamlDiagnostic(document.errors[0]),
735
+ });
736
+ }
737
+
738
+ function parseLooseFrontmatter(source, path) {
739
+ const frontmatter = {};
740
+ const seen = new Set();
741
+ let currentKey;
742
+ for (const [index, line] of source.split(/\r?\n/).entries()) {
743
+ if (!line.trim() || line.trimStart().startsWith('#')) continue;
744
+ const pair = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
745
+ if (pair) {
746
+ currentKey = pair[1];
747
+ if (seen.has(currentKey)) {
748
+ throw new Error(
749
+ `duplicate Markdown frontmatter key in ${path}: LOOSE_DUPLICATE_KEY at line ${index + 2}, column 1`
750
+ );
751
+ }
752
+ seen.add(currentKey);
753
+ frontmatter[currentKey] = looseScalar(pair[2]);
754
+ continue;
755
+ }
756
+ const listItem = /^\s{2}-\s*(.*)$/.exec(line);
757
+ if (listItem && currentKey && frontmatter[currentKey] === '') {
758
+ frontmatter[currentKey] = [unquote(listItem[1].trim())];
759
+ continue;
760
+ }
761
+ if (listItem && currentKey && Array.isArray(frontmatter[currentKey])) {
762
+ frontmatter[currentKey].push(unquote(listItem[1].trim()));
763
+ continue;
764
+ }
765
+ if (/^\s+/.test(line)) {
766
+ throw new Error(
767
+ `unsupported nested Markdown frontmatter in ${path}: LOOSE_UNSUPPORTED_NESTING at line ${index + 2}, column ${line.search(/\S/) + 1}`
768
+ );
769
+ }
770
+ throw new Error(
771
+ `invalid Markdown frontmatter line in ${path}: LOOSE_INVALID_LINE at line ${index + 2}, column 1`
772
+ );
773
+ }
774
+ return frontmatter;
775
+ }
776
+
777
+ function stableYamlDiagnostic(error) {
778
+ const code = /^[A-Z][A-Z0-9_]+$/.test(error?.code) ? error.code : 'YAML_PARSE_ERROR';
779
+ const position = error?.linePos?.[0];
780
+ const line = Number.isInteger(position?.line) ? position.line + 1 : 1;
781
+ const column = Number.isInteger(position?.col) ? position.col : 1;
782
+ return `${code} at line ${line}, column ${column}`;
783
+ }
784
+
785
+ function safeMarkdown(parsed) {
786
+ const body = sanitizeUntrustedText(parsed.body);
787
+ return {
788
+ ...parsed,
789
+ body: body.value,
790
+ ...(body.findings.length > 0 ? { secretStatus: { $maudeSecret: 'literal-rejected' } } : {}),
791
+ };
792
+ }
793
+
794
+ function validateMcpServer(server, path, name) {
795
+ if (!isPlainObject(server)) throw new Error(`MCP server ${name} in ${path} must be an object`);
796
+ const type = server.type ?? (typeof server.command === 'string' ? 'stdio' : undefined);
797
+ if (server.disabled) {
798
+ if (typeof server.url === 'string') {
799
+ sanitizeRemoteMcpUrl(server, path, name, type ?? 'remote');
800
+ }
801
+ return;
802
+ }
803
+ if (type === 'stdio') {
804
+ if (typeof server.command !== 'string' || server.command.length === 0) {
805
+ throw new Error(`STDIO MCP server ${name} in ${path} requires command`);
806
+ }
807
+ if (
808
+ server.args &&
809
+ (!Array.isArray(server.args) ||
810
+ server.args.some(
811
+ (arg) =>
812
+ typeof arg !== 'string' &&
813
+ !(arg && typeof arg === 'object' && arg.$maudeSecret === 'literal-rejected')
814
+ ))
815
+ ) {
816
+ throw new Error(`STDIO MCP server ${name} in ${path} has invalid args`);
817
+ }
818
+ return;
819
+ }
820
+ if (type === 'http' || type === 'sse') {
821
+ sanitizeRemoteMcpUrl(server, path, name, type);
822
+ return;
823
+ }
824
+ throw new Error(`MCP server ${name} in ${path} has unsupported type`);
825
+ }
826
+
827
+ function sanitizeRemoteMcpUrl(server, path, name, type) {
828
+ let url;
829
+ try {
830
+ url = new URL(server.url);
831
+ } catch {
832
+ throw new Error(`${type.toUpperCase()} MCP server ${name} in ${path} has invalid URL`);
833
+ }
834
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
835
+ throw new Error(`${type.toUpperCase()} MCP server ${name} in ${path} has unsafe URL`);
836
+ }
837
+ const rawQuery = url.search.slice(1);
838
+ if (rawQuery) {
839
+ const components = rawQuery.split('&').map((component) => {
840
+ const separator = component.indexOf('=');
841
+ const rawKey = separator === -1 ? component : component.slice(0, separator);
842
+ const rawValue = separator === -1 ? undefined : component.slice(separator + 1);
843
+ const key = sanitizeUrlQueryComponent(rawKey);
844
+ const value = rawValue === undefined ? undefined : sanitizeUrlQueryComponent(rawValue);
845
+ if (key.rejected || value?.rejected) {
846
+ server.secretStatus = { $maudeSecret: 'literal-rejected' };
847
+ }
848
+ return value === undefined ? key.value : `${key.value}=${value.value}`;
849
+ });
850
+ url.search = components.join('&');
851
+ }
852
+ const fragment = decodeUrlSegment(url.hash.slice(1));
853
+ if (fragment && !isCredentialReference(fragment)) {
854
+ url.hash = encodeURIComponent('[REDACTED_LITERAL_SECRET]');
855
+ server.secretStatus = { $maudeSecret: 'literal-rejected' };
856
+ }
857
+ const pathSegments = url.pathname.split('/');
858
+ for (let index = 0; index < pathSegments.length; index += 1) {
859
+ const decoded = decodeUrlSegment(pathSegments[index]);
860
+ if (!classifyCredential(`https://credential.invalid/${decoded}`)) continue;
861
+ pathSegments[index] = encodeURIComponent('[REDACTED_LITERAL_SECRET]');
862
+ server.secretStatus = { $maudeSecret: 'literal-rejected' };
863
+ }
864
+ url.pathname = pathSegments.join('/');
865
+ server.url = url.toString();
866
+ }
867
+
868
+ function sanitizeUrlQueryComponent(component) {
869
+ if (!component) return { rejected: false, value: component };
870
+ const decoded = decodeUrlQueryComponent(component);
871
+ if (decoded !== undefined && isCredentialReference(decoded)) {
872
+ return { rejected: false, value: component };
873
+ }
874
+ return {
875
+ rejected: true,
876
+ value: encodeURIComponent('[REDACTED_LITERAL_SECRET]'),
877
+ };
878
+ }
879
+
880
+ function decodeUrlQueryComponent(component) {
881
+ try {
882
+ return decodeURIComponent(component.replaceAll('+', ' '));
883
+ } catch {
884
+ return undefined;
885
+ }
886
+ }
887
+
888
+ function sanitizeMcpServer(server) {
889
+ let rejected = false;
890
+ for (const field of ['env', 'headers']) {
891
+ if (server[field] === undefined) continue;
892
+ if (!isPlainObject(server[field])) throw new Error(`MCP server ${field} must be an object`);
893
+ for (const [key, value] of Object.entries(server[field])) {
894
+ if (typeof value !== 'string') continue;
895
+ const requiresReference = field === 'env' || classifyCredential(value, { key });
896
+ if (requiresReference && !isCredentialReference(value)) {
897
+ server[field][key] = '[REDACTED_LITERAL_SECRET]';
898
+ rejected = true;
899
+ }
900
+ }
901
+ }
902
+ if (Array.isArray(server.args)) {
903
+ for (let index = 0; index < server.args.length; index += 1) {
904
+ const value = server.args[index];
905
+ if (value?.$maudeSecret === 'literal-rejected') {
906
+ rejected = true;
907
+ continue;
908
+ }
909
+ if (typeof value !== 'string') continue;
910
+ const splitKind = mcpSplitArgumentKind(value);
911
+ if (splitKind) {
912
+ const next = server.args[index + 1];
913
+ if (typeof next === 'string' && mcpArgumentValueRejected(splitKind, next)) {
914
+ server.args[index + 1] = '[REDACTED_LITERAL_SECRET]';
915
+ rejected = true;
916
+ }
917
+ continue;
918
+ }
919
+ const concatenated = mcpConcatenatedArgument(value);
920
+ if (concatenated && mcpArgumentValueRejected(concatenated.kind, concatenated.value)) {
921
+ server.args[index] = '[REDACTED_LITERAL_SECRET]';
922
+ rejected = true;
923
+ }
924
+ }
925
+ }
926
+ if (rejected) server.secretStatus = { $maudeSecret: 'literal-rejected' };
927
+ }
928
+
929
+ function mcpSplitArgumentKind(value) {
930
+ if (value === '--env' || value === '-e') return 'env';
931
+ if (value === '--header' || value === '-H') return 'header';
932
+ return undefined;
933
+ }
934
+
935
+ function mcpConcatenatedArgument(value) {
936
+ if (value.startsWith('--env=')) return { kind: 'env', value: value.slice('--env='.length) };
937
+ if (value.startsWith('-e') && value.length > 2) return { kind: 'env', value: value.slice(2) };
938
+ if (value.startsWith('--header=')) {
939
+ return { kind: 'header', value: value.slice('--header='.length) };
940
+ }
941
+ if (value.startsWith('-H') && value.length > 2) return { kind: 'header', value: value.slice(2) };
942
+ return undefined;
943
+ }
944
+
945
+ function mcpArgumentValueRejected(kind, value) {
946
+ if (kind === 'env') {
947
+ const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(value);
948
+ return Boolean(
949
+ assignment && sanitizeConfiguredEnvironmentValue(assignment[1], assignment[2]).rejected
950
+ );
951
+ }
952
+ const header = /^([^:]+):\s*(.*)$/.exec(value);
953
+ return Boolean(
954
+ header &&
955
+ classifyCredential(header[2].trim(), { key: header[1] }) &&
956
+ !isCredentialReference(header[2].trim())
957
+ );
958
+ }
959
+
960
+ async function inspectInstructionImport(context, importPath, sourcePath, allowedRoot) {
961
+ if (isAbsolute(importPath) || importPath.startsWith('~')) {
962
+ return {
963
+ value: { contained: false, reason: 'absolute and home-relative imports are forbidden' },
964
+ };
965
+ }
966
+ const candidate = resolve(dirname(sourcePath), importPath);
967
+ if (!isWithin(candidate, allowedRoot)) {
968
+ return { value: { contained: false, reason: 'import escapes its allowed root' } };
969
+ }
970
+ const canonicalRoot = await realpath(allowedRoot);
971
+ const relativePath = relative(canonicalRoot, candidate).replaceAll(sep, '/');
972
+ let source;
973
+ try {
974
+ source = await readPinnedRelativeFile(context, canonicalRoot, relativePath);
975
+ } catch (error) {
976
+ if (error.code === 'ENOENT') {
977
+ return { value: { contained: false, reason: 'import is missing' } };
978
+ }
979
+ if (['ELOOP', 'ENOTDIR'].includes(error.code)) {
980
+ return { value: { contained: false, reason: 'instruction import path contains a symlink' } };
981
+ }
982
+ if (error.code === 'MAUDE_NOT_REGULAR') {
983
+ return { value: { contained: false, reason: 'instruction import is not a regular file' } };
984
+ }
985
+ throw error;
986
+ }
987
+ const sanitized = sanitizeUntrustedText(source.bytes.toString('utf8'));
988
+ const sourceHash = sha256(
989
+ `${relativePath}\0${source.identity.dev}:${source.identity.ino}\0${source.hash}`
990
+ );
991
+ return {
992
+ contributor: contributor(candidate, 'import', 0, sourceHash),
993
+ path: candidate,
994
+ sourceHash,
995
+ value: {
996
+ body: sanitized.value,
997
+ contained: true,
998
+ relativePath,
999
+ sourceIdentity: {
1000
+ device: String(source.identity.dev),
1001
+ inode: String(source.identity.ino),
1002
+ },
1003
+ ...(sanitized.findings.length > 0
1004
+ ? { secretStatus: { $maudeSecret: 'literal-rejected' } }
1005
+ : {}),
1006
+ },
1007
+ };
1008
+ }
1009
+
1010
+ async function readPinnedRelativeFile(context, root, relativePath) {
1011
+ const parts = relativePath.split('/').filter(Boolean);
1012
+ if (parts.length === 0 || parts.some((part) => part === '.' || part === '..')) {
1013
+ throw new Error(`instruction import has invalid canonical identity: ${relativePath}`);
1014
+ }
1015
+ if (parts.length - 1 > context.limits.maxDepth) {
1016
+ throw new Error(`${relativePath} exceeds maximum nesting depth ${context.limits.maxDepth}`);
1017
+ }
1018
+ const pins = [];
1019
+ let fileHandle;
1020
+ try {
1021
+ let parent = await pinImportDirectory(root, root);
1022
+ pins.push(parent);
1023
+ await context.failpoint('after-instruction-import-parent-pin', {
1024
+ depth: 0,
1025
+ relativePath,
1026
+ });
1027
+ for (let index = 0; index < parts.length - 1; index += 1) {
1028
+ const logicalPath = join(root, ...parts.slice(0, index + 1));
1029
+ parent = await pinImportDirectory(join(parent.descriptorPath, parts[index]), logicalPath);
1030
+ pins.push(parent);
1031
+ await context.failpoint('after-instruction-import-parent-pin', {
1032
+ depth: index + 1,
1033
+ relativePath,
1034
+ });
1035
+ }
1036
+
1037
+ const descriptorPath = join(parent.descriptorPath, parts.at(-1));
1038
+ fileHandle = await open(
1039
+ descriptorPath,
1040
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
1041
+ );
1042
+ const before = await fileHandle.stat();
1043
+ if (!before.isFile()) {
1044
+ const error = new Error(`instruction import is not a regular file: ${relativePath}`);
1045
+ error.code = 'MAUDE_NOT_REGULAR';
1046
+ throw error;
1047
+ }
1048
+ if (before.size > context.limits.maxFileBytes) {
1049
+ throw new Error(`${join(root, relativePath)} exceeds ${context.limits.maxFileBytes} bytes`);
1050
+ }
1051
+ const bytes = await fileHandle.readFile();
1052
+ const after = await fileHandle.stat();
1053
+ if (
1054
+ after.dev !== before.dev ||
1055
+ after.ino !== before.ino ||
1056
+ after.size !== before.size ||
1057
+ after.mtimeMs !== before.mtimeMs ||
1058
+ after.ctimeMs !== before.ctimeMs ||
1059
+ bytes.length !== before.size
1060
+ ) {
1061
+ throw new Error(`instruction import changed during descriptor read: ${relativePath}`);
1062
+ }
1063
+ context.files += 1;
1064
+ context.totalBytes += bytes.length;
1065
+ if (context.files > context.limits.maxFiles) {
1066
+ throw new Error(`Claude source exceeds ${context.limits.maxFiles} files`);
1067
+ }
1068
+ if (context.totalBytes > context.limits.maxTotalBytes) {
1069
+ throw new Error(`Claude source exceeds ${context.limits.maxTotalBytes} total bytes`);
1070
+ }
1071
+ return { bytes, hash: sha256(bytes), identity: { dev: before.dev, ino: before.ino } };
1072
+ } finally {
1073
+ await fileHandle?.close();
1074
+ await Promise.all(pins.reverse().map((pin) => pin.handle.close()));
1075
+ }
1076
+ }
1077
+
1078
+ async function pinImportDirectory(descriptorPath, logicalPath) {
1079
+ const handle = await open(
1080
+ descriptorPath,
1081
+ constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0)
1082
+ );
1083
+ try {
1084
+ const identity = await handle.stat();
1085
+ if (!identity.isDirectory()) {
1086
+ const error = new Error(`instruction import parent is not a directory: ${logicalPath}`);
1087
+ error.code = 'ENOTDIR';
1088
+ throw error;
1089
+ }
1090
+ let pinnedPath;
1091
+ if (process.platform === 'darwin') {
1092
+ pinnedPath = `/.vol/${identity.dev}/${identity.ino}`;
1093
+ } else if (process.platform === 'linux') {
1094
+ pinnedPath = `/proc/self/fd/${handle.fd}`;
1095
+ } else {
1096
+ throw new Error(
1097
+ `platform cannot safely read instruction imports descriptor-relative: ${process.platform}`
1098
+ );
1099
+ }
1100
+ const pinnedIdentity = await stat(pinnedPath);
1101
+ if (
1102
+ !pinnedIdentity.isDirectory() ||
1103
+ pinnedIdentity.dev !== identity.dev ||
1104
+ pinnedIdentity.ino !== identity.ino
1105
+ ) {
1106
+ throw new Error(`platform cannot resolve pinned instruction import parent: ${logicalPath}`);
1107
+ }
1108
+ return { descriptorPath: pinnedPath, handle };
1109
+ } catch (error) {
1110
+ await handle.close();
1111
+ throw error;
1112
+ }
1113
+ }
1114
+
1115
+ function decodeUrlSegment(segment) {
1116
+ try {
1117
+ return decodeURIComponent(segment);
1118
+ } catch {
1119
+ return segment;
1120
+ }
1121
+ }
1122
+
1123
+ function looseScalar(raw) {
1124
+ const value = raw.trim();
1125
+ if (value.startsWith('[') && value.endsWith(']')) {
1126
+ return value
1127
+ .slice(1, -1)
1128
+ .split(',')
1129
+ .map((part) => unquote(part.trim()))
1130
+ .filter(Boolean);
1131
+ }
1132
+ if (value === 'true') return true;
1133
+ if (value === 'false') return false;
1134
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
1135
+ return unquote(value);
1136
+ }
1137
+
1138
+ function unquote(value) {
1139
+ if (
1140
+ value.length >= 2 &&
1141
+ ((value.startsWith('"') && value.endsWith('"')) ||
1142
+ (value.startsWith("'") && value.endsWith("'")))
1143
+ ) {
1144
+ return value.slice(1, -1);
1145
+ }
1146
+ return value;
1147
+ }
1148
+
1149
+ async function readJsonIfPresent(context, path, allowedRoot) {
1150
+ const source = await readTextIfPresent(context, path, allowedRoot);
1151
+ if (!source) return undefined;
1152
+ try {
1153
+ const parsed = JSON.parse(source.value);
1154
+ if (!isPlainObject(parsed)) throw new Error('root value must be an object');
1155
+ const sanitized = sanitizeUntrustedValue(parsed, {
1156
+ maxDepth: context.limits.maxStructureDepth,
1157
+ maxNodes: context.limits.maxStructureNodes,
1158
+ });
1159
+ return {
1160
+ ...source,
1161
+ findings: sanitized.findings,
1162
+ hash: sha256(JSON.stringify(sanitized.value)),
1163
+ value: sanitized.value,
1164
+ };
1165
+ } catch (error) {
1166
+ throw new Error(`invalid JSON in ${path}: ${error.message}`);
1167
+ }
1168
+ }
1169
+
1170
+ async function readTextIfPresent(context, path, allowedRoot) {
1171
+ if (!(await pathExists(path))) return undefined;
1172
+ return readText(context, path, allowedRoot);
1173
+ }
1174
+
1175
+ async function readText(context, path, allowedRoot) {
1176
+ const source = await readBytes(context, path, allowedRoot);
1177
+ return { hash: source.hash, value: source.bytes.toString('utf8') };
1178
+ }
1179
+
1180
+ async function readBytes(context, path, allowedRoot, rejectSymlink = false) {
1181
+ const sourceInfo = await lstat(path);
1182
+ if (rejectSymlink && sourceInfo.isSymbolicLink()) {
1183
+ throw new Error(`Claude source cannot be a symlink: ${path}`);
1184
+ }
1185
+ const canonical = await realpath(path);
1186
+ const canonicalRoot = await realpath(allowedRoot);
1187
+ assertWithin(canonical, canonicalRoot, sourceInfo.isSymbolicLink() ? 'symlink source' : 'source');
1188
+ const handle = await open(canonical, constants.O_RDONLY | constants.O_NOFOLLOW);
1189
+ try {
1190
+ const info = await handle.stat();
1191
+ if (!info.isFile()) throw new Error(`Claude source is not a file: ${path}`);
1192
+ if (info.size > context.limits.maxFileBytes) {
1193
+ throw new Error(`${path} exceeds ${context.limits.maxFileBytes} bytes`);
1194
+ }
1195
+ context.files += 1;
1196
+ context.totalBytes += info.size;
1197
+ if (context.files > context.limits.maxFiles) {
1198
+ throw new Error(`Claude source exceeds ${context.limits.maxFiles} files`);
1199
+ }
1200
+ if (context.totalBytes > context.limits.maxTotalBytes) {
1201
+ throw new Error(`Claude source exceeds ${context.limits.maxTotalBytes} total bytes`);
1202
+ }
1203
+ const bytes = await handle.readFile();
1204
+ const rechecked = await realpath(path);
1205
+ if (rechecked !== canonical) throw new Error(`Claude source changed during read: ${path}`);
1206
+ return { bytes, hash: sha256(bytes) };
1207
+ } finally {
1208
+ await handle.close();
1209
+ }
1210
+ }
1211
+
1212
+ async function inventorySkillDirectory(
1213
+ context,
1214
+ directory,
1215
+ allowedRoot,
1216
+ depth = 0,
1217
+ skillRoot = directory
1218
+ ) {
1219
+ if (depth > context.limits.maxDepth) {
1220
+ throw new Error(`${directory} exceeds maximum nesting depth ${context.limits.maxDepth}`);
1221
+ }
1222
+ const info = await lstat(directory);
1223
+ if (info.isSymbolicLink())
1224
+ throw new Error(`skill directory cannot contain symlink: ${directory}`);
1225
+ if (!info.isDirectory()) throw new Error(`skill root is not a directory: ${directory}`);
1226
+ const canonicalDirectoryPath = await realpath(directory);
1227
+ const canonicalRoot = await realpath(allowedRoot);
1228
+ assertWithin(canonicalDirectoryPath, canonicalRoot, 'skill directory');
1229
+ const files = [];
1230
+ for (const entry of (await readdir(canonicalDirectoryPath, { withFileTypes: true })).sort(
1231
+ (a, b) => a.name.localeCompare(b.name)
1232
+ )) {
1233
+ context.entries += 1;
1234
+ if (context.entries > context.limits.maxEntries) {
1235
+ throw new Error(`Claude source exceeds ${context.limits.maxEntries} directory entries`);
1236
+ }
1237
+ const path = join(canonicalDirectoryPath, entry.name);
1238
+ if (entry.isSymbolicLink()) throw new Error(`skill directory cannot contain symlink: ${path}`);
1239
+ if (entry.isDirectory()) {
1240
+ const nested = await inventorySkillDirectory(
1241
+ context,
1242
+ path,
1243
+ canonicalRoot,
1244
+ depth + 1,
1245
+ skillRoot
1246
+ );
1247
+ files.push(...nested.files);
1248
+ continue;
1249
+ }
1250
+ if (!entry.isFile()) throw new Error(`skill directory contains non-regular file: ${path}`);
1251
+ if (isSkillRuntimeCacheFile(entry.name)) continue;
1252
+ const source = await readBytes(context, path, canonicalRoot, true);
1253
+ files.push({
1254
+ bytes: source.bytes,
1255
+ hash: source.hash,
1256
+ path: relative(skillRoot, path).replaceAll(sep, '/'),
1257
+ });
1258
+ }
1259
+ files.sort((left, right) => left.path.localeCompare(right.path));
1260
+ const sourceClosure = files.map(({ path, hash }) => `${path}\0${hash}`).join('\n');
1261
+ return { files, treeHash: sha256(sourceClosure) };
1262
+ }
1263
+
1264
+ function isSkillRuntimeCacheFile(name) {
1265
+ return name === '.DS_Store' || name.endsWith('.pyc') || name.endsWith('.pyo');
1266
+ }
1267
+
1268
+ async function markdownFiles(context, directory, allowedRoot, recursive) {
1269
+ return listFiles(context, directory, allowedRoot, {
1270
+ recursive,
1271
+ matches: (name) => name.endsWith('.md') && !name.startsWith('_'),
1272
+ });
1273
+ }
1274
+
1275
+ async function namedFiles(context, directory, allowedRoot, targetName) {
1276
+ return listFiles(context, directory, allowedRoot, {
1277
+ recursive: true,
1278
+ matches: (name) => name === targetName,
1279
+ });
1280
+ }
1281
+
1282
+ async function listFiles(
1283
+ context,
1284
+ directory,
1285
+ allowedRoot,
1286
+ { recursive, matches },
1287
+ depth = 0,
1288
+ visited = new Set()
1289
+ ) {
1290
+ if (!(await pathExists(directory))) return [];
1291
+ if (depth > context.limits.maxDepth) {
1292
+ throw new Error(`${directory} exceeds maximum nesting depth ${context.limits.maxDepth}`);
1293
+ }
1294
+ const directoryInfo = await lstat(directory);
1295
+ const canonicalDirectoryPath = await realpath(directory);
1296
+ const canonicalRoot = await realpath(allowedRoot);
1297
+ assertWithin(
1298
+ canonicalDirectoryPath,
1299
+ canonicalRoot,
1300
+ directoryInfo.isSymbolicLink() ? 'symlink directory' : 'directory'
1301
+ );
1302
+ if (visited.has(canonicalDirectoryPath)) return [];
1303
+ visited.add(canonicalDirectoryPath);
1304
+ const resolvedDirectoryInfo = directoryInfo.isSymbolicLink()
1305
+ ? await stat(canonicalDirectoryPath)
1306
+ : directoryInfo;
1307
+ if (!resolvedDirectoryInfo.isDirectory()) {
1308
+ throw new Error(`Claude asset root is not a directory: ${directory}`);
1309
+ }
1310
+ const entries = await readdir(canonicalDirectoryPath, { withFileTypes: true });
1311
+ const files = [];
1312
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1313
+ context.entries += 1;
1314
+ if (context.entries > context.limits.maxEntries) {
1315
+ throw new Error(`Claude source exceeds ${context.limits.maxEntries} directory entries`);
1316
+ }
1317
+ const path = join(canonicalDirectoryPath, entry.name);
1318
+ if (entry.isSymbolicLink()) {
1319
+ const canonicalPath = await realpath(path);
1320
+ if (!isWithin(canonicalPath, canonicalRoot)) {
1321
+ throw new Error(`symlink source escapes its allowed root: ${path}`);
1322
+ }
1323
+ const resolvedInfo = await stat(canonicalPath);
1324
+ if (recursive && resolvedInfo.isDirectory()) {
1325
+ files.push(
1326
+ ...(await listFiles(
1327
+ context,
1328
+ canonicalPath,
1329
+ canonicalRoot,
1330
+ { recursive, matches },
1331
+ depth + 1,
1332
+ visited
1333
+ ))
1334
+ );
1335
+ continue;
1336
+ }
1337
+ throw new Error(`Claude asset cannot contain symlink: ${path}`);
1338
+ }
1339
+ if (entry.isFile() && matches(entry.name)) files.push(path);
1340
+ if (recursive && entry.isDirectory()) {
1341
+ files.push(
1342
+ ...(await listFiles(
1343
+ context,
1344
+ path,
1345
+ canonicalRoot,
1346
+ { recursive, matches },
1347
+ depth + 1,
1348
+ visited
1349
+ ))
1350
+ );
1351
+ }
1352
+ }
1353
+ return files;
1354
+ }
1355
+
1356
+ async function canonicalDirectory(path, label) {
1357
+ const absolute = resolve(path);
1358
+ const info = await lstat(absolute);
1359
+ if (info.isSymbolicLink()) throw new Error(`${label} cannot be a symlink: ${absolute}`);
1360
+ if (!info.isDirectory()) throw new Error(`${label} is not a directory: ${absolute}`);
1361
+ return realpath(absolute);
1362
+ }
1363
+
1364
+ async function existingCanonicalDirectories(paths) {
1365
+ const directories = [];
1366
+ for (const path of paths) {
1367
+ if (!(await pathExists(path))) continue;
1368
+ directories.push(await canonicalDirectory(path, 'approved plugin root'));
1369
+ }
1370
+ return directories;
1371
+ }
1372
+
1373
+ function isWithin(path, root) {
1374
+ const rel = relative(root, path);
1375
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
1376
+ }
1377
+
1378
+ function assertWithin(path, root, label) {
1379
+ const rel = relative(root, path);
1380
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
1381
+ throw new Error(`${label} path escapes its allowed root: ${path}`);
1382
+ }
1383
+ }
1384
+
1385
+ async function pathExists(path) {
1386
+ try {
1387
+ await stat(path);
1388
+ return true;
1389
+ } catch (error) {
1390
+ if (error.code === 'ENOENT') return false;
1391
+ throw error;
1392
+ }
1393
+ }