@lesliechan721/aw 0.1.0-beta.10 → 0.1.0-beta.101

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 (864) hide show
  1. package/dist/authoring/assets/aw-config.d.mts +1 -50
  2. package/dist/authoring/assets/aw-config.mjs +58 -928
  3. package/dist/authoring/assets/aw-config.mjs.map +1 -1
  4. package/dist/authoring/assets/aw-runtime-config.d.mts +13 -0
  5. package/dist/authoring/assets/aw-runtime-config.mjs +221 -0
  6. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -0
  7. package/dist/authoring/assets/command-runtime-config.d.mts +9 -0
  8. package/dist/authoring/assets/command-runtime-config.mjs +134 -0
  9. package/dist/authoring/assets/command-runtime-config.mjs.map +1 -0
  10. package/dist/authoring/scripts/add-skill.mjs +16 -39
  11. package/dist/authoring/scripts/add-skill.mjs.map +1 -1
  12. package/dist/authoring/scripts/init-plugin.mjs +43 -71
  13. package/dist/authoring/scripts/init-plugin.mjs.map +1 -1
  14. package/dist/authoring/scripts/lib/plugin-root.mjs +4 -4
  15. package/dist/authoring/scripts/lib/plugin-root.mjs.map +1 -1
  16. package/dist/authoring/scripts/lib/plugin-version-check.d.mts +1 -0
  17. package/dist/authoring/scripts/lib/plugin-version-check.mjs +230 -9
  18. package/dist/authoring/scripts/lib/plugin-version-check.mjs.map +1 -1
  19. package/dist/authoring/scripts/lib/skill-scaffold.d.mts +3 -3
  20. package/dist/authoring/scripts/lib/skill-scaffold.mjs +5 -8
  21. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -1
  22. package/dist/authoring/scripts/remove-plugin.mjs +1 -1
  23. package/dist/authoring/scripts/remove-plugin.mjs.map +1 -1
  24. package/dist/authoring/scripts/validate-plugin.mjs +408 -1748
  25. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  26. package/dist/authoring/scripts/validate-skill.mjs +1 -1
  27. package/dist/index.js +2 -6
  28. package/dist/index.js.map +1 -1
  29. package/dist/native-runtime/reader-runtime.mjs +34 -0
  30. package/dist/native-runtime/reader.d.mts +6 -0
  31. package/dist/native-runtime/reader.mjs +11 -0
  32. package/dist/scripts/aw-skill-eval-materializer.d.ts +11 -1
  33. package/dist/scripts/aw-skill-eval-materializer.js +119 -114
  34. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  35. package/dist/scripts/bundle-plugins.js +32 -7
  36. package/dist/scripts/bundle-plugins.js.map +1 -1
  37. package/dist/scripts/plugin-staging.d.ts +1 -1
  38. package/dist/scripts/plugin-staging.js +5 -2
  39. package/dist/scripts/plugin-staging.js.map +1 -1
  40. package/dist/scripts/plugin-test-context-guard.d.mts +1 -0
  41. package/dist/scripts/plugin-test-context-guard.mjs +59 -0
  42. package/dist/scripts/plugin-test-context-guard.mjs.map +1 -0
  43. package/dist/scripts/plugin-test-reporter.d.mts +2 -0
  44. package/dist/scripts/plugin-test-reporter.mjs +21 -0
  45. package/dist/scripts/plugin-test-reporter.mjs.map +1 -0
  46. package/dist/scripts/test-plugin-scripts.d.ts +5 -0
  47. package/dist/scripts/test-plugin-scripts.js +343 -58
  48. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  49. package/dist/scripts/test-workers.d.mts +24 -0
  50. package/dist/scripts/test-workers.mjs +59 -0
  51. package/dist/scripts/test-workers.mjs.map +1 -0
  52. package/dist/src/adapters/helpers.d.ts +7 -0
  53. package/dist/src/adapters/helpers.js.map +1 -1
  54. package/dist/src/authoring/workspace-commands.d.ts +3 -0
  55. package/dist/src/authoring/workspace-commands.js +7 -2
  56. package/dist/src/authoring/workspace-commands.js.map +1 -1
  57. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  58. package/dist/src/commands/aw-capabilities.js +48 -19
  59. package/dist/src/commands/aw-capabilities.js.map +1 -1
  60. package/dist/src/commands/catalog-dev-source.d.ts +40 -3
  61. package/dist/src/commands/catalog-dev-source.js +333 -42
  62. package/dist/src/commands/catalog-dev-source.js.map +1 -1
  63. package/dist/src/commands/catalog-generation.d.ts +5 -0
  64. package/dist/src/commands/catalog-generation.js.map +1 -1
  65. package/dist/src/commands/catalog-publication-inspection.d.ts +11 -3
  66. package/dist/src/commands/catalog-publication-inspection.js +211 -59
  67. package/dist/src/commands/catalog-publication-inspection.js.map +1 -1
  68. package/dist/src/commands/catalog-publication-journal.d.ts +12 -0
  69. package/dist/src/commands/catalog-publication-journal.js +78 -1
  70. package/dist/src/commands/catalog-publication-journal.js.map +1 -1
  71. package/dist/src/commands/catalog-publish.d.ts +21 -1
  72. package/dist/src/commands/catalog-publish.js +133 -92
  73. package/dist/src/commands/catalog-publish.js.map +1 -1
  74. package/dist/src/commands/catalog-source.d.ts +26 -5
  75. package/dist/src/commands/catalog-source.js +154 -27
  76. package/dist/src/commands/catalog-source.js.map +1 -1
  77. package/dist/src/commands/catalog-status.js +2 -2
  78. package/dist/src/commands/catalog-status.js.map +1 -1
  79. package/dist/src/commands/catalog-store.d.ts +35 -7
  80. package/dist/src/commands/catalog-store.js +469 -79
  81. package/dist/src/commands/catalog-store.js.map +1 -1
  82. package/dist/src/commands/catalog-workspace-resolution.d.ts +4 -0
  83. package/dist/src/commands/catalog-workspace-resolution.js +18 -3
  84. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -1
  85. package/dist/src/commands/console.js +33 -20
  86. package/dist/src/commands/console.js.map +1 -1
  87. package/dist/src/commands/dependency-operation-plan.d.ts +7 -0
  88. package/dist/src/commands/dependency-operation-plan.js +66 -30
  89. package/dist/src/commands/dependency-operation-plan.js.map +1 -1
  90. package/dist/src/commands/deployment-confirmation.d.ts +11 -0
  91. package/dist/src/commands/deployment-confirmation.js +101 -0
  92. package/dist/src/commands/deployment-confirmation.js.map +1 -0
  93. package/dist/src/commands/init.js +1 -1
  94. package/dist/src/commands/init.js.map +1 -1
  95. package/dist/src/commands/intent-command.d.ts +35 -0
  96. package/dist/src/commands/intent-command.js +174 -0
  97. package/dist/src/commands/intent-command.js.map +1 -0
  98. package/dist/src/commands/lifecycle-command-package.d.ts +45 -0
  99. package/dist/src/commands/lifecycle-command-package.js +199 -0
  100. package/dist/src/commands/lifecycle-command-package.js.map +1 -0
  101. package/dist/src/commands/managed-commands.d.ts +41 -0
  102. package/dist/src/commands/managed-commands.js +408 -0
  103. package/dist/src/commands/managed-commands.js.map +1 -0
  104. package/dist/src/commands/offline-cleanup-evidence.d.ts +12 -2
  105. package/dist/src/commands/offline-cleanup-evidence.js +57 -35
  106. package/dist/src/commands/offline-cleanup-evidence.js.map +1 -1
  107. package/dist/src/commands/operation-plan.d.ts +72 -2
  108. package/dist/src/commands/operation-plan.js +54 -3
  109. package/dist/src/commands/operation-plan.js.map +1 -1
  110. package/dist/src/commands/operation-planner.d.ts +6 -5
  111. package/dist/src/commands/operation-planner.js +23 -20
  112. package/dist/src/commands/operation-planner.js.map +1 -1
  113. package/dist/src/commands/options.d.ts +11 -16
  114. package/dist/src/commands/options.js +31 -25
  115. package/dist/src/commands/options.js.map +1 -1
  116. package/dist/src/commands/permission-batch.d.ts +5 -0
  117. package/dist/src/commands/permission-batch.js +83 -0
  118. package/dist/src/commands/permission-batch.js.map +1 -0
  119. package/dist/src/commands/plugin-capabilities.js +128 -58
  120. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  121. package/dist/src/commands/public-config-confirmation.d.ts +14 -0
  122. package/dist/src/commands/public-config-confirmation.js +73 -0
  123. package/dist/src/commands/public-config-confirmation.js.map +1 -0
  124. package/dist/src/commands/public-interruption.d.ts +9 -0
  125. package/dist/src/commands/public-interruption.js +23 -0
  126. package/dist/src/commands/public-interruption.js.map +1 -0
  127. package/dist/src/commands/public-lifecycle-result.d.ts +107 -0
  128. package/dist/src/commands/public-lifecycle-result.js +536 -0
  129. package/dist/src/commands/public-lifecycle-result.js.map +1 -0
  130. package/dist/src/commands/public-lifecycle.d.ts +28 -0
  131. package/dist/src/commands/public-lifecycle.js +633 -0
  132. package/dist/src/commands/public-lifecycle.js.map +1 -0
  133. package/dist/src/commands/public-plugin-query.d.ts +16 -0
  134. package/dist/src/commands/public-plugin-query.js +235 -0
  135. package/dist/src/commands/public-plugin-query.js.map +1 -0
  136. package/dist/src/commands/rebuild-command.d.ts +177 -16
  137. package/dist/src/commands/rebuild-command.js +3374 -1558
  138. package/dist/src/commands/rebuild-command.js.map +1 -1
  139. package/dist/src/commands/rebuild-integration.d.ts +100 -55
  140. package/dist/src/commands/rebuild-integration.js +866 -3275
  141. package/dist/src/commands/rebuild-integration.js.map +1 -1
  142. package/dist/src/commands/rebuild-operations.d.ts +68 -13
  143. package/dist/src/commands/rebuild-operations.js +309 -120
  144. package/dist/src/commands/rebuild-operations.js.map +1 -1
  145. package/dist/src/commands/rebuild-platform-integration.d.ts +99 -0
  146. package/dist/src/commands/rebuild-platform-integration.js +2329 -0
  147. package/dist/src/commands/rebuild-platform-integration.js.map +1 -0
  148. package/dist/src/commands/reconcile-operation-plan.d.ts +14 -9
  149. package/dist/src/commands/reconcile-operation-plan.js +26 -6
  150. package/dist/src/commands/reconcile-operation-plan.js.map +1 -1
  151. package/dist/src/commands/review-inspection.d.ts +60 -0
  152. package/dist/src/commands/review-inspection.js +437 -0
  153. package/dist/src/commands/review-inspection.js.map +1 -0
  154. package/dist/src/commands/review-preparation.d.ts +51 -0
  155. package/dist/src/commands/review-preparation.js +400 -0
  156. package/dist/src/commands/review-preparation.js.map +1 -0
  157. package/dist/src/commands/runtime.d.ts +7 -1
  158. package/dist/src/commands/runtime.js +41 -8
  159. package/dist/src/commands/runtime.js.map +1 -1
  160. package/dist/src/commands/skill-eval.d.ts +8 -0
  161. package/dist/src/commands/skill-eval.js +126 -73
  162. package/dist/src/commands/skill-eval.js.map +1 -1
  163. package/dist/src/commands/status-v6.d.ts +148 -35
  164. package/dist/src/commands/status-v6.js +1166 -307
  165. package/dist/src/commands/status-v6.js.map +1 -1
  166. package/dist/src/commands/targets-command.d.ts +38 -0
  167. package/dist/src/commands/targets-command.js +210 -0
  168. package/dist/src/commands/targets-command.js.map +1 -0
  169. package/dist/src/commands/wizard.d.ts +7 -3
  170. package/dist/src/commands/wizard.js +7 -4
  171. package/dist/src/commands/wizard.js.map +1 -1
  172. package/dist/src/commands/write-commands.d.ts +7 -1
  173. package/dist/src/commands/write-commands.js +129 -38
  174. package/dist/src/commands/write-commands.js.map +1 -1
  175. package/dist/src/constants.d.ts +2 -3
  176. package/dist/src/constants.js +2 -3
  177. package/dist/src/constants.js.map +1 -1
  178. package/dist/src/eval/manifest-v1.d.ts +6 -3
  179. package/dist/src/eval/manifest-v1.js +44 -33
  180. package/dist/src/eval/manifest-v1.js.map +1 -1
  181. package/dist/src/generators/local-plugin.d.ts +4 -2
  182. package/dist/src/generators/local-plugin.js +319 -353
  183. package/dist/src/generators/local-plugin.js.map +1 -1
  184. package/dist/src/generators/permissions.d.ts +20 -2
  185. package/dist/src/generators/permissions.js +82 -15
  186. package/dist/src/generators/permissions.js.map +1 -1
  187. package/dist/src/index.d.ts +3 -34
  188. package/dist/src/index.js +1711 -1935
  189. package/dist/src/index.js.map +1 -1
  190. package/dist/src/intent/deployment-preferences.d.ts +63 -0
  191. package/dist/src/intent/deployment-preferences.js +170 -0
  192. package/dist/src/intent/deployment-preferences.js.map +1 -0
  193. package/dist/src/intent/diagnostics.d.ts +11 -0
  194. package/dist/src/intent/diagnostics.js +14 -0
  195. package/dist/src/intent/diagnostics.js.map +1 -0
  196. package/dist/src/intent/intent-codec.d.ts +19 -0
  197. package/dist/src/intent/intent-codec.js +117 -0
  198. package/dist/src/intent/intent-codec.js.map +1 -0
  199. package/dist/src/intent/intent-store.d.ts +43 -0
  200. package/dist/src/intent/intent-store.js +118 -0
  201. package/dist/src/intent/intent-store.js.map +1 -0
  202. package/dist/src/intent/scope-context.d.ts +35 -0
  203. package/dist/src/intent/scope-context.js +179 -0
  204. package/dist/src/intent/scope-context.js.map +1 -0
  205. package/dist/src/intent/work-context.d.ts +13 -0
  206. package/dist/src/intent/work-context.js +22 -0
  207. package/dist/src/intent/work-context.js.map +1 -0
  208. package/dist/src/output/cli-progress.d.ts +30 -0
  209. package/dist/src/output/cli-progress.js +424 -0
  210. package/dist/src/output/cli-progress.js.map +1 -0
  211. package/dist/src/output/command-receipt.d.ts +6 -2
  212. package/dist/src/output/command-receipt.js +67 -32
  213. package/dist/src/output/command-receipt.js.map +1 -1
  214. package/dist/src/output/component-delivery.d.ts +28 -0
  215. package/dist/src/output/component-delivery.js +141 -0
  216. package/dist/src/output/component-delivery.js.map +1 -0
  217. package/dist/src/output/model.d.ts +123 -1
  218. package/dist/src/output/model.js +45 -1
  219. package/dist/src/output/model.js.map +1 -1
  220. package/dist/src/output/public-command-ids.d.ts +8 -0
  221. package/dist/src/output/public-command-ids.js +38 -0
  222. package/dist/src/output/public-command-ids.js.map +1 -0
  223. package/dist/src/output/public-result.d.ts +71 -0
  224. package/dist/src/output/public-result.js +40 -0
  225. package/dist/src/output/public-result.js.map +1 -0
  226. package/dist/src/output/rebuild-progress.d.ts +3 -0
  227. package/dist/src/output/rebuild-progress.js +34 -9
  228. package/dist/src/output/rebuild-progress.js.map +1 -1
  229. package/dist/src/output/receipt-projection.d.ts +7 -0
  230. package/dist/src/output/receipt-projection.js +670 -0
  231. package/dist/src/output/receipt-projection.js.map +1 -0
  232. package/dist/src/output/render/document.d.ts +55 -0
  233. package/dist/src/output/render/document.js +176 -0
  234. package/dist/src/output/render/document.js.map +1 -0
  235. package/dist/src/output/render/shared.d.ts +18 -0
  236. package/dist/src/output/render/shared.js +245 -0
  237. package/dist/src/output/render/shared.js.map +1 -0
  238. package/dist/src/output/render/style.d.ts +45 -0
  239. package/dist/src/output/render/style.js +155 -0
  240. package/dist/src/output/render/style.js.map +1 -0
  241. package/dist/src/output/render/views/commands-self.d.ts +6 -0
  242. package/dist/src/output/render/views/commands-self.js +210 -0
  243. package/dist/src/output/render/views/commands-self.js.map +1 -0
  244. package/dist/src/output/render/views/config.d.ts +2 -0
  245. package/dist/src/output/render/views/config.js +203 -0
  246. package/dist/src/output/render/views/config.js.map +1 -0
  247. package/dist/src/output/render/views/dev.d.ts +2 -0
  248. package/dist/src/output/render/views/dev.js +278 -0
  249. package/dist/src/output/render/views/dev.js.map +1 -0
  250. package/dist/src/output/render/views/fallback.d.ts +2 -0
  251. package/dist/src/output/render/views/fallback.js +6 -0
  252. package/dist/src/output/render/views/fallback.js.map +1 -0
  253. package/dist/src/output/render/views/index.d.ts +3 -0
  254. package/dist/src/output/render/views/index.js +79 -0
  255. package/dist/src/output/render/views/index.js.map +1 -0
  256. package/dist/src/output/render/views/lifecycle.d.ts +5 -0
  257. package/dist/src/output/render/views/lifecycle.js +170 -0
  258. package/dist/src/output/render/views/lifecycle.js.map +1 -0
  259. package/dist/src/output/render/views/sources-cache.d.ts +3 -0
  260. package/dist/src/output/render/views/sources-cache.js +322 -0
  261. package/dist/src/output/render/views/sources-cache.js.map +1 -0
  262. package/dist/src/output/render/views/targets.d.ts +2 -0
  263. package/dist/src/output/render/views/targets.js +82 -0
  264. package/dist/src/output/render/views/targets.js.map +1 -0
  265. package/dist/src/output/skill-invocation-notices.d.ts +18 -0
  266. package/dist/src/output/skill-invocation-notices.js +84 -0
  267. package/dist/src/output/skill-invocation-notices.js.map +1 -0
  268. package/dist/src/platforms/antigravity-permissions.d.ts +50 -0
  269. package/dist/src/platforms/antigravity-permissions.js +388 -0
  270. package/dist/src/platforms/antigravity-permissions.js.map +1 -0
  271. package/dist/src/platforms/capabilities.d.ts +9 -0
  272. package/dist/src/platforms/capabilities.js +125 -0
  273. package/dist/src/platforms/capabilities.js.map +1 -0
  274. package/dist/src/platforms/contracts.d.ts +394 -0
  275. package/dist/src/platforms/contracts.js +2 -0
  276. package/dist/src/platforms/contracts.js.map +1 -0
  277. package/dist/src/platforms/cursor-workspace-hook.d.ts +28 -0
  278. package/dist/src/platforms/cursor-workspace-hook.js +198 -0
  279. package/dist/src/platforms/cursor-workspace-hook.js.map +1 -0
  280. package/dist/src/platforms/discovery.d.ts +100 -0
  281. package/dist/src/platforms/discovery.js +796 -0
  282. package/dist/src/platforms/discovery.js.map +1 -0
  283. package/dist/src/platforms/grok-permission-config.d.ts +23 -0
  284. package/dist/src/platforms/grok-permission-config.js +184 -0
  285. package/dist/src/platforms/grok-permission-config.js.map +1 -0
  286. package/dist/src/platforms/grok-permission-document.d.ts +4 -0
  287. package/dist/src/platforms/grok-permission-document.js +145 -0
  288. package/dist/src/platforms/grok-permission-document.js.map +1 -0
  289. package/dist/src/platforms/grok-permissions.d.ts +17 -0
  290. package/dist/src/platforms/grok-permissions.js +311 -0
  291. package/dist/src/platforms/grok-permissions.js.map +1 -0
  292. package/dist/src/platforms/host-permission-policy.d.ts +38 -0
  293. package/dist/src/platforms/host-permission-policy.js +86 -0
  294. package/dist/src/platforms/host-permission-policy.js.map +1 -0
  295. package/dist/src/platforms/identity.d.ts +4 -0
  296. package/dist/src/platforms/identity.js +22 -0
  297. package/dist/src/platforms/identity.js.map +1 -0
  298. package/dist/src/platforms/inspection-grok.d.ts +4 -0
  299. package/dist/src/platforms/inspection-grok.js +380 -0
  300. package/dist/src/platforms/inspection-grok.js.map +1 -0
  301. package/dist/src/platforms/inspection-native.d.ts +8 -0
  302. package/dist/src/platforms/inspection-native.js +584 -0
  303. package/dist/src/platforms/inspection-native.js.map +1 -0
  304. package/dist/src/platforms/inspection-opencode.d.ts +4 -0
  305. package/dist/src/platforms/inspection-opencode.js +98 -0
  306. package/dist/src/platforms/inspection-opencode.js.map +1 -0
  307. package/dist/src/platforms/inspection-pi.d.ts +9 -0
  308. package/dist/src/platforms/inspection-pi.js +490 -0
  309. package/dist/src/platforms/inspection-pi.js.map +1 -0
  310. package/dist/src/platforms/inspection-query.d.ts +26 -0
  311. package/dist/src/platforms/inspection-query.js +118 -0
  312. package/dist/src/platforms/inspection-query.js.map +1 -0
  313. package/dist/src/platforms/inspection.d.ts +20 -0
  314. package/dist/src/platforms/inspection.js +259 -0
  315. package/dist/src/platforms/inspection.js.map +1 -0
  316. package/dist/src/platforms/layout.d.ts +35 -0
  317. package/dist/src/platforms/layout.js +332 -0
  318. package/dist/src/platforms/layout.js.map +1 -0
  319. package/dist/src/platforms/lifecycle-native-services.d.ts +3 -0
  320. package/dist/src/platforms/lifecycle-native-services.js +213 -0
  321. package/dist/src/platforms/lifecycle-native-services.js.map +1 -0
  322. package/dist/src/platforms/lifecycle-native.d.ts +14 -0
  323. package/dist/src/platforms/lifecycle-native.js +234 -0
  324. package/dist/src/platforms/lifecycle-native.js.map +1 -0
  325. package/dist/src/platforms/lifecycle.d.ts +29 -0
  326. package/dist/src/platforms/lifecycle.js +688 -0
  327. package/dist/src/platforms/lifecycle.js.map +1 -0
  328. package/dist/src/platforms/opencode-permission-config.d.ts +13 -0
  329. package/dist/src/platforms/opencode-permission-config.js +253 -0
  330. package/dist/src/platforms/opencode-permission-config.js.map +1 -0
  331. package/dist/src/platforms/opencode-permissions.d.ts +39 -0
  332. package/dist/src/platforms/opencode-permissions.js +212 -0
  333. package/dist/src/platforms/opencode-permissions.js.map +1 -0
  334. package/dist/src/platforms/opencode-related-permissions.d.ts +40 -0
  335. package/dist/src/platforms/opencode-related-permissions.js +177 -0
  336. package/dist/src/platforms/opencode-related-permissions.js.map +1 -0
  337. package/dist/src/platforms/permission-ownership.d.ts +89 -0
  338. package/dist/src/platforms/permission-ownership.js +543 -0
  339. package/dist/src/platforms/permission-ownership.js.map +1 -0
  340. package/dist/src/platforms/permission-sidecar.d.ts +70 -0
  341. package/dist/src/platforms/permission-sidecar.js +215 -0
  342. package/dist/src/platforms/permission-sidecar.js.map +1 -0
  343. package/dist/src/platforms/projection-code-extension.d.ts +8 -0
  344. package/dist/src/platforms/projection-code-extension.js +126 -0
  345. package/dist/src/platforms/projection-code-extension.js.map +1 -0
  346. package/dist/src/platforms/projection-command-resources.d.ts +7 -0
  347. package/dist/src/platforms/projection-command-resources.js +74 -0
  348. package/dist/src/platforms/projection-command-resources.js.map +1 -0
  349. package/dist/src/platforms/projection-files.d.ts +28 -0
  350. package/dist/src/platforms/projection-files.js +113 -0
  351. package/dist/src/platforms/projection-files.js.map +1 -0
  352. package/dist/src/platforms/projection-marketplace.d.ts +19 -0
  353. package/dist/src/platforms/projection-marketplace.js +42 -0
  354. package/dist/src/platforms/projection-marketplace.js.map +1 -0
  355. package/dist/src/platforms/projection.d.ts +13 -0
  356. package/dist/src/platforms/projection.js +578 -0
  357. package/dist/src/platforms/projection.js.map +1 -0
  358. package/dist/src/platforms/read-only-retry-policy.d.ts +34 -0
  359. package/dist/src/platforms/read-only-retry-policy.js +70 -0
  360. package/dist/src/platforms/read-only-retry-policy.js.map +1 -0
  361. package/dist/src/platforms/registry.d.ts +4 -0
  362. package/dist/src/platforms/registry.js +30 -0
  363. package/dist/src/platforms/registry.js.map +1 -0
  364. package/dist/src/platforms/retirement-native.d.ts +6 -0
  365. package/dist/src/platforms/retirement-native.js +95 -0
  366. package/dist/src/platforms/retirement-native.js.map +1 -0
  367. package/dist/src/platforms/supplement-layout.d.ts +20 -0
  368. package/dist/src/platforms/supplement-layout.js +54 -0
  369. package/dist/src/platforms/supplement-layout.js.map +1 -0
  370. package/dist/src/platforms/supplement-state.d.ts +13 -0
  371. package/dist/src/platforms/supplement-state.js +93 -0
  372. package/dist/src/platforms/supplement-state.js.map +1 -0
  373. package/dist/src/portable/commands.d.ts +60 -11
  374. package/dist/src/portable/commands.js +88 -346
  375. package/dist/src/portable/commands.js.map +1 -1
  376. package/dist/src/portable/historical-materialization.d.ts +25 -0
  377. package/dist/src/portable/historical-materialization.js +148 -0
  378. package/dist/src/portable/historical-materialization.js.map +1 -0
  379. package/dist/src/portable/materializer.d.ts +46 -2
  380. package/dist/src/portable/materializer.js +262 -259
  381. package/dist/src/portable/materializer.js.map +1 -1
  382. package/dist/src/portable/recovery-layout.d.ts +17 -0
  383. package/dist/src/portable/recovery-layout.js +42 -0
  384. package/dist/src/portable/recovery-layout.js.map +1 -0
  385. package/dist/src/portable/recovery.d.ts +177 -0
  386. package/dist/src/portable/recovery.js +597 -0
  387. package/dist/src/portable/recovery.js.map +1 -0
  388. package/dist/src/portable/writer.d.ts +67 -0
  389. package/dist/src/portable/writer.js +321 -0
  390. package/dist/src/portable/writer.js.map +1 -0
  391. package/dist/src/recovery/coordinator.d.ts +175 -0
  392. package/dist/src/recovery/coordinator.js +1629 -0
  393. package/dist/src/recovery/coordinator.js.map +1 -0
  394. package/dist/src/recovery/demand.d.ts +53 -0
  395. package/dist/src/recovery/demand.js +189 -0
  396. package/dist/src/recovery/demand.js.map +1 -0
  397. package/dist/src/recovery/install-concurrency.d.ts +48 -0
  398. package/dist/src/recovery/install-concurrency.js +196 -0
  399. package/dist/src/recovery/install-concurrency.js.map +1 -0
  400. package/dist/src/recovery/interruption.d.ts +19 -0
  401. package/dist/src/recovery/interruption.js +43 -0
  402. package/dist/src/recovery/interruption.js.map +1 -0
  403. package/dist/src/recovery/joint-coordinator.d.ts +46 -0
  404. package/dist/src/recovery/joint-coordinator.js +1728 -0
  405. package/dist/src/recovery/joint-coordinator.js.map +1 -0
  406. package/dist/src/recovery/joint-demand.d.ts +72 -0
  407. package/dist/src/recovery/joint-demand.js +332 -0
  408. package/dist/src/recovery/joint-demand.js.map +1 -0
  409. package/dist/src/recovery/joint-install-execution.d.ts +19 -0
  410. package/dist/src/recovery/joint-install-execution.js +312 -0
  411. package/dist/src/recovery/joint-install-execution.js.map +1 -0
  412. package/dist/src/recovery/joint-install-native-rebase.d.ts +4 -0
  413. package/dist/src/recovery/joint-install-native-rebase.js +67 -0
  414. package/dist/src/recovery/joint-install-native-rebase.js.map +1 -0
  415. package/dist/src/recovery/performance.d.ts +4 -0
  416. package/dist/src/recovery/performance.js +26 -0
  417. package/dist/src/recovery/performance.js.map +1 -0
  418. package/dist/src/recovery/receipt.d.ts +131 -0
  419. package/dist/src/recovery/receipt.js +91 -0
  420. package/dist/src/recovery/receipt.js.map +1 -0
  421. package/dist/src/recovery/retirement.d.ts +47 -0
  422. package/dist/src/recovery/retirement.js +504 -0
  423. package/dist/src/recovery/retirement.js.map +1 -0
  424. package/dist/src/recovery/status.d.ts +143 -0
  425. package/dist/src/recovery/status.js +1528 -0
  426. package/dist/src/recovery/status.js.map +1 -0
  427. package/dist/src/recovery/types.d.ts +85 -0
  428. package/dist/src/recovery/types.js +2 -0
  429. package/dist/src/recovery/types.js.map +1 -0
  430. package/dist/src/review/eval-source-input.d.ts +44 -0
  431. package/dist/src/review/eval-source-input.js +213 -0
  432. package/dist/src/review/eval-source-input.js.map +1 -0
  433. package/dist/src/review/platform-profile.d.ts +5 -0
  434. package/dist/src/review/platform-profile.js +13 -0
  435. package/dist/src/review/platform-profile.js.map +1 -0
  436. package/dist/src/review/review-profile.d.ts +20 -0
  437. package/dist/src/review/review-profile.js +286 -0
  438. package/dist/src/review/review-profile.js.map +1 -0
  439. package/dist/src/review/review-selection.d.ts +20 -0
  440. package/dist/src/review/review-selection.js +502 -0
  441. package/dist/src/review/review-selection.js.map +1 -0
  442. package/dist/src/review/review-types.d.ts +71 -0
  443. package/dist/src/review/review-types.js +16 -0
  444. package/dist/src/review/review-types.js.map +1 -0
  445. package/dist/src/review/skill-materialization.d.ts +67 -0
  446. package/dist/src/review/skill-materialization.js +235 -0
  447. package/dist/src/review/skill-materialization.js.map +1 -0
  448. package/dist/src/review/source-binding.d.ts +203 -0
  449. package/dist/src/review/source-binding.js +791 -0
  450. package/dist/src/review/source-binding.js.map +1 -0
  451. package/dist/src/tui/agent-management.d.ts +23 -0
  452. package/dist/src/tui/agent-management.js +319 -0
  453. package/dist/src/tui/agent-management.js.map +1 -0
  454. package/dist/src/tui/agent-settings.d.ts +47 -0
  455. package/dist/src/tui/agent-settings.js +97 -0
  456. package/dist/src/tui/agent-settings.js.map +1 -0
  457. package/dist/src/tui/catalog-generation.d.ts +9 -0
  458. package/dist/src/tui/catalog-generation.js +96 -6
  459. package/dist/src/tui/catalog-generation.js.map +1 -1
  460. package/dist/src/tui/catalog-sources/projection.d.ts +2 -2
  461. package/dist/src/tui/catalog-sources/screens.js +19 -12
  462. package/dist/src/tui/catalog-sources/screens.js.map +1 -1
  463. package/dist/src/tui/catalog-sources/session.d.ts +11 -1
  464. package/dist/src/tui/catalog-sources/session.js +80 -5
  465. package/dist/src/tui/catalog-sources/session.js.map +1 -1
  466. package/dist/src/tui/catalog-sources/types.d.ts +15 -2
  467. package/dist/src/tui/catalog-store-task.d.ts +16 -0
  468. package/dist/src/tui/catalog-store-task.js +19 -0
  469. package/dist/src/tui/catalog-store-task.js.map +1 -0
  470. package/dist/src/tui/clipboard.d.ts +13 -0
  471. package/dist/src/tui/clipboard.js +95 -0
  472. package/dist/src/tui/clipboard.js.map +1 -0
  473. package/dist/src/tui/components.d.ts +113 -3
  474. package/dist/src/tui/components.js +201 -34
  475. package/dist/src/tui/components.js.map +1 -1
  476. package/dist/src/tui/config-array-draft.d.ts +30 -0
  477. package/dist/src/tui/config-array-draft.js +51 -0
  478. package/dist/src/tui/config-array-draft.js.map +1 -0
  479. package/dist/src/tui/config-leaf-editor.d.ts +44 -0
  480. package/dist/src/tui/config-leaf-editor.js +227 -0
  481. package/dist/src/tui/config-leaf-editor.js.map +1 -0
  482. package/dist/src/tui/config-object-suggestions.d.ts +15 -0
  483. package/dist/src/tui/config-object-suggestions.js +71 -0
  484. package/dist/src/tui/config-object-suggestions.js.map +1 -0
  485. package/dist/src/tui/config-references.d.ts +38 -0
  486. package/dist/src/tui/config-references.js +82 -0
  487. package/dist/src/tui/config-references.js.map +1 -0
  488. package/dist/src/tui/config-suggestions.d.ts +27 -0
  489. package/dist/src/tui/config-suggestions.js +62 -0
  490. package/dist/src/tui/config-suggestions.js.map +1 -0
  491. package/dist/src/tui/config-value-presentation.d.ts +23 -0
  492. package/dist/src/tui/config-value-presentation.js +151 -0
  493. package/dist/src/tui/config-value-presentation.js.map +1 -0
  494. package/dist/src/tui/console-app-v4.d.ts +14 -5
  495. package/dist/src/tui/console-app-v4.js +9779 -2488
  496. package/dist/src/tui/console-app-v4.js.map +1 -1
  497. package/dist/src/tui/content-item-card.d.ts +13 -0
  498. package/dist/src/tui/content-item-card.js +51 -0
  499. package/dist/src/tui/content-item-card.js.map +1 -0
  500. package/dist/src/tui/controller-runtime.d.ts +4 -3
  501. package/dist/src/tui/controller-runtime.js +1610 -590
  502. package/dist/src/tui/controller-runtime.js.map +1 -1
  503. package/dist/src/tui/controller.d.ts +583 -80
  504. package/dist/src/tui/controller.js +3362 -263
  505. package/dist/src/tui/controller.js.map +1 -1
  506. package/dist/src/tui/dependency-graph-view.d.ts +39 -0
  507. package/dist/src/tui/dependency-graph-view.js +121 -0
  508. package/dist/src/tui/dependency-graph-view.js.map +1 -0
  509. package/dist/src/tui/dependency-graph.d.ts +81 -0
  510. package/dist/src/tui/dependency-graph.js +452 -0
  511. package/dist/src/tui/dependency-graph.js.map +1 -0
  512. package/dist/src/tui/deployment-view.d.ts +14 -0
  513. package/dist/src/tui/deployment-view.js +175 -0
  514. package/dist/src/tui/deployment-view.js.map +1 -0
  515. package/dist/src/tui/diagnostic-projection.d.ts +31 -0
  516. package/dist/src/tui/diagnostic-projection.js +681 -0
  517. package/dist/src/tui/diagnostic-projection.js.map +1 -0
  518. package/dist/src/tui/diagnostics.d.ts +6 -2
  519. package/dist/src/tui/diagnostics.js +14 -2
  520. package/dist/src/tui/diagnostics.js.map +1 -1
  521. package/dist/src/tui/entity-cards.d.ts +56 -0
  522. package/dist/src/tui/entity-cards.js +327 -0
  523. package/dist/src/tui/entity-cards.js.map +1 -0
  524. package/dist/src/tui/glossary.d.ts +25 -0
  525. package/dist/src/tui/glossary.js +78 -0
  526. package/dist/src/tui/glossary.js.map +1 -0
  527. package/dist/src/tui/guided-setup.d.ts +25 -0
  528. package/dist/src/tui/guided-setup.js +101 -0
  529. package/dist/src/tui/guided-setup.js.map +1 -0
  530. package/dist/src/tui/index.d.ts +4 -1
  531. package/dist/src/tui/index.js +4 -1
  532. package/dist/src/tui/index.js.map +1 -1
  533. package/dist/src/tui/input-display.d.ts +1 -0
  534. package/dist/src/tui/input-display.js +23 -1
  535. package/dist/src/tui/input-display.js.map +1 -1
  536. package/dist/src/tui/keys.d.ts +44 -0
  537. package/dist/src/tui/keys.js +43 -15
  538. package/dist/src/tui/keys.js.map +1 -1
  539. package/dist/src/tui/lifecycle-action-view.d.ts +6 -0
  540. package/dist/src/tui/lifecycle-action-view.js +36 -0
  541. package/dist/src/tui/lifecycle-action-view.js.map +1 -0
  542. package/dist/src/tui/model.d.ts +141 -28
  543. package/dist/src/tui/model.js +968 -285
  544. package/dist/src/tui/model.js.map +1 -1
  545. package/dist/src/tui/operation-diagnostic-screens.d.ts +8 -0
  546. package/dist/src/tui/operation-diagnostic-screens.js +76 -0
  547. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -0
  548. package/dist/src/tui/operation-history.d.ts +91 -0
  549. package/dist/src/tui/operation-history.js +167 -0
  550. package/dist/src/tui/operation-history.js.map +1 -0
  551. package/dist/src/tui/operation-review-planner.d.ts +7 -0
  552. package/dist/src/tui/operation-review-planner.js +980 -146
  553. package/dist/src/tui/operation-review-planner.js.map +1 -1
  554. package/dist/src/tui/plugin-content.d.ts +33 -0
  555. package/dist/src/tui/plugin-content.js +245 -0
  556. package/dist/src/tui/plugin-content.js.map +1 -0
  557. package/dist/src/tui/plugin-detail.d.ts +75 -0
  558. package/dist/src/tui/plugin-detail.js +267 -0
  559. package/dist/src/tui/plugin-detail.js.map +1 -0
  560. package/dist/src/tui/plugin-write-task.d.ts +69 -0
  561. package/dist/src/tui/plugin-write-task.js +286 -0
  562. package/dist/src/tui/plugin-write-task.js.map +1 -0
  563. package/dist/src/tui/query-header.d.ts +30 -0
  564. package/dist/src/tui/query-header.js +40 -0
  565. package/dist/src/tui/query-header.js.map +1 -0
  566. package/dist/src/tui/reader.d.ts +38 -0
  567. package/dist/src/tui/reader.js +49 -0
  568. package/dist/src/tui/reader.js.map +1 -0
  569. package/dist/src/tui/router.d.ts +170 -39
  570. package/dist/src/tui/router.js +338 -50
  571. package/dist/src/tui/router.js.map +1 -1
  572. package/dist/src/tui/scoped-flow.d.ts +49 -0
  573. package/dist/src/tui/scoped-flow.js +212 -0
  574. package/dist/src/tui/scoped-flow.js.map +1 -0
  575. package/dist/src/tui/scoped-inventory.d.ts +139 -0
  576. package/dist/src/tui/scoped-inventory.js +295 -0
  577. package/dist/src/tui/scoped-inventory.js.map +1 -0
  578. package/dist/src/tui/screen-registry.d.ts +696 -0
  579. package/dist/src/tui/screen-registry.js +226 -0
  580. package/dist/src/tui/screen-registry.js.map +1 -0
  581. package/dist/src/tui/session-console-app.d.ts +8 -0
  582. package/dist/src/tui/session-console-app.js +24 -0
  583. package/dist/src/tui/session-console-app.js.map +1 -0
  584. package/dist/src/tui/session-host.d.ts +45 -0
  585. package/dist/src/tui/session-host.js +219 -0
  586. package/dist/src/tui/session-host.js.map +1 -0
  587. package/dist/src/tui/source-detail-card.d.ts +29 -0
  588. package/dist/src/tui/source-detail-card.js +45 -0
  589. package/dist/src/tui/source-detail-card.js.map +1 -0
  590. package/dist/src/tui/theme.d.ts +12 -0
  591. package/dist/src/tui/theme.js +12 -0
  592. package/dist/src/tui/theme.js.map +1 -1
  593. package/dist/src/tui/viewport.d.ts +1 -0
  594. package/dist/src/tui/viewport.js +23 -0
  595. package/dist/src/tui/viewport.js.map +1 -1
  596. package/dist/src/tui/wizard.js +26 -4
  597. package/dist/src/tui/wizard.js.map +1 -1
  598. package/dist/src/types.d.ts +105 -83
  599. package/dist/src/types.js +1 -1
  600. package/dist/src/types.js.map +1 -1
  601. package/dist/src/utils/agent-version.d.ts +10 -4
  602. package/dist/src/utils/agent-version.js +6 -8
  603. package/dist/src/utils/agent-version.js.map +1 -1
  604. package/dist/src/utils/artifact-plan.d.ts +18 -25
  605. package/dist/src/utils/artifact-plan.js +59 -445
  606. package/dist/src/utils/artifact-plan.js.map +1 -1
  607. package/dist/src/utils/artifact-renderer.d.ts +64 -90
  608. package/dist/src/utils/artifact-renderer.js +202 -303
  609. package/dist/src/utils/artifact-renderer.js.map +1 -1
  610. package/dist/src/utils/artifact-request.d.ts +19 -14
  611. package/dist/src/utils/artifact-request.js +51 -36
  612. package/dist/src/utils/artifact-request.js.map +1 -1
  613. package/dist/src/utils/artifact-sources.d.ts +4 -8
  614. package/dist/src/utils/artifact-sources.js +15 -6
  615. package/dist/src/utils/artifact-sources.js.map +1 -1
  616. package/dist/src/utils/aw-home-mutation-lock.d.ts +1 -0
  617. package/dist/src/utils/aw-home-mutation-lock.js +28 -6
  618. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  619. package/dist/src/utils/bundle-layout.d.ts +2 -0
  620. package/dist/src/utils/bundle-layout.js +88 -158
  621. package/dist/src/utils/bundle-layout.js.map +1 -1
  622. package/dist/src/utils/catalog-capability-projection.d.ts +8 -0
  623. package/dist/src/utils/catalog-capability-projection.js +14 -0
  624. package/dist/src/utils/catalog-capability-projection.js.map +1 -0
  625. package/dist/src/utils/catalog-digests.d.ts +2 -12
  626. package/dist/src/utils/catalog-digests.js +7 -55
  627. package/dist/src/utils/catalog-digests.js.map +1 -1
  628. package/dist/src/utils/catalog-generation-resolver.d.ts +28 -4
  629. package/dist/src/utils/catalog-generation-resolver.js +146 -40
  630. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  631. package/dist/src/utils/catalog-generation-service.d.ts +25 -2
  632. package/dist/src/utils/catalog-generation-service.js +99 -48
  633. package/dist/src/utils/catalog-generation-service.js.map +1 -1
  634. package/dist/src/utils/catalog-generation-state.js +1 -1
  635. package/dist/src/utils/catalog-generation-state.js.map +1 -1
  636. package/dist/src/utils/catalog-generation-store.d.ts +5 -0
  637. package/dist/src/utils/catalog-generation-store.js +69 -10
  638. package/dist/src/utils/catalog-generation-store.js.map +1 -1
  639. package/dist/src/utils/catalog-operation-context.d.ts +61 -4
  640. package/dist/src/utils/catalog-operation-context.js +225 -4
  641. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  642. package/dist/src/utils/catalog-public-error.js +4 -0
  643. package/dist/src/utils/catalog-public-error.js.map +1 -1
  644. package/dist/src/utils/catalog-runtime-projection.d.ts +4 -3
  645. package/dist/src/utils/catalog-runtime-projection.js.map +1 -1
  646. package/dist/src/utils/catalog-snapshot.d.ts +3 -0
  647. package/dist/src/utils/catalog-snapshot.js +4 -1
  648. package/dist/src/utils/catalog-snapshot.js.map +1 -1
  649. package/dist/src/utils/catalog-source-impact.d.ts +3 -2
  650. package/dist/src/utils/catalog-source-impact.js +142 -20
  651. package/dist/src/utils/catalog-source-impact.js.map +1 -1
  652. package/dist/src/utils/catalog-source-references.d.ts +57 -1
  653. package/dist/src/utils/catalog-source-references.js +755 -162
  654. package/dist/src/utils/catalog-source-references.js.map +1 -1
  655. package/dist/src/utils/catalog-sources.d.ts +1 -1
  656. package/dist/src/utils/catalog-sources.js +21 -5
  657. package/dist/src/utils/catalog-sources.js.map +1 -1
  658. package/dist/src/utils/codex-config.d.ts +3 -0
  659. package/dist/src/utils/codex-config.js +7 -0
  660. package/dist/src/utils/codex-config.js.map +1 -1
  661. package/dist/src/utils/codex-executable-discovery.d.ts +28 -0
  662. package/dist/src/utils/codex-executable-discovery.js +431 -0
  663. package/dist/src/utils/codex-executable-discovery.js.map +1 -0
  664. package/dist/src/utils/codex-manager.d.ts +23 -42
  665. package/dist/src/utils/codex-manager.js +79 -767
  666. package/dist/src/utils/codex-manager.js.map +1 -1
  667. package/dist/src/utils/codex-native-observation.d.ts +40 -1
  668. package/dist/src/utils/codex-native-observation.js +172 -0
  669. package/dist/src/utils/codex-native-observation.js.map +1 -1
  670. package/dist/src/utils/codex-reconciler.d.ts +2 -7
  671. package/dist/src/utils/codex-reconciler.js +33 -5
  672. package/dist/src/utils/codex-reconciler.js.map +1 -1
  673. package/dist/src/utils/codex-shared-native.d.ts +8 -26
  674. package/dist/src/utils/codex-shared-native.js +63 -83
  675. package/dist/src/utils/codex-shared-native.js.map +1 -1
  676. package/dist/src/utils/codex-skill-staging.d.ts +4 -3
  677. package/dist/src/utils/codex-skill-staging.js.map +1 -1
  678. package/dist/src/utils/codex-skills-root.d.ts +4 -0
  679. package/dist/src/utils/codex-skills-root.js +29 -0
  680. package/dist/src/utils/codex-skills-root.js.map +1 -0
  681. package/dist/src/utils/codex-surface-analysis.d.ts +6 -2
  682. package/dist/src/utils/codex-surface-analysis.js +31 -56
  683. package/dist/src/utils/codex-surface-analysis.js.map +1 -1
  684. package/dist/src/utils/component-agent-binding.d.ts +17 -0
  685. package/dist/src/utils/component-agent-binding.js +119 -0
  686. package/dist/src/utils/component-agent-binding.js.map +1 -0
  687. package/dist/src/utils/component-command-preparation.d.ts +33 -0
  688. package/dist/src/utils/component-command-preparation.js +129 -0
  689. package/dist/src/utils/component-command-preparation.js.map +1 -0
  690. package/dist/src/utils/component-gap.d.ts +4 -0
  691. package/dist/src/utils/component-gap.js +16 -0
  692. package/dist/src/utils/component-gap.js.map +1 -0
  693. package/dist/src/utils/component-resources.d.ts +53 -0
  694. package/dist/src/utils/component-resources.js +340 -0
  695. package/dist/src/utils/component-resources.js.map +1 -0
  696. package/dist/src/utils/config-platforms.d.ts +21 -0
  697. package/dist/src/utils/config-platforms.js +51 -0
  698. package/dist/src/utils/config-platforms.js.map +1 -0
  699. package/dist/src/utils/dynamic-skill-tree.d.ts +18 -6
  700. package/dist/src/utils/dynamic-skill-tree.js +33 -40
  701. package/dist/src/utils/dynamic-skill-tree.js.map +1 -1
  702. package/dist/src/utils/git-catalog-provider.d.ts +3 -0
  703. package/dist/src/utils/git-catalog-provider.js +49 -3
  704. package/dist/src/utils/git-catalog-provider.js.map +1 -1
  705. package/dist/src/utils/inventory-recovery-diagnostic.d.ts +4 -0
  706. package/dist/src/utils/inventory-recovery-diagnostic.js +15 -0
  707. package/dist/src/utils/inventory-recovery-diagnostic.js.map +1 -0
  708. package/dist/src/utils/local-marketplace.d.ts +19 -12
  709. package/dist/src/utils/local-marketplace.js +97 -194
  710. package/dist/src/utils/local-marketplace.js.map +1 -1
  711. package/dist/src/utils/managed-command-cli-review.d.ts +53 -0
  712. package/dist/src/utils/managed-command-cli-review.js +431 -0
  713. package/dist/src/utils/managed-command-cli-review.js.map +1 -0
  714. package/dist/src/utils/managed-command-closure.d.ts +14 -0
  715. package/dist/src/utils/managed-command-closure.js +156 -0
  716. package/dist/src/utils/managed-command-closure.js.map +1 -0
  717. package/dist/src/utils/managed-command-errors.d.ts +5 -0
  718. package/dist/src/utils/managed-command-errors.js +10 -0
  719. package/dist/src/utils/managed-command-errors.js.map +1 -0
  720. package/dist/src/utils/managed-command-materialization.d.ts +90 -0
  721. package/dist/src/utils/managed-command-materialization.js +375 -0
  722. package/dist/src/utils/managed-command-materialization.js.map +1 -0
  723. package/dist/src/utils/managed-command-preparation.d.ts +30 -0
  724. package/dist/src/utils/managed-command-preparation.js +39 -0
  725. package/dist/src/utils/managed-command-preparation.js.map +1 -0
  726. package/dist/src/utils/managed-command-review.d.ts +33 -0
  727. package/dist/src/utils/managed-command-review.js +80 -0
  728. package/dist/src/utils/managed-command-review.js.map +1 -0
  729. package/dist/src/utils/managed-command-runtime.d.ts +36 -0
  730. package/dist/src/utils/managed-command-runtime.js +126 -0
  731. package/dist/src/utils/managed-command-runtime.js.map +1 -0
  732. package/dist/src/utils/managed-command-snapshots.d.ts +24 -0
  733. package/dist/src/utils/managed-command-snapshots.js +89 -0
  734. package/dist/src/utils/managed-command-snapshots.js.map +1 -0
  735. package/dist/src/utils/managed-command-store.d.ts +141 -0
  736. package/dist/src/utils/managed-command-store.js +839 -0
  737. package/dist/src/utils/managed-command-store.js.map +1 -0
  738. package/dist/src/utils/multi-source-catalog.d.ts +6 -1
  739. package/dist/src/utils/multi-source-catalog.js +9 -4
  740. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  741. package/dist/src/utils/native-cli-interruption.d.ts +11 -0
  742. package/dist/src/utils/native-cli-interruption.js +106 -0
  743. package/dist/src/utils/native-cli-interruption.js.map +1 -0
  744. package/dist/src/utils/native-cli.d.ts +37 -6
  745. package/dist/src/utils/native-cli.js +523 -60
  746. package/dist/src/utils/native-cli.js.map +1 -1
  747. package/dist/src/utils/native-demand.d.ts +29 -0
  748. package/dist/src/utils/native-demand.js +4 -0
  749. package/dist/src/utils/native-demand.js.map +1 -0
  750. package/dist/src/utils/native-tool-context.d.ts +17 -0
  751. package/dist/src/utils/native-tool-context.js +40 -0
  752. package/dist/src/utils/native-tool-context.js.map +1 -0
  753. package/dist/src/utils/native-tool-review.d.ts +8 -0
  754. package/dist/src/utils/native-tool-review.js +14 -0
  755. package/dist/src/utils/native-tool-review.js.map +1 -0
  756. package/dist/src/utils/ownership.d.ts +38 -3
  757. package/dist/src/utils/ownership.js +118 -11
  758. package/dist/src/utils/ownership.js.map +1 -1
  759. package/dist/src/utils/package-content.d.ts +7 -0
  760. package/dist/src/utils/package-content.js +70 -0
  761. package/dist/src/utils/package-content.js.map +1 -0
  762. package/dist/src/utils/path-catalog-provider.js +2 -0
  763. package/dist/src/utils/path-catalog-provider.js.map +1 -1
  764. package/dist/src/utils/paths.d.ts +1 -1
  765. package/dist/src/utils/paths.js +5 -2
  766. package/dist/src/utils/paths.js.map +1 -1
  767. package/dist/src/utils/platform-empty-state.d.ts +69 -0
  768. package/dist/src/utils/platform-empty-state.js +249 -0
  769. package/dist/src/utils/platform-empty-state.js.map +1 -0
  770. package/dist/src/utils/platform-support.d.ts +1 -1
  771. package/dist/src/utils/platform-support.js +1 -1
  772. package/dist/src/utils/platform-support.js.map +1 -1
  773. package/dist/src/utils/plugin-config-command-apply.d.ts +33 -0
  774. package/dist/src/utils/plugin-config-command-apply.js +142 -0
  775. package/dist/src/utils/plugin-config-command-apply.js.map +1 -0
  776. package/dist/src/utils/plugin-config-diagnostics.d.ts +16 -0
  777. package/dist/src/utils/plugin-config-diagnostics.js +44 -0
  778. package/dist/src/utils/plugin-config-diagnostics.js.map +1 -0
  779. package/dist/src/utils/plugin-config-impact.d.ts +76 -0
  780. package/dist/src/utils/plugin-config-impact.js +359 -0
  781. package/dist/src/utils/plugin-config-impact.js.map +1 -0
  782. package/dist/src/utils/plugin-config-references.d.ts +116 -0
  783. package/dist/src/utils/plugin-config-references.js +379 -0
  784. package/dist/src/utils/plugin-config-references.js.map +1 -0
  785. package/dist/src/utils/plugin-config-suggestion-runner.d.ts +83 -0
  786. package/dist/src/utils/plugin-config-suggestion-runner.js +308 -0
  787. package/dist/src/utils/plugin-config-suggestion-runner.js.map +1 -0
  788. package/dist/src/utils/plugin-config-suggestions.d.ts +50 -0
  789. package/dist/src/utils/plugin-config-suggestions.js +322 -0
  790. package/dist/src/utils/plugin-config-suggestions.js.map +1 -0
  791. package/dist/src/utils/plugin-config-write.d.ts +108 -19
  792. package/dist/src/utils/plugin-config-write.js +781 -568
  793. package/dist/src/utils/plugin-config-write.js.map +1 -1
  794. package/dist/src/utils/plugin-config.d.ts +122 -43
  795. package/dist/src/utils/plugin-config.js +574 -610
  796. package/dist/src/utils/plugin-config.js.map +1 -1
  797. package/dist/src/utils/plugin-dependencies.d.ts +1 -1
  798. package/dist/src/utils/plugin-dependencies.js.map +1 -1
  799. package/dist/src/utils/plugin-scripts.d.ts +41 -17
  800. package/dist/src/utils/plugin-scripts.js +586 -123
  801. package/dist/src/utils/plugin-scripts.js.map +1 -1
  802. package/dist/src/utils/process-lock.d.ts +1 -0
  803. package/dist/src/utils/process-lock.js +22 -5
  804. package/dist/src/utils/process-lock.js.map +1 -1
  805. package/dist/src/utils/process-tree.d.ts +2 -2
  806. package/dist/src/utils/process-tree.js +1 -1
  807. package/dist/src/utils/process-tree.js.map +1 -1
  808. package/dist/src/utils/project-boundary.d.ts +11 -1
  809. package/dist/src/utils/project-boundary.js +33 -11
  810. package/dist/src/utils/project-boundary.js.map +1 -1
  811. package/dist/src/utils/rendered-contract.js +24 -1
  812. package/dist/src/utils/rendered-contract.js.map +1 -1
  813. package/dist/src/utils/runtime-config.d.ts +18 -0
  814. package/dist/src/utils/runtime-config.js +64 -0
  815. package/dist/src/utils/runtime-config.js.map +1 -0
  816. package/dist/src/utils/runtime-skill-closure.d.ts +2 -2
  817. package/dist/src/utils/runtime-skill-closure.js +50 -7
  818. package/dist/src/utils/runtime-skill-closure.js.map +1 -1
  819. package/dist/src/utils/safe-operation-diagnostic.d.ts +15 -0
  820. package/dist/src/utils/safe-operation-diagnostic.js +33 -0
  821. package/dist/src/utils/safe-operation-diagnostic.js.map +1 -0
  822. package/dist/src/utils/sensitive-content.d.ts +4 -0
  823. package/dist/src/utils/sensitive-content.js +36 -0
  824. package/dist/src/utils/sensitive-content.js.map +1 -0
  825. package/dist/src/utils/skill-invocation-warning.d.ts +19 -0
  826. package/dist/src/utils/skill-invocation-warning.js +43 -0
  827. package/dist/src/utils/skill-invocation-warning.js.map +1 -0
  828. package/dist/src/utils/skill-validation.js +0 -5
  829. package/dist/src/utils/skill-validation.js.map +1 -1
  830. package/dist/src/utils/state-paths.d.ts +8 -3
  831. package/dist/src/utils/state-paths.js +53 -16
  832. package/dist/src/utils/state-paths.js.map +1 -1
  833. package/dist/src/utils/target-eligibility.d.ts +2 -2
  834. package/dist/src/utils/target-eligibility.js.map +1 -1
  835. package/dist/src/utils/windows-claude-shim.d.ts +7 -0
  836. package/dist/src/utils/windows-claude-shim.js +10 -0
  837. package/dist/src/utils/windows-claude-shim.js.map +1 -0
  838. package/dist/src/utils/windows-npm-shim.d.ts +16 -0
  839. package/dist/src/utils/windows-npm-shim.js +155 -0
  840. package/dist/src/utils/windows-npm-shim.js.map +1 -0
  841. package/dist/vitest.config.js +109 -9
  842. package/dist/vitest.config.js.map +1 -1
  843. package/package.json +20 -12
  844. package/dist/authoring/templates/aw-config-runtime.d.mts +0 -2
  845. package/dist/authoring/templates/aw-config-runtime.mjs +0 -407
  846. package/dist/authoring/templates/aw-config-runtime.mjs.map +0 -1
  847. package/dist/src/commands/review-publication.d.ts +0 -99
  848. package/dist/src/commands/review-publication.js +0 -904
  849. package/dist/src/commands/review-publication.js.map +0 -1
  850. package/dist/src/commands/sync-command.d.ts +0 -23
  851. package/dist/src/commands/sync-command.js +0 -242
  852. package/dist/src/commands/sync-command.js.map +0 -1
  853. package/dist/src/portable/skills-cli.d.ts +0 -43
  854. package/dist/src/portable/skills-cli.js +0 -148
  855. package/dist/src/portable/skills-cli.js.map +0 -1
  856. package/dist/src/utils/codex-native-render-receipt.d.ts +0 -40
  857. package/dist/src/utils/codex-native-render-receipt.js +0 -205
  858. package/dist/src/utils/codex-native-render-receipt.js.map +0 -1
  859. package/dist/src/utils/plugin-intent-state.d.ts +0 -34
  860. package/dist/src/utils/plugin-intent-state.js +0 -289
  861. package/dist/src/utils/plugin-intent-state.js.map +0 -1
  862. package/dist/src/utils/slash-commands.d.ts +0 -1
  863. package/dist/src/utils/slash-commands.js +0 -2
  864. package/dist/src/utils/slash-commands.js.map +0 -1
@@ -0,0 +1,2329 @@
1
+ import crypto from 'node:crypto';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import fs from 'fs-extra';
5
+ import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
6
+ import { sealPermissionBatches } from './permission-batch.js';
7
+ import { COMMAND_ROUTE_UNREACHABLE, HOST_PERMISSION_ADDITIONAL_IMPACT, publicHostPermissionResource } from '../output/component-delivery.js';
8
+ import { createMarketplaceManifestEntry, getComponentFeatureRequirements, normalizeStaticPluginComponents } from '@lesliechan721/aw-plugin-core/manifest';
9
+ import { selectNativeProduct, supportsSharedNativeProbe } from '../platforms/discovery.js';
10
+ import { getAgentPluginAdapter } from '../platforms/registry.js';
11
+ import { getQualifiedPlatformProfile } from '../platforms/capabilities.js';
12
+ import { getDeploymentLayout, getDeploymentResourceKey, getInvocationPolicyPhysicalKey, scopedPermissionPath, isAntigravityProjectDirectory, hasSharedUserPackage } from '../platforms/layout.js';
13
+ import { getPhysicalKey, identityDigest } from '../platforms/identity.js';
14
+ import { antigravityLegacyProjectComponent, deploymentPackageComponent, inspectStaticSupplements, requiredDeploymentActivation } from '../platforms/inspection.js';
15
+ import { hasCompleteDeliveryDeclaration } from '../platforms/lifecycle.js';
16
+ import { piAgentConsumerDiagnostic, piProjectListContainsOnly } from '../platforms/inspection-pi.js';
17
+ import { grokRegistrationOwned, piProjectEmptyDeliveryObserved, piProjectRegistrationHidden, piProjectRemovalConfirmed } from '../platforms/lifecycle-native.js';
18
+ import { createNativeLifecycleServices } from '../platforms/lifecycle-native-services.js';
19
+ import { cursorWorkspaceOpenCommand } from '../platforms/projection.js';
20
+ import { grokProjectPermissionsAuthorized } from '../platforms/grok-permission-config.js';
21
+ import { isPermissionHost } from '../platforms/host-permission-policy.js';
22
+ import { hostPermissionFingerprint, missingPermissionOwnershipWarning, pendingRelatedProjectNotices, permissionComponent, permissionOwnerContentDigest, updateHostPermissions } from '../platforms/permission-ownership.js';
23
+ import { permissionFileFingerprint, readPermissionSidecar } from '../platforms/permission-sidecar.js';
24
+ import { canonicalizePathThroughExistingAncestor } from '../utils/state-paths.js';
25
+ import { cursorHookEntryCommand, cursorHooks } from '../platforms/cursor-workspace-hook.js';
26
+ import { gapSupplementFiles, ownedSupplementFile, staticSupplementFiles } from '../platforms/supplement-layout.js';
27
+ import { projectPlatformMarketplace } from '../platforms/projection-marketplace.js';
28
+ import { readStrictNamespacedMarketplaceRoot } from '../utils/local-marketplace.js';
29
+ import { isDeliveryCapabilityGap } from '../utils/component-gap.js';
30
+ import { artifactValueDigest, mergeExpectedComponentSets } from '../utils/artifact-plan.js';
31
+ import { preparePlatformComponents, resolveArtifactRenderConfig } from '../utils/artifact-renderer.js';
32
+ import { skillAgentBinding } from '../utils/component-agent-binding.js';
33
+ import { finalizePlatformSkillProducers } from '../utils/component-command-preparation.js';
34
+ import { resolveStaticPlatformResourceRoot } from '../utils/component-resources.js';
35
+ import { cleanupOwnedComponents, createSharedOwnerToken, inspectOwnedComponents, renderOwnedTextFile, writeOwnedTextFile, writeSkillOwnerMarker } from '../utils/ownership.js';
36
+ import { createPlatformInputEvidence, platformPackageInputDigest, platformPermissionNotices, readPlatformPackageContentDigest, writePlatformEmptyState } from '../utils/platform-empty-state.js';
37
+ import { writePlatformSupplementState } from '../platforms/supplement-state.js';
38
+ import { atomicReplaceSafeFile, assertSafeFileMutationPath } from '../utils/safe-fs.js';
39
+ import { captureManagedCommandReviewEvidence } from '../utils/managed-command-review.js';
40
+ import { readClaudeSettings } from '../adapters/helpers.js';
41
+ import { skillInvocationWarning } from '../utils/skill-invocation-warning.js';
42
+ import { readCodexConfigFile } from '../utils/codex-config.js';
43
+ import { parseOwnedTextHeader, readSkillOwnerMarker } from '../utils/ownership.js';
44
+ import { applyPlannedOperationAction, isNativeActivationOnlyTarget } from './rebuild-integration.js';
45
+ import { recoveryInterruptionCode } from '../recovery/interruption.js';
46
+ /** Resources touched by the frozen adapter plans, including host-managed writes. */
47
+ export function nativeInstallResources(plans) {
48
+ if (!plans.length)
49
+ return [{ kind: 'exclusive' }];
50
+ const paths = new Set();
51
+ const readPaths = new Set();
52
+ for (const plan of plans) {
53
+ const { binding, evidence } = plan;
54
+ const { layout } = evidence;
55
+ paths.add(layout.packageRoot);
56
+ for (const project of evidence.permissionBatch?.relatedProjects ?? [])
57
+ paths.add(project.path);
58
+ for (const { component } of evidence.ownership) {
59
+ if ('path' in component)
60
+ paths.add(component.path);
61
+ else if (component.kind === 'shared-config' && component.locator.kind === 'claude-permissions')
62
+ paths.add(component.locator.settingsPath);
63
+ else if (component.kind === 'shared-config' && component.locator.kind === 'host-permissions') {
64
+ const { settingsPath } = component.locator;
65
+ // A plugin with no current permissions may still own rules from an earlier version.
66
+ if (plan.effects.some((effect) => effect.destination === settingsPath))
67
+ paths.add(settingsPath);
68
+ else
69
+ readPaths.add(settingsPath);
70
+ }
71
+ else if (component.kind === 'shared-config' && component.locator.kind === 'cursor-workspace-hook')
72
+ paths.add(component.locator.hooksPath);
73
+ }
74
+ for (const projection of plan.projections) {
75
+ for (const supplement of projection.supplements)
76
+ paths.add(supplement.destination);
77
+ }
78
+ if (layout.marketplaceRoot) {
79
+ for (const file of evidence.marketplace?.files ?? [])
80
+ paths.add(path.join(layout.marketplaceRoot, file.relativePath));
81
+ }
82
+ // Grok inspects the entire project's packages and rules in one inventory.
83
+ // Keep peers out until this write and its confirming inspection finish.
84
+ if (binding.route === 'grok-directory') {
85
+ const entry = binding.consumers.find((consumer) => consumer.entry?.kind === 'cli')?.entry;
86
+ if (entry?.kind === 'cli')
87
+ readPaths.add(path.join(entry.configRoot, 'config.toml'));
88
+ if (plan.effects.length)
89
+ paths.add(layout.activationPath);
90
+ continue;
91
+ }
92
+ // These routes publish an entire, plugin-specific directory. activationPath
93
+ // is its parent and is never replaced by the directory publisher.
94
+ if (binding.route === 'opencode-directory' || binding.route === 'antigravity-directory')
95
+ continue;
96
+ paths.add(layout.activationPath);
97
+ if (binding.route === 'pi-package' || binding.route === 'cursor-workspace-hook')
98
+ continue;
99
+ for (const consumer of binding.consumers) {
100
+ if (!consumer.entry || consumer.entry.kind === 'generic')
101
+ return [{ kind: 'exclusive' }];
102
+ paths.add(consumer.entry.configRoot);
103
+ }
104
+ }
105
+ return [
106
+ ...Array.from(paths, (value) => ({ kind: 'path', value })),
107
+ ...[...readPaths].filter((value) => !paths.has(value)).map((value) => ({ kind: 'path', value, access: 'read' })),
108
+ ];
109
+ }
110
+ async function readOptionalUtf8(file) {
111
+ try {
112
+ const stat = await fs.lstat(file);
113
+ if (!stat.isFile() || stat.size > 1024 * 1024)
114
+ return null;
115
+ return await fs.readFile(file, 'utf8');
116
+ }
117
+ catch (error) {
118
+ if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
119
+ return null;
120
+ return null;
121
+ }
122
+ }
123
+ function isPlainRecord(value) {
124
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
125
+ }
126
+ function isGrokDisableConfigTransition(beforeText, afterText, packageName) {
127
+ if (afterText === null || beforeText === afterText)
128
+ return false;
129
+ try {
130
+ const beforeDoc = beforeText === null ? {} : getStaticTOMLValue(parseTOML(beforeText));
131
+ const afterDoc = getStaticTOMLValue(parseTOML(afterText));
132
+ if (!isPlainRecord(beforeDoc) || !isPlainRecord(afterDoc))
133
+ return false;
134
+ const { plugins: beforePluginsRaw, ...beforeRest } = beforeDoc;
135
+ const { plugins: afterPluginsRaw, ...afterRest } = afterDoc;
136
+ if (artifactValueDigest(beforeRest) !== artifactValueDigest(afterRest))
137
+ return false;
138
+ const beforePlugins = beforePluginsRaw === undefined ? {} : beforePluginsRaw;
139
+ const afterPlugins = afterPluginsRaw === undefined ? {} : afterPluginsRaw;
140
+ if (!isPlainRecord(beforePlugins) || !isPlainRecord(afterPlugins))
141
+ return false;
142
+ const { enabled: beforeEnabledRaw, disabled: beforeDisabledRaw, ...beforePluginRest } = beforePlugins;
143
+ const { enabled: afterEnabledRaw, disabled: afterDisabledRaw, ...afterPluginRest } = afterPlugins;
144
+ if (artifactValueDigest(beforePluginRest) !== artifactValueDigest(afterPluginRest))
145
+ return false;
146
+ const beforeEnabled = beforeEnabledRaw === undefined ? [] : beforeEnabledRaw;
147
+ const beforeDisabled = beforeDisabledRaw === undefined ? [] : beforeDisabledRaw;
148
+ const afterEnabled = afterEnabledRaw === undefined ? [] : afterEnabledRaw;
149
+ const afterDisabled = afterDisabledRaw === undefined ? [] : afterDisabledRaw;
150
+ if (![beforeEnabled, beforeDisabled, afterEnabled, afterDisabled].every((list) => Array.isArray(list) && list.every((entry) => typeof entry === 'string')))
151
+ return false;
152
+ const expectedEnabled = beforeEnabled.filter((name) => name !== packageName);
153
+ const expectedDisabled = beforeDisabled.includes(packageName)
154
+ ? beforeDisabled : [...beforeDisabled, packageName];
155
+ return artifactValueDigest(afterEnabled) === artifactValueDigest(expectedEnabled)
156
+ && artifactValueDigest(afterDisabled) === artifactValueDigest(expectedDisabled);
157
+ }
158
+ catch {
159
+ return false;
160
+ }
161
+ }
162
+ function matchesGrokComponentOrder(before, after, publishedRoots) {
163
+ // Leave newly added or removed identities out of both sides. Every other
164
+ // row, including a surviving component of an upgraded package, anchors order.
165
+ const retained = (order, other) => {
166
+ const otherKeys = new Set(other.map(({ key }) => key));
167
+ return order.filter(({ sourceRoot, key }) => sourceRoot === null || !publishedRoots.has(sourceRoot) || otherKeys.has(key));
168
+ };
169
+ const previous = retained(before, after);
170
+ const current = retained(after, before);
171
+ return previous.length === current.length && previous.every((row, index) => row.key === current[index].key);
172
+ }
173
+ function grokSourceDigest(sources, root, name, scope, version) {
174
+ const index = sources.sources.findIndex((source) => path.normalize(source.path) === root);
175
+ const source = sources.sources[index];
176
+ if (!sources.overlaps.includes(name) && source?.name === name && source.version
177
+ && (!version || source.version === version) && source.scope === scope && source.origin === 'native' && source.enabled === true) {
178
+ return sources.grokScopeEvidence?.sourceDigests[index];
179
+ }
180
+ }
181
+ async function grokUserContentDigest({ installedRoot, owner, hasPackageHook }) {
182
+ try {
183
+ await assertSafeFileMutationPath({ filePath: path.join(installedRoot, '.grok-plugin', 'plugin.json'),
184
+ allowedRoot: path.dirname(path.dirname(installedRoot)), label: 'Grok installed package' });
185
+ const marker = await readSkillOwnerMarker({ skillRoot: owner.path, allowedRoot: owner.allowedRoot, expectedIdentity: owner.identity });
186
+ const projection = marker?.nativeProjection;
187
+ if (hasPackageHook && !projection?.components.some((component) => component.relativeOutputs.includes('hooks/hooks.json')))
188
+ return;
189
+ const digest = projection?.contentDigest;
190
+ if (digest && (await Promise.all([owner.path, installedRoot].map(readPlatformPackageContentDigest))).every((value) => value === digest))
191
+ return digest;
192
+ }
193
+ catch { /* Unverified bytes cannot explain the change of visible source. */ }
194
+ }
195
+ async function grokUserBehindProject(ctx, binding, before) {
196
+ const sources = before.prerequisites.nativeSources;
197
+ const evidence = sources?.grokScopeEvidence;
198
+ if (binding.route !== 'grok-directory' || before.package !== 'absent' || before.ownership !== 'absent'
199
+ || sources?.observation !== 'complete' || !evidence?.userRegistrationDigest)
200
+ return;
201
+ const name = before.nativeIdentity?.packageId;
202
+ const user = sources.sources.find((source) => source.name === name && source.scope === 'user');
203
+ if (!user)
204
+ return;
205
+ const nativeDigest = grokSourceDigest(sources, user.path, user.name, 'user', binding.plugin.version);
206
+ if (!nativeDigest)
207
+ return;
208
+ const personal = { ...binding, route: 'grok-cli', scope: { kind: 'user' } };
209
+ const layout = await getDeploymentLayout(ctx, personal);
210
+ if (evidence.userRegistrationDigest !== artifactValueDigest([user.path, layout.packageRoot]))
211
+ return;
212
+ const owner = deploymentPackageComponent({ ...personal, physicalKey: getPhysicalKey(layout.physicalIdentity) }, layout);
213
+ const hasPackageHook = evidence.hookOrder.some((row) => row.sourceRoot === user.path);
214
+ return { installedRoot: user.path, owner, nativeDigest, hasPackageHook };
215
+ }
216
+ function nativeCopyIncomplete(binding, after, contentDigest) {
217
+ return ['antigravity-cli', 'grok-cli'].includes(binding.route)
218
+ && after.nativePackageContentDigest !== contentDigest;
219
+ }
220
+ function piProjectInventoryKey(binding, settingsPath) {
221
+ if (binding.route !== 'pi-package' || binding.scope.kind !== 'project')
222
+ return undefined;
223
+ const product = selectNativeProduct(binding.consumers);
224
+ return product ? JSON.stringify([binding.scope.projectRoot, settingsPath, product.id]) : undefined;
225
+ }
226
+ function packageDeliveryConfirmed(binding, after, contentDigest, requireIndependentActivation) {
227
+ return after.package === 'present' && ['aw', 'shared'].includes(after.ownership)
228
+ && !nativeCopyIncomplete(binding, after, contentDigest)
229
+ && ['present', 'not-applicable'].includes(after.registration)
230
+ && ['enabled', 'not-applicable'].includes(requiredDeploymentActivation(binding, after, requireIndependentActivation))
231
+ && (binding.route !== 'cursor-workspace-hook' || after.workspaceOpen === 'present')
232
+ && (binding.route !== 'claude-marketplace' || after.scopeRegistration === undefined || after.scopeRegistration === 'present');
233
+ }
234
+ function componentSupplementFiles(plan) {
235
+ return plan.projections.filter((projection) => plan.evidence.renderUnits?.some((unit) => unit.id === projection.renderUnitId && unit.output === 'supplement')).flatMap((projection) => projection.supplements
236
+ .filter((contribution) => contribution.kind === 'owned-file'));
237
+ }
238
+ export function nativeDeploymentHasVerifiedComponentWrite(plan, receipt) {
239
+ const { after, effects, unmet } = receipt;
240
+ if (receipt.bindingId !== plan.binding.id || after.physicalKey !== plan.binding.physicalKey)
241
+ return false;
242
+ const delivered = after.components.filter(({ id, presence, reasonCodes }) => presence === 'present' && !reasonCodes.length
243
+ && !unmet.some((gap) => !isDeliveryCapabilityGap(gap) && (gap.componentId ?? gap.id) === id));
244
+ if (!delivered.length)
245
+ return false;
246
+ const bundle = plan.projections.find((projection) => projection.bundle)?.bundle;
247
+ const supplementFiles = componentSupplementFiles(plan);
248
+ return plan.effects.some((effect) => {
249
+ if (!effects.some(({ id, status, mutation }) => id === effect.id && status === 'applied' && mutation === 'confirmed'))
250
+ return false;
251
+ const deliversComponents = effect.kind === 'publish-package'
252
+ ? !plan.evidence.retainPackage && bundle && packageDeliveryConfirmed(plan.binding, after, bundle.contentDigest, true)
253
+ : effect.kind === 'write-supplement' && supplementFiles.some((file) => file.destination === effect.destination);
254
+ return deliversComponents && effect.componentIds.some((id) => delivered.some((component) => component.id === id));
255
+ });
256
+ }
257
+ function recheckCopilotMarketplaceTimeout(receipt, fresh) {
258
+ const { ownership, registration, diagnostics } = receipt.after;
259
+ const [timeout] = diagnostics;
260
+ if (ownership !== 'unknown' || registration !== 'present' || diagnostics.length !== 1
261
+ || timeout?.code !== 'nativeMarketplaceUnconfirmed' || timeout.detail?.reasonCode !== 'nativeCliTimedOut')
262
+ return false;
263
+ // Keep the local owner, marketplace, registration and activation from the same
264
+ // read. Postcheck may annotate the receipt's components independently of rebase.
265
+ receipt.after = structuredClone(fresh);
266
+ receipt.diagnostics = receipt.diagnostics.filter((entry) => entry !== timeout);
267
+ receipt.diagnostics.push(...receipt.after.diagnostics);
268
+ return true;
269
+ }
270
+ function checkRetainedCopilotDeactivation(prepared, receipt, fresh) {
271
+ const { binding, operation, effects, evidence } = prepared.plan;
272
+ if (binding.route !== 'copilot-marketplace' || operation !== 'remove' || evidence.sharedReferences === 'none')
273
+ return;
274
+ const deactivate = effects.find((effect) => effect.kind === 'deactivate');
275
+ if (!deactivate)
276
+ return;
277
+ const outcome = receipt.effects.find((effect) => effect.id === deactivate.id);
278
+ const unchanged = outcome?.status === 'unchanged' && outcome.mutation === 'none';
279
+ if (!unchanged && !(outcome?.status === 'applied' && outcome.mutation === 'confirmed'))
280
+ return;
281
+ const disabled = (after) => after.physicalKey === binding.physicalKey
282
+ && after.package === 'present' && after.registration === 'present' && after.copilotRegistration?.source === 'canonical'
283
+ && after.configuration?.activation === 'disabled' && after.consumers.length > 0
284
+ && after.consumers.every((consumer) => consumer.activationKey === deactivate.activationKey && consumer.activation === 'disabled'
285
+ && binding.consumers.some((product) => product.id === consumer.productId && product.product === 'cli'));
286
+ const confirmed = (after) => disabled(after) && after.copilotRegistration?.marketplace === 'canonical'
287
+ && ['aw', 'shared'].includes(after.ownership) && after.ownership === prepared.driverState.before.ownership;
288
+ const sourceConflict = (after) => after.ownership === 'foreign'
289
+ || after.copilotRegistration?.source === 'foreign' || after.copilotRegistration?.marketplace === 'foreign';
290
+ const firstConflict = sourceConflict(receipt.after);
291
+ if (fresh) {
292
+ if (confirmed(fresh)) {
293
+ if (!unchanged && disabled(receipt.after) && recheckCopilotMarketplaceTimeout(receipt, fresh))
294
+ return;
295
+ if (confirmed(receipt.after)) {
296
+ receipt.after = structuredClone(fresh);
297
+ return;
298
+ }
299
+ // A healthy rebase cannot clear a different failure in the first read.
300
+ }
301
+ else {
302
+ // Retain the first diagnostics alongside the latest independent observation.
303
+ receipt.after = structuredClone(fresh);
304
+ receipt.diagnostics.push(...fresh.diagnostics);
305
+ }
306
+ }
307
+ else if (unchanged && confirmed(receipt.after))
308
+ return;
309
+ // Even if the more recent read fails, do not erase a confirmed source conflict.
310
+ const reasonCode = firstConflict || sourceConflict(receipt.after) ? 'deploymentOwnershipConflict'
311
+ : receipt.after.copilotRegistration?.source === 'unknown' ? 'nativeIdentityUnconfirmed' : undefined;
312
+ receipt.diagnostics.push({ code: 'nativeMutationPostcheckFailed', severity: 'error',
313
+ message: 'The retained Copilot package or its scoped deactivation could not be confirmed. Check status before retrying.',
314
+ subject: { target: binding.platform, pluginId: binding.plugin.pluginId, scope: binding.scope.kind },
315
+ ...(reasonCode ? { detail: { reasonCode } } : {}) });
316
+ }
317
+ /** Fingerprints are operation-local evidence; they confer no ownership or deletion rights. */
318
+ async function pathEvidence(location) {
319
+ const stat = await fs.lstat(location).catch((error) => {
320
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
321
+ return null;
322
+ throw error;
323
+ });
324
+ if (!stat)
325
+ return null;
326
+ if (stat.isSymbolicLink())
327
+ return { link: await fs.readlink(location) };
328
+ if (stat.isDirectory())
329
+ return Promise.all((await fs.readdir(location)).sort().map(async (name) => [name, await pathEvidence(path.join(location, name))]));
330
+ if (!stat.isFile())
331
+ throw new Error('deploymentEvidenceInvalid: a deployment resource is not a regular file.');
332
+ return { mode: stat.mode & 0o777, digest: crypto.createHash('sha256').update(await fs.readFile(location)).digest('hex') };
333
+ }
334
+ async function ownedContentDigest(component, ctx) {
335
+ if (component.kind === 'owned-directory' || component.kind === 'skill-directory')
336
+ return readPlatformPackageContentDigest(component.path);
337
+ if (component.kind === 'shared-config') {
338
+ if (component.locator.kind === 'host-permissions')
339
+ return permissionOwnerContentDigest(ctx, component.locator);
340
+ let value;
341
+ if (component.locator.kind === 'claude-permissions') {
342
+ const permissions = (await readClaudeSettings(component.locator.settingsPath)).awGenerated?.permissions?.[component.locator.ownerKey];
343
+ if (permissions)
344
+ value = { kind: 'claude-permissions', permissions };
345
+ }
346
+ else if (component.locator.kind === 'cursor-workspace-hook') {
347
+ const locator = component.locator;
348
+ const entries = cursorHooks(await jsonObject(locator.hooksPath)).entries;
349
+ if (entries.some((entry) => cursorHookEntryCommand(entry) === locator.command))
350
+ value = { version: 1, hooks: { workspaceOpen: [{ command: locator.command }] } };
351
+ }
352
+ return value === undefined ? undefined : `sha256:${crypto.createHash('sha256').update(`${JSON.stringify(value, null, 2)}\n`).digest('hex')}`;
353
+ }
354
+ if (component.kind !== 'owned-text-file')
355
+ return undefined;
356
+ try {
357
+ const parsed = parseOwnedTextHeader(await fs.readFile(component.path, 'utf8'), component.identity);
358
+ return parsed ? `sha256:${crypto.createHash('sha256').update(parsed.content).digest('hex')}` : undefined;
359
+ }
360
+ catch {
361
+ return undefined;
362
+ }
363
+ }
364
+ async function ownedSupplements(binding, root, physicalKey) {
365
+ if (!root || !physicalKey)
366
+ return [];
367
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch((error) => {
368
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
369
+ return [];
370
+ throw error;
371
+ });
372
+ const result = [];
373
+ for (const entry of entries) {
374
+ const location = path.join(root, entry.name);
375
+ let identity;
376
+ if (entry.isDirectory() && !entry.isSymbolicLink())
377
+ identity = (await readSkillOwnerMarker({ skillRoot: location, allowedRoot: root }).catch(() => null)) ?? undefined;
378
+ else if (entry.isFile())
379
+ identity = parseOwnedTextHeader(await fs.readFile(location, 'utf8').catch(() => ''))?.identity;
380
+ if (!identity || identity.sourceId !== binding.plugin.sourceId || identity.pluginId !== binding.plugin.pluginId
381
+ || identity.sourceIdentity !== binding.plugin.sourceIdentity || identity.physicalKey !== physicalKey
382
+ || identity.platform !== binding.platform || identity.scope !== binding.scope.kind)
383
+ continue;
384
+ result.push({ kind: entry.isDirectory() ? 'owned-directory' : 'owned-text-file', path: location, allowedRoot: root, identity });
385
+ }
386
+ return result;
387
+ }
388
+ function readContext(context, cwd, confirmedCatalogRetirement) {
389
+ return { cwd, invocationCwd: context.invocationCwd, env: context.env, runner: context.nativeCliRunner, signal: context.signal,
390
+ confirmedCatalogRetirement, codexObservationSession: confirmedCatalogRetirement ? undefined : context.codexObservationSession };
391
+ }
392
+ function operation(input) {
393
+ return input.command === 'uninstall' ? 'remove' : input.command === 'cleanup' ? 'cleanup'
394
+ : input.command === 'reinstall' ? 'reinstall' : 'ensure';
395
+ }
396
+ function sourceIdentity(input) {
397
+ const sourceId = input.sourceId ?? input.plugin.sourceId;
398
+ const sourceIdentity = input.sourceIdentity ?? input.plugin.sourceIdentity;
399
+ const pluginId = input.pluginId ?? input.plugin.pluginId;
400
+ if (!sourceId || !sourceIdentity || !pluginId)
401
+ throw new Error('deploymentSourceIdentityMissing: a native deployment requires a verified catalog source.');
402
+ return { sourceId, sourceIdentity, pluginId, version: input.plugin.manifest.version };
403
+ }
404
+ function targetIdentity(input) {
405
+ return { ...sourceIdentity(input), pluginName: input.plugin.manifest.name,
406
+ pluginVersion: input.plugin.manifest.version, platform: input.platform, scope: input.scope, cwd: input.cwd };
407
+ }
408
+ function contributionComponent(binding, contribution, physicalKey) {
409
+ if (contribution.kind === 'owned-file')
410
+ return ownedSupplementFile(binding, physicalKey, contribution.destination);
411
+ const identity = { owner: 'agent-workflows', sourceId: binding.plugin.sourceId,
412
+ pluginId: binding.plugin.pluginId, plugin: binding.plugin.pluginId.split('/').at(-1),
413
+ sourceIdentity: binding.plugin.sourceIdentity, physicalKey,
414
+ platform: binding.platform, scope: binding.scope.kind, artifactKey: path.basename(contribution.destination) };
415
+ if (contribution.kind === 'config-entry') {
416
+ if (isPermissionHost(binding.platform) && contribution.mergeKey?.startsWith(`${binding.platform}-permissions:`)) {
417
+ return permissionComponent(binding, contribution.destination, physicalKey);
418
+ }
419
+ if (binding.platform === 'claude' && contribution.mergeKey?.startsWith('claude-permissions:')) {
420
+ const owner = { ...identity, artifactKey: contribution.mergeKey.replace(':', '-') };
421
+ return { kind: 'shared-config', identity: owner, label: contribution.destination,
422
+ locator: { kind: 'claude-permissions', settingsPath: contribution.destination, ownerKey: createSharedOwnerToken(owner) } };
423
+ }
424
+ if (binding.platform !== 'cursor' || !contribution.mergeKey)
425
+ throw new Error('platformContributionUnsupported');
426
+ return { kind: 'shared-config', identity: { ...identity, artifactKey: `workspaceOpen-${identity.plugin}` },
427
+ label: contribution.destination, locator: { kind: 'cursor-workspace-hook', hooksPath: contribution.destination,
428
+ ownerKey: contribution.mergeKey, command: '' } };
429
+ }
430
+ return { kind: 'owned-directory',
431
+ path: contribution.destination, allowedRoot: path.dirname(contribution.destination), identity };
432
+ }
433
+ async function jsonObject(file) {
434
+ let value;
435
+ try {
436
+ value = await fs.readJson(file);
437
+ }
438
+ catch (error) {
439
+ if (error.code === 'ENOENT')
440
+ return {};
441
+ throw error;
442
+ }
443
+ if (!value || typeof value !== 'object' || Array.isArray(value))
444
+ throw new Error('sharedConfigurationInvalid');
445
+ return value;
446
+ }
447
+ export const platformOwnership = {
448
+ async inspectShared(component) {
449
+ if (component.locator.kind !== 'cursor-workspace-hook')
450
+ throw new Error('sharedOwnershipUnsupported');
451
+ const locator = component.locator;
452
+ const { entries } = cursorHooks(await jsonObject(locator.hooksPath));
453
+ return entries.some((entry) => cursorHookEntryCommand(entry) === locator.command) ? 'present' : 'absent';
454
+ },
455
+ async removeShared(component) {
456
+ if (component.locator.kind !== 'cursor-workspace-hook')
457
+ throw new Error('sharedOwnershipUnsupported');
458
+ const locator = component.locator;
459
+ const value = await jsonObject(locator.hooksPath);
460
+ const { hooks, entries } = cursorHooks(value);
461
+ const retained = entries.filter((entry) => cursorHookEntryCommand(entry) !== locator.command);
462
+ if (retained.length === entries.length)
463
+ return;
464
+ await atomicReplaceSafeFile({ filePath: component.locator.hooksPath, allowedRoot: path.dirname(component.locator.hooksPath),
465
+ content: `${JSON.stringify({ ...value, hooks: { ...hooks, workspaceOpen: retained } }, null, 2)}\n`, label: 'Cursor workspaceOpen' });
466
+ },
467
+ };
468
+ async function requireWritable(component, executor = platformOwnership) {
469
+ const inspection = await inspectOwnedComponents({ components: [component], executor });
470
+ const state = inspection.components[0].state;
471
+ if (state !== 'present' && state !== 'absent')
472
+ throw new Error('operationPlanStale: deployment ownership changed.');
473
+ return state;
474
+ }
475
+ async function publishDirectory(source, component, nativeProjection, staged) {
476
+ if (component.kind !== 'owned-directory')
477
+ throw new Error('deploymentPackageOwnerInvalid');
478
+ await requireWritable(component);
479
+ await assertSafeFileMutationPath({ filePath: path.join(component.allowedRoot, '.aw-publication-probe'),
480
+ allowedRoot: component.allowedRoot, label: 'Native package', createParent: true });
481
+ const staging = await fs.mkdtemp(path.join(component.allowedRoot, '.aw-package-'));
482
+ const candidate = path.join(staging, component.identity.artifactKey);
483
+ const verifiesContents = component.identity.platform === 'antigravity' && component.identity.scope === 'project';
484
+ const backupRoot = `${staging}.previous`;
485
+ const backup = verifiesContents ? path.join(backupRoot, component.identity.artifactKey) : backupRoot;
486
+ let moved = false;
487
+ try {
488
+ if (staged && nativeProjection) {
489
+ // A queued package can outlive its staging step. Verify its bytes before
490
+ // consuming it and keep the final rename on the destination filesystem.
491
+ if (await readPlatformPackageContentDigest(staged) !== nativeProjection.contentDigest) {
492
+ throw new Error('operationPlanStale: staged native package content changed.');
493
+ }
494
+ try {
495
+ await fs.rename(staged, candidate);
496
+ }
497
+ catch (error) {
498
+ if (error.code !== 'EXDEV')
499
+ throw error;
500
+ await fs.copy(staged, candidate, { dereference: false });
501
+ }
502
+ }
503
+ else
504
+ await fs.copy(source, candidate, { dereference: false });
505
+ await writeSkillOwnerMarker({ skillRoot: candidate, allowedRoot: staging, identity: component.identity, nativeProjection });
506
+ const state = await requireWritable(component);
507
+ if (verifiesContents ? state === 'present' : await fs.pathExists(component.path)) {
508
+ await fs.move(component.path, backup);
509
+ moved = true;
510
+ }
511
+ try {
512
+ if (verifiesContents && moved && await requireWritable({ ...component, path: backup, allowedRoot: backupRoot }) !== 'present') {
513
+ throw new Error('operationPlanStale: deployment backup could not be verified.');
514
+ }
515
+ await fs.move(candidate, component.path);
516
+ }
517
+ catch (error) {
518
+ if (moved && !await fs.pathExists(component.path))
519
+ await fs.move(backup, component.path);
520
+ throw error;
521
+ }
522
+ await fs.remove(backup);
523
+ return { mutation: 'confirmed', changed: true };
524
+ }
525
+ finally {
526
+ await fs.remove(staging);
527
+ if (verifiesContents)
528
+ await fs.rmdir(backupRoot).catch(() => undefined);
529
+ }
530
+ }
531
+ async function sharedReferences(context, binding, observation, layout) {
532
+ if (!['codex-marketplace', 'claude-marketplace', 'copilot-marketplace'].includes(binding.route))
533
+ return 'none';
534
+ const view = context.sharedReferenceView;
535
+ const same = (reference) => reference.pluginId === binding.plugin.pluginId
536
+ && reference.sourceIdentity === binding.plugin.sourceIdentity && reference.platform === binding.platform
537
+ && (reference.physicalKey === undefined || reference.physicalKey === binding.physicalKey);
538
+ const current = (reference) => reference.scope === binding.scope.kind
539
+ && (reference.scope !== 'project' || binding.scope.kind === 'project' && reference.projectRoot === binding.scope.projectRoot);
540
+ if (view && [...view.desired, ...view.observed].some((reference) => same(reference) && !current(reference)))
541
+ return 'present';
542
+ const host = binding.consumers.find((consumer) => consumer.entry?.kind === 'cli')?.entry;
543
+ if (!host || host.kind !== 'cli' || observation.registration === 'unknown')
544
+ return 'unknown';
545
+ if (binding.route === 'claude-marketplace') {
546
+ try {
547
+ const installed = await jsonObject(path.join(host.configRoot, 'plugins', 'installed_plugins.json'));
548
+ const plugins = installed.plugins;
549
+ if (plugins !== undefined && (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)))
550
+ return 'unknown';
551
+ const raw = plugins?.[layout.nativeIdentity.registrationId];
552
+ const records = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw];
553
+ for (const rawRecord of records) {
554
+ if (!rawRecord || typeof rawRecord !== 'object')
555
+ return 'unknown';
556
+ const record = rawRecord;
557
+ if (record.scope !== 'user' && record.scope !== 'local')
558
+ return 'unknown';
559
+ if (record.scope === 'local' && (typeof record.projectPath !== 'string' || !path.isAbsolute(record.projectPath)))
560
+ return 'unknown';
561
+ if (record.scope === 'user' ? binding.scope.kind !== 'user'
562
+ : binding.scope.kind !== 'project' || path.resolve(record.projectPath) !== path.resolve(binding.scope.projectRoot))
563
+ return 'present';
564
+ }
565
+ return view && !view.desiredComplete ? 'unknown' : 'none';
566
+ }
567
+ catch {
568
+ return 'unknown';
569
+ }
570
+ }
571
+ if (binding.route === 'codex-marketplace' && view?.desiredComplete && view.scopes.includes('user')
572
+ && view.scopes.includes('project') && view.projectRoot) {
573
+ const covered = view.observations.filter((reference) => same(reference) && reference.physicalKey === binding.physicalKey && reference.complete);
574
+ if (covered.some((reference) => reference.scope === 'user')
575
+ && covered.some((reference) => reference.scope === 'project' && reference.projectRoot === view.projectRoot)) {
576
+ try {
577
+ const config = await readCodexConfigFile(path.join(host.configRoot, 'config.toml'));
578
+ // Only the already authorized project is read. Any additional native
579
+ // project reference keeps the shared payload until its scope is observed.
580
+ if (Object.values(config.snapshot.projects).some((project) => path.resolve(project.path) !== path.resolve(view.projectRoot)))
581
+ return 'unknown';
582
+ if (binding.scope.kind === 'project' && config.snapshot.plugins[layout.nativeIdentity.registrationId]?.enabled === true)
583
+ return 'present';
584
+ const project = await readCodexConfigFile(path.join(view.projectRoot, '.codex', 'config.toml'));
585
+ if (binding.scope.kind === 'user' && project.snapshot.plugins[layout.nativeIdentity.registrationId]?.enabled === true)
586
+ return 'present';
587
+ return 'none';
588
+ }
589
+ catch {
590
+ return 'unknown';
591
+ }
592
+ }
593
+ }
594
+ // These routes do not expose a complete global activation inventory. An absent
595
+ // registration is sufficient for orphan payload cleanup; otherwise keep it.
596
+ return observation.registration === 'absent' && view?.desiredComplete === true
597
+ && view.scopes.includes('user') && view.scopes.includes('project') ? 'none' : 'unknown';
598
+ }
599
+ export class PlatformRebuildSession {
600
+ context;
601
+ adapterFor;
602
+ targets = new Map();
603
+ resolutions = new Map();
604
+ rawUnits = new Map();
605
+ units = new Map();
606
+ published = new Map();
607
+ nativeEffects = new Map();
608
+ piProjectRegisteredRoots = new Map();
609
+ // A sibling target can update the same permission file. Only the exact pair
610
+ // of host and sidecar bytes confirmed by our own write inherits its baseline.
611
+ permissionWrites = new Map();
612
+ openCodeProjectBatches = new Map();
613
+ pendingOpenCodeProjectNotices(interrupted) {
614
+ return [...this.openCodeProjectBatches.values()].flatMap((batch) => pendingRelatedProjectNotices(batch, interrupted));
615
+ }
616
+ grokPermissionWrites = new Map();
617
+ recordPermissionWrite(target, previous, current, host) {
618
+ const last = this.permissionWrites.get(target);
619
+ this.permissionWrites.set(target, { previous: last?.current === previous ? last.previous : previous, current });
620
+ if (host && host.previous !== host.current) {
621
+ const earlier = this.grokPermissionWrites.get(target);
622
+ this.grokPermissionWrites.set(target, { previous: earlier && earlier.current === host.previous ? earlier.previous : host.previous, current: host.current });
623
+ }
624
+ }
625
+ async recordGrokDisableConfigWrite(configPath, beforeText, afterText) {
626
+ const prevDigest = beforeText === null ? null : crypto.createHash('sha256').update(beforeText).digest('hex');
627
+ const nextDigest = crypto.createHash('sha256').update(afterText).digest('hex');
628
+ if (prevDigest !== nextDigest) {
629
+ const earlier = this.grokPermissionWrites.get(configPath);
630
+ this.grokPermissionWrites.set(configPath, {
631
+ previous: earlier && earlier.current === prevDigest ? earlier.previous : prevDigest,
632
+ current: nextDigest,
633
+ });
634
+ }
635
+ const sidecar = await readPermissionSidecar(this.context.env, 'grok', configPath).catch(() => undefined);
636
+ if (sidecar && !sidecar.unreadable && sidecar.raw !== null) {
637
+ const previous = permissionFileFingerprint(beforeText, sidecar.raw);
638
+ const current = permissionFileFingerprint(afterText, sidecar.raw);
639
+ if (previous !== current) {
640
+ const last = this.permissionWrites.get(configPath);
641
+ this.permissionWrites.set(configPath, { previous: last?.current === previous ? last.previous : previous, current });
642
+ }
643
+ }
644
+ }
645
+ grokPublications = new Map();
646
+ grokProjectRetirements = new Map();
647
+ grokRemovals = new Map();
648
+ offlinePermissionRemovals = new Map();
649
+ recordOfflinePermissionRemoval(settingsPath, ownerKey) {
650
+ let owners = this.offlinePermissionRemovals.get(settingsPath);
651
+ if (!owners)
652
+ this.offlinePermissionRemovals.set(settingsPath, owners = new Set());
653
+ owners.add(ownerKey);
654
+ }
655
+ exclusions = new Map();
656
+ contexts = new Set();
657
+ mutableChecks = new Map();
658
+ requestedOperations = new Map();
659
+ marketplaceTargets = new Set();
660
+ marketplaceCandidatesFrozen = false;
661
+ ownership = platformOwnership;
662
+ marketplaces = new Map();
663
+ closedObservationBatch;
664
+ staging;
665
+ constructor(context, adapterFor = getAgentPluginAdapter) {
666
+ this.context = context;
667
+ this.adapterFor = adapterFor;
668
+ }
669
+ updateContext(context) {
670
+ this.context = context;
671
+ for (const ctx of this.contexts)
672
+ Object.assign(ctx, readContext(context, ctx.cwd, ctx.confirmedCatalogRetirement));
673
+ }
674
+ setOwnershipExecutor(executor) { this.ownership = executor; }
675
+ root() { return this.staging ??= fs.mkdtemp(path.join(os.tmpdir(), 'aw-deployment-')); }
676
+ ordinaryReadContext(ctx, platform) {
677
+ const batch = this.context.nativeObservationBatch;
678
+ // A locked re-Review starts its own observation batch. Cached targets of
679
+ // the earlier Review do not close the new batch before its first build.
680
+ const open = platform === 'pi'
681
+ ? batch !== this.closedObservationBatch : this.targets.size === 0 && platform !== 'codex';
682
+ return open && batch ? { ...ctx, ...batch } : ctx;
683
+ }
684
+ recordGrokWrites(prepared, receipt, packagePublished, writtenFiles, shadowedUser) {
685
+ const { binding, operation, evidence: { layout } } = prepared.plan;
686
+ const sources = receipt.after.prerequisites.nativeSources;
687
+ const evidence = sources?.grokScopeEvidence;
688
+ if (!['grok-cli', 'grok-directory'].includes(binding.route) || operation !== 'ensure'
689
+ || receipt.diagnostics.some((item) => item.severity === 'error') || sources?.observation !== 'complete' || !evidence)
690
+ return;
691
+ const incomplete = receipt.effects.filter((effect) => ['failed', 'unknown', 'blocked', 'skipped'].includes(effect.status));
692
+ if (incomplete.length) {
693
+ // First registration can be refused without touching the native copy,
694
+ // while an independent rule is confirmed. Never normalize uncertain
695
+ // native mutations or other failures against a sibling's frozen plan.
696
+ const registration = prepared.plan.effects.find(({ kind }) => kind === 'register');
697
+ const refusal = incomplete.find((effect) => effect.id === registration?.id && effect.status === 'blocked'
698
+ && effect.diagnostics.some(({ code }) => code === 'nativeTrustRequired')
699
+ && effect.diagnostics.every(({ code, severity }) => severity !== 'error' || code === 'nativeTrustRequired'));
700
+ if (binding.route !== 'grok-cli' || receipt.after.registration !== 'absent' || !refusal
701
+ || receipt.effects.some(({ mutation }) => mutation === 'possible')
702
+ || incomplete.some((effect) => effect.mutation !== 'none' || effect !== refusal
703
+ && !(effect.status === 'skipped' && effect.diagnostics.length > 0
704
+ && effect.diagnostics.every(({ code }) => code === 'deploymentDependencyFailed'))))
705
+ return;
706
+ }
707
+ const scope = binding.scope.kind;
708
+ const scopeRoot = binding.scope.kind === 'project' ? binding.scope.projectRoot : layout.activationPath;
709
+ const { before, packageComponent: owner, bundle, contributions } = prepared.driverState;
710
+ const priorSources = before.prerequisites.nativeSources;
711
+ const identity = receipt.after.nativeIdentity;
712
+ const registrationId = identity?.registrationId;
713
+ const refreshed = binding.route === 'grok-cli' && registrationId && bundle
714
+ && before.grokScopeAuthorization === 'granted' && receipt.after.grokScopeAuthorization === 'granted'
715
+ && grokRegistrationOwned(binding, prepared.plan.evidence, before, identity)
716
+ && grokRegistrationOwned(binding, prepared.plan.evidence, receipt.after, identity)
717
+ && receipt.after.nativePackageContentDigest === bundle.contentDigest
718
+ && prepared.plan.effects.some((effect) => effect.kind === 'refresh' && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'));
719
+ // A previous refusal can leave the AW source up to date. Only the confirmed
720
+ // native refresh explains a change to the User inventory in this operation.
721
+ const installedRoot = refreshed ? path.join(scopeRoot, 'installed-plugins', registrationId) : undefined;
722
+ const root = installedRoot ?? path.normalize(layout.packageRoot);
723
+ if (!incomplete.length && (refreshed || binding.route === 'grok-directory' && packagePublished) && priorSources?.observation === 'complete'
724
+ && receipt.after.package === 'present' && receipt.after.ownership === 'aw' && bundle
725
+ && owner?.kind === 'owned-directory' && owner.path === layout.packageRoot && identity?.route === binding.route
726
+ && identity.sourceLocation === layout.packageRoot) {
727
+ const newlyInstalled = binding.route === 'grok-directory' && before.package === 'absent' && before.ownership === 'absent'
728
+ && !priorSources.sources.some((source) => path.normalize(source.path) === root
729
+ || source.name === identity.packageId && source.path !== shadowedUser?.installedRoot)
730
+ && (!shadowedUser || !sources.sources.some((source) => source.path === shadowedUser.installedRoot));
731
+ const priorNativeDigest = before.package === 'present' && before.ownership === 'aw' && (refreshed || before.packageVersion)
732
+ ? grokSourceDigest(priorSources, root, identity.packageId, scope, refreshed ? undefined : before.packageVersion) : undefined;
733
+ const nativeDigest = grokSourceDigest(sources, root, identity.packageId, scope, binding.plugin.version);
734
+ const knownHooks = !evidence.hookOrder.some((row) => row.sourceRoot === root) || prepared.plan.projections.some((projection) => projection.bundle
735
+ && projection.components.some((component) => component.relativeOutputs.includes('hooks/hooks.json')));
736
+ if ((newlyInstalled || priorNativeDigest) && nativeDigest && knownHooks) {
737
+ this.grokPublications.set(root, { scope, scopeRoot, installedRoot, nativeDigest, priorNativeDigest, contentDigest: bundle.contentDigest,
738
+ owner, orderAfter: evidence, shadowedUser,
739
+ sourceOrderAfter: shadowedUser && sources.sources.map((source) => path.normalize(source.path)) });
740
+ }
741
+ }
742
+ const prior = priorSources?.grokScopeEvidence?.instructions;
743
+ for (const { effectId, component } of contributions) {
744
+ if (component.kind !== 'owned-text-file' || !prior)
745
+ continue;
746
+ const written = writtenFiles.get(component.path);
747
+ const rows = evidence.instructions.filter((row) => row.rulePath === component.path);
748
+ const previous = prior.filter((row) => row.rulePath === component.path);
749
+ if (written && rows.length === 1 && previous.length <= 1 && receipt.effects.some((effect) => effect.id === effectId && effect.status === 'applied' && effect.mutation === 'confirmed')) {
750
+ this.grokPublications.set(component.path, { scope, scopeRoot, nativeDigest: rows[0].digest,
751
+ priorNativeDigest: previous[0]?.digest, contentDigest: written.digest, owner: component });
752
+ }
753
+ }
754
+ }
755
+ recordGrokRemovals(prepared, receipt) {
756
+ const { binding, operation, evidence: { layout } } = prepared.plan;
757
+ const sources = receipt.after.prerequisites.nativeSources;
758
+ const evidence = sources?.grokScopeEvidence;
759
+ if (!['grok-cli', 'grok-directory'].includes(binding.route) || !['remove', 'cleanup'].includes(operation)
760
+ || receipt.diagnostics.some((item) => item.severity === 'error')
761
+ || receipt.effects.some((effect) => effect.mutation === 'possible' || ['failed', 'unknown', 'blocked', 'skipped'].includes(effect.status))
762
+ || sources?.observation !== 'complete' || !evidence)
763
+ return;
764
+ const { before, removals } = prepared.driverState;
765
+ const priorSources = before.prerequisites.nativeSources;
766
+ const priorEvidence = priorSources?.grokScopeEvidence;
767
+ if (priorSources?.observation !== 'complete' || !priorEvidence)
768
+ return;
769
+ const scope = binding.scope.kind;
770
+ const scopeRoot = binding.scope.kind === 'project' ? binding.scope.projectRoot : layout.activationPath;
771
+ if (binding.route === 'grok-cli' && receipt.after.registration === 'absent') {
772
+ const registrationId = before.nativeIdentity?.registrationId;
773
+ const packageName = before.nativeIdentity?.packageId;
774
+ const unregistered = prepared.plan.effects.some((effect) => effect.kind === 'unregister'
775
+ && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'));
776
+ if (unregistered && registrationId && packageName) {
777
+ const index = priorSources.sources.findIndex((source) => source.name === packageName && source.scope === 'user' && source.origin === 'native'
778
+ && path.basename(source.path) === registrationId && path.basename(path.dirname(source.path)) === 'installed-plugins');
779
+ const priorNativeDigest = index >= 0 ? priorEvidence.sourceDigests[index] : undefined;
780
+ const installedRoot = index >= 0 ? path.normalize(priorSources.sources[index].path) : undefined;
781
+ if (installedRoot && priorNativeDigest && !sources.sources.some((source) => path.normalize(source.path) === installedRoot)) {
782
+ this.grokRemovals.set(installedRoot, {
783
+ kind: 'package', scope: 'user', scopeRoot, pluginId: binding.plugin.pluginId, packageName,
784
+ installedRoot, priorNativeDigest,
785
+ sourceOrderAfter: sources.sources.map((source) => path.normalize(source.path)),
786
+ });
787
+ }
788
+ }
789
+ }
790
+ if (layout.supplementRoot) {
791
+ for (const { effectId, component } of removals) {
792
+ if (component.kind !== 'owned-text-file')
793
+ continue;
794
+ const rulePath = path.normalize(component.path);
795
+ if (path.dirname(rulePath) !== layout.supplementRoot)
796
+ continue;
797
+ if (!receipt.effects.some((effect) => effect.id === effectId && effect.status === 'applied' && effect.mutation === 'confirmed'))
798
+ continue;
799
+ const priorRows = priorEvidence.instructions.filter((row) => row.rulePath === rulePath);
800
+ if (priorRows.length === 1 && !evidence.instructions.some((row) => row.rulePath === rulePath)) {
801
+ this.grokRemovals.set(rulePath, {
802
+ kind: 'rule', scope, scopeRoot, pluginId: binding.plugin.pluginId, rulePath,
803
+ priorInstructionDigest: priorRows[0].digest,
804
+ });
805
+ }
806
+ }
807
+ }
808
+ }
809
+ recordGrokOfflineRuleRemoval(removal) {
810
+ const rulePath = path.normalize(removal.rulePath);
811
+ if (!this.grokRemovals.has(rulePath)) {
812
+ this.grokRemovals.set(rulePath, { kind: 'rule', ...removal, rulePath });
813
+ }
814
+ }
815
+ recordGrokProjectRetirement(projectRoot, project, user, removed) {
816
+ const old = project.nativeIdentity;
817
+ const replacement = user.nativeIdentity;
818
+ if (old?.route !== 'grok-directory' || project.ownership !== 'aw' || project.package !== 'present'
819
+ || replacement?.route !== 'grok-cli' || replacement.packageId !== old.packageId || !replacement.registrationId
820
+ || user.ownership !== 'aw' || user.registration !== 'present' || user.nativePackage !== 'present' || !user.nativePackageContentDigest
821
+ || path.dirname(old.sourceLocation) !== path.join(projectRoot, '.grok', 'plugins') || !removed.includes(path.basename(old.sourceLocation)))
822
+ return;
823
+ const before = project.prerequisites.nativeSources;
824
+ const personal = user.prerequisites.nativeSources;
825
+ if (before?.observation !== 'complete' || personal?.observation !== 'complete')
826
+ return;
827
+ const source = personal.sources.find(({ name, path: location }) => name === old.packageId
828
+ && path.basename(location) === replacement.registrationId && path.basename(path.dirname(location)) === 'installed-plugins');
829
+ const projectDigest = grokSourceDigest(before, old.sourceLocation, old.packageId, 'project');
830
+ const userDigest = source && grokSourceDigest(personal, source.path, old.packageId, 'user');
831
+ if (!projectDigest || !source || !userDigest)
832
+ return;
833
+ // Retirement can reveal an inherited static Skill provider only.
834
+ if (personal.grokScopeEvidence?.hookOrder.some((row) => row.sourceRoot === source.path))
835
+ return;
836
+ this.grokProjectRetirements.set(old.sourceLocation, { projectRoot, name: old.packageId, projectPackage: old.sourceLocation,
837
+ projectDigest, userPackage: source.path, userDigest, userSource: replacement.sourceLocation,
838
+ userContentDigest: user.nativePackageContentDigest, userPhysicalKey: user.physicalKey });
839
+ }
840
+ async dispose() {
841
+ await Promise.allSettled([...this.rawUnits.values(), ...this.units.values()]);
842
+ if (this.staging)
843
+ await fs.remove(await this.staging);
844
+ this.staging = undefined;
845
+ this.targets.clear();
846
+ this.resolutions.clear();
847
+ this.rawUnits.clear();
848
+ this.units.clear();
849
+ this.published.clear();
850
+ this.nativeEffects.clear();
851
+ this.piProjectRegisteredRoots.clear();
852
+ this.exclusions.clear();
853
+ this.grokPublications.clear();
854
+ this.grokProjectRetirements.clear();
855
+ this.grokRemovals.clear();
856
+ this.offlinePermissionRemovals.clear();
857
+ this.contexts.clear();
858
+ this.mutableChecks.clear();
859
+ this.requestedOperations.clear();
860
+ this.marketplaces.clear();
861
+ this.marketplaceTargets.clear();
862
+ this.marketplaceCandidatesFrozen = false;
863
+ }
864
+ freezeMarketplaceCandidates() { this.marketplaceCandidatesFrozen = true; }
865
+ retirementMode(input) {
866
+ return input.command === 'cleanup' && hasSharedUserPackage(input.platform) && this.context.confirmedCatalogRetirement === true ? true : undefined;
867
+ }
868
+ key(input) {
869
+ return artifactValueDigest({ plugin: sourceIdentity(input), platform: input.platform, scope: input.scope, cwd: input.scope === 'project' ? input.cwd : null,
870
+ operation: operation(input), confirmedCatalogRetirement: this.retirementMode(input) });
871
+ }
872
+ resolve(input, placementProbeGroup) {
873
+ const key = this.key(input);
874
+ // Inspection of a shared package does not request activation in that scope.
875
+ if (!input.readOnlyInspectionPlan)
876
+ this.requestedOperations.set(key, input);
877
+ let result = this.resolutions.get(key);
878
+ if (!result) {
879
+ result = (async () => {
880
+ const adapter = this.adapterFor(input.platform);
881
+ const mode = this.retirementMode(input);
882
+ const readCtx = readContext(this.context, input.cwd, mode);
883
+ const ctx = mode ? readCtx : input.readOnlyInspectionPlan && input.observationBatch ? { ...readCtx, ...input.observationBatch }
884
+ : this.ordinaryReadContext(readCtx, input.platform);
885
+ const plugin = sourceIdentity(input);
886
+ const recoveryCandidates = (this.context.recoveryCandidates ?? []).filter((candidate) => candidate.binding.platform === input.platform
887
+ && candidate.binding.plugin.sourceIdentity === plugin.sourceIdentity && candidate.binding.plugin.pluginId === plugin.pluginId
888
+ && candidate.binding.scope.kind === input.scope && (candidate.binding.scope.kind !== 'project' || candidate.binding.scope.projectRoot === input.cwd));
889
+ const scope = input.scope === 'project' ? { kind: 'project', projectRoot: input.cwd } : { kind: 'user' };
890
+ const discovery = await adapter.discover(placementProbeGroup ? { ...ctx, placementProbeGroup } : ctx);
891
+ const resolution = await adapter.resolve(ctx, { plugin, scope, operation: operation(input), discovery, recoveryCandidates });
892
+ this.exclusions.set(key, resolution.exclusions.flatMap((exclusion) => {
893
+ if (!exclusion.productId)
894
+ return [];
895
+ const product = discovery.installations.find((item) => item.id === exclusion.productId) ?? null;
896
+ if (product?.availability === 'missing' || product?.availability === 'notApplicable')
897
+ return [];
898
+ return [{ platform: input.platform, pluginId: plugin.pluginId, scope, productId: exclusion.productId,
899
+ product: product ? structuredClone(product) : null, reasonCode: exclusion.reasonCode, execution: 'not-run',
900
+ recoveryActions: ['Check the identified client version and installation entry, then retry this product.'] }];
901
+ }));
902
+ if (recoveryCandidates.length) {
903
+ const allowed = new Set(recoveryCandidates.map((candidate) => candidate.binding.physicalKey));
904
+ resolution.bindings = resolution.bindings.filter((binding) => allowed.has(binding.physicalKey));
905
+ const unitIds = new Set(resolution.bindings.flatMap((binding) => binding.renderUnitIds));
906
+ resolution.renderUnits = resolution.renderUnits.filter((unit) => unitIds.has(unit.id));
907
+ }
908
+ return ctx.discoveryCache ? { ...resolution,
909
+ ordinaryEvidence: { discovery: artifactValueDigest(discovery), observations: new Map() } } : resolution;
910
+ })();
911
+ this.resolutions.set(key, result);
912
+ }
913
+ return result;
914
+ }
915
+ /** Resolve the whole selected scope before any physical unit is rendered. */
916
+ async resolveAll(inputs) {
917
+ const first = inputs[0];
918
+ const samePlacement = supportsSharedNativeProbe && first && inputs.length > 1
919
+ && this.context.batchInstallPlatform === first.platform && this.context.nativeObservationBatch?.scriptFreePlacement === true
920
+ && inputs.every((input) => input.platform === first.platform && input.scope === first.scope && input.cwd === first.cwd
921
+ && operation(input) === 'ensure');
922
+ const group = samePlacement ? { scope: first.scope, probes: new Map() } : undefined;
923
+ await Promise.allSettled(inputs.map((input) => this.resolve(input, group)));
924
+ }
925
+ async freezeSharedPreApplyActions(targets) {
926
+ const prepared = (await Promise.allSettled(this.targets.values())).flatMap((result) => result.status === 'fulfilled' ? [result.value] : []);
927
+ for (const target of targets) {
928
+ if (target.identity.scope !== 'project' || !target.operationActions?.some((action) => action.kind === 'runPreApply'))
929
+ continue;
930
+ const plans = target.platformDeployment?.plans ?? [];
931
+ if (!plans.length || plans.some((plan) => !['codex-marketplace', 'claude-marketplace', 'copilot-marketplace'].includes(plan.binding.route)
932
+ || plan.effects.some((effect) => effect.physicalKey !== plan.binding.physicalKey)
933
+ || plan.projections.some((projection) => projection.supplements.length > 0)
934
+ || !plan.evidence.renderUnits?.some((unit) => unit.output === 'package' && unit.renderScope.kind === 'user')))
935
+ continue;
936
+ const provider = prepared.find((candidate) => candidate.identity.scope === 'user' && candidate.identity.platform === target.identity.platform
937
+ && candidate.identity.pluginId === target.identity.pluginId && candidate.identity.sourceIdentity === target.identity.sourceIdentity
938
+ && candidate.operationActions?.some((action) => action.kind === 'runPreApply')
939
+ && plans.every((plan) => candidate.platformDeployment?.plans.some((other) => other.binding.physicalKey === plan.binding.physicalKey)));
940
+ if (!provider)
941
+ continue;
942
+ const input = { sourceId: target.identity.sourceId, sourceIdentity: target.identity.sourceIdentity,
943
+ pluginName: target.plugin.manifest.name, manifest: target.plugin.manifest, platform: target.identity.platform,
944
+ logicalIdentity: target.plugin.catalogLogicalIdentity, cwd: target.identity.cwd,
945
+ env: this.context.env, referencePlugins: this.context.referencePlugins };
946
+ const [userConfig, projectConfig] = await Promise.all([
947
+ resolveArtifactRenderConfig({ ...input, scope: 'user' }), resolveArtifactRenderConfig({ ...input, scope: 'project' }),
948
+ ]);
949
+ if (artifactValueDigest(userConfig.values) !== artifactValueDigest(projectConfig.values))
950
+ continue;
951
+ target.operationActions = target.operationActions.filter((action) => action.kind !== 'runPreApply');
952
+ }
953
+ }
954
+ /** Freeze one complete source descriptor after all eligible packages have been prepared. */
955
+ async sealMarketplaceGenerations(targets) {
956
+ if (this.marketplaceCandidatesFrozen && targets.some((target) => !this.marketplaceTargets.has(target))) {
957
+ throw new Error('operationPlanStale: the reviewed marketplace candidates changed.');
958
+ }
959
+ for (const target of targets)
960
+ this.marketplaceTargets.add(target);
961
+ targets = [...this.marketplaceTargets];
962
+ await this.freezeSharedPreApplyActions(targets);
963
+ await sealPermissionBatches(targets, (target) => readContext(this.context, target.identity.cwd), this.adapterFor, this.offlinePermissionRemovals);
964
+ const retained = new Map(targets.flatMap((target) => (target.platformDeployment?.plans ?? [])
965
+ .filter((plan) => plan.evidence.retainPackage).map((plan) => [plan.binding.physicalKey, plan.expected.unmet])));
966
+ for (const target of targets)
967
+ for (const deployment of [...target.platformDeployment?.deployments ?? []]) {
968
+ const unmet = retained.get(deployment.plan.binding.physicalKey);
969
+ if (!unmet || deployment.plan.evidence.retainPackage)
970
+ continue;
971
+ const next = this.adapterFor(deployment.plan.binding.platform).lifecycle.prepare({ ...deployment.plan,
972
+ observation: deployment.driverState.before, expected: { ...deployment.plan.expected,
973
+ unmet: [...deployment.plan.expected.unmet, ...unmet] }, evidence: { ...deployment.plan.evidence, retainPackage: true } });
974
+ if (next.status !== 'ready')
975
+ throw new Error('sharedPackageRetentionUnconfirmed');
976
+ const prepared = target.platformDeployment;
977
+ prepared.deployments.splice(prepared.deployments.indexOf(deployment), 1, next.prepared);
978
+ prepared.plans.splice(prepared.plans.findIndex((plan) => plan.binding.id === deployment.plan.binding.id), 1, next.prepared.plan);
979
+ }
980
+ const groups = new Map();
981
+ for (const target of targets)
982
+ for (const deployment of target.platformDeployment?.deployments ?? []) {
983
+ const root = deployment.plan.evidence.layout.marketplaceRoot;
984
+ if (!root || deployment.plan.evidence.retainPackage || !deployment.plan.projections.some((projection) => projection.bundle))
985
+ continue;
986
+ const values = groups.get(root) ?? [];
987
+ values.push({ target, deployment });
988
+ groups.set(root, values);
989
+ }
990
+ for (const [root, entries] of groups) {
991
+ const first = entries[0];
992
+ const binding = first.deployment.plan.binding;
993
+ if (binding.platform !== 'codex' && binding.platform !== 'claude' && binding.platform !== 'copilot')
994
+ throw new Error('platformMarketplaceRouteUnsupported');
995
+ const marketplaceName = first.deployment.plan.evidence.layout.marketplaceName;
996
+ const previous = await readStrictNamespacedMarketplaceRoot({ rootDir: root, sourceId: binding.plugin.sourceId,
997
+ sourceIdentity: binding.plugin.sourceIdentity, marketplaceName, platform: binding.platform });
998
+ const candidates = [...new Map(entries.map(({ target }) => [target.plugin.manifest.name,
999
+ { ...createMarketplaceManifestEntry(target.plugin), version: target.plugin.manifest.version }])).values()];
1000
+ const descriptor = projectPlatformMarketplace({ binding, marketplaceName, entries: candidates });
1001
+ const projected = JSON.parse(descriptor.bytes.toString('utf8'));
1002
+ const previousEntries = previous?.manifest.plugins ?? [];
1003
+ if (!Array.isArray(previousEntries))
1004
+ throw new Error('marketplaceRootInvalid: plugins must be an array.');
1005
+ const retained = previousEntries.filter((item) => {
1006
+ if (!item || typeof item !== 'object' || !('name' in item) || typeof item.name !== 'string'
1007
+ || !('source' in item) || item.source !== `./plugins/${item.name}`
1008
+ || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(item.name))
1009
+ throw new Error('marketplaceRootInvalid: an existing entry has an unverified location.');
1010
+ return !candidates.some((candidate) => candidate.name === item.name);
1011
+ });
1012
+ if (!Array.isArray(projected.plugins))
1013
+ throw new Error('platformMarketplaceProjectionInvalid');
1014
+ projected.plugins = [...retained, ...projected.plugins].sort((left, right) => String(left.name).localeCompare(String(right.name)));
1015
+ const contents = [{ relativePath: descriptor.relativePath, bytes: Buffer.from(`${JSON.stringify(projected, null, 2)}\n`) },
1016
+ { relativePath: 'config.json', bytes: Buffer.from(`${JSON.stringify({ schemaVersion: 2, sourceId: binding.plugin.sourceId,
1017
+ sourceIdentity: binding.plugin.sourceIdentity, marketplaceName, logicalIdentity: first.target.plugin.catalogLogicalIdentity }, null, 2)}\n`) }];
1018
+ const files = contents.map(({ relativePath, bytes }) => ({ relativePath, contentBase64: bytes.toString('base64'),
1019
+ contentDigest: `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}` }));
1020
+ const currentFingerprint = artifactValueDigest(await Promise.all(files.map((file) => pathEvidence(path.join(root, file.relativePath)))));
1021
+ const previousGeneration = this.marketplaces.get(root);
1022
+ const candidatesChanged = previousGeneration !== undefined
1023
+ && artifactValueDigest(previousGeneration.evidence.files) !== artifactValueDigest(files);
1024
+ if (previousGeneration && (previousGeneration.currentFingerprint !== currentFingerprint
1025
+ || candidatesChanged && (this.marketplaceCandidatesFrozen || previousGeneration.publication))) {
1026
+ throw new Error('operationPlanStale: the shared marketplace generation changed.');
1027
+ }
1028
+ // Scope plans can arrive separately during preparation. Complete the same
1029
+ // generation before Review; once frozen or published, its bytes cannot grow.
1030
+ const evidence = previousGeneration && !candidatesChanged ? previousGeneration.evidence
1031
+ : { files, fingerprint: artifactValueDigest({ currentFingerprint, files }) };
1032
+ this.marketplaces.set(root, previousGeneration && !candidatesChanged ? previousGeneration : { evidence, currentFingerprint });
1033
+ for (const { target, deployment } of entries) {
1034
+ const adapter = this.adapterFor(deployment.plan.binding.platform);
1035
+ const next = adapter.lifecycle.prepare({ ...deployment.plan, observation: deployment.driverState.before,
1036
+ evidence: { ...deployment.plan.evidence, marketplace: evidence } });
1037
+ if (next.status !== 'ready')
1038
+ throw new Error('operationPlanStale: the marketplace generation could not be sealed.');
1039
+ const prepared = target.platformDeployment;
1040
+ prepared.deployments.splice(prepared.deployments.indexOf(deployment), 1, next.prepared);
1041
+ prepared.plans.splice(prepared.plans.findIndex((plan) => plan.binding.id === deployment.plan.binding.id), 1, next.prepared.plan);
1042
+ }
1043
+ }
1044
+ }
1045
+ async verifyMarketplace(plan) {
1046
+ if (!plan.evidence.layout.marketplaceRoot || !plan.evidence.marketplace)
1047
+ return true;
1048
+ const root = plan.evidence.layout.marketplaceRoot;
1049
+ const generation = this.marketplaces.get(root);
1050
+ return !!generation && artifactValueDigest(await Promise.all(generation.evidence.files.map((file) => pathEvidence(path.join(root, file.relativePath))))) === generation.currentFingerprint;
1051
+ }
1052
+ async publishMarketplace(plan) {
1053
+ const root = plan.evidence.layout.marketplaceRoot;
1054
+ if (!root)
1055
+ return;
1056
+ const generation = this.marketplaces.get(root);
1057
+ if (!generation || !plan.evidence.marketplace)
1058
+ throw new Error('marketplaceGenerationNotPrepared');
1059
+ if (!generation.publication)
1060
+ generation.publication = (async () => {
1061
+ if (!await this.verifyMarketplace(plan))
1062
+ throw new Error('operationPlanStale: the marketplace source changed.');
1063
+ for (const file of generation.evidence.files) {
1064
+ await atomicReplaceSafeFile({ filePath: path.join(root, file.relativePath), allowedRoot: root,
1065
+ content: Buffer.from(file.contentBase64, 'base64').toString('utf8'), label: 'Native marketplace source' });
1066
+ }
1067
+ generation.currentFingerprint = artifactValueDigest(await Promise.all(generation.evidence.files.map((file) => pathEvidence(path.join(root, file.relativePath)))));
1068
+ })();
1069
+ await generation.publication;
1070
+ }
1071
+ async buildTarget(input) {
1072
+ if (input.readOnlyInspectionPlan)
1073
+ return this.build(input);
1074
+ const key = this.key(input);
1075
+ let verifyInitial;
1076
+ let target = this.targets.get(key);
1077
+ if (!target) {
1078
+ target = this.build(input, (check) => { verifyInitial = check; });
1079
+ this.targets.set(key, target);
1080
+ }
1081
+ // A writable build or cached-target verification ends ordinary sharing,
1082
+ // before any renderer, plan verification or mutation can consume it.
1083
+ if (this.context.nativeObservationBatch)
1084
+ this.closedObservationBatch = this.context.nativeObservationBatch;
1085
+ const result = await target;
1086
+ if (verifyInitial)
1087
+ await verifyInitial();
1088
+ else
1089
+ await result.platformDeployment?.verify(input.observationBatch);
1090
+ return result;
1091
+ }
1092
+ prepareRawUnit(key, requestFor) {
1093
+ let result = this.rawUnits.get(key);
1094
+ if (!result) {
1095
+ result = requestFor().then(async (request) => ({ request, prepared: await preparePlatformComponents(request) }));
1096
+ this.rawUnits.set(key, result);
1097
+ }
1098
+ return result;
1099
+ }
1100
+ async prepareCodexUserAgents(raw, resolved) {
1101
+ const key = raw.unit.physicalKey;
1102
+ // The User supplement and Project-only in-memory view share one raw batch, independently of package finalization.
1103
+ const result = await this.prepareRawUnit(key + ':user-agents', async () => {
1104
+ const request = { ...raw.request, kinds: ['agent'] };
1105
+ const sibling = resolved.find((entry) => entry.request?.scope === 'user'
1106
+ && !['remove', 'cleanup'].includes(operation(entry.request))
1107
+ && entry.resolution?.bindings.some((binding) => binding.physicalKey === key));
1108
+ const binding = sibling?.resolution?.bindings.find((other) => other.physicalKey === key);
1109
+ const renderUnit = sibling?.resolution?.renderUnits.find((other) => binding?.renderUnitIds.includes(other.id)
1110
+ && other.output === 'supplement' && other.renderScope.kind === 'user');
1111
+ if (!binding || !renderUnit || !sibling?.request)
1112
+ return request;
1113
+ // The Project target can be built first, before a known User target starts preparing its supplement.
1114
+ const adapter = this.adapterFor('codex');
1115
+ const cwd = sibling.request.cwd;
1116
+ const capabilities = adapter.capabilities({ binding, renderUnit, profile: getQualifiedPlatformProfile('codex') });
1117
+ return { ...request, cwd, capabilities };
1118
+ });
1119
+ return result.prepared;
1120
+ }
1121
+ async build(input, receiveInitialVerifier) {
1122
+ const { command: pluginCommand, scripts } = input.plugin.manifest;
1123
+ const cursorPreviewBatch = input.platform === 'cursor'
1124
+ && this.context.nativeObservationBatch?.initialInstallPreview === true
1125
+ && pluginCommand?.mode !== 'dynamic' && !scripts?.artifacts?.render && !scripts?.preApply && !scripts?.node?.build
1126
+ ? this.context.nativeObservationBatch : undefined;
1127
+ const confirmedCatalogRetirement = this.retirementMode(input);
1128
+ const ctx = readContext(this.context, input.cwd, confirmedCatalogRetirement);
1129
+ const ordinaryCtx = confirmedCatalogRetirement ? ctx : input.readOnlyInspectionPlan && input.observationBatch ? { ...ctx, ...input.observationBatch }
1130
+ : this.ordinaryReadContext(ctx, input.platform);
1131
+ const resolution = await this.resolve(input);
1132
+ if (!resolution.bindings.length)
1133
+ throw Object.assign(new Error(`platformUnavailable: ${resolution.exclusions.map((item) => item.reasonCode).join(', ') || input.platform}`), { deploymentExclusions: this.exclusions.get(this.key(input)) ?? [] });
1134
+ const adapter = this.adapterFor(input.platform);
1135
+ // An activation-only Project action restores access to its existing User provider.
1136
+ const requireIndependentActivation = input.platform !== 'codex' || !isNativeActivationOnlyTarget(this.context, {
1137
+ pluginId: sourceIdentity(input).pluginId, platform: input.platform, scope: input.scope,
1138
+ });
1139
+ this.contexts.add(ctx);
1140
+ const observed = await Promise.all(resolution.bindings.map(async (binding) => ({ binding,
1141
+ observation: await adapter.inspect(ordinaryCtx, binding), layout: await getDeploymentLayout(ctx, binding) })));
1142
+ const { ordinaryEvidence } = resolution;
1143
+ if (ordinaryEvidence && (ordinaryCtx.nativeQuerySession || !input.readOnlyInspectionPlan)) {
1144
+ // Keep the first observation used for placement, including for targets
1145
+ // built after the observation batch has already ended.
1146
+ for (const { binding, observation } of observed) {
1147
+ const digest = artifactValueDigest(observation);
1148
+ const previous = ordinaryEvidence.observations.get(binding.id);
1149
+ if (previous === undefined)
1150
+ ordinaryEvidence.observations.set(binding.id, digest);
1151
+ else if (!input.readOnlyInspectionPlan && previous !== digest) {
1152
+ throw new Error('operationPlanStale: deployment evidence changed after the ordinary observation.');
1153
+ }
1154
+ }
1155
+ }
1156
+ if (input.readOnlyInspectionPlan && !input.readOnlyShallowInspectionPlan)
1157
+ for (const entry of observed) {
1158
+ const unit = entry.layout.renderUnits.find((candidate) => candidate.output === 'supplement');
1159
+ if (!unit)
1160
+ continue;
1161
+ const staticResourceRoot = await resolveStaticPlatformResourceRoot(input.plugin.rootDir, input.platform);
1162
+ const expected = await normalizeStaticPluginComponents({ pluginRoot: input.plugin.rootDir, staticResourceRoot,
1163
+ manifest: input.plugin.manifest, platform: input.platform,
1164
+ capabilities: adapter.capabilities({ binding: entry.binding, renderUnit: unit,
1165
+ profile: getQualifiedPlatformProfile(input.platform) }), allowedOutputKinds: unit.kinds });
1166
+ const supplements = await inspectStaticSupplements(ctx, entry.binding, expected.components);
1167
+ entry.observation.components.push(...supplements.components);
1168
+ }
1169
+ const owned = observed.flatMap(({ binding, layout }) => [deploymentPackageComponent(binding, layout),
1170
+ ...(input.readOnlyInspectionPlan ? staticSupplementFiles(binding, layout, input.plugin.manifest) : [])]);
1171
+ const target = { plugin: input.plugin, identity: targetIdentity(input), ownedComponents: owned,
1172
+ platformObservations: observed.map(({ binding, observation }) => ({ binding, observation })),
1173
+ desiredOwnedComponents: owned, requiresNative: false, writeNativeRequired: false, artifacts: [], preApplySource: input.plugin,
1174
+ deploymentExclusions: this.exclusions.get(this.key(input)) ?? [] };
1175
+ if (input.readOnlyInspectionPlan)
1176
+ return target;
1177
+ const removing = operation(input) === 'remove' || operation(input) === 'cleanup';
1178
+ const preparedUnits = new Map();
1179
+ if (!removing) {
1180
+ const resolved = await Promise.all([...this.resolutions].map(async ([key, promise]) => ({
1181
+ request: this.requestedOperations.get(key), resolution: await promise.catch(() => undefined),
1182
+ })));
1183
+ const allUnits = resolved.flatMap((entry) => entry.resolution?.renderUnits ?? []);
1184
+ const rawUnits = new Map();
1185
+ const profile = getQualifiedPlatformProfile(input.platform);
1186
+ for (const unit of resolution.renderUnits) {
1187
+ const bindingEntry = observed.find(({ binding }) => binding.renderUnitIds.includes(unit.id));
1188
+ if (!bindingEntry)
1189
+ throw new Error('deploymentRenderUnitUnbound');
1190
+ const compatible = allUnits.filter((item) => item.physicalKey === unit.physicalKey);
1191
+ if (compatible.some((item) => artifactValueDigest({ scope: item.renderScope, kinds: item.kinds, output: item.output })
1192
+ !== artifactValueDigest({ scope: unit.renderScope, kinds: unit.kinds, output: unit.output })))
1193
+ throw new Error('shared-projection-conflict');
1194
+ const commonUnit = { ...unit, consumers: [...new Map(compatible.flatMap((item) => item.consumers).map((consumer) => [consumer.id, consumer])).values()] };
1195
+ const codexUserRoles = input.platform === 'codex' && unit.output === 'supplement' && unit.renderScope.kind === 'user';
1196
+ const key = codexUserRoles ? bindingEntry.binding.physicalKey + ':user-agents' : unit.physicalKey;
1197
+ const raw = await this.prepareRawUnit(key, async () => {
1198
+ const capabilities = adapter.capabilities({ binding: bindingEntry.binding, renderUnit: commonUnit, profile });
1199
+ const config = await resolveArtifactRenderConfig({ ...sourceIdentity(input), logicalIdentity: input.plugin.catalogLogicalIdentity,
1200
+ pluginName: input.plugin.manifest.name, manifest: input.plugin.manifest, platform: input.platform,
1201
+ scope: unit.renderScope.kind, cwd: unit.renderScope.kind === 'project' ? unit.renderScope.projectRoot : input.cwd,
1202
+ env: this.context.env, referencePlugins: this.context.referencePlugins });
1203
+ const staticResourceRoot = await resolveStaticPlatformResourceRoot(input.plugin.rootDir, input.platform);
1204
+ const grokRoleUnit = input.platform === 'grok' && unit.output === 'supplement'
1205
+ ? bindingEntry.layout.renderUnits.find((candidate) => candidate.output === 'package'
1206
+ && artifactValueDigest(candidate.renderScope) === artifactValueDigest(unit.renderScope)) : undefined;
1207
+ return { plugin: input.plugin, platform: input.platform, staticResourceRoot,
1208
+ renderScope: unit.renderScope.kind, kinds: unit.kinds, capabilities, config, cwd: input.cwd,
1209
+ hasInstructionAgentRecipients: grokRoleUnit && rawUnits.get(grokRoleUnit.id)?.prepared.expected.components.some(({ kind }) => kind === 'agent'),
1210
+ commandEnv: this.context.env, signal: this.context.signal, scriptTimeoutMs: this.context.scriptTimeoutMs,
1211
+ preparedResults: this.context.preparedArtifactRenderResults };
1212
+ });
1213
+ rawUnits.set(unit.id, { unit: commonUnit, ...raw });
1214
+ }
1215
+ for (const raw of rawUnits.values()) {
1216
+ const { unit, request: { config, capabilities } } = raw;
1217
+ let promise = this.units.get(unit.physicalKey);
1218
+ if (!promise) {
1219
+ promise = (async () => {
1220
+ const binding = observed.find((entry) => entry.binding.renderUnitIds.includes(unit.id)).binding;
1221
+ const peers = binding.renderUnitIds.map((id) => rawUnits.get(id));
1222
+ const sharedCodexPackage = input.platform === 'codex' && unit.output === 'package' && unit.renderScope.kind === 'user';
1223
+ const extraAgents = sharedCodexPackage ? () => this.prepareCodexUserAgents(raw, resolved) : undefined;
1224
+ const finalized = await finalizePlatformSkillProducers({ plugin: input.plugin, plugins: this.context.referencePlugins,
1225
+ platform: input.platform, renderUnit: unit, prepared: raw.prepared, agentBinding: skillAgentBinding(raw, peers, extraAgents),
1226
+ skillWorkRoot: path.join(await this.root(), artifactValueDigest(unit.physicalKey).slice(7), 'skills'),
1227
+ cwd: input.cwd, env: this.context.env, signal: this.context.signal, scriptTimeoutMs: this.context.scriptTimeoutMs,
1228
+ commandRecord: input.commandRecord });
1229
+ return { unit, prepared: finalized.prepared, finalized, evidenceInput: { renderUnit: unit, capabilities, config } };
1230
+ })();
1231
+ this.units.set(unit.physicalKey, promise);
1232
+ }
1233
+ preparedUnits.set(unit.id, await promise);
1234
+ }
1235
+ }
1236
+ const deployments = [];
1237
+ const plans = [];
1238
+ const blockedReceipts = [];
1239
+ const cleanupResults = [];
1240
+ const checks = new Map();
1241
+ const shadowedUsers = new Map();
1242
+ let initialDiscoveryCheck;
1243
+ const emptyStates = new Map();
1244
+ const gapStates = new Map();
1245
+ const inputDigests = new Map();
1246
+ const supplementInputDigests = new Map();
1247
+ for (const entry of observed) {
1248
+ const units = entry.binding.renderUnitIds.flatMap((id) => preparedUnits.has(id) ? [preparedUnits.get(id)] : []);
1249
+ const projections = [];
1250
+ const hostEntry = entry.binding.consumers[0]?.entry;
1251
+ const hostRoot = hostEntry && hostEntry.kind !== 'generic' ? hostEntry.configRoot : undefined;
1252
+ const grokProjectBlocked = entry.binding.platform === 'grok' && entry.binding.scope.kind === 'project'
1253
+ && (entry.observation.grokScopeAuthorization !== 'granted' || !hostRoot
1254
+ || !await grokProjectPermissionsAuthorized(ctx, hostRoot, entry.binding.scope.projectRoot));
1255
+ for (const unit of units) {
1256
+ const sameScope = units.filter((candidate) => artifactValueDigest(candidate.unit.renderScope) === artifactValueDigest(unit.unit.renderScope));
1257
+ const components = mergeExpectedComponentSets(sameScope.map((candidate) => candidate.prepared.expected)).components;
1258
+ const resources = { resources: sameScope.flatMap((candidate) => candidate.prepared.resources.resources),
1259
+ bundleFiles: sameScope.flatMap((candidate) => candidate.prepared.resources.bundleFiles),
1260
+ files: sameScope.flatMap((candidate) => candidate.prepared.resources.files),
1261
+ commandResources: sameScope.flatMap((candidate) => candidate.prepared.resources.commandResources),
1262
+ digest: artifactValueDigest(sameScope.map((candidate) => candidate.prepared.resources.digest)) };
1263
+ const projection = await adapter.project({ ...ctx, stagingRoot: path.join(await this.root(), 'projection') }, {
1264
+ binding: entry.binding, renderUnit: unit.unit,
1265
+ capabilities: adapter.capabilities({ binding: entry.binding, renderUnit: unit.unit, profile: getQualifiedPlatformProfile(input.platform) }),
1266
+ components, resources, policy: unit.finalized.invocationPolicy.policy,
1267
+ ...(grokProjectBlocked ? { grokScopeAuthorization: 'denied' } : {})
1268
+ });
1269
+ for (const notice of unit.finalized.invocationPolicy.diagnostics) {
1270
+ projection.diagnostics.push({ ...notice, subject: { ...notice.subject, scope: entry.binding.scope.kind } });
1271
+ }
1272
+ projections.push(projection);
1273
+ }
1274
+ const hostPolicyPath = isPermissionHost(input.platform) && (input.platform !== 'antigravity' || entry.binding.route === 'antigravity-cli')
1275
+ ? await scopedPermissionPath(ctx, input.platform, entry.binding.scope, hostEntry && hostEntry.kind !== 'generic' ? hostEntry.configRoot : undefined)
1276
+ : undefined;
1277
+ const policyKey = hostPolicyPath || input.platform === 'codex' || input.platform === 'claude'
1278
+ ? await getInvocationPolicyPhysicalKey(ctx, entry.binding) : undefined;
1279
+ const expected = mergeExpectedComponentSets(units.map((unit) => unit.prepared.expected));
1280
+ const currentComponents = [deploymentPackageComponent(entry.binding, entry.layout),
1281
+ ...projections.flatMap((projection) => projection.supplements.map((contribution) => contributionComponent(entry.binding, contribution, policyKey && (contribution.mergeKey?.startsWith(`${input.platform}-permissions:`) || input.platform === 'codex' && contribution.destination.endsWith('.rules'))
1282
+ ? policyKey : entry.layout.renderUnits.find((unit) => unit.id === projection.renderUnitId).physicalKey)))];
1283
+ const historical = await ownedSupplements(entry.binding, entry.layout.supplementRoot, entry.layout.renderUnits.find((unit) => unit.output === 'supplement')?.physicalKey);
1284
+ const antigravityProject = isAntigravityProjectDirectory(entry.binding);
1285
+ const legacyPackage = entry.observation.antigravityLegacyProjectPackage?.state === 'owned'
1286
+ ? antigravityLegacyProjectComponent(entry.binding, entry.layout) : undefined;
1287
+ if (legacyPackage)
1288
+ historical.push(legacyPackage);
1289
+ if (entry.binding.platform === 'codex' && policyKey)
1290
+ historical.push(...await ownedSupplements(entry.binding, path.join(entry.layout.activationPath, 'rules'), policyKey));
1291
+ if (hostPolicyPath && policyKey && !grokProjectBlocked) {
1292
+ historical.push(permissionComponent(entry.binding, hostPolicyPath, policyKey));
1293
+ }
1294
+ if (entry.binding.platform === 'claude' && policyKey) {
1295
+ const destination = path.join(entry.layout.activationPath, entry.binding.scope.kind === 'project' ? 'settings.local.json' : 'settings.json');
1296
+ historical.push(contributionComponent(entry.binding, { id: 'policy:claude-permissions', componentIds: [], kind: 'config-entry',
1297
+ destination, contentDigest: '', stagingPath: '', mergeKey: `claude-permissions:${getDeploymentResourceKey(entry.binding.plugin)}` }, policyKey));
1298
+ }
1299
+ if (entry.binding.platform === 'cursor' && !projections.some((projection) => projection.supplements.some((item) => item.kind === 'config-entry'))) {
1300
+ const component = contributionComponent(entry.binding, { id: 'cursor-workspace-open', componentIds: [], kind: 'config-entry',
1301
+ destination: entry.layout.activationPath, stagingPath: '', contentDigest: '', mergeKey: `workspaceOpen:${getDeploymentResourceKey(entry.binding.plugin)}` }, entry.binding.physicalKey);
1302
+ if (component.kind === 'shared-config' && component.locator.kind === 'cursor-workspace-hook')
1303
+ component.locator.command = cursorWorkspaceOpenCommand(entry.binding, ctx.platform);
1304
+ historical.push(component);
1305
+ }
1306
+ for (const slot of gapSupplementFiles(entry.binding, entry.layout, expected.unmet)) {
1307
+ if (!historical.some((component) => 'path' in component && component.path === slot.path))
1308
+ historical.push(slot);
1309
+ }
1310
+ const components = [...currentComponents, ...historical.filter((component) => !currentComponents.some((current) => 'path' in current && 'path' in component && current.path === component.path
1311
+ || current.kind === 'shared-config' && component.kind === 'shared-config' && artifactValueDigest(current.locator) === artifactValueDigest(component.locator)))];
1312
+ for (const component of components)
1313
+ if (component.kind === 'shared-config' && component.locator.kind === 'cursor-workspace-hook') {
1314
+ const locator = component.locator;
1315
+ const contribution = projections.flatMap((projection) => projection.supplements).find((item) => item.destination === locator.hooksPath);
1316
+ if (!contribution)
1317
+ continue;
1318
+ const { entries } = cursorHooks(await jsonObject(contribution.stagingPath));
1319
+ const command = entries.map(cursorHookEntryCommand).find((value) => value !== undefined);
1320
+ if (!command)
1321
+ throw new Error('cursorWorkspaceHookInvalid');
1322
+ component.locator.command = command;
1323
+ }
1324
+ const inspected = await inspectOwnedComponents({ components, executor: this.ownership });
1325
+ const managedCommandReview = await captureManagedCommandReviewEvidence({ binding: entry.binding,
1326
+ renderUnits: entry.layout.renderUnits, inactivePermissions: units.flatMap((unit) => unit.finalized.invocationPolicy.inactivePermissions), projections });
1327
+ const currentMutable = async (batch) => {
1328
+ const observation = await adapter.inspect(batch && !confirmedCatalogRetirement ? { ...ctx, ...batch } : ctx, entry.binding);
1329
+ return { observation, references: await sharedReferences(this.context, entry.binding, observation, entry.layout),
1330
+ paths: await Promise.all(components.map(async (component) => {
1331
+ if ('path' in component)
1332
+ return pathEvidence(component.path);
1333
+ const ownership = await inspectOwnedComponents({ components: [component], executor: this.ownership });
1334
+ if (component.kind === 'shared-config' && component.locator.kind === 'host-permissions') {
1335
+ const locator = component.locator;
1336
+ const plannedWrite = projections.some((projection) => projection.supplements.some((item) => item.destination === locator.settingsPath));
1337
+ const fingerprint = await hostPermissionFingerprint(ctx, locator, plannedWrite);
1338
+ const last = this.permissionWrites.get(component.locator.settingsPath);
1339
+ return { ownership, fingerprint: last?.current === fingerprint ? last.previous : fingerprint };
1340
+ }
1341
+ return { ownership, contentDigest: await ownedContentDigest(component, ctx) };
1342
+ })) };
1343
+ };
1344
+ const shadowedUser = operation(input) === 'ensure' ? await grokUserBehindProject(ctx, entry.binding, entry.observation) : undefined;
1345
+ const fingerprintParts = async (discovery) => ({
1346
+ confirmedCatalogRetirement: this.retirementMode(input),
1347
+ ...(shadowedUser && { grokUserContent: await grokUserContentDigest(shadowedUser) }),
1348
+ managedCommandReview,
1349
+ source: removing ? null : await pathEvidence(input.plugin.rootDir),
1350
+ discovery: discovery ? discovery.value : removing ? { consumers: entry.binding.consumers, executables: await Promise.all(entry.binding.consumers.map((consumer) => consumer.entry?.kind === 'cli' ? pathEvidence(consumer.entry.executable) : null)) } : await adapter.discover(ctx),
1351
+ sharedReferenceView: this.context.sharedReferenceView,
1352
+ layout: await getDeploymentLayout(ctx, entry.binding),
1353
+ config: await Promise.all(units.map((unit) => resolveArtifactRenderConfig({ ...sourceIdentity(input), pluginName: input.plugin.manifest.name,
1354
+ logicalIdentity: input.plugin.catalogLogicalIdentity, manifest: input.plugin.manifest, platform: input.platform,
1355
+ scope: unit.unit.renderScope.kind, cwd: input.cwd, env: this.context.env, referencePlugins: this.context.referencePlugins }))),
1356
+ staging: await Promise.all(projections.map(async (projection) => ({
1357
+ bundle: projection.bundle ? await pathEvidence(projection.bundle.stagingRoot) : null,
1358
+ supplements: await Promise.all(projection.supplements.map((contribution) => pathEvidence(contribution.stagingPath))),
1359
+ }))),
1360
+ });
1361
+ // Discovery and inspection are independent reads for these routes. Settle
1362
+ // both before comparing or throwing, while preserving immutable priority.
1363
+ const parallelNativeReads = ['copilot-marketplace', 'pi-package'].includes(entry.binding.route);
1364
+ const initialReads = parallelNativeReads
1365
+ ? await Promise.allSettled([fingerprintParts(), currentMutable()]) : null;
1366
+ if (initialReads?.[0].status === 'rejected')
1367
+ throw initialReads[0].reason;
1368
+ const initialParts = initialReads?.[0].status === 'fulfilled' ? initialReads[0].value : await fingerprintParts();
1369
+ if (shadowedUser && initialParts.grokUserContent) {
1370
+ shadowedUsers.set(entry.binding.id, { ...shadowedUser, contentDigest: initialParts.grokUserContent });
1371
+ }
1372
+ if (!removing && ordinaryEvidence && ordinaryEvidence.discovery !== artifactValueDigest(initialParts.discovery)) {
1373
+ throw new Error('operationPlanStale: client discovery changed after the ordinary observation.');
1374
+ }
1375
+ const initial = artifactValueDigest(initialParts);
1376
+ const fingerprint = async (discovery) => artifactValueDigest(await fingerprintParts(discovery));
1377
+ if (initialReads?.[1].status === 'rejected')
1378
+ throw initialReads[1].reason;
1379
+ let mutableBaseline = initialReads?.[1].status === 'fulfilled' ? initialReads[1].value : await currentMutable();
1380
+ const ordinaryObservation = ordinaryEvidence?.observations.get(entry.binding.id);
1381
+ if (ordinaryObservation !== undefined && ordinaryObservation !== artifactValueDigest(mutableBaseline.observation)) {
1382
+ throw new Error('operationPlanStale: deployment evidence changed after the ordinary observation.');
1383
+ }
1384
+ const preparationObservation = confirmedCatalogRetirement || entry.binding.route === 'antigravity-cli' || antigravityProject
1385
+ ? mutableBaseline.observation : entry.observation;
1386
+ const piInventoryKey = piProjectInventoryKey(entry.binding, entry.layout.activationPath);
1387
+ const matchesMutable = (current) => {
1388
+ const currentDigest = artifactValueDigest(current);
1389
+ if (currentDigest === artifactValueDigest(mutableBaseline))
1390
+ return true;
1391
+ const registered = piInventoryKey && this.piProjectRegisteredRoots.get(piInventoryKey);
1392
+ if (!registered || operation(input) !== 'ensure' || !piProjectEmptyDeliveryObserved(entry.binding, mutableBaseline.observation)
1393
+ || current.observation.registration !== 'absent' || !piProjectListContainsOnly(current.observation, registered))
1394
+ return false;
1395
+ // The first successful register in an empty Project can expose its
1396
+ // section. Compare every other fact with the original empty target.
1397
+ const { observation: before, ...baseline } = mutableBaseline;
1398
+ return currentDigest === artifactValueDigest({ ...baseline,
1399
+ observation: { ...before, registration: 'absent',
1400
+ diagnostics: before.diagnostics.filter(({ code }) => code !== 'piProjectRegistrationNotVisible') } });
1401
+ };
1402
+ const matchesAfterGrokPublications = async (current) => {
1403
+ const { binding } = entry;
1404
+ const scopeRoot = binding.route === 'grok-cli' ? entry.layout.activationPath
1405
+ : binding.route === 'grok-directory' && binding.scope.kind === 'project' ? binding.scope.projectRoot : null;
1406
+ const publications = scopeRoot && operation(input) === 'ensure' ? [...this.grokPublications.values()].filter((item) => item.scope === binding.scope.kind && item.scopeRoot === scopeRoot && item.owner.identity.pluginId !== binding.plugin.pluginId) : [];
1407
+ const retirements = binding.route === 'grok-directory' && operation(input) === 'ensure'
1408
+ ? [...this.grokProjectRetirements.values()].filter((item) => item.projectRoot === scopeRoot) : [];
1409
+ const removals = scopeRoot && ['remove', 'cleanup'].includes(operation(input))
1410
+ ? [...this.grokRemovals.values()].filter((item) => item.scope === binding.scope.kind && item.scopeRoot === scopeRoot && item.pluginId !== binding.plugin.pluginId) : [];
1411
+ const baselineDigest = artifactValueDigest(mutableBaseline);
1412
+ if (artifactValueDigest(current) === baselineDigest)
1413
+ return true;
1414
+ if (!scopeRoot || !publications.length && !retirements.length && !removals.length && !this.grokPermissionWrites.size)
1415
+ return false;
1416
+ const before = mutableBaseline.observation.prerequisites.nativeSources;
1417
+ const after = current.observation.prerequisites.nativeSources;
1418
+ const priorEvidence = before?.grokScopeEvidence;
1419
+ const scopeEvidence = after?.grokScopeEvidence;
1420
+ if (before?.observation !== 'complete' || after?.observation !== 'complete' || !scopeEvidence || !priorEvidence
1421
+ || scopeEvidence.scopeDigest !== priorEvidence.scopeDigest)
1422
+ return false;
1423
+ let permissionChanged = false;
1424
+ if (scopeEvidence.permissionConfigs.length !== priorEvidence.permissionConfigs.length)
1425
+ return false;
1426
+ for (const [index, file] of scopeEvidence.permissionConfigs.entries()) {
1427
+ const prior = priorEvidence.permissionConfigs[index];
1428
+ if (prior.path !== file.path)
1429
+ return false;
1430
+ if (prior.digest === file.digest)
1431
+ continue;
1432
+ const write = this.grokPermissionWrites.get(file.path);
1433
+ if (!write || write.previous !== prior.digest || write.current !== file.digest)
1434
+ return false;
1435
+ permissionChanged = true;
1436
+ }
1437
+ if (!permissionChanged && scopeEvidence.permissionInventoryDigest !== priorEvidence.permissionInventoryDigest)
1438
+ return false;
1439
+ const paths = after.sources.map((source) => path.normalize(source.path));
1440
+ const priorPaths = before.sources.map((source) => path.normalize(source.path));
1441
+ if (new Set(paths).size !== paths.length || new Set(priorPaths).size !== priorPaths.length)
1442
+ return false;
1443
+ const sources = [...after.sources];
1444
+ const sourceDigests = [...scopeEvidence.sourceDigests];
1445
+ const addedSources = new Set();
1446
+ const publishedRoots = new Set();
1447
+ const orderChecks = [priorEvidence];
1448
+ const instructions = [...scopeEvidence.instructions];
1449
+ const retiredSources = new Set();
1450
+ const retiredRules = new Set();
1451
+ let adjusted = permissionChanged;
1452
+ for (const removal of removals) {
1453
+ ctx.signal?.throwIfAborted();
1454
+ if (removal.kind === 'package') {
1455
+ if (removal.packageName === entry.layout.nativeIdentity.packageId)
1456
+ return false;
1457
+ const priorIndex = priorPaths.indexOf(removal.installedRoot);
1458
+ if (priorIndex < 0)
1459
+ continue;
1460
+ if (priorEvidence.sourceDigests[priorIndex] !== removal.priorNativeDigest
1461
+ || paths.includes(removal.installedRoot)
1462
+ || await pathEvidence(removal.installedRoot) !== null)
1463
+ return false;
1464
+ retiredSources.add(removal.installedRoot);
1465
+ publishedRoots.add(removal.installedRoot);
1466
+ adjusted = true;
1467
+ }
1468
+ else {
1469
+ const priorRows = priorEvidence.instructions.filter((row) => row.rulePath === removal.rulePath);
1470
+ if (!priorRows.length)
1471
+ continue;
1472
+ if (priorRows.length !== 1
1473
+ || removal.priorInstructionDigest !== undefined && priorRows[0].digest !== removal.priorInstructionDigest
1474
+ || instructions.some((row) => row.rulePath === removal.rulePath)
1475
+ || await pathEvidence(removal.rulePath) !== null)
1476
+ return false;
1477
+ retiredRules.add(removal.rulePath);
1478
+ adjusted = true;
1479
+ }
1480
+ }
1481
+ for (const retirement of retirements) {
1482
+ const { name, projectPackage, projectDigest, userPackage, userDigest, userSource, userContentDigest, userPhysicalKey } = retirement;
1483
+ if (!priorPaths.includes(projectPackage))
1484
+ continue;
1485
+ if (name === entry.layout.nativeIdentity.packageId || priorPaths.includes(userPackage) || paths.includes(projectPackage)
1486
+ || grokSourceDigest(before, projectPackage, name, 'project') !== projectDigest
1487
+ || grokSourceDigest(after, userPackage, name, 'user') !== userDigest
1488
+ || await pathEvidence(projectPackage) !== null)
1489
+ return false;
1490
+ await assertSafeFileMutationPath({ filePath: path.join(userPackage, '.grok-plugin', 'plugin.json'),
1491
+ allowedRoot: path.dirname(path.dirname(userPackage)), label: 'Grok installed package' });
1492
+ const [installed, source, marker] = await Promise.all([readPlatformPackageContentDigest(userPackage), readPlatformPackageContentDigest(userSource),
1493
+ readSkillOwnerMarker({ skillRoot: userSource, allowedRoot: path.dirname(userSource) })]);
1494
+ if (installed !== userContentDigest || source !== userContentDigest || marker?.physicalKey !== userPhysicalKey)
1495
+ return false;
1496
+ // The Project copy hid this exact User copy. Both may leave their
1497
+ // old positions, and the remaining sources and components keep theirs.
1498
+ retiredSources.add(projectPackage);
1499
+ addedSources.add(userPackage);
1500
+ publishedRoots.add(projectPackage);
1501
+ publishedRoots.add(userPackage);
1502
+ adjusted = true;
1503
+ }
1504
+ for (const { owner, scopeRoot: publishedRoot, installedRoot, nativeDigest, contentDigest, priorNativeDigest, orderAfter, shadowedUser } of publications) {
1505
+ ctx.signal?.throwIfAborted();
1506
+ if (owner.kind === 'owned-directory') {
1507
+ const root = installedRoot ?? owner.path;
1508
+ const index = paths.indexOf(root);
1509
+ if (scopeEvidence.sourceDigests[index] !== nativeDigest || after.sources[index]?.name === entry.layout.nativeIdentity.packageId)
1510
+ return false;
1511
+ const priorIndex = priorPaths.indexOf(root);
1512
+ const priorDigest = priorEvidence.sourceDigests[priorIndex];
1513
+ if (shadowedUser) {
1514
+ const hidden = shadowedUser.installedRoot;
1515
+ if (paths.includes(hidden) || await grokUserContentDigest(shadowedUser) !== shadowedUser.contentDigest)
1516
+ return false;
1517
+ if (priorIndex < 0) {
1518
+ if (grokSourceDigest(before, hidden, owner.identity.plugin, 'user') !== shadowedUser.nativeDigest)
1519
+ return false;
1520
+ retiredSources.add(hidden);
1521
+ publishedRoots.add(hidden);
1522
+ }
1523
+ }
1524
+ if (priorDigest !== nativeDigest) {
1525
+ if (priorDigest !== priorNativeDigest)
1526
+ return false;
1527
+ publishedRoots.add(root);
1528
+ if (orderAfter)
1529
+ orderChecks.push(orderAfter);
1530
+ // Restore the frozen source at its current position. Moving a
1531
+ // source or changing any other source still invalidates the plan.
1532
+ if (priorIndex < 0)
1533
+ addedSources.add(root);
1534
+ else {
1535
+ sources[index] = before.sources[priorIndex];
1536
+ sourceDigests[index] = priorDigest;
1537
+ }
1538
+ adjusted = true;
1539
+ }
1540
+ const marker = await readSkillOwnerMarker({ skillRoot: owner.path, allowedRoot: owner.allowedRoot,
1541
+ expectedIdentity: owner.identity }).catch(() => null);
1542
+ const observedContent = marker?.nativeProjection?.contentDigest === contentDigest
1543
+ ? await readPlatformPackageContentDigest(owner.path).catch(() => undefined) : undefined;
1544
+ if (observedContent !== contentDigest)
1545
+ return false;
1546
+ if (installedRoot) {
1547
+ try {
1548
+ await assertSafeFileMutationPath({ filePath: path.join(installedRoot, '.grok-plugin', 'plugin.json'),
1549
+ allowedRoot: publishedRoot, label: 'Grok installed package' });
1550
+ if (await readPlatformPackageContentDigest(installedRoot) !== contentDigest)
1551
+ return false;
1552
+ }
1553
+ catch {
1554
+ ctx.signal?.throwIfAborted();
1555
+ return false;
1556
+ }
1557
+ }
1558
+ }
1559
+ else {
1560
+ const matches = instructions.filter((row) => row.rulePath === owner.path);
1561
+ if (matches.length !== 1 || matches[0].digest !== nativeDigest)
1562
+ return false;
1563
+ const index = instructions.indexOf(matches[0]);
1564
+ const prior = priorEvidence.instructions.find((row) => row.rulePath === owner.path);
1565
+ if (prior?.digest !== nativeDigest) {
1566
+ if (prior?.digest !== priorNativeDigest)
1567
+ return false;
1568
+ instructions.splice(index, 1, ...(prior ? [prior] : []));
1569
+ adjusted = true;
1570
+ }
1571
+ // The written hash includes the exact owner header. Grok's size
1572
+ // and token count alone cannot detect a same-length external edit.
1573
+ try {
1574
+ await assertSafeFileMutationPath({ filePath: owner.path, allowedRoot: publishedRoot, label: 'Grok rule' });
1575
+ const bytes = await fs.readFile(owner.path);
1576
+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== contentDigest)
1577
+ return false;
1578
+ }
1579
+ catch {
1580
+ ctx.signal?.throwIfAborted();
1581
+ return false;
1582
+ }
1583
+ }
1584
+ }
1585
+ ctx.signal?.throwIfAborted();
1586
+ if (!adjusted)
1587
+ return artifactValueDigest(current) === baselineDigest;
1588
+ for (const sourceOrderAfter of [
1589
+ ...publications.flatMap((item) => item.sourceOrderAfter ? [item.sourceOrderAfter] : []),
1590
+ ...removals.flatMap((item) => item.kind === 'package' ? [item.sourceOrderAfter] : []),
1591
+ ]) {
1592
+ // Sources that remained visible since the Project publication or User removal keep their receipt order.
1593
+ if (artifactValueDigest(sourceOrderAfter.filter((root) => paths.includes(root)))
1594
+ !== artifactValueDigest(paths.filter((root) => sourceOrderAfter.includes(root))))
1595
+ return false;
1596
+ }
1597
+ // The reviewed order anchors surviving rows. Each publication's receipt
1598
+ // also anchors its new rows against later cross-package moves.
1599
+ for (const previous of orderChecks) {
1600
+ if (!matchesGrokComponentOrder(previous.listOrder, scopeEvidence.listOrder, publishedRoots)
1601
+ || !matchesGrokComponentOrder(previous.hookOrder, scopeEvidence.hookOrder, publishedRoots)
1602
+ || !scopeEvidence.resourceOrder.every((order, index) => matchesGrokComponentOrder(previous.resourceOrder[index], order, publishedRoots)))
1603
+ return false;
1604
+ }
1605
+ const normalizedSources = { ...after, sources: sources.filter((_, index) => !addedSources.has(paths[index])),
1606
+ configurationEvidence: before.configurationEvidence, grokScopeEvidence: { ...scopeEvidence, instructions, permissionConfigs: priorEvidence.permissionConfigs,
1607
+ permissionInventoryDigest: priorEvidence.permissionInventoryDigest, listOrder: priorEvidence.listOrder, hookOrder: priorEvidence.hookOrder,
1608
+ resourceOrder: priorEvidence.resourceOrder,
1609
+ sourceDigests: sourceDigests.filter((_, index) => !addedSources.has(paths[index])) } };
1610
+ const observation = { ...current.observation, prerequisites: { ...current.observation.prerequisites, nativeSources: normalizedSources } };
1611
+ const remainingBeforeSources = before.sources.filter((_, index) => !retiredSources.has(priorPaths[index]));
1612
+ const normalizedBeforeOverlaps = retiredSources.size
1613
+ ? [...new Set(remainingBeforeSources.filter((source) => remainingBeforeSources.some((other) => other !== source && other.name === source.name))
1614
+ .map((source) => source.name))].sort()
1615
+ : before.overlaps;
1616
+ const normalizedBefore = { ...before, sources: remainingBeforeSources, overlaps: normalizedBeforeOverlaps,
1617
+ grokScopeEvidence: { ...priorEvidence,
1618
+ sourceDigests: priorEvidence.sourceDigests.filter((_, index) => !retiredSources.has(priorPaths[index])),
1619
+ instructions: retiredRules.size
1620
+ ? priorEvidence.instructions.filter((row) => row.rulePath === null || !retiredRules.has(row.rulePath))
1621
+ : priorEvidence.instructions } };
1622
+ const baselineDiagnostics = before.overlaps.length > 0 && normalizedBeforeOverlaps.length === 0
1623
+ ? mutableBaseline.observation.diagnostics.filter(({ code }) => code !== 'nativeCompatibilityOverlap')
1624
+ : mutableBaseline.observation.diagnostics;
1625
+ const baselineObservation = { ...mutableBaseline.observation, diagnostics: baselineDiagnostics,
1626
+ prerequisites: { ...mutableBaseline.observation.prerequisites, nativeSources: normalizedBefore } };
1627
+ return artifactValueDigest({ ...current, observation }) === artifactValueDigest({ ...mutableBaseline, observation: baselineObservation });
1628
+ };
1629
+ const check = async (discovery, batch) => {
1630
+ const reads = parallelNativeReads ? await Promise.allSettled([fingerprintParts(discovery), currentMutable(batch)]) : null;
1631
+ if (reads?.[0].status === 'rejected')
1632
+ throw reads[0].reason;
1633
+ const parts = reads?.[0].status === 'fulfilled' ? reads[0].value : await fingerprintParts(discovery);
1634
+ if (artifactValueDigest(parts) !== initial) {
1635
+ return artifactValueDigest(parts.discovery) !== artifactValueDigest(initialParts.discovery)
1636
+ ? 'clientDiscoveryChanged' : 'deploymentInputsChanged';
1637
+ }
1638
+ if (reads?.[1].status === 'rejected')
1639
+ throw reads[1].reason;
1640
+ const current = reads?.[1].status === 'fulfilled' ? reads[1].value : await currentMutable(batch);
1641
+ if (parallelNativeReads ? matchesMutable(current) : await matchesAfterGrokPublications(current))
1642
+ return true;
1643
+ if (current.references !== mutableBaseline.references)
1644
+ return 'deploymentReferencesChanged';
1645
+ if (artifactValueDigest(current.paths) !== artifactValueDigest(mutableBaseline.paths))
1646
+ return 'deploymentPathsChanged';
1647
+ return 'deploymentObservationChanged';
1648
+ };
1649
+ checks.set(entry.binding.id, (batch) => check(undefined, batch));
1650
+ if (resolution.bindings.length === 1 && (entry.binding.route === 'pi-package'
1651
+ || cursorPreviewBatch && entry.binding.route === 'cursor-workspace-hook')) {
1652
+ initialDiscoveryCheck = () => check({ value: initialParts.discovery });
1653
+ }
1654
+ this.mutableChecks.set(entry.binding.id, { physicalKey: entry.binding.physicalKey,
1655
+ marketplaceRoot: entry.layout.marketplaceRoot, sourceId: entry.binding.plugin.sourceId,
1656
+ sourceIdentity: entry.binding.plugin.sourceIdentity,
1657
+ assertStable: async () => {
1658
+ if (await checks.get(entry.binding.id)() !== true)
1659
+ throw new Error('operationPlanStale: deployment evidence changed before source registration.');
1660
+ },
1661
+ acceptMarketplaceRegistration: async () => {
1662
+ const current = await currentMutable();
1663
+ if (artifactValueDigest(current) === artifactValueDigest(mutableBaseline))
1664
+ return;
1665
+ const withoutRegistration = { ...current, observation: { ...current.observation,
1666
+ registration: mutableBaseline.observation.registration } };
1667
+ const onlyRegistration = mutableBaseline.observation.registration === 'absent' && current.observation.registration === 'present'
1668
+ && artifactValueDigest(withoutRegistration) === artifactValueDigest(mutableBaseline);
1669
+ const onlyMarketplace = ['codex-marketplace', 'claude-marketplace'].includes(entry.binding.route)
1670
+ && current.observation.configuration?.marketplace === 'canonical'
1671
+ && mutableBaseline.observation.configuration?.marketplace === 'absent'
1672
+ && (current.observation.registration === mutableBaseline.observation.registration
1673
+ || mutableBaseline.observation.registration === 'absent' && current.observation.registration === 'present')
1674
+ && artifactValueDigest({ ...withoutRegistration, observation: { ...withoutRegistration.observation,
1675
+ configuration: { ...current.observation.configuration, marketplace: mutableBaseline.observation.configuration.marketplace },
1676
+ } }) === artifactValueDigest(mutableBaseline);
1677
+ if ((!onlyRegistration && !onlyMarketplace) || await fingerprint() !== initial) {
1678
+ throw new Error('operationPlanStale: deployment evidence changed during source registration.');
1679
+ }
1680
+ // This is the one shared observation changed by our confirmed source
1681
+ // registration. The reviewed package, references and bytes stay frozen.
1682
+ mutableBaseline = current;
1683
+ },
1684
+ rebase: async (writtenFiles) => {
1685
+ const reads = parallelNativeReads
1686
+ ? await Promise.allSettled([fingerprintParts(), currentMutable()]) : null;
1687
+ if (reads?.[0].status === 'rejected')
1688
+ throw reads[0].reason;
1689
+ const current = reads?.[0].status === 'fulfilled' ? reads[0].value : await fingerprintParts();
1690
+ if (artifactValueDigest(current) !== initial) {
1691
+ const changed = Object.keys(initialParts)
1692
+ .filter((key) => artifactValueDigest(current[key]) !== artifactValueDigest(initialParts[key]));
1693
+ throw new Error(`operationPlanStale: immutable deployment input changed (${changed.join(', ')}).`);
1694
+ }
1695
+ if (reads?.[1].status === 'rejected')
1696
+ throw reads[1].reason;
1697
+ const mutable = reads?.[1].status === 'fulfilled' ? reads[1].value : await currentMutable();
1698
+ mutableBaseline = mutable;
1699
+ // The same rebase already hashes the exact paths. Match the owner's
1700
+ // header and the desired bytes without opening each file again.
1701
+ const verifiedSupplementIds = writtenFiles?.size ? components.flatMap((component, index) => {
1702
+ if (component.kind !== 'owned-text-file')
1703
+ return [];
1704
+ const written = writtenFiles.get(component.path);
1705
+ const observed = mutable.paths[index];
1706
+ return written && observed && typeof observed === 'object' && 'digest' in observed && observed.digest === written.digest
1707
+ ? written.componentIds : [];
1708
+ }) : [];
1709
+ return { observation: mutable.observation, verifiedSupplementIds };
1710
+ } });
1711
+ const evidence = { confirmedCatalogRetirement, fingerprint: initial, managedCommandReview, layout: entry.layout, renderUnits: entry.layout.renderUnits,
1712
+ ownership: await Promise.all(inspected.components.map(async ({ component, state }) => ({ component, state,
1713
+ contentDigest: state === 'present' ? await ownedContentDigest(component, ctx) : undefined,
1714
+ physicalKey: component.identity.physicalKey ?? entry.binding.physicalKey }))),
1715
+ sharedReferences: await sharedReferences(this.context, entry.binding, preparationObservation, entry.layout),
1716
+ nativeIdentity: preparationObservation.nativeIdentity ?? entry.layout.nativeIdentity,
1717
+ contentMatches: projections.some((projection) => projection.bundle !== null)
1718
+ && (!antigravityProject || preparationObservation.ownership === 'aw')
1719
+ && await readPlatformPackageContentDigest(entry.layout.packageRoot) === projections.find((projection) => projection.bundle !== null)?.bundle?.contentDigest };
1720
+ if (removing && isPermissionHost(entry.binding.platform) && (entry.binding.platform === 'opencode' || hostPolicyPath)) {
1721
+ const permission = historical.find((component) => component.kind === 'shared-config' && component.locator.kind === 'host-permissions');
1722
+ const settingsPath = permission?.kind === 'shared-config' && permission.locator.kind === 'host-permissions'
1723
+ ? permission.locator.settingsPath : undefined;
1724
+ const notice = await missingPermissionOwnershipWarning(ctx, entry.binding.plugin.pluginId, entry.binding.scope.kind, settingsPath ?? hostPolicyPath, entry.binding.platform, grokProjectBlocked);
1725
+ if (notice)
1726
+ evidence.permissionOwnershipWarning = notice;
1727
+ }
1728
+ if (!confirmedCatalogRetirement && entry.binding.platform === 'codex') {
1729
+ const hostEntry = entry.binding.consumers.find((consumer) => consumer.entry?.kind === 'cli'
1730
+ || removing && consumer.entry?.kind === 'directory')?.entry;
1731
+ if (!hostEntry || hostEntry.kind === 'generic')
1732
+ throw new Error('nativeActivationEvidenceUnknown');
1733
+ const config = await readCodexConfigFile(path.join(hostEntry.configRoot, 'config.toml'));
1734
+ evidence.userActivationEnabled = config.snapshot.plugins[entry.layout.nativeIdentity.registrationId]?.enabled === true;
1735
+ }
1736
+ if (!confirmedCatalogRetirement && entry.binding.platform === 'copilot') {
1737
+ const hostEntry = entry.binding.consumers.find((consumer) => consumer.entry?.kind === 'cli')?.entry;
1738
+ if (hostEntry?.kind === 'cli') {
1739
+ const settings = await jsonObject(path.join(hostEntry.configRoot, 'settings.json'));
1740
+ const enabled = settings.enabledPlugins;
1741
+ evidence.userActivationEnabled = enabled === undefined ? false : enabled && typeof enabled === 'object' && !Array.isArray(enabled)
1742
+ ? enabled[entry.layout.nativeIdentity.registrationId] === true : 'unknown';
1743
+ }
1744
+ }
1745
+ if (!confirmedCatalogRetirement && entry.binding.scope.kind === 'project' && ['codex', 'copilot'].includes(entry.binding.platform)) {
1746
+ const plannedUser = [...this.requestedOperations.values()].find((request) => request.scope === 'user'
1747
+ && request.platform === input.platform && sourceIdentity(request).sourceIdentity === entry.binding.plugin.sourceIdentity
1748
+ && sourceIdentity(request).pluginId === entry.binding.plugin.pluginId);
1749
+ if (plannedUser) {
1750
+ evidence.userActivationEnabled = !['remove', 'cleanup'].includes(operation(plannedUser));
1751
+ }
1752
+ }
1753
+ const priorPackage = inspected.components.find((slot) => 'path' in slot.component
1754
+ && slot.component.path === entry.layout.packageRoot && ['present', 'partial'].includes(slot.state))?.component;
1755
+ if (!removing && expected.unmet.length && priorPackage?.kind === 'owned-directory') {
1756
+ const complete = hasCompleteDeliveryDeclaration(expected);
1757
+ const old = await readSkillOwnerMarker({ skillRoot: priorPackage.path, allowedRoot: priorPackage.allowedRoot,
1758
+ expectedIdentity: priorPackage.identity }).catch(() => null);
1759
+ const next = new Set(projections.filter((item) => item.bundle).flatMap((item) => item.components.map(({ id }) => id)));
1760
+ const dropsPriorComponent = !old?.nativeProjection || old.nativeProjection.components.some(({ id }) => !next.has(id));
1761
+ const currentDigest = evidence.ownership.find((slot) => slot.component === priorPackage)?.contentDigest;
1762
+ // The marker identifies the directory. Only its recorded digest proves
1763
+ // that replacing or withdrawing the whole tree would discard exclusively AW bytes.
1764
+ const previousContentsVerified = !!old?.nativeProjection && old.nativeProjection.contentDigest === currentDigest;
1765
+ const hasNativeCopy = ['grok-cli', 'antigravity-cli'].includes(entry.binding.route) && preparationObservation.registration === 'present';
1766
+ const previousCopyUnconfirmed = hasNativeCopy && (!old?.nativeProjection
1767
+ || old.nativeProjection.contentDigest !== preparationObservation.nativePackageContentDigest);
1768
+ evidence.retainPackage = expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap) && gap.reasonCode !== COMMAND_ROUTE_UNREACHABLE) || previousCopyUnconfirmed
1769
+ || !evidence.contentMatches && (!previousContentsVerified || dropsPriorComponent
1770
+ && (!complete || evidence.sharedReferences !== 'none' || preparationObservation.ownership !== 'aw'));
1771
+ }
1772
+ if (!removing) {
1773
+ const inputEvidence = await createPlatformInputEvidence({ plugin: input.plugin, commandRoutes: input.commandRecord?.routes, binding: entry.binding, units: units.map((unit) => unit.evidenceInput) });
1774
+ const packageComponents = projections.find((projection) => projection.bundle)?.components;
1775
+ inputDigests.set(entry.binding.id, platformPackageInputDigest(inputEvidence, packageComponents));
1776
+ if (expected.unmet.every(isDeliveryCapabilityGap)) {
1777
+ const permissionNotices = platformPermissionNotices(projections.flatMap(({ diagnostics }) => diagnostics)
1778
+ .filter((notice) => !notice.subject?.pluginId || notice.subject.pluginId === entry.binding.plugin.pluginId));
1779
+ const noticeFields = permissionNotices.length ? { permissionNotices } : {};
1780
+ if (expected.unmet.length || expected.components.length && permissionNotices.length)
1781
+ gapStates.set(entry.binding.id, { ...inputEvidence,
1782
+ kind: 'aw-platform-empty-state', result: 'capability-gaps', gaps: expected.unmet,
1783
+ installedComponentIds: expected.components.map(({ id }) => id), ...noticeFields });
1784
+ if (expected.components.length === 0 && expected.unmet.length === 0) {
1785
+ emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state', result: 'intentional-empty', ...noticeFields });
1786
+ }
1787
+ else if (entry.layout.supplementRoot && input.plugin.manifest.artifacts) {
1788
+ const supplement = inputEvidence.units.find((unit) => unit.output === 'supplement');
1789
+ if (supplement) {
1790
+ supplementInputDigests.set(entry.binding.id, supplement.inputDigest);
1791
+ if (!expected.unmet.length && !projections.some((projection) => projection.bundle)) {
1792
+ emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state',
1793
+ result: 'intentional-empty-package', installedComponentIds: expected.components.map(({ id }) => id).sort(), ...noticeFields });
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+ }
1799
+ const result = adapter.lifecycle.prepare({ operation: operation(input), binding: entry.binding, observation: preparationObservation,
1800
+ projections, expected, evidence });
1801
+ if (result.status === 'blocked') {
1802
+ plans.push({ operation: operation(input), binding: entry.binding, projections, expected, evidence, effects: [] });
1803
+ blockedReceipts.push({ bindingId: entry.binding.id, effects: [], after: preparationObservation,
1804
+ unmet: expected.unmet.map((gap) => ({ ...gap, productIds: entry.binding.consumers.map((consumer) => consumer.id) })),
1805
+ reload: 'none', diagnostics: result.diagnostics });
1806
+ }
1807
+ else {
1808
+ deployments.push(result.prepared);
1809
+ plans.push(result.prepared.plan);
1810
+ }
1811
+ }
1812
+ target.ownedComponents = plans.flatMap((plan) => plan.evidence.ownership.map((item) => item.component));
1813
+ target.desiredOwnedComponents = target.ownedComponents;
1814
+ const verifyChecks = async (selected, batch) => {
1815
+ for (const check of selected)
1816
+ if (await check(batch) !== true)
1817
+ throw new Error('operationPlanStale: deployment evidence changed.');
1818
+ for (const plan of plans)
1819
+ if (!await this.verifyMarketplace(plan))
1820
+ throw new Error('operationPlanStale: marketplace evidence changed.');
1821
+ };
1822
+ const verify = (batch) => verifyChecks(checks.values(), batch);
1823
+ const canVerifyAtExecution = () => {
1824
+ const prepared = deployments[0];
1825
+ if (!prepared || deployments.length !== 1 || plans.length !== 1 || plans[0] !== prepared.plan || blockedReceipts.length
1826
+ || target.operationActions === undefined || target.operationActions.some((action) => action.kind === 'runPreApply' || action.kind === 'syncManagedCommandPackage' || action.kind === 'removeManagedCommandPackage'))
1827
+ return false;
1828
+ const { plan, driverState } = prepared;
1829
+ const hiddenEmptyPiProject = piProjectRegistrationHidden(plan.binding, driverState.before)
1830
+ && driverState.before.package === 'absent' && driverState.before.ownership === 'absent'
1831
+ && plan.evidence.sharedReferences === 'none' && plan.evidence.ownership.every((item) => item.state === 'absent')
1832
+ && plan.effects.every((effect) => ['publish-package', 'register'].includes(effect.kind));
1833
+ const checkedBatch = this.context.batchInstallPlatform === plan.binding.platform && plan.binding.platform !== 'codex';
1834
+ const isBuiltinCursorWorkspaceHook = (effect) => effect.kind === 'write-supplement'
1835
+ && plan.binding.route === 'cursor-workspace-hook'
1836
+ && driverState.contributions.some((entry) => entry.effectId === effect.id && entry.contribution.id === 'cursor-workspace-open');
1837
+ return plan.operation === 'ensure' && (checkedBatch || ['copilot-marketplace', 'pi-package'].includes(plan.binding.route))
1838
+ && plan.binding.platform === target.identity.platform && plan.expected.components.length > 0 && plan.expected.unmet.every(isDeliveryCapabilityGap)
1839
+ && driverState.before.package !== 'unknown' && (driverState.before.registration !== 'unknown' || hiddenEmptyPiProject)
1840
+ && ['absent', 'aw', 'shared'].includes(driverState.before.ownership)
1841
+ && plan.effects.every((effect) => ['publish-package', 'register', 'refresh', 'activate'].includes(effect.kind)
1842
+ || isBuiltinCursorWorkspaceHook(effect));
1843
+ };
1844
+ let privateStaging;
1845
+ let stagedPackage;
1846
+ const packagePlan = plans.length === 1 ? plans[0] : undefined;
1847
+ const bundle = packagePlan?.projections.find((projection) => projection.bundle)?.bundle;
1848
+ // Registration mutates a shared client. Copy independent bytes outside its
1849
+ // namespace first; publication still checks the original frozen live plan.
1850
+ const privatePackage = packagePlan && bundle && packagePlan.operation === 'ensure'
1851
+ && ['pi-package', 'claude-marketplace'].includes(packagePlan.binding.route)
1852
+ && packagePlan.effects.some((effect) => effect.kind === 'publish-package') ? {
1853
+ prepare: async () => {
1854
+ privateStaging = await fs.mkdtemp(path.join(await this.root(), 'private-package-'));
1855
+ stagedPackage = path.join(privateStaging, input.plugin.manifest.name);
1856
+ await fs.copy(bundle.stagingRoot, stagedPackage, { dereference: false });
1857
+ },
1858
+ dispose: async () => {
1859
+ if (privateStaging)
1860
+ await fs.remove(privateStaging);
1861
+ privateStaging = undefined;
1862
+ stagedPackage = undefined;
1863
+ },
1864
+ } : undefined;
1865
+ target.platformDeployment = { deployments, plans, blockedReceipts, cleanupResults, privatePackage,
1866
+ canVerifyAtExecution,
1867
+ verify,
1868
+ postcheck: async (receipts, options) => {
1869
+ let incomplete = false;
1870
+ for (const { plan } of deployments) {
1871
+ if (!['ensure', 'reinstall'].includes(plan.operation) || !plan.expected.components.length)
1872
+ continue;
1873
+ const receipt = receipts.find((entry) => entry.bindingId === plan.binding.id);
1874
+ if (!receipt || options?.deliveredSkillsOnly && plan.evidence.retainPackage)
1875
+ continue;
1876
+ const after = options?.refresh ? await adapter.inspect(ctx, plan.binding) : receipt.after;
1877
+ const supplementFiles = componentSupplementFiles(plan);
1878
+ const supplementIds = new Set(supplementFiles.flatMap((contribution) => contribution.componentIds));
1879
+ if (!options?.deliveredSkillsOnly) {
1880
+ const supplements = await inspectStaticSupplements(ctx, plan.binding, plan.expected.components.filter((component) => supplementIds.has(component.id)));
1881
+ after.components = [...after.components.filter((component) => !supplementIds.has(component.id)), ...supplements.components];
1882
+ }
1883
+ if (options?.refresh) {
1884
+ receipt.after = after;
1885
+ receipt.diagnostics.push(...after.diagnostics);
1886
+ }
1887
+ const packageIds = new Set(plan.projections.filter((projection) => projection.bundle)
1888
+ .flatMap((projection) => projection.components.map((component) => component.id)));
1889
+ const bundle = plan.projections.find((projection) => projection.bundle)?.bundle;
1890
+ const requiredActivation = requiredDeploymentActivation(plan.binding, after, requireIndependentActivation);
1891
+ if (!options?.deliveredSkillsOnly && !requireIndependentActivation && requiredActivation === 'enabled') {
1892
+ receipt.diagnostics = receipt.diagnostics.filter((entry) => entry.code !== 'codexProjectActivationUnconfirmed');
1893
+ }
1894
+ const nativeContentIncomplete = bundle && nativeCopyIncomplete(plan.binding, after, bundle.contentDigest);
1895
+ // Partial execution already verified the frozen plan and recorded each package publication.
1896
+ const publication = options?.deliveredSkillsOnly && plan.effects.find((effect) => effect.kind === 'publish-package');
1897
+ const packageIncomplete = bundle && (!packageDeliveryConfirmed(plan.binding, after, bundle.contentDigest, requireIndependentActivation)
1898
+ || (options?.deliveredSkillsOnly
1899
+ ? !plan.evidence.contentMatches && !receipt.effects.some((effect) => publication && effect.id === publication.id
1900
+ && effect.status === 'applied' && effect.mutation === 'confirmed')
1901
+ : await readPlatformPackageContentDigest(plan.evidence.layout.packageRoot) !== bundle.contentDigest));
1902
+ const delivered = new Set(after.components.filter((component) => component.presence === 'present' && !component.reasonCodes.length)
1903
+ .map((component) => component.id));
1904
+ const roleIds = plan.expected.components.filter((component) => component.kind === 'agent' && delivered.has(component.id)
1905
+ && packageIds.has(component.id) && !packageIncomplete && !plan.evidence.retainPackage).map(({ id }) => id);
1906
+ const roleDiagnostic = piAgentConsumerDiagnostic(plan.binding, after, roleIds);
1907
+ if (roleDiagnostic)
1908
+ receipt.diagnostics.push(roleDiagnostic);
1909
+ const gaps = plan.expected.components.filter((component) => packageIncomplete && packageIds.has(component.id) || !delivered.has(component.id));
1910
+ if (bundle && !packageIncomplete && !plan.evidence.retainPackage) {
1911
+ for (const unitId of plan.binding.renderUnitIds) {
1912
+ const unit = preparedUnits.get(unitId);
1913
+ if (!unit?.finalized.skills.length)
1914
+ continue;
1915
+ const capabilities = adapter.capabilities({ binding: plan.binding, renderUnit: unit.unit,
1916
+ profile: getQualifiedPlatformProfile(input.platform) });
1917
+ for (const skill of unit.finalized.skills) {
1918
+ if (!packageIds.has(skill.componentId) || !delivered.has(skill.componentId))
1919
+ continue;
1920
+ const component = unit.prepared.expected.components.find((item) => item.id === skill.componentId);
1921
+ const requested = getComponentFeatureRequirements(component, { skillText: skill.tree.files['SKILL.md'].toString('utf8') });
1922
+ const warning = skillInvocationWarning(component.name, requested, { pluginId: plan.binding.plugin.pluginId, target: plan.binding.platform, scope: plan.binding.scope.kind }, capabilities, plan.binding.platform === 'antigravity' ? unit.unit.consumers.flatMap((reader) => reader.availability === 'available' && reader.product !== 'generic'
1923
+ ? [{ product: reader.product, observed: after.skillInvocationPolicies?.find(({ componentId, productId }) => componentId === component.id && productId === reader.id)?.features }] : []) : []);
1924
+ if (warning)
1925
+ receipt.diagnostics.push(warning);
1926
+ }
1927
+ }
1928
+ }
1929
+ if (options?.deliveredSkillsOnly)
1930
+ continue;
1931
+ const inputDigest = supplementInputDigests.get(plan.binding.id);
1932
+ if (inputDigest && [...supplementIds].every((id) => delivered.has(id))
1933
+ && receipt.unmet.every(isDeliveryCapabilityGap) && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
1934
+ try {
1935
+ await writePlatformSupplementState(ctx, plan.binding, inputDigest, supplementFiles.map((file) => ({
1936
+ id: file.id, fileName: path.basename(file.destination), contentDigest: file.contentDigest,
1937
+ })));
1938
+ const emptyPackage = emptyStates.get(plan.binding.id);
1939
+ if (!gaps.length && emptyPackage?.result === 'intentional-empty-package'
1940
+ && supplementIds.size === emptyPackage.installedComponentIds.length
1941
+ && emptyPackage.installedComponentIds.every((id) => supplementIds.has(id))
1942
+ && after.package === 'absent' && ['absent', 'not-applicable'].includes(after.registration)) {
1943
+ // The package absence and permission notices describe the same binding.
1944
+ await writePlatformEmptyState({ state: emptyPackage, env: this.context.env });
1945
+ continue;
1946
+ }
1947
+ }
1948
+ catch {
1949
+ ctx.signal?.throwIfAborted();
1950
+ receipt.diagnostics.push({ code: 'componentOutputUnconfirmed', severity: 'warning',
1951
+ message: 'The scope-local supplemental output could not be recorded. Run sync to restore the status evidence.',
1952
+ subject: { target: plan.binding.platform, pluginId: plan.binding.plugin.pluginId, scope: plan.binding.scope.kind } });
1953
+ }
1954
+ }
1955
+ if (!gaps.length) {
1956
+ const gapState = gapStates.get(plan.binding.id);
1957
+ if (gapState && !receipt.diagnostics.some((entry) => entry.severity === 'error')) {
1958
+ if (gapState.result === 'capability-gaps' && !gapState.gaps.length) {
1959
+ // A notice alone is optional status evidence. Failure to retain it does not undo verified delivery.
1960
+ await writePlatformEmptyState({ state: gapState, env: this.context.env }).catch(() => ctx.signal?.throwIfAborted());
1961
+ }
1962
+ else {
1963
+ await writePlatformEmptyState({ state: gapState, env: this.context.env });
1964
+ }
1965
+ }
1966
+ continue;
1967
+ }
1968
+ incomplete = true;
1969
+ const code = plan.binding.route === 'grok-directory' && requiredActivation === 'blocked' ? 'grokProjectAuthorizationDenied'
1970
+ : plan.binding.route === 'codex-marketplace' && requireIndependentActivation && after.scopeActivation === 'unknown'
1971
+ ? 'codexProjectActivationUnconfirmed'
1972
+ : nativeContentIncomplete ? 'nativeInstallContentPostcheckFailed' : 'deploymentPostcheckFailed';
1973
+ receipt.diagnostics.push({ code, severity: 'error',
1974
+ message: code === 'nativeInstallContentPostcheckFailed'
1975
+ ? 'The installed native copy does not confirm the frozen package bytes. Check status and sync the affected target.'
1976
+ : code === 'grokProjectAuthorizationDenied'
1977
+ ? 'Grok denied authorization for the selected project. Review the project in Grok before syncing.'
1978
+ : code === 'codexProjectActivationUnconfirmed'
1979
+ ? 'Codex reports effective activation but does not distinguish this project from User inheritance.'
1980
+ : 'The final observation does not confirm the requested deployment. Check status and sync the affected target.',
1981
+ subject: { target: plan.binding.platform, pluginId: plan.binding.plugin.pluginId, scope: plan.binding.scope.kind } });
1982
+ receipt.unmet.push(...gaps.map((component) => ({ id: `postcheck:${plan.binding.id}:${component.id}`,
1983
+ componentId: component.id, kind: component.kind, reasonCode: code, requiredFeatures: [],
1984
+ productIds: plan.binding.consumers.map((consumer) => consumer.id) })));
1985
+ }
1986
+ if (incomplete)
1987
+ throw new Error('deploymentPostcheckFailed: the final observation does not confirm the requested deployment.');
1988
+ },
1989
+ execute: async (options) => {
1990
+ let verifiedPlan;
1991
+ if (options?.verifyBeforeExecution) {
1992
+ if (!canVerifyAtExecution())
1993
+ throw new Error('deploymentExecutionVerificationUnsupported');
1994
+ // Keep failures outside the lifecycle catch so the caller retains its
1995
+ // preflight error classification. Only this call can consume success.
1996
+ await verify();
1997
+ verifiedPlan = deployments[0].plan;
1998
+ }
1999
+ cleanupResults.length = 0;
2000
+ const receipts = [...blockedReceipts];
2001
+ for (const prepared of deployments) {
2002
+ const batch = prepared.plan.evidence.permissionBatch;
2003
+ let relatedProjectBatch;
2004
+ if (batch && prepared.plan.binding.platform === 'opencode' && prepared.plan.binding.scope.kind === 'user') {
2005
+ const key = identityDigest({ owners: batch.owners, projects: batch.relatedProjects });
2006
+ relatedProjectBatch = this.openCodeProjectBatches.get(key) ?? { writes: new Map(), pending: new Map() };
2007
+ this.openCodeProjectBatches.set(key, relatedProjectBatch);
2008
+ }
2009
+ const supplementFiles = componentSupplementFiles(prepared.plan);
2010
+ const writtenFiles = new Map();
2011
+ const appliedPermissionNotices = [];
2012
+ let receipt;
2013
+ const peers = prepared.plan.binding.route === 'codex-marketplace' ? [...this.mutableChecks.values()].filter((check) => check.physicalKey !== prepared.plan.binding.physicalKey && check.marketplaceRoot === prepared.plan.evidence.layout.marketplaceRoot
2014
+ && check.sourceId === prepared.plan.binding.plugin.sourceId && check.sourceIdentity === prepared.plan.binding.plugin.sourceIdentity) : [];
2015
+ const nativeServices = createNativeLifecycleServices(ctx, prepared.plan.evidence, peers.length ? async () => {
2016
+ for (const peer of peers)
2017
+ await peer.assertStable();
2018
+ } : undefined);
2019
+ const grokDisablePackage = prepared.plan.binding.route === 'grok-cli'
2020
+ && ['remove', 'cleanup'].includes(prepared.plan.operation)
2021
+ && prepared.plan.effects.some((effect) => effect.kind === 'deactivate')
2022
+ ? prepared.driverState.before.nativeIdentity?.packageId ?? prepared.driverState.identity?.packageId
2023
+ : undefined;
2024
+ const grokDisableConfigPath = grokDisablePackage
2025
+ ? path.join(await canonicalizePathThroughExistingAncestor(prepared.plan.evidence.layout.activationPath), 'config.toml')
2026
+ : undefined;
2027
+ const grokDisableConfigBefore = grokDisableConfigPath ? await readOptionalUtf8(grokDisableConfigPath) : undefined;
2028
+ let grokDisableConfigRecorded = false;
2029
+ try {
2030
+ receipt = await adapter.lifecycle.execute({ ...ctx, nativeEffects: this.nativeEffects, inspect: (binding) => adapter.inspect(ctx, binding), services: {
2031
+ ...nativeServices,
2032
+ registerMarketplace: async (binding, identity) => {
2033
+ const outcome = await nativeServices.registerMarketplace(binding, identity);
2034
+ if (outcome.mutation === 'confirmed') {
2035
+ ctx.codexObservationSession?.invalidate(prepared.plan.evidence.layout.marketplaceName ?? undefined);
2036
+ for (const peer of peers)
2037
+ await peer.acceptMarketplaceRegistration();
2038
+ }
2039
+ return outcome;
2040
+ },
2041
+ verifyEvidence: async (plan) => {
2042
+ const verified = verifiedPlan === plan;
2043
+ verifiedPlan = undefined;
2044
+ if (verified)
2045
+ return true;
2046
+ const evidence = await checks.get(plan.binding.id)();
2047
+ if (evidence !== true)
2048
+ return evidence;
2049
+ return await this.verifyMarketplace(plan) || 'marketplaceChanged';
2050
+ },
2051
+ publishPackage: async (_binding, bundle, _destination, component) => {
2052
+ if (!('path' in component) || component.path !== _destination)
2053
+ throw new Error('deploymentDestinationMismatch');
2054
+ await this.publishMarketplace(prepared.plan);
2055
+ let publication = this.published.get(prepared.plan.binding.physicalKey);
2056
+ if (!publication) {
2057
+ publication = publishDirectory(bundle.stagingRoot, component, {
2058
+ components: prepared.plan.projections.filter((projection) => projection.bundle !== null).flatMap((projection) => projection.components),
2059
+ inputDigest: inputDigests.get(prepared.plan.binding.id), contentDigest: bundle.contentDigest,
2060
+ ...(bundle.piExtensionDigest ? { piExtensionDigest: bundle.piExtensionDigest } : {}),
2061
+ preparation: prepared.plan.expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap)) ? 'partial' : 'complete',
2062
+ physicalIdentity: (await getDeploymentLayout(ctx, prepared.plan.binding)).physicalIdentity,
2063
+ }, stagedPackage);
2064
+ this.published.set(prepared.plan.binding.physicalKey, publication);
2065
+ }
2066
+ return publication;
2067
+ },
2068
+ writeContribution: async (_binding, contribution, component) => {
2069
+ await requireWritable(component, this.ownership);
2070
+ if (component.kind === 'owned-directory')
2071
+ return publishDirectory(contribution.stagingPath, component);
2072
+ if (component.kind === 'owned-text-file') {
2073
+ const content = await fs.readFile(contribution.stagingPath, 'utf8');
2074
+ await writeOwnedTextFile({ ...component, content });
2075
+ if (supplementFiles.includes(contribution)) {
2076
+ writtenFiles.set(component.path, { componentIds: contribution.componentIds,
2077
+ digest: crypto.createHash('sha256').update(renderOwnedTextFile(content, component.identity)).digest('hex') });
2078
+ }
2079
+ }
2080
+ else if (component.kind === 'shared-config' && component.locator.kind === 'cursor-workspace-hook') {
2081
+ const locator = component.locator;
2082
+ const value = await jsonObject(locator.hooksPath);
2083
+ const { hooks, entries } = cursorHooks(value);
2084
+ const desired = cursorHooks(await jsonObject(contribution.stagingPath)).entries;
2085
+ await atomicReplaceSafeFile({ filePath: component.locator.hooksPath, allowedRoot: path.dirname(component.locator.hooksPath), label: 'Cursor workspaceOpen',
2086
+ content: `${JSON.stringify({ ...value, hooks: { ...hooks, workspaceOpen: [...entries.filter((item) => cursorHookEntryCommand(item) !== locator.command), ...desired] } }, null, 2)}\n` });
2087
+ }
2088
+ else if (component.kind === 'shared-config' && component.locator.kind === 'host-permissions') {
2089
+ const locator = component.locator;
2090
+ const changed = await updateHostPermissions(ctx, locator, await jsonObject(contribution.stagingPath), (previous, current, target = locator.settingsPath, host) => this.recordPermissionWrite(target, previous, current, locator.platform === 'grok' ? host : undefined), batch, (notices) => appliedPermissionNotices.push(...notices), undefined, relatedProjectBatch);
2091
+ return { mutation: changed ? 'confirmed' : 'none', changed };
2092
+ }
2093
+ else if (component.kind === 'shared-config' && component.locator.kind === 'claude-permissions') {
2094
+ const content = await jsonObject(contribution.stagingPath);
2095
+ if (content.kind !== 'claude-permissions')
2096
+ throw new Error('platformContributionUnsupported');
2097
+ const added = await applyPlannedOperationAction({ kind: 'updateSharedConfig', pluginId: prepared.plan.binding.plugin.pluginId,
2098
+ platform: 'claude', scope: prepared.plan.binding.scope.kind, owner: component.identity, locator: component.locator,
2099
+ contentDigest: contribution.contentDigest, mutation: { kind: 'claude-permissions', permissions: content.permissions } });
2100
+ for (const projection of prepared.plan.projections) {
2101
+ for (const notice of projection.diagnostics) {
2102
+ const { permissionAction, permissionResource, path } = notice.detail ?? {};
2103
+ if (notice.code === HOST_PERMISSION_ADDITIONAL_IMPACT && path === contribution.destination
2104
+ && permissionAction && permissionResource
2105
+ && added[permissionAction].some((rule) => publicHostPermissionResource(rule) === permissionResource)) {
2106
+ appliedPermissionNotices.push(notice);
2107
+ }
2108
+ }
2109
+ }
2110
+ }
2111
+ else
2112
+ throw new Error('platformContributionUnsupported');
2113
+ return { mutation: 'confirmed', changed: true };
2114
+ },
2115
+ removeOwned: async (binding, component) => {
2116
+ if (isAntigravityProjectDirectory(binding) && component.kind === 'owned-directory'
2117
+ && component.path !== prepared.plan.evidence.layout.packageRoot && prepared.driverState.bundle) {
2118
+ const replacement = prepared.driverState.packageComponent;
2119
+ if (replacement?.kind !== 'owned-directory' || await requireWritable(replacement, this.ownership) !== 'present'
2120
+ || await readPlatformPackageContentDigest(replacement.path) !== prepared.driverState.bundle.contentDigest) {
2121
+ throw Object.assign(new Error('The Antigravity replacement package could not be verified.'), {
2122
+ code: 'operationPlanStale', mutation: 'none',
2123
+ });
2124
+ }
2125
+ }
2126
+ const locator = component.kind === 'shared-config' && component.locator.kind === 'host-permissions' ? component.locator : undefined;
2127
+ const restorations = [];
2128
+ let permissionFailure;
2129
+ const executor = locator ? { ...this.ownership, removeShared: async () => {
2130
+ try {
2131
+ if (grokDisableConfigPath && grokDisablePackage && !grokDisableConfigRecorded
2132
+ && locator.platform === 'grok' && locator.settingsPath === grokDisableConfigPath) {
2133
+ const midText = await readOptionalUtf8(grokDisableConfigPath);
2134
+ if (midText !== null && isGrokDisableConfigTransition(grokDisableConfigBefore ?? null, midText, grokDisablePackage)) {
2135
+ await this.recordGrokDisableConfigWrite(grokDisableConfigPath, grokDisableConfigBefore ?? null, midText);
2136
+ grokDisableConfigRecorded = true;
2137
+ }
2138
+ }
2139
+ await updateHostPermissions(ctx, locator, undefined, (previous, current, target = locator.settingsPath, host) => this.recordPermissionWrite(target, previous, current, locator.platform === 'grok' ? host : undefined), batch, (notices) => {
2140
+ for (const notice of notices) {
2141
+ (notice.code === 'hostPermissionRestored' ? restorations : appliedPermissionNotices).push(notice);
2142
+ }
2143
+ }, undefined, relatedProjectBatch);
2144
+ }
2145
+ catch (error) {
2146
+ permissionFailure = error;
2147
+ throw error;
2148
+ }
2149
+ } } : this.ownership;
2150
+ const result = await cleanupOwnedComponents({ components: [component], executor });
2151
+ cleanupResults.push(result);
2152
+ if (result.failures.length || result.residual.length || result.quarantined.length) {
2153
+ if (permissionFailure)
2154
+ throw permissionFailure;
2155
+ throw Object.assign(new Error('deploymentCleanupIncomplete'), result.removed.length || result.quarantined.length
2156
+ ? { mutation: 'confirmed' } : {});
2157
+ }
2158
+ return { mutation: result.removed.length ? 'confirmed' : 'none', changed: result.removed.length > 0, diagnostics: restorations };
2159
+ },
2160
+ } }, prepared);
2161
+ }
2162
+ catch (error) {
2163
+ const diagnostic = { code: recoveryInterruptionCode(error) ?? 'platformExecutionFailed', severity: 'error',
2164
+ message: error instanceof Error ? error.message : String(error),
2165
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind } };
2166
+ receipt = { bindingId: prepared.plan.binding.id, effects: prepared.plan.effects.map((effect) => ({
2167
+ id: effect.id, status: 'unknown', mutation: 'possible', diagnostics: [diagnostic]
2168
+ })),
2169
+ after: await adapter.inspect(ctx, prepared.plan.binding).catch(() => prepared.driverState.before),
2170
+ unmet: prepared.plan.expected.unmet.map((gap) => ({ ...gap, productIds: prepared.plan.binding.consumers.map(({ id }) => id) })),
2171
+ reload: 'unknown', diagnostics: [diagnostic] };
2172
+ }
2173
+ receipt.diagnostics.push(...appliedPermissionNotices);
2174
+ receipts.push(receipt);
2175
+ if (receipt.diagnostics.some(({ code }) => code === 'processCleanupUnconfirmed'))
2176
+ return receipts;
2177
+ if ((prepared.plan.operation === 'remove' || prepared.plan.operation === 'cleanup'
2178
+ || prepared.plan.expected.components.length === 0 && prepared.plan.expected.unmet.length === 0)
2179
+ && prepared.plan.evidence.confirmedCatalogRetirement !== true
2180
+ && prepared.plan.evidence.sharedReferences !== 'none' && receipt.after.package === 'present') {
2181
+ receipt.diagnostics.push({ code: prepared.plan.evidence.sharedReferences === 'unknown' ? 'sharedReferenceUnknown' : 'sharedPackageRetained', severity: 'warning',
2182
+ message: prepared.plan.evidence.sharedReferences === 'unknown'
2183
+ ? 'The shared package was kept because references outside the observed scope could not be ruled out.'
2184
+ : 'The shared package was kept for another scope.',
2185
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind } });
2186
+ }
2187
+ const publish = prepared.plan.effects.find((effect) => effect.kind === 'publish-package');
2188
+ const publication = receipt.effects.find((result) => result.id === publish?.id && result.status === 'applied');
2189
+ try {
2190
+ let copilotRebase;
2191
+ if (receipt.effects.some((effect) => effect.mutation !== 'none')) {
2192
+ for (const [bindingId, check] of this.mutableChecks)
2193
+ if (check.physicalKey === prepared.plan.binding.physicalKey) {
2194
+ const { observation: fresh, verifiedSupplementIds } = await check.rebase(bindingId === receipt.bindingId ? writtenFiles : undefined);
2195
+ if (verifiedSupplementIds.length) {
2196
+ receipt.after.components = [
2197
+ ...receipt.after.components.filter(({ id }) => !verifiedSupplementIds.includes(id)),
2198
+ ...verifiedSupplementIds.map((id) => ({ id, presence: 'present', reasonCodes: [] })),
2199
+ ];
2200
+ }
2201
+ if (bindingId === receipt.bindingId && prepared.plan.binding.route === 'copilot-marketplace') {
2202
+ copilotRebase = fresh;
2203
+ }
2204
+ }
2205
+ }
2206
+ if (prepared.plan.operation === 'remove' && prepared.plan.evidence.sharedReferences !== 'none') {
2207
+ checkRetainedCopilotDeactivation(prepared, receipt, copilotRebase);
2208
+ }
2209
+ else if (prepared.plan.operation !== 'remove' && copilotRebase
2210
+ && receipt.effects.some((result) => result.status === 'applied' && result.mutation === 'confirmed')) {
2211
+ recheckCopilotMarketplaceTimeout(receipt, copilotRebase);
2212
+ }
2213
+ }
2214
+ catch (error) {
2215
+ receipt.diagnostics.push({ code: recoveryInterruptionCode(error) ?? 'operationPlanStale', severity: 'error', message: error instanceof Error ? error.message : String(error),
2216
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind } });
2217
+ continue;
2218
+ }
2219
+ if (prepared.plan.evidence.retainPackage || receipt.diagnostics.some((diagnostic) => diagnostic.code === 'operationPlanStale'))
2220
+ continue;
2221
+ // A Grok rule can be independently written even when native package
2222
+ // registration needs explicit trust. Account for the confirmed rule
2223
+ // bytes before considering the next target, not for the blocked package.
2224
+ this.recordGrokWrites(prepared, receipt, publication?.mutation === 'confirmed', writtenFiles, shadowedUsers.get(prepared.plan.binding.id));
2225
+ if (grokDisableConfigPath && grokDisablePackage && !grokDisableConfigRecorded
2226
+ && !receipt.diagnostics.some((item) => item.severity === 'error')
2227
+ && !receipt.effects.some((effect) => effect.mutation === 'possible' || ['failed', 'unknown', 'blocked', 'skipped'].includes(effect.status))
2228
+ && prepared.plan.effects.some((effect) => effect.kind === 'deactivate'
2229
+ && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'))) {
2230
+ const afterText = await readOptionalUtf8(grokDisableConfigPath);
2231
+ if (afterText !== null && isGrokDisableConfigTransition(grokDisableConfigBefore ?? null, afterText, grokDisablePackage)) {
2232
+ await this.recordGrokDisableConfigWrite(grokDisableConfigPath, grokDisableConfigBefore ?? null, afterText);
2233
+ grokDisableConfigRecorded = true;
2234
+ }
2235
+ }
2236
+ this.recordGrokRemovals(prepared, receipt);
2237
+ if (receipt.effects.some((effect) => ['failed', 'unknown', 'blocked', 'skipped'].includes(effect.status)))
2238
+ continue;
2239
+ const piInventoryKey = piProjectInventoryKey(prepared.plan.binding, prepared.plan.evidence.layout.activationPath);
2240
+ if (piInventoryKey && piProjectEmptyDeliveryObserved(prepared.plan.binding, prepared.driverState.before)
2241
+ && receipt.after.registration === 'present' && receipt.after.ownership === 'aw' && receipt.after.configuration?.activation === 'enabled'
2242
+ && prepared.plan.effects.some((effect) => effect.kind === 'register' && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'))) {
2243
+ const registered = this.piProjectRegisteredRoots.get(piInventoryKey) ?? new Set();
2244
+ registered.add(prepared.plan.evidence.layout.packageRoot);
2245
+ this.piProjectRegisteredRoots.set(piInventoryKey, registered);
2246
+ }
2247
+ try {
2248
+ const root = prepared.plan.evidence.layout.packageRoot;
2249
+ const mappings = prepared.plan.projections.filter((projection) => projection.bundle !== null).flatMap((projection) => projection.components);
2250
+ const bundle = prepared.plan.projections.find((projection) => projection.bundle)?.bundle;
2251
+ const packageOwner = prepared.plan.evidence.ownership.find((slot) => 'path' in slot.component && slot.component.path === root)?.component;
2252
+ if (bundle && packageOwner?.kind === 'owned-directory' && prepared.plan.evidence.contentMatches
2253
+ && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')
2254
+ && packageDeliveryConfirmed(prepared.plan.binding, receipt.after, bundle.contentDigest, requireIndependentActivation)
2255
+ && await readPlatformPackageContentDigest(root) === bundle.contentDigest) {
2256
+ const marker = await readSkillOwnerMarker({ skillRoot: root, allowedRoot: packageOwner.allowedRoot, expectedIdentity: packageOwner.identity });
2257
+ const projection = { components: mappings, contentDigest: bundle.contentDigest,
2258
+ inputDigest: inputDigests.get(prepared.plan.binding.id), preparation: prepared.plan.expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap)) ? 'partial' : 'complete',
2259
+ ...(bundle.piExtensionDigest && marker?.nativeProjection?.piExtensionDigest === bundle.piExtensionDigest
2260
+ ? { piExtensionDigest: bundle.piExtensionDigest } : {}),
2261
+ physicalIdentity: (await getDeploymentLayout(ctx, prepared.plan.binding)).physicalIdentity };
2262
+ if (marker && (!marker.nativeProjection || artifactValueDigest(marker.nativeProjection) !== artifactValueDigest(projection))) {
2263
+ await writeSkillOwnerMarker({ skillRoot: root, allowedRoot: packageOwner.allowedRoot, identity: packageOwner.identity, nativeProjection: projection });
2264
+ for (const check of this.mutableChecks.values())
2265
+ if (check.physicalKey === prepared.plan.binding.physicalKey)
2266
+ await check.rebase();
2267
+ receipt.after = await adapter.inspect(ctx, prepared.plan.binding);
2268
+ }
2269
+ }
2270
+ const emptyState = gapStates.get(prepared.plan.binding.id) ?? emptyStates.get(prepared.plan.binding.id);
2271
+ const removedByCommand = piProjectRemovalConfirmed(prepared.plan, receipt);
2272
+ const inactiveScope = removedByCommand || receipt.after.registration === 'absent'
2273
+ || receipt.after.package === 'absent' && receipt.after.registration === 'not-applicable'
2274
+ || receipt.after.scopeRegistration === 'absent'
2275
+ || prepared.plan.binding.scope.kind === 'project'
2276
+ && ['codex-marketplace', 'copilot-marketplace'].includes(prepared.plan.binding.route)
2277
+ && receipt.after.configuration?.activation === 'absent'
2278
+ || receipt.after.consumers.every((consumer) => ['disabled', 'not-applicable'].includes(consumer.activation));
2279
+ if (emptyState && !prepared.plan.expected.components.length && receipt.unmet.every(isDeliveryCapabilityGap)
2280
+ && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
2281
+ const residual = await inspectOwnedComponents({ components: prepared.plan.evidence.ownership
2282
+ .filter((slot) => !('path' in slot.component) || slot.component.path !== root)
2283
+ .map((slot) => slot.component), executor: this.ownership });
2284
+ const hiddenEmptyPi = emptyState.result === 'capability-gaps' && piProjectEmptyDeliveryObserved(prepared.plan.binding, receipt.after);
2285
+ const clear = (receipt.after.registration !== 'unknown' || removedByCommand || hiddenEmptyPi)
2286
+ && (emptyState.result !== 'capability-gaps' || prepared.plan.binding.route !== 'pi-package' || receipt.after.configuration?.activation === 'absent')
2287
+ && receipt.after.package !== 'unknown' && !['foreign', 'unknown'].includes(receipt.after.ownership)
2288
+ && (inactiveScope || hiddenEmptyPi)
2289
+ && (emptyState.result === 'intentional-empty' || receipt.after.package === 'absent')
2290
+ && residual.components.every((slot) => slot.state === 'absent');
2291
+ if (clear)
2292
+ await writePlatformEmptyState({ state: emptyState, env: this.context.env });
2293
+ else if (emptyState.result === 'capability-gaps')
2294
+ receipt.diagnostics.push({ code: 'previousDeploymentRetained', severity: 'error',
2295
+ message: 'Previous output or registration could not be confirmed absent. Check the scoped deployment before retrying.',
2296
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind },
2297
+ detail: { reasonCode: 'previousDeploymentRetained', path: root } });
2298
+ }
2299
+ }
2300
+ catch (error) {
2301
+ receipt.diagnostics.push({ code: 'platformProjectionEvidenceFailed', severity: 'error',
2302
+ message: error instanceof Error ? error.message : String(error),
2303
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind } });
2304
+ }
2305
+ }
2306
+ return receipts;
2307
+ },
2308
+ };
2309
+ if (initialDiscoveryCheck) {
2310
+ const firstCheck = initialDiscoveryCheck;
2311
+ const canReuseDiscovery = () => (cursorPreviewBatch
2312
+ ? this.context.nativeObservationBatch === cursorPreviewBatch : this.targets.size === 1)
2313
+ && deployments.length === 1 && plans.length === 1
2314
+ && plans[0] === deployments[0].plan && !blockedReceipts.length && plans[0].operation === 'ensure'
2315
+ && plans[0].expected.components.length > 0 && !plans[0].expected.unmet.length;
2316
+ receiveInitialVerifier?.(async () => {
2317
+ if (!canReuseDiscovery())
2318
+ return verify();
2319
+ // Only this creator reuses the discovery captured after rendering.
2320
+ // Inspect still rereads all native facts and local copy/config evidence.
2321
+ await verifyChecks([firstCheck]);
2322
+ if (!canReuseDiscovery())
2323
+ await verify();
2324
+ });
2325
+ }
2326
+ return target;
2327
+ }
2328
+ }
2329
+ //# sourceMappingURL=rebuild-platform-integration.js.map