@lesliechan721/aw 0.1.0-beta.9 → 0.1.0-beta.90

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