@wowok/agent-mcp 2.7.0 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.d.ts +5 -1
  13. package/dist/customer/risk-assessment.js +1 -397
  14. package/dist/customer/types.js +1 -13
  15. package/dist/customer/user-preferences.js +1 -460
  16. package/dist/evaluation/arbitration-game.d.ts +23 -0
  17. package/dist/evaluation/arbitration-game.js +1 -0
  18. package/dist/evaluation/builtins/demand-match.d.ts +15 -0
  19. package/dist/evaluation/builtins/demand-match.js +1 -0
  20. package/dist/evaluation/builtins/index.d.ts +3 -0
  21. package/dist/evaluation/builtins/index.js +1 -0
  22. package/dist/evaluation/builtins/service-risk.d.ts +6 -0
  23. package/dist/evaluation/builtins/service-risk.js +1 -0
  24. package/dist/evaluation/capability.d.ts +50 -0
  25. package/dist/evaluation/capability.js +1 -0
  26. package/dist/evaluation/composer.d.ts +13 -0
  27. package/dist/evaluation/composer.js +1 -0
  28. package/dist/evaluation/engine.d.ts +18 -0
  29. package/dist/evaluation/engine.js +1 -0
  30. package/dist/evaluation/extract.d.ts +30 -0
  31. package/dist/evaluation/extract.js +1 -0
  32. package/dist/evaluation/game-strategy.d.ts +27 -0
  33. package/dist/evaluation/game-strategy.js +1 -0
  34. package/dist/evaluation/gap.d.ts +2 -0
  35. package/dist/evaluation/gap.js +1 -0
  36. package/dist/evaluation/index.d.ts +12 -0
  37. package/dist/evaluation/index.js +1 -0
  38. package/dist/evaluation/node-game.d.ts +62 -0
  39. package/dist/evaluation/node-game.js +1 -0
  40. package/dist/evaluation/region.d.ts +10 -0
  41. package/dist/evaluation/region.js +1 -0
  42. package/dist/evaluation/types.d.ts +77 -0
  43. package/dist/evaluation/types.js +1 -0
  44. package/dist/evaluation/user-injection.d.ts +6 -0
  45. package/dist/evaluation/user-injection.js +1 -0
  46. package/dist/examples/education-contact-create.json +40 -0
  47. package/dist/examples/freelance-contact-create.json +40 -0
  48. package/dist/examples/insurance-machine-create.json +1 -1
  49. package/dist/examples/insurance-service-allocators.json +1 -1
  50. package/dist/examples/machine-publish.json +1 -1
  51. package/dist/examples/rental-ziroom-service-create.json +1 -1
  52. package/dist/examples/retail-adv-guard-messenger-proof-create.json +1 -1
  53. package/dist/examples/retail-myshop-service-create.json +1 -1
  54. package/dist/examples/retail-myshop-service-customer-required.json +1 -1
  55. package/dist/examples/subscription-contact-create.json +40 -0
  56. package/dist/examples/threebody-machine-create.json +1 -1
  57. package/dist/examples/travel-machine-create.json +1 -1
  58. package/dist/examples/travel-service-create.json +1 -1
  59. package/dist/experience/experience-reuse.js +1 -103
  60. package/dist/experience/index.js +1 -5
  61. package/dist/experience/intent-distill.js +1 -83
  62. package/dist/experience/realtime-feedback.js +1 -94
  63. package/dist/experience/types.js +1 -1
  64. package/dist/experience/user-profile.js +1 -171
  65. package/dist/extensions/business-modules.js +1 -287
  66. package/dist/extensions/capability-manifest.js +1 -781
  67. package/dist/extensions/constraint-registry.js +1 -198
  68. package/dist/extensions/index.js +1 -6
  69. package/dist/extensions/metric-registry.js +1 -257
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.js +1 -717
  73. package/dist/extensions/types.js +1 -1
  74. package/dist/harness/auto-escalation.js +1 -68
  75. package/dist/harness/checkpoint.js +1 -129
  76. package/dist/harness/index.js +1 -78
  77. package/dist/harness/plan.js +1 -276
  78. package/dist/harness/recover.js +1 -139
  79. package/dist/harness/types.js +1 -1
  80. package/dist/harness/verify.js +1 -237
  81. package/dist/index.js +1 -273
  82. package/dist/intent/enrich.d.ts +1 -0
  83. package/dist/intent/enrich.js +1 -0
  84. package/dist/intent/index.d.ts +23 -0
  85. package/dist/intent/index.js +1 -0
  86. package/dist/intent/matcher.d.ts +2 -0
  87. package/dist/intent/matcher.js +1 -0
  88. package/dist/intent/store.d.ts +19 -0
  89. package/dist/intent/store.js +1 -0
  90. package/dist/intent/types.d.ts +33 -0
  91. package/dist/intent/types.js +1 -0
  92. package/dist/knowledge/acquisition-flywheel.js +1 -192
  93. package/dist/knowledge/allocation-confirm.js +1 -534
  94. package/dist/knowledge/allocation-context.js +1 -249
  95. package/dist/knowledge/allocation-ledger.js +1 -463
  96. package/dist/knowledge/allocation-puzzle.js +1 -298
  97. package/dist/knowledge/allocation-risk.js +1 -568
  98. package/dist/knowledge/allocation-templates.js +1 -970
  99. package/dist/knowledge/allocation-translation.js +1 -585
  100. package/dist/knowledge/arb-risk.js +1 -210
  101. package/dist/knowledge/arbitration-confirm.js +1 -559
  102. package/dist/knowledge/arbitration-context.js +1 -505
  103. package/dist/knowledge/arbitration-ledger.js +1 -521
  104. package/dist/knowledge/arbitration-puzzle.js +1 -304
  105. package/dist/knowledge/arbitration-risk.js +1 -433
  106. package/dist/knowledge/arbitration-templates.js +1 -276
  107. package/dist/knowledge/arbitration-translation.js +1 -487
  108. package/dist/knowledge/arbitration-trust.js +1 -117
  109. package/dist/knowledge/audit-rules.js +1 -141
  110. package/dist/knowledge/bridge-risk.js +1 -263
  111. package/dist/knowledge/contact-risk.js +1 -200
  112. package/dist/knowledge/contact-templates.d.ts +27 -0
  113. package/dist/knowledge/contact-templates.js +1 -0
  114. package/dist/knowledge/demand-confirm.js +1 -206
  115. package/dist/knowledge/demand-matching.js +1 -132
  116. package/dist/knowledge/demand-risk.js +1 -240
  117. package/dist/knowledge/demand-translation.js +1 -354
  118. package/dist/knowledge/deployment-scanner.js +1 -823
  119. package/dist/knowledge/dynamic-pricing.js +1 -87
  120. package/dist/knowledge/examples-scanner-cli.js +1 -26
  121. package/dist/knowledge/examples-scanner.js +1 -825
  122. package/dist/knowledge/flywheel-loop.js +1 -404
  123. package/dist/knowledge/fund-layer.js +1 -973
  124. package/dist/knowledge/glossary.js +1 -211
  125. package/dist/knowledge/guard-confirm.js +1 -406
  126. package/dist/knowledge/guard-context.js +1 -287
  127. package/dist/knowledge/guard-design-patterns.js +1 -360
  128. package/dist/knowledge/guard-ledger.js +1 -260
  129. package/dist/knowledge/guard-lint.js +1 -670
  130. package/dist/knowledge/guard-migration.js +1 -228
  131. package/dist/knowledge/guard-puzzle.js +1 -805
  132. package/dist/knowledge/guard-render.js +1 -700
  133. package/dist/knowledge/guard-risk.js +1 -1879
  134. package/dist/knowledge/guard-submission-prompt.js +1 -171
  135. package/dist/knowledge/guard-templates.js +1 -1105
  136. package/dist/knowledge/guard-translation.js +1 -1119
  137. package/dist/knowledge/index.js +1 -436
  138. package/dist/knowledge/industry-evolution.js +1 -323
  139. package/dist/knowledge/industry-generalizer.js +1 -381
  140. package/dist/knowledge/industry-registry.js +1 -174
  141. package/dist/knowledge/intent-metrics.d.ts +4 -3
  142. package/dist/knowledge/intent-metrics.js +1 -566
  143. package/dist/knowledge/machine-confirm.js +1 -559
  144. package/dist/knowledge/machine-context.js +1 -833
  145. package/dist/knowledge/machine-ledger.js +1 -338
  146. package/dist/knowledge/machine-puzzle.js +1 -494
  147. package/dist/knowledge/machine-render.js +1 -565
  148. package/dist/knowledge/machine-risk.js +1 -670
  149. package/dist/knowledge/machine-templates.js +1 -1597
  150. package/dist/knowledge/machine-topology.js +1 -234
  151. package/dist/knowledge/machine-translation.js +1 -513
  152. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  153. package/dist/knowledge/mcp-schema-audit.d.ts +1 -1
  154. package/dist/knowledge/mcp-schema-audit.js +1 -773
  155. package/dist/knowledge/onchain-constants.js +1 -35
  156. package/dist/knowledge/order-confirm.js +1 -573
  157. package/dist/knowledge/order-context.js +1 -390
  158. package/dist/knowledge/order-ledger.js +1 -341
  159. package/dist/knowledge/order-puzzle.js +1 -255
  160. package/dist/knowledge/order-risk.js +1 -653
  161. package/dist/knowledge/order-templates.js +1 -368
  162. package/dist/knowledge/order-translation.js +1 -550
  163. package/dist/knowledge/overrides-loader.js +1 -65
  164. package/dist/knowledge/passport-confirm.js +1 -531
  165. package/dist/knowledge/passport-context.js +1 -306
  166. package/dist/knowledge/passport-ledger.js +1 -282
  167. package/dist/knowledge/passport-puzzle.js +1 -333
  168. package/dist/knowledge/passport-risk.js +1 -450
  169. package/dist/knowledge/passport-templates.js +1 -568
  170. package/dist/knowledge/passport-translation.js +1 -516
  171. package/dist/knowledge/payment-risk.js +1 -249
  172. package/dist/knowledge/permission-confirm.js +1 -426
  173. package/dist/knowledge/permission-context.js +1 -224
  174. package/dist/knowledge/permission-ledger.js +1 -403
  175. package/dist/knowledge/permission-puzzle.js +1 -173
  176. package/dist/knowledge/permission-risk.js +1 -411
  177. package/dist/knowledge/permission-templates.js +1 -234
  178. package/dist/knowledge/permission-translation.js +1 -350
  179. package/dist/knowledge/personal-risk.js +1 -212
  180. package/dist/knowledge/process-model.js +1 -160
  181. package/dist/knowledge/progress-confirm.js +1 -456
  182. package/dist/knowledge/progress-context.js +1 -452
  183. package/dist/knowledge/progress-ledger.js +1 -330
  184. package/dist/knowledge/progress-puzzle.js +1 -219
  185. package/dist/knowledge/progress-risk.js +1 -461
  186. package/dist/knowledge/progress-templates.js +1 -228
  187. package/dist/knowledge/progress-translation.js +1 -405
  188. package/dist/knowledge/proof-confirm.js +1 -187
  189. package/dist/knowledge/proof-risk.js +1 -207
  190. package/dist/knowledge/proof-translation.js +1 -283
  191. package/dist/knowledge/registrar-risk.js +1 -217
  192. package/dist/knowledge/repository-confirm.js +1 -286
  193. package/dist/knowledge/repository-risk.js +1 -373
  194. package/dist/knowledge/repository-translation.js +1 -445
  195. package/dist/knowledge/reputation-rules.js +1 -99
  196. package/dist/knowledge/resource-risk.js +1 -157
  197. package/dist/knowledge/reward-confirm.js +1 -526
  198. package/dist/knowledge/reward-context.js +1 -504
  199. package/dist/knowledge/reward-ledger.js +1 -502
  200. package/dist/knowledge/reward-puzzle.js +1 -300
  201. package/dist/knowledge/reward-risk.js +1 -627
  202. package/dist/knowledge/reward-templates.js +1 -197
  203. package/dist/knowledge/reward-translation.js +1 -501
  204. package/dist/knowledge/safety-rules.js +1 -404
  205. package/dist/knowledge/scenario-modes.js +1 -321
  206. package/dist/knowledge/service-confirm.js +1 -807
  207. package/dist/knowledge/service-context.js +1 -403
  208. package/dist/knowledge/service-ledger.js +1 -609
  209. package/dist/knowledge/service-puzzle.js +1 -236
  210. package/dist/knowledge/service-risk.js +1 -615
  211. package/dist/knowledge/service-templates.js +1 -456
  212. package/dist/knowledge/service-translation.js +1 -622
  213. package/dist/knowledge/template-registry.d.ts +1 -1
  214. package/dist/knowledge/template-registry.js +1 -341
  215. package/dist/knowledge/tool-constraints.js +1 -195
  216. package/dist/knowledge/tools-reference.js +1 -155
  217. package/dist/knowledge/treasury-confirm.js +1 -512
  218. package/dist/knowledge/treasury-context.js +1 -363
  219. package/dist/knowledge/treasury-ledger.js +1 -300
  220. package/dist/knowledge/treasury-puzzle.js +1 -216
  221. package/dist/knowledge/treasury-risk.js +1 -440
  222. package/dist/knowledge/treasury-templates.js +1 -358
  223. package/dist/knowledge/treasury-translation.js +1 -498
  224. package/dist/knowledge/trust-metrics.js +1 -198
  225. package/dist/knowledge/util-risk.js +1 -135
  226. package/dist/loop-engineering/aggregate.js +1 -132
  227. package/dist/loop-engineering/context-collect.js +1 -83
  228. package/dist/loop-engineering/diagnose.js +1 -273
  229. package/dist/loop-engineering/improve.js +1 -405
  230. package/dist/loop-engineering/index.js +1 -4
  231. package/dist/loop-engineering/pipeline.js +1 -56
  232. package/dist/mode-market/index.js +1 -3
  233. package/dist/mode-market/registry.js +1 -124
  234. package/dist/mode-market/review.js +1 -214
  235. package/dist/mode-market/submission.js +1 -85
  236. package/dist/participation/collaborator-interest.d.ts +23 -0
  237. package/dist/participation/collaborator-interest.js +1 -0
  238. package/dist/participation/customer-interest.d.ts +25 -0
  239. package/dist/participation/customer-interest.js +1 -0
  240. package/dist/participation/merchant-interest.js +1 -100
  241. package/dist/participation/radar-core.d.ts +13 -3
  242. package/dist/participation/radar-core.js +1 -269
  243. package/dist/participation/supplier-interest.d.ts +25 -0
  244. package/dist/participation/supplier-interest.js +1 -0
  245. package/dist/persona/analyzer.d.ts +16 -0
  246. package/dist/persona/analyzer.js +1 -0
  247. package/dist/persona/bridge.d.ts +5 -0
  248. package/dist/persona/bridge.js +1 -0
  249. package/dist/persona/defaults.d.ts +4 -0
  250. package/dist/persona/defaults.js +1 -0
  251. package/dist/persona/experience-bridge.d.ts +3 -0
  252. package/dist/persona/experience-bridge.js +1 -0
  253. package/dist/persona/index.d.ts +18 -0
  254. package/dist/persona/index.js +1 -0
  255. package/dist/persona/model.d.ts +7 -0
  256. package/dist/persona/model.js +1 -0
  257. package/dist/persona/store.d.ts +19 -0
  258. package/dist/persona/store.js +1 -0
  259. package/dist/persona/types.d.ts +45 -0
  260. package/dist/persona/types.js +1 -0
  261. package/dist/project/business-puzzle.js +1 -383
  262. package/dist/project/context-assembly.js +1 -254
  263. package/dist/project/deployment-bridge.js +1 -120
  264. package/dist/project/deployment-doc.js +1 -1126
  265. package/dist/project/edit-planner.js +1 -1342
  266. package/dist/project/evaluation.js +1 -2011
  267. package/dist/project/game-theory.js +1 -177
  268. package/dist/project/graph-builder.js +1 -656
  269. package/dist/project/graph.js +1 -340
  270. package/dist/project/handlers.d.ts +5 -0
  271. package/dist/project/handlers.js +1 -1762
  272. package/dist/project/index.d.ts +1 -0
  273. package/dist/project/index.js +1 -301
  274. package/dist/project/intent-analyzer.js +1 -149
  275. package/dist/project/machine-nodes.js +1 -36
  276. package/dist/project/merchant-guide.js +1 -264
  277. package/dist/project/migration.js +1 -125
  278. package/dist/project/mode-actions.js +1 -309
  279. package/dist/project/namespace.js +1 -206
  280. package/dist/project/participation-radar.js +1 -428
  281. package/dist/project/pipeline-actions.js +1 -109
  282. package/dist/project/project-store.js +1 -422
  283. package/dist/project/query.js +1 -153
  284. package/dist/project/reverse-mapping.d.ts +34 -0
  285. package/dist/project/reverse-mapping.js +1 -0
  286. package/dist/project/risk-aggregator.js +1 -295
  287. package/dist/project/rollback-policy.js +1 -290
  288. package/dist/project/semantic-assembler.js +1 -345
  289. package/dist/project/semantic-graph.js +1 -245
  290. package/dist/project/stage-gate.js +1 -369
  291. package/dist/project/substep-trace.js +1 -332
  292. package/dist/project/task-tracker.js +1 -78
  293. package/dist/role/derivation.d.ts +18 -0
  294. package/dist/role/derivation.js +1 -0
  295. package/dist/role/index.d.ts +5 -0
  296. package/dist/role/index.js +1 -0
  297. package/dist/role/model.d.ts +8 -0
  298. package/dist/role/model.js +1 -0
  299. package/dist/role/resolution.d.ts +11 -0
  300. package/dist/role/resolution.js +1 -0
  301. package/dist/role/types.d.ts +11 -0
  302. package/dist/role/types.js +1 -0
  303. package/dist/rules.d.ts +2 -0
  304. package/dist/rules.js +1 -9
  305. package/dist/safety/confirm-gate.js +1 -88
  306. package/dist/safety/index.js +1 -3
  307. package/dist/safety/preview.js +1 -52
  308. package/dist/schema/call/allocation.js +1 -34
  309. package/dist/schema/call/arbitration.js +1 -113
  310. package/dist/schema/call/base.d.ts +15 -15
  311. package/dist/schema/call/base.js +1 -370
  312. package/dist/schema/call/bridge-handler.js +1 -265
  313. package/dist/schema/call/bridge.d.ts +7 -7
  314. package/dist/schema/call/bridge.js +1 -458
  315. package/dist/schema/call/contact.js +1 -37
  316. package/dist/schema/call/demand.js +1 -47
  317. package/dist/schema/call/guard.js +1 -161
  318. package/dist/schema/call/handler.js +1 -322
  319. package/dist/schema/call/index.js +1 -20
  320. package/dist/schema/call/machine.js +1 -193
  321. package/dist/schema/call/order.js +1 -35
  322. package/dist/schema/call/payment.js +1 -37
  323. package/dist/schema/call/permission-handler.js +1 -54
  324. package/dist/schema/call/permission.js +1 -105
  325. package/dist/schema/call/personal.js +1 -78
  326. package/dist/schema/call/progress.js +1 -47
  327. package/dist/schema/call/proof.js +1 -33
  328. package/dist/schema/call/repository.js +1 -77
  329. package/dist/schema/call/reward.js +1 -30
  330. package/dist/schema/call/semantic.js +1 -1657
  331. package/dist/schema/call/service.js +1 -178
  332. package/dist/schema/call/treasury.js +1 -71
  333. package/dist/schema/common/index.js +1 -407
  334. package/dist/schema/config/index.js +1 -68
  335. package/dist/schema/evaluation/index.d.ts +4436 -0
  336. package/dist/schema/evaluation/index.js +1 -0
  337. package/dist/schema/index.d.ts +4 -0
  338. package/dist/schema/index.js +1 -13
  339. package/dist/schema/intent-radar/index.d.ts +284 -0
  340. package/dist/schema/intent-radar/index.js +1 -0
  341. package/dist/schema/local/index.d.ts +21 -21
  342. package/dist/schema/local/index.js +1 -927
  343. package/dist/schema/local/wip.js +1 -187
  344. package/dist/schema/messenger/index.d.ts +7 -7
  345. package/dist/schema/messenger/index.js +1 -475
  346. package/dist/schema/operations.d.ts +7 -7
  347. package/dist/schema/operations.js +1 -520
  348. package/dist/schema/persona/index.d.ts +1985 -0
  349. package/dist/schema/persona/index.js +1 -0
  350. package/dist/schema/project/index.d.ts +96 -50
  351. package/dist/schema/project/index.js +1 -2057
  352. package/dist/schema/query/index.d.ts +423 -7
  353. package/dist/schema/query/index.js +1 -1640
  354. package/dist/schema/schema-query/index.js +1 -104
  355. package/dist/schema/schema-version.js +1 -76
  356. package/dist/schema/sync-layer4.d.ts +1 -1
  357. package/dist/schema/sync-layer4.js +1 -282
  358. package/dist/schema/task-status.d.ts +168 -0
  359. package/dist/schema/task-status.js +1 -0
  360. package/dist/schema/trust/index.js +1 -314
  361. package/dist/schema/utils/guard-parser.js +1 -419
  362. package/dist/schema/utils/guard-query-utils.js +1 -46
  363. package/dist/schema/utils/node-parser.js +1 -369
  364. package/dist/schema/utils/object-type-utils.js +1 -35
  365. package/dist/schema/utils/permission-index-utils.js +1 -7
  366. package/dist/schema/utils/permission-machine-check.js +1 -121
  367. package/dist/schema/utils/skills-recommendation.js +1 -77
  368. package/dist/schema-query/index.js +1 -810
  369. package/dist/schemas/account_operation.output.json +5 -2
  370. package/dist/schemas/bridge_operation.output.json +5 -2
  371. package/dist/schemas/evaluation_operation.output.json +782 -0
  372. package/dist/schemas/evaluation_operation.schema.json +990 -0
  373. package/dist/schemas/index.json +25 -1
  374. package/dist/schemas/intent_radar.output.json +232 -0
  375. package/dist/schemas/intent_radar.schema.json +138 -0
  376. package/dist/schemas/local_info_operation.output.json +5 -2
  377. package/dist/schemas/local_mark_operation.output.json +5 -2
  378. package/dist/schemas/messenger_operation.output.json +5 -2
  379. package/dist/schemas/onchain_events.output.json +5 -2
  380. package/dist/schemas/onchain_operations.output.json +5 -2
  381. package/dist/schemas/onchain_operations.schema.json +6 -6
  382. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  383. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  384. package/dist/schemas/onchain_operations_service.schema.json +3 -3
  385. package/dist/schemas/onchain_table_data.output.json +6 -3
  386. package/dist/schemas/persona_operation.output.json +392 -0
  387. package/dist/schemas/persona_operation.schema.json +250 -0
  388. package/dist/schemas/project_operation.output.json +28 -8
  389. package/dist/schemas/query_task_status.output.json +115 -0
  390. package/dist/schemas/query_task_status.schema.json +24 -0
  391. package/dist/schemas/query_toolkit.output.json +9 -6
  392. package/dist/schemas/trust_score.schema.json +1 -1
  393. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  394. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  395. package/dist/telemetry/index.js +1 -112
  396. package/dist/telemetry/redact.js +1 -23
  397. package/dist/telemetry/storage.js +1 -80
  398. package/dist/tools/handlers/bridge.js +1 -1
  399. package/dist/tools/handlers/config.js +1 -74
  400. package/dist/tools/handlers/evaluation.d.ts +2 -0
  401. package/dist/tools/handlers/evaluation.js +1 -0
  402. package/dist/tools/handlers/file-export.js +1 -90
  403. package/dist/tools/handlers/intent-radar.d.ts +2 -0
  404. package/dist/tools/handlers/intent-radar.js +1 -0
  405. package/dist/tools/handlers/local.js +1 -53
  406. package/dist/tools/handlers/messenger.js +1 -188
  407. package/dist/tools/handlers/onchain.js +1 -1082
  408. package/dist/tools/handlers/persona.d.ts +4 -0
  409. package/dist/tools/handlers/persona.js +1 -0
  410. package/dist/tools/handlers/project.js +1 -211
  411. package/dist/tools/handlers/query.js +1 -434
  412. package/dist/tools/handlers/schema-query.js +1 -176
  413. package/dist/tools/handlers/task-status.d.ts +0 -168
  414. package/dist/tools/handlers/task-status.js +1 -55
  415. package/dist/tools/handlers/trust.js +1 -380
  416. package/dist/tools/handlers/wip.js +1 -90
  417. package/dist/tools/index.js +1 -1306
  418. package/dist/tools/retry.js +1 -85
  419. package/dist/tools/rules-hook.js +1 -23
  420. package/dist/tools/shared.js +1 -130
  421. package/dist/tools/types.js +1 -1
  422. package/dist/tools/upgrade-check.d.ts +19 -0
  423. package/dist/tools/upgrade-check.js +1 -0
  424. package/dist/tools/wip-deploy-assist.d.ts +1 -1
  425. package/dist/tools/wip-deploy-assist.js +1 -278
  426. package/dist/tools/wrap.js +1 -500
  427. package/package.json +5 -3
@@ -1,1342 +1 @@
1
- import { randomUUID, createHash } from "node:crypto";
2
- import { LocalProject, LocalMark, query_objects } from "@wowok/wowok";
3
- import { fetchMachineNodes } from "./machine-nodes.js";
4
- import { parseMachineTreeIndented, } from "../knowledge/machine-render.js";
5
- import { parseGuardTreeIndented, parseGuardTableJSON, } from "../knowledge/guard-render.js";
6
- const PLAN_TTL_MS = 10 * 60 * 1000;
7
- const planStore = new Map();
8
- function cleanupExpiredPlans() {
9
- const now = Date.now();
10
- for (const [id, plan] of planStore) {
11
- if (now > plan.expires_at) {
12
- planStore.delete(id);
13
- }
14
- }
15
- }
16
- const localProject = LocalProject.Instance();
17
- async function resolveProjectId(v) {
18
- if (v.project_id)
19
- return v.project_id;
20
- if (v.project) {
21
- const p = await localProject.getProjectByPrefix(v.project);
22
- if (!p)
23
- throw new Error(`Project not found by prefix: ${v.project}`);
24
- return p.id;
25
- }
26
- throw new Error("Either 'project_id' or 'project' (prefix) is required for this action");
27
- }
28
- async function resolveObjectAddress(v) {
29
- if (v.object_address) {
30
- const addr = v.object_address;
31
- const isHexAddress = /^0x[0-9a-fA-F]{32,64}$/.test(addr);
32
- const isDraftSentinel = addr.startsWith("draft:");
33
- if (!isHexAddress && !isDraftSentinel) {
34
- throw new Error(`Invalid object_address format: '${addr.slice(0, 40)}'. ` +
35
- `Expected a valid Sui address (0x + 32-64 hex chars) or 'draft:<name>' sentinel.`);
36
- }
37
- return addr;
38
- }
39
- if (v.object_name_add) {
40
- const mark = await LocalMark.Instance().get(v.object_name_add);
41
- if (mark?.address)
42
- return mark.address;
43
- throw new Error(`LocalMark name not found: ${v.object_name_add}`);
44
- }
45
- throw new Error("Either 'object_address' or 'object_name_add' is required");
46
- }
47
- function sha256(text) {
48
- return createHash("sha256").update(text, "utf8").digest("hex");
49
- }
50
- function diffMachine(oldNodes, oldEdges, newNodes, newEdges) {
51
- const added = [];
52
- const removed = [];
53
- const modified = [];
54
- const oldNodeNames = new Set(oldNodes.map(n => n.name));
55
- const newNodeNames = new Set(newNodes.map(n => n.name));
56
- for (const name of newNodeNames) {
57
- if (!oldNodeNames.has(name))
58
- added.push(`node: ${name}`);
59
- }
60
- for (const name of oldNodeNames) {
61
- if (!newNodeNames.has(name))
62
- removed.push(`node: ${name}`);
63
- }
64
- const oldEdgeMap = new Map();
65
- for (const e of oldEdges)
66
- oldEdgeMap.set(`${e.from}->${e.to}`, e);
67
- const newEdgeMap = new Map();
68
- for (const e of newEdges)
69
- newEdgeMap.set(`${e.from}->${e.to}`, e);
70
- for (const [key, newEdge] of newEdgeMap) {
71
- if (!oldEdgeMap.has(key)) {
72
- added.push(`edge: ${key}`);
73
- }
74
- else {
75
- const oldEdge = oldEdgeMap.get(key);
76
- if (oldEdge.threshold !== newEdge.threshold) {
77
- modified.push(`edge ${key}: threshold ${oldEdge.threshold} -> ${newEdge.threshold}`);
78
- }
79
- const oldFwdNames = new Set(oldEdge.forwards.map(f => f.name));
80
- const newFwdNames = new Set(newEdge.forwards.map(f => f.name));
81
- for (const fname of newFwdNames) {
82
- if (!oldFwdNames.has(fname)) {
83
- added.push(`forward: ${key} / ${fname}`);
84
- }
85
- else {
86
- const oldFwd = oldEdge.forwards.find(f => f.name === fname);
87
- const newFwd = newEdge.forwards.find(f => f.name === fname);
88
- const changes = [];
89
- if (oldFwd.guard !== newFwd.guard)
90
- changes.push(`guard ${oldFwd.guard} -> ${newFwd.guard}`);
91
- if (oldFwd.permission_index !== newFwd.permission_index)
92
- changes.push(`perm ${oldFwd.permission_index} -> ${newFwd.permission_index}`);
93
- if (oldFwd.named_operator !== newFwd.named_operator)
94
- changes.push(`op ${oldFwd.named_operator} -> ${newFwd.named_operator}`);
95
- if (oldFwd.weight !== newFwd.weight)
96
- changes.push(`weight ${oldFwd.weight} -> ${newFwd.weight}`);
97
- if (changes.length > 0) {
98
- modified.push(`forward ${key} / ${fname}: ${changes.join(", ")}`);
99
- }
100
- }
101
- }
102
- for (const fname of oldFwdNames) {
103
- if (!newFwdNames.has(fname)) {
104
- removed.push(`forward: ${key} / ${fname}`);
105
- }
106
- }
107
- }
108
- }
109
- for (const key of oldEdgeMap.keys()) {
110
- if (!newEdgeMap.has(key))
111
- removed.push(`edge: ${key}`);
112
- }
113
- const summary = `${added.length} added, ${removed.length} removed, ${modified.length} modified`;
114
- return { added, removed, modified, summary };
115
- }
116
- function diffGuard(oldRoot, newRoot, oldTable, newTable) {
117
- const added = [];
118
- const removed = [];
119
- const modified = [];
120
- function walk(oldNode, newNode, path) {
121
- if (!oldNode && newNode) {
122
- added.push(`node: ${path} (${newNode.type})`);
123
- return;
124
- }
125
- if (oldNode && !newNode) {
126
- removed.push(`node: ${path} (${oldNode.type})`);
127
- return;
128
- }
129
- if (!oldNode || !newNode)
130
- return;
131
- if (oldNode.type !== newNode.type) {
132
- modified.push(`node ${path}: type ${oldNode.type} -> ${newNode.type}`);
133
- return;
134
- }
135
- if (oldNode.type === "identifier" && newNode.type === "identifier") {
136
- if (oldNode.identifier !== newNode.identifier) {
137
- modified.push(`node ${path}: identifier ${oldNode.identifier} -> ${newNode.identifier}`);
138
- }
139
- }
140
- if (oldNode.type === "context" && newNode.type === "context") {
141
- if (oldNode.context !== newNode.context) {
142
- modified.push(`node ${path}: context ${oldNode.context} -> ${newNode.context}`);
143
- }
144
- }
145
- if (oldNode.type === "query" && newNode.type === "query") {
146
- if (oldNode.query !== newNode.query) {
147
- modified.push(`node ${path}: query ${oldNode.query} -> ${newNode.query}`);
148
- }
149
- }
150
- const oldChildren = getGuardChildren(oldNode);
151
- const newChildren = getGuardChildren(newNode);
152
- const maxLen = Math.max(oldChildren.length, newChildren.length);
153
- for (let i = 0; i < maxLen; i++) {
154
- walk(oldChildren[i]?.node, newChildren[i]?.node, `${path}.${newChildren[i]?.label ?? oldChildren[i]?.label ?? i}`);
155
- }
156
- }
157
- walk(oldRoot, newRoot, "root");
158
- const oldTableMap = new Map(oldTable.map(t => [t.identifier, t]));
159
- const newTableMap = new Map(newTable.map(t => [t.identifier, t]));
160
- for (const [id, newEntry] of newTableMap) {
161
- if (!oldTableMap.has(id)) {
162
- added.push(`table: id[${id}]`);
163
- }
164
- else {
165
- const oldEntry = oldTableMap.get(id);
166
- const changes = [];
167
- if (oldEntry.value_type !== newEntry.value_type)
168
- changes.push(`type ${oldEntry.value_type} -> ${newEntry.value_type}`);
169
- if (oldEntry.b_submission !== newEntry.b_submission)
170
- changes.push(`submission ${oldEntry.b_submission} -> ${newEntry.b_submission}`);
171
- if (JSON.stringify(oldEntry.value) !== JSON.stringify(newEntry.value))
172
- changes.push(`value changed`);
173
- if (changes.length > 0)
174
- modified.push(`table id[${id}]: ${changes.join(", ")}`);
175
- }
176
- }
177
- for (const id of oldTableMap.keys()) {
178
- if (!newTableMap.has(id))
179
- removed.push(`table: id[${id}]`);
180
- }
181
- const summary = `${added.length} added, ${removed.length} removed, ${modified.length} modified`;
182
- return { added, removed, modified, summary };
183
- }
184
- function getGuardChildren(node) {
185
- const children = [];
186
- if (node.nodes)
187
- node.nodes.forEach((c, i) => children.push({ node: c, label: `child[${i}]` }));
188
- if (node.node)
189
- children.push({ node: node.node, label: "child" });
190
- if (node.nodeLeft)
191
- children.push({ node: node.nodeLeft, label: "left" });
192
- if (node.nodeRight)
193
- children.push({ node: node.nodeRight, label: "right" });
194
- if (node.parameters)
195
- node.parameters.forEach((c, i) => children.push({ node: c, label: `param[${i}]` }));
196
- if (node.historyIdx)
197
- children.push({ node: node.historyIdx, label: "historyIdx" });
198
- if (node.sessionIdx)
199
- children.push({ node: node.sessionIdx, label: "sessionIdx" });
200
- if (node.forwardIdx)
201
- children.push({ node: node.forwardIdx, label: "forwardIdx" });
202
- if (node.where)
203
- children.push({ node: node.where, label: "where" });
204
- if (node.find)
205
- children.push({ node: node.find, label: "find" });
206
- if (node.objectLeft)
207
- children.push({ node: node.objectLeft, label: "objLeft" });
208
- if (node.objectRight)
209
- children.push({ node: node.objectRight, label: "objRight" });
210
- if (node.recipient)
211
- children.push({ node: node.recipient, label: "recipient" });
212
- return children;
213
- }
214
- function validateMachine(nodes, edges) {
215
- const warnings = [];
216
- const blocking_errors = [];
217
- const hasEntry = edges.some(e => e.from === "");
218
- if (!hasEntry) {
219
- blocking_errors.push({
220
- id: "E-01",
221
- description: "No entry forward found (no edge with from=''). Every Machine must have at least one entry forward.",
222
- impact: "The Machine cannot start — no way to create the first Progress entry.",
223
- });
224
- }
225
- const nodeNames = new Set(nodes.map(n => n.name));
226
- for (const edge of edges) {
227
- if (edge.from && !nodeNames.has(edge.from)) {
228
- blocking_errors.push({
229
- id: "E-02",
230
- description: `Edge ${edge.from}->${edge.to} references unknown source node '${edge.from}'.`,
231
- impact: "The on-chain Machine will reject this — all edge endpoints must exist as nodes.",
232
- });
233
- }
234
- if (!nodeNames.has(edge.to)) {
235
- blocking_errors.push({
236
- id: "E-02",
237
- description: `Edge ${edge.from}->${edge.to} references unknown target node '${edge.to}'.`,
238
- impact: "The on-chain Machine will reject this — all edge endpoints must exist as nodes.",
239
- });
240
- }
241
- }
242
- if (nodes.length > 200) {
243
- blocking_errors.push({
244
- id: "E-03",
245
- description: `Node count ${nodes.length} exceeds on-chain MAX_NODE_COUNT (200).`,
246
- impact: "The on-chain Machine will reject this — split the workflow into multiple Machines.",
247
- });
248
- }
249
- const nodesWithIncoming = new Set(edges.filter(e => e.from !== "").map(e => e.to));
250
- const entryNodes = new Set(edges.filter(e => e.from === "").map(e => e.to));
251
- for (const node of nodes) {
252
- if (!nodesWithIncoming.has(node.name) && !entryNodes.has(node.name)) {
253
- warnings.push({
254
- id: "W-01",
255
- description: `Node '${node.name}' has no incoming edges and is not an entry node (unreachable).`,
256
- impact: "This node will never be reached during workflow execution.",
257
- });
258
- }
259
- }
260
- for (const edge of edges) {
261
- if (edge.from === edge.to && edge.from !== "") {
262
- warnings.push({
263
- id: "W-02",
264
- description: `Self-loop detected on node '${edge.from}' (revision cycle).`,
265
- impact: "This is intentional for revision workflows, but ensure there's an exit forward to break the cycle.",
266
- });
267
- }
268
- }
269
- return { warnings, blocking_errors };
270
- }
271
- function validateGuard(root, table) {
272
- const warnings = [];
273
- const blocking_errors = [];
274
- if (!root) {
275
- blocking_errors.push({
276
- id: "E-01",
277
- description: "Guard tree has no root node.",
278
- impact: "The on-chain Guard will reject this — every Guard must have a root computation node.",
279
- });
280
- return { warnings, blocking_errors };
281
- }
282
- const tableIds = new Set(table.map(t => t.identifier));
283
- const referencedIds = new Set();
284
- function collectIds(node) {
285
- if (node.type === "identifier" && typeof node.identifier === "number") {
286
- referencedIds.add(node.identifier);
287
- }
288
- for (const child of getGuardChildren(node)) {
289
- collectIds(child.node);
290
- }
291
- }
292
- collectIds(root);
293
- for (const id of referencedIds) {
294
- if (!tableIds.has(id)) {
295
- blocking_errors.push({
296
- id: "E-02",
297
- description: `Identifier ${id} is referenced in the tree but not defined in the table.`,
298
- impact: "The on-chain Guard will reject this — all identifier references must have a table entry.",
299
- });
300
- }
301
- }
302
- if (table.length > 256) {
303
- blocking_errors.push({
304
- id: "E-03",
305
- description: `Table size ${table.length} exceeds on-chain MAX_TABLE_SIZE (256).`,
306
- impact: "The on-chain Guard will reject this — reduce the number of table entries.",
307
- });
308
- }
309
- const submissionSlots = table.filter(t => t.b_submission);
310
- for (const slot of submissionSlots) {
311
- if (!referencedIds.has(slot.identifier)) {
312
- const label = slot.name ? `'${slot.name}' (id=${slot.identifier})` : `id=${slot.identifier}`;
313
- warnings.push({
314
- id: "W-01",
315
- description: `Submission slot ${label} is declared in the table but never referenced by any identifier node in the tree.`,
316
- impact: "This slot is dead — submitting a value for it has no effect on the guard result. Remove it or add an identifier reference.",
317
- });
318
- }
319
- }
320
- for (const entry of table) {
321
- if (!referencedIds.has(entry.identifier)) {
322
- if (entry.b_submission)
323
- continue;
324
- const label = entry.name ? `'${entry.name}' (id=${entry.identifier})` : `id=${entry.identifier}`;
325
- warnings.push({
326
- id: "W-02",
327
- description: `Table entry ${label} is declared but never referenced by any identifier node in the tree.`,
328
- impact: "This entry is orphaned — it consumes table space without affecting the guard result. Remove it to reduce table size.",
329
- });
330
- }
331
- }
332
- function maxDepth(node, depth) {
333
- if (depth > 16)
334
- return depth;
335
- const children = getGuardChildren(node);
336
- if (children.length === 0)
337
- return depth;
338
- return Math.max(...children.map(c => maxDepth(c.node, depth + 1)));
339
- }
340
- const depth = maxDepth(root, 1);
341
- if (depth > 16) {
342
- warnings.push({
343
- id: "W-03",
344
- description: `Guard tree depth ${depth} exceeds 16 (heuristic threshold for on-chain recursion safety).`,
345
- impact: "Deep trees may hit on-chain stack/gas limits or fail audit. Consider flattening logic (e.g. split into multiple guards connected via rely) or simplifying nested computations.",
346
- });
347
- }
348
- return { warnings, blocking_errors };
349
- }
350
- function prepareMachineCall(objectName, objectAddress, nodes, edges) {
351
- const nodeMap = new Map();
352
- for (const node of nodes) {
353
- nodeMap.set(node.name, {
354
- name: node.name,
355
- description: node.description ?? null,
356
- pairs: [],
357
- });
358
- }
359
- for (const edge of edges) {
360
- if (!nodeMap.has(edge.to)) {
361
- nodeMap.set(edge.to, { name: edge.to, description: null, pairs: [] });
362
- }
363
- nodeMap.get(edge.to).pairs.push({
364
- prev_node: edge.from,
365
- threshold: edge.threshold,
366
- forwards: edge.forwards.map(f => ({
367
- name: f.name,
368
- weight: f.weight,
369
- namedOperator: f.named_operator ?? "",
370
- permissionIndex: f.permission_index ?? 0,
371
- guard: f.guard ? { guard: f.guard } : null,
372
- retained_submission: f.retained_submission ?? null,
373
- })),
374
- });
375
- }
376
- const nodeList = Array.from(nodeMap.values());
377
- const jsonContent = JSON.stringify(nodeList, null, 2);
378
- return {
379
- operation_type: "machine",
380
- data: {
381
- namedNew: { name: objectName ?? objectAddress },
382
- node: {
383
- json_or_markdown: jsonContent,
384
- },
385
- bReplace: true,
386
- },
387
- };
388
- }
389
- function prepareGuardCall(objectName, objectAddress, root, table, rely) {
390
- const data = {
391
- namedNew: { name: objectName ?? objectAddress },
392
- root: {
393
- type: "inline_json",
394
- json: JSON.stringify(root, null, 2),
395
- },
396
- table: table.map(t => ({
397
- identifier: t.identifier,
398
- b_submission: t.b_submission,
399
- value_type: typeof t.value_type === "string" ? t.value_type : t.value_type,
400
- value: t.value,
401
- name: t.name,
402
- })),
403
- };
404
- if (rely && Array.isArray(rely.guards) && rely.guards.length > 0) {
405
- data.rely = {
406
- guards: rely.guards,
407
- logic_or: rely.logic_or,
408
- };
409
- }
410
- return {
411
- operation_type: "guard",
412
- data,
413
- };
414
- }
415
- export async function handlePlanObjectEdit(v) {
416
- cleanupExpiredPlans();
417
- const projectId = await resolveProjectId(v);
418
- const objectAddress = await resolveObjectAddress(v);
419
- const objectKind = v.object_kind;
420
- const editFormat = v.edit_format ?? "tree_outline";
421
- const editedContent = v.edited_content;
422
- if (!objectKind) {
423
- throw new Error("'object_kind' is required for plan_object_edit (must be 'machine' or 'guard')");
424
- }
425
- if (!editedContent) {
426
- throw new Error("'edited_content' is required for plan_object_edit");
427
- }
428
- const project = await localProject.getProject(projectId);
429
- if (!project)
430
- throw new Error(`Project not found (id: ${projectId})`);
431
- let objectName = null;
432
- try {
433
- const mark = await LocalMark.Instance().get(objectAddress);
434
- objectName = mark?.name ?? null;
435
- }
436
- catch {
437
- }
438
- const network = (project.network ?? "testnet");
439
- let parsedResult;
440
- if (objectKind === "machine") {
441
- parsedResult = parseMachineTreeIndented(editedContent);
442
- }
443
- else {
444
- parsedResult = parseGuardTreeIndented(editedContent);
445
- }
446
- if (!parsedResult.success || !parsedResult.data) {
447
- const plan = {
448
- plan_id: randomUUID(),
449
- object_kind: objectKind,
450
- object_address: objectAddress,
451
- object_name: objectName,
452
- expected_hash: sha256(editedContent),
453
- edited_content: editedContent,
454
- edit_format: editFormat,
455
- diff: { added: [], removed: [], modified: [], summary: "parse failed — no diff computed" },
456
- warnings: [],
457
- blocking_errors: [{
458
- id: "E-PARSE",
459
- description: `Failed to parse edited content: ${parsedResult.errors.join("; ")}`,
460
- impact: "The edited content is malformed and cannot be applied. Fix the syntax and try again.",
461
- }],
462
- can_apply: false,
463
- prepared_call: null,
464
- created_at: Date.now(),
465
- expires_at: Date.now() + PLAN_TTL_MS,
466
- summary: `Parse failed — ${parsedResult.errors.length} error(s)`,
467
- };
468
- planStore.set(plan.plan_id, plan);
469
- return {
470
- action: "plan_object_edit",
471
- plan_id: plan.plan_id,
472
- object_kind: plan.object_kind,
473
- object_address: plan.object_address,
474
- object_name: plan.object_name,
475
- expected_hash: plan.expected_hash,
476
- diff: plan.diff,
477
- warnings: plan.warnings,
478
- blocking_errors: plan.blocking_errors,
479
- can_apply: plan.can_apply,
480
- prepared_call: plan.prepared_call,
481
- expires_at: new Date(plan.expires_at).toISOString(),
482
- summary: plan.summary,
483
- };
484
- }
485
- const stateHash = sha256(JSON.stringify(parsedResult.data) + editedContent);
486
- if (objectKind === "machine") {
487
- const newNodes = parsedResult.data.nodes;
488
- const newEdges = parsedResult.data.edges;
489
- let oldNodes = [];
490
- let oldEdges = [];
491
- try {
492
- const currentResult = await fetchCurrentMachine(objectAddress, network);
493
- oldNodes = currentResult.nodes;
494
- oldEdges = currentResult.edges;
495
- }
496
- catch {
497
- }
498
- const diff = diffMachine(oldNodes, oldEdges, newNodes, newEdges);
499
- const validation = validateMachine(newNodes, newEdges);
500
- const canApply = validation.blocking_errors.length === 0;
501
- const preparedCall = canApply ? prepareMachineCall(objectName, objectAddress, newNodes, newEdges) : null;
502
- const plan = {
503
- plan_id: randomUUID(),
504
- object_kind: objectKind,
505
- object_address: objectAddress,
506
- object_name: objectName,
507
- expected_hash: stateHash,
508
- edited_content: editedContent,
509
- edit_format: editFormat,
510
- diff,
511
- warnings: validation.warnings,
512
- blocking_errors: validation.blocking_errors,
513
- can_apply: canApply,
514
- prepared_call: preparedCall,
515
- created_at: Date.now(),
516
- expires_at: Date.now() + PLAN_TTL_MS,
517
- summary: `Machine edit: ${diff.summary}. ${validation.blocking_errors.length} blocking error(s), ${validation.warnings.length} warning(s).`,
518
- };
519
- planStore.set(plan.plan_id, plan);
520
- return {
521
- action: "plan_object_edit",
522
- plan_id: plan.plan_id,
523
- object_kind: plan.object_kind,
524
- object_address: plan.object_address,
525
- object_name: plan.object_name,
526
- expected_hash: plan.expected_hash,
527
- diff: plan.diff,
528
- warnings: plan.warnings,
529
- blocking_errors: plan.blocking_errors,
530
- can_apply: plan.can_apply,
531
- prepared_call: plan.prepared_call,
532
- expires_at: new Date(plan.expires_at).toISOString(),
533
- summary: plan.summary,
534
- };
535
- }
536
- const newRoot = parsedResult.data;
537
- let newTable = [];
538
- const tableJson = parseGuardTableJSON(editedContent);
539
- if (tableJson && tableJson.length > 0) {
540
- newTable = tableJson;
541
- }
542
- else {
543
- const tableMatch = editedContent.match(/##\s*Table[^\n]*\n([\s\S]*?)(?=\n##\s|$)/i);
544
- if (tableMatch) {
545
- const tableLines = tableMatch[1].split("\n").filter(l => l.trim().startsWith("| "));
546
- for (const line of tableLines.slice(2)) {
547
- const cells = line.split("|").map(c => c.trim()).filter(Boolean);
548
- if (cells.length >= 4) {
549
- newTable.push({
550
- identifier: parseInt(cells[0], 10),
551
- b_submission: cells[1] === "true",
552
- value_type: cells[2],
553
- value: cells[3] === "-" ? undefined : cells[3],
554
- name: cells[4] === "-" ? undefined : cells[4],
555
- });
556
- }
557
- }
558
- }
559
- }
560
- let oldRoot = null;
561
- let oldTable = [];
562
- let oldRely = null;
563
- try {
564
- const currentResult = await fetchCurrentGuard(objectAddress, network);
565
- oldRoot = currentResult.root;
566
- oldTable = currentResult.table;
567
- oldRely = currentResult.rely;
568
- }
569
- catch {
570
- }
571
- const diff = diffGuard(oldRoot ?? newRoot, newRoot, oldTable, newTable);
572
- const validation = validateGuard(newRoot, newTable);
573
- const canApply = validation.blocking_errors.length === 0;
574
- const preparedCall = canApply ? prepareGuardCall(objectName, objectAddress, newRoot, newTable, oldRely) : null;
575
- const plan = {
576
- plan_id: randomUUID(),
577
- object_kind: objectKind,
578
- object_address: objectAddress,
579
- object_name: objectName,
580
- expected_hash: stateHash,
581
- edited_content: editedContent,
582
- edit_format: editFormat,
583
- diff,
584
- warnings: validation.warnings,
585
- blocking_errors: validation.blocking_errors,
586
- can_apply: canApply,
587
- prepared_call: preparedCall,
588
- created_at: Date.now(),
589
- expires_at: Date.now() + PLAN_TTL_MS,
590
- summary: `Guard edit: ${diff.summary}. ${validation.blocking_errors.length} blocking error(s), ${validation.warnings.length} warning(s).`,
591
- };
592
- planStore.set(plan.plan_id, plan);
593
- return {
594
- action: "plan_object_edit",
595
- plan_id: plan.plan_id,
596
- object_kind: plan.object_kind,
597
- object_address: plan.object_address,
598
- object_name: plan.object_name,
599
- expected_hash: plan.expected_hash,
600
- diff: plan.diff,
601
- warnings: plan.warnings,
602
- blocking_errors: plan.blocking_errors,
603
- can_apply: plan.can_apply,
604
- prepared_call: plan.prepared_call,
605
- expires_at: new Date(plan.expires_at).toISOString(),
606
- summary: plan.summary,
607
- };
608
- }
609
- export async function handleApplyObjectEdit(v) {
610
- cleanupExpiredPlans();
611
- const planId = v.plan_id;
612
- const expectedHash = v.expected_hash;
613
- if (!planId) {
614
- throw new Error("'plan_id' is required for apply_object_edit");
615
- }
616
- if (!expectedHash) {
617
- throw new Error("'expected_hash' is required for apply_object_edit");
618
- }
619
- const plan = planStore.get(planId);
620
- if (!plan) {
621
- return {
622
- action: "apply_object_edit",
623
- plan_id: planId,
624
- applied: false,
625
- hash_match: false,
626
- prepared_call: null,
627
- error: `Plan not found (id: ${planId}). The plan may have expired (10-minute TTL) or never existed.`,
628
- next_step: "Re-run plan_object_edit to create a new plan.",
629
- };
630
- }
631
- if (Date.now() > plan.expires_at) {
632
- planStore.delete(planId);
633
- return {
634
- action: "apply_object_edit",
635
- plan_id: planId,
636
- applied: false,
637
- hash_match: false,
638
- prepared_call: null,
639
- error: `Plan expired at ${new Date(plan.expires_at).toISOString()}. Plans have a 10-minute TTL.`,
640
- next_step: "Re-run plan_object_edit to create a new plan.",
641
- };
642
- }
643
- const hashMatch = plan.expected_hash === expectedHash;
644
- if (!hashMatch) {
645
- return {
646
- action: "apply_object_edit",
647
- plan_id: planId,
648
- applied: false,
649
- hash_match: false,
650
- prepared_call: null,
651
- error: `Hash mismatch — the on-chain state may have changed between plan and apply, or the edited_content was modified. Expected: ${plan.expected_hash}, got: ${expectedHash}.`,
652
- next_step: "Re-run plan_object_edit to create a fresh plan based on the current on-chain state.",
653
- };
654
- }
655
- if (!plan.can_apply) {
656
- return {
657
- action: "apply_object_edit",
658
- plan_id: planId,
659
- applied: false,
660
- hash_match: true,
661
- prepared_call: null,
662
- error: `Plan has ${plan.blocking_errors.length} blocking error(s). Fix them before applying: ${plan.blocking_errors.map(e => e.description).join("; ")}`,
663
- next_step: "Fix the blocking errors in the edited content, then re-run plan_object_edit.",
664
- };
665
- }
666
- return {
667
- action: "apply_object_edit",
668
- plan_id: planId,
669
- applied: true,
670
- hash_match: true,
671
- prepared_call: plan.prepared_call,
672
- error: null,
673
- next_step: "Pass the prepared_call to onchain_operations to execute the edit on-chain. Review the call data before executing — it will modify the on-chain object.",
674
- };
675
- }
676
- async function fetchCurrentMachine(machineAddress, network) {
677
- const rawNodes = await fetchMachineNodes(machineAddress, network);
678
- const nodeMap = new Map();
679
- const edges = [];
680
- for (const nodeObj of rawNodes) {
681
- const nodeName = nodeObj.name;
682
- if (!nodeName)
683
- continue;
684
- if (!nodeMap.has(nodeName)) {
685
- nodeMap.set(nodeName, { name: nodeName, description: null });
686
- }
687
- const pairs = Array.isArray(nodeObj.value) ? nodeObj.value : [];
688
- for (const pair of pairs) {
689
- if (!pair || typeof pair !== "object")
690
- continue;
691
- const from = typeof pair.prev_node === "string" ? pair.prev_node : "";
692
- const to = nodeName;
693
- const threshold = typeof pair.threshold === "number" ? pair.threshold : 1;
694
- const forwardsRaw = Array.isArray(pair.forwards) ? pair.forwards : [];
695
- const forwards = forwardsRaw.map((f) => ({
696
- name: f.name ?? "",
697
- weight: f.weight ?? 1,
698
- named_operator: f.namedOperator ?? null,
699
- permission_index: f.permissionIndex ?? null,
700
- guard: f.guard?.guard ?? f.guard ?? null,
701
- retained_submission: f.retained_submission ?? null,
702
- }));
703
- edges.push({ from, to, threshold, forwards });
704
- }
705
- }
706
- for (const edge of edges) {
707
- if (!nodeMap.has(edge.from))
708
- nodeMap.set(edge.from, { name: edge.from, description: null });
709
- if (!nodeMap.has(edge.to))
710
- nodeMap.set(edge.to, { name: edge.to, description: null });
711
- }
712
- return { nodes: Array.from(nodeMap.values()), edges };
713
- }
714
- async function fetchCurrentGuard(guardAddress, network) {
715
- const queryResult = await query_objects({
716
- objects: [guardAddress],
717
- network,
718
- });
719
- const guardData = queryResult?.objects?.[0] ?? null;
720
- if (!guardData) {
721
- throw new Error(`Guard ${guardAddress} not found on ${network}`);
722
- }
723
- const root = guardData.root ?? guardData.data?.root ?? null;
724
- const table = guardData.table ?? guardData.data?.table ?? [];
725
- const relies = guardData.relies ?? guardData.data?.relies ?? null;
726
- const reliesLogicAnd = guardData.relies_logic_and ?? guardData.data?.relies_logic_and ?? null;
727
- let rely = null;
728
- if (Array.isArray(relies) && relies.length > 0) {
729
- rely = {
730
- guards: relies,
731
- logic_or: typeof reliesLogicAnd === "boolean" ? !reliesLogicAnd : undefined,
732
- };
733
- }
734
- return {
735
- root: root,
736
- table: Array.isArray(table) ? table.map((t) => ({
737
- identifier: t.identifier,
738
- name: t.name,
739
- value_type: t.value_type,
740
- b_submission: t.b_submission,
741
- value: t.value,
742
- })) : [],
743
- rely,
744
- };
745
- }
746
- function parsePatchOperation(opStr) {
747
- const parts = opStr.trim().split(/\s+/);
748
- if (parts.length < 2)
749
- return null;
750
- const [cmd, subcmd, ...rest] = parts;
751
- if (cmd === "add" && subcmd === "node" && rest.length >= 1) {
752
- return { type: "add_node", args: rest, raw: opStr };
753
- }
754
- if (cmd === "remove" && subcmd === "node" && rest.length >= 1) {
755
- return { type: "remove_node", args: rest, raw: opStr };
756
- }
757
- if (cmd === "add" && subcmd === "edge" && rest.length >= 2) {
758
- return { type: "add_edge", args: rest, raw: opStr };
759
- }
760
- if (cmd === "remove" && subcmd === "edge" && rest.length >= 2) {
761
- return { type: "remove_edge", args: rest, raw: opStr };
762
- }
763
- if (cmd === "add" && subcmd === "forward" && rest.length >= 3) {
764
- return { type: "add_forward", args: rest, raw: opStr };
765
- }
766
- if (cmd === "remove" && subcmd === "forward" && rest.length >= 3) {
767
- return { type: "remove_forward", args: rest, raw: opStr };
768
- }
769
- if (cmd === "set" && subcmd === "threshold" && rest.length >= 3) {
770
- return { type: "set_threshold", args: rest, raw: opStr };
771
- }
772
- if (cmd === "set" && subcmd === "guard" && rest.length >= 4) {
773
- return { type: "set_guard", args: rest, raw: opStr };
774
- }
775
- if (cmd === "set" && subcmd === "permission" && rest.length >= 4) {
776
- return { type: "set_permission", args: rest, raw: opStr };
777
- }
778
- if (cmd === "set" && subcmd === "operator" && rest.length >= 4) {
779
- return { type: "set_operator", args: rest, raw: opStr };
780
- }
781
- if (cmd === "set" && subcmd === "weight" && rest.length >= 4) {
782
- return { type: "set_weight", args: rest, raw: opStr };
783
- }
784
- if (cmd === "set" && subcmd === "retained_submission" && rest.length >= 4) {
785
- return { type: "set_retained_submission", args: rest, raw: opStr };
786
- }
787
- if (cmd === "set" && subcmd === "description" && rest.length >= 2) {
788
- return { type: "set_description", args: rest, raw: opStr };
789
- }
790
- return null;
791
- }
792
- function applyPatchOperation(op, nodes, edges) {
793
- switch (op.type) {
794
- case "add_node": {
795
- const name = op.args[0];
796
- if (nodes.some(n => n.name === name)) {
797
- return { success: false, error: `Node '${name}' already exists` };
798
- }
799
- nodes.push({ name, description: null });
800
- return { success: true };
801
- }
802
- case "remove_node": {
803
- const name = op.args[0];
804
- const idx = nodes.findIndex(n => n.name === name);
805
- if (idx === -1) {
806
- return { success: false, error: `Node '${name}' not found` };
807
- }
808
- const hasEdges = edges.some(e => e.from === name || e.to === name);
809
- if (hasEdges) {
810
- return { success: false, error: `Node '${name}' has edges — remove them first` };
811
- }
812
- nodes.splice(idx, 1);
813
- return { success: true };
814
- }
815
- case "add_edge": {
816
- const [from, to] = op.args;
817
- if (!nodes.some(n => n.name === to)) {
818
- return { success: false, error: `Target node '${to}' not found` };
819
- }
820
- if (from !== "" && !nodes.some(n => n.name === from)) {
821
- return { success: false, error: `Source node '${from}' not found` };
822
- }
823
- if (edges.some(e => e.from === from && e.to === to)) {
824
- return { success: false, error: `Edge '${from}->${to}' already exists` };
825
- }
826
- edges.push({ from, to, threshold: 1, forwards: [] });
827
- return { success: true };
828
- }
829
- case "remove_edge": {
830
- const [from, to] = op.args;
831
- const idx = edges.findIndex(e => e.from === from && e.to === to);
832
- if (idx === -1) {
833
- return { success: false, error: `Edge '${from}->${to}' not found` };
834
- }
835
- edges.splice(idx, 1);
836
- return { success: true };
837
- }
838
- case "add_forward": {
839
- const [from, to, fwdName] = op.args;
840
- const edge = edges.find(e => e.from === from && e.to === to);
841
- if (!edge) {
842
- return { success: false, error: `Edge '${from}->${to}' not found` };
843
- }
844
- if (edge.forwards.some(f => f.name === fwdName)) {
845
- return { success: false, error: `Forward '${fwdName}' already exists on edge '${from}->${to}'` };
846
- }
847
- edge.forwards.push({
848
- name: fwdName,
849
- weight: 1,
850
- named_operator: null,
851
- permission_index: null,
852
- guard: null,
853
- retained_submission: null,
854
- });
855
- return { success: true };
856
- }
857
- case "remove_forward": {
858
- const [from, to, fwdName] = op.args;
859
- const edge = edges.find(e => e.from === from && e.to === to);
860
- if (!edge) {
861
- return { success: false, error: `Edge '${from}->${to}' not found` };
862
- }
863
- const idx = edge.forwards.findIndex(f => f.name === fwdName);
864
- if (idx === -1) {
865
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
866
- }
867
- edge.forwards.splice(idx, 1);
868
- return { success: true };
869
- }
870
- case "set_threshold": {
871
- const [from, to, valStr] = op.args;
872
- const val = parseInt(valStr, 10);
873
- if (isNaN(val) || val < 1) {
874
- return { success: false, error: `Invalid threshold value: ${valStr}` };
875
- }
876
- const edge = edges.find(e => e.from === from && e.to === to);
877
- if (!edge) {
878
- return { success: false, error: `Edge '${from}->${to}' not found` };
879
- }
880
- edge.threshold = val;
881
- return { success: true };
882
- }
883
- case "set_guard": {
884
- const [from, to, fwdName, guardAddr] = op.args;
885
- const edge = edges.find(e => e.from === from && e.to === to);
886
- if (!edge) {
887
- return { success: false, error: `Edge '${from}->${to}' not found` };
888
- }
889
- const fwd = edge.forwards.find(f => f.name === fwdName);
890
- if (!fwd) {
891
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
892
- }
893
- fwd.guard = guardAddr === "none" ? null : guardAddr;
894
- return { success: true };
895
- }
896
- case "set_permission": {
897
- const [from, to, fwdName, permStr] = op.args;
898
- const edge = edges.find(e => e.from === from && e.to === to);
899
- if (!edge) {
900
- return { success: false, error: `Edge '${from}->${to}' not found` };
901
- }
902
- const fwd = edge.forwards.find(f => f.name === fwdName);
903
- if (!fwd) {
904
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
905
- }
906
- const perm = parseInt(permStr, 10);
907
- if (isNaN(perm) || perm < 0) {
908
- return { success: false, error: `Invalid permission index: ${permStr} (must be a non-negative integer)` };
909
- }
910
- fwd.permission_index = perm;
911
- return { success: true };
912
- }
913
- case "set_operator": {
914
- const [from, to, fwdName, ...opRest] = op.args;
915
- const namedOperator = opRest.join(" ");
916
- const edge = edges.find(e => e.from === from && e.to === to);
917
- if (!edge) {
918
- return { success: false, error: `Edge '${from}->${to}' not found` };
919
- }
920
- const fwd = edge.forwards.find(f => f.name === fwdName);
921
- if (!fwd) {
922
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
923
- }
924
- if (namedOperator === "none") {
925
- fwd.named_operator = null;
926
- }
927
- else {
928
- fwd.named_operator = namedOperator;
929
- }
930
- return { success: true };
931
- }
932
- case "set_weight": {
933
- const [from, to, fwdName, weightStr] = op.args;
934
- const edge = edges.find(e => e.from === from && e.to === to);
935
- if (!edge) {
936
- return { success: false, error: `Edge '${from}->${to}' not found` };
937
- }
938
- const fwd = edge.forwards.find(f => f.name === fwdName);
939
- if (!fwd) {
940
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
941
- }
942
- const weight = parseInt(weightStr, 10);
943
- if (isNaN(weight) || weight < 1) {
944
- return { success: false, error: `Invalid weight: ${weightStr} (must be a positive integer)` };
945
- }
946
- fwd.weight = weight;
947
- return { success: true };
948
- }
949
- case "set_retained_submission": {
950
- const [from, to, fwdName, indicesStr] = op.args;
951
- const edge = edges.find(e => e.from === from && e.to === to);
952
- if (!edge) {
953
- return { success: false, error: `Edge '${from}->${to}' not found` };
954
- }
955
- const fwd = edge.forwards.find(f => f.name === fwdName);
956
- if (!fwd) {
957
- return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
958
- }
959
- if (indicesStr === "none") {
960
- fwd.retained_submission = null;
961
- return { success: true };
962
- }
963
- const indices = indicesStr.split(",").map(s => {
964
- const n = parseInt(s.trim(), 10);
965
- if (isNaN(n) || n < 0)
966
- return -1;
967
- return n;
968
- });
969
- if (indices.some(n => n < 0)) {
970
- return { success: false, error: `Invalid retained_submission indices: ${indicesStr} (must be comma-separated non-negative integers or 'none')` };
971
- }
972
- fwd.retained_submission = indices;
973
- return { success: true };
974
- }
975
- case "set_description": {
976
- const [nodeName, ...descParts] = op.args;
977
- const node = nodes.find(n => n.name === nodeName);
978
- if (!node) {
979
- return { success: false, error: `Node '${nodeName}' not found` };
980
- }
981
- const desc = descParts.join(" ");
982
- node.description = desc === "none" ? null : desc;
983
- return { success: true };
984
- }
985
- default:
986
- return { success: false, error: `Unknown operation type: ${op.type}` };
987
- }
988
- }
989
- export async function handlePatchMachineNodes(v) {
990
- const projectId = await resolveProjectId(v);
991
- const machineAddress = await resolveObjectAddress(v);
992
- const operations = v.patch_operations ?? [];
993
- if (operations.length === 0) {
994
- throw new Error("'patch_operations' is required for patch_machine_nodes (non-empty array)");
995
- }
996
- const project = await localProject.getProject(projectId);
997
- if (!project)
998
- throw new Error(`Project not found (id: ${projectId})`);
999
- let machineName = null;
1000
- try {
1001
- const mark = await LocalMark.Instance().get(machineAddress);
1002
- machineName = mark?.name ?? null;
1003
- }
1004
- catch {
1005
- }
1006
- const network = (project.network ?? "testnet");
1007
- const current = await fetchCurrentMachine(machineAddress, network);
1008
- const oldNodes = current.nodes.map(n => ({ ...n }));
1009
- const oldEdges = current.edges.map(e => ({
1010
- ...e,
1011
- forwards: e.forwards.map(f => ({ ...f })),
1012
- }));
1013
- const operationsFailed = [];
1014
- let operationsApplied = 0;
1015
- for (const opStr of operations) {
1016
- const op = parsePatchOperation(opStr);
1017
- if (!op) {
1018
- operationsFailed.push({
1019
- operation: opStr,
1020
- error: "Invalid operation format. See patch_operations schema for supported formats.",
1021
- });
1022
- continue;
1023
- }
1024
- const result = applyPatchOperation(op, current.nodes, current.edges);
1025
- if (result.success) {
1026
- operationsApplied++;
1027
- }
1028
- else {
1029
- operationsFailed.push({
1030
- operation: opStr,
1031
- error: result.error ?? "Unknown error",
1032
- });
1033
- }
1034
- }
1035
- const diff = diffMachine(oldNodes, oldEdges, current.nodes, current.edges);
1036
- const validation = validateMachine(current.nodes, current.edges);
1037
- const blocking_errors = [];
1038
- for (const fail of operationsFailed) {
1039
- blocking_errors.push({
1040
- id: "E-OP",
1041
- description: `Operation '${fail.operation}' failed: ${fail.error}`,
1042
- impact: "This operation was not applied. The patch cannot be executed on-chain until all operations succeed.",
1043
- });
1044
- }
1045
- for (const be of validation.blocking_errors) {
1046
- blocking_errors.push(be);
1047
- }
1048
- const canApply = blocking_errors.length === 0;
1049
- const preparedCall = canApply
1050
- ? prepareMachineCall(machineName, machineAddress, current.nodes, current.edges)
1051
- : null;
1052
- const summary = `Patch: ${operationsApplied} applied, ${operationsFailed.length} failed. ${diff.summary}.`;
1053
- return {
1054
- action: "patch_machine_nodes",
1055
- machine_address: machineAddress,
1056
- machine_name: machineName,
1057
- operations_applied: operationsApplied,
1058
- operations_failed: operationsFailed,
1059
- patched_nodes: current.nodes,
1060
- patched_edges: current.edges,
1061
- diff,
1062
- warnings: validation.warnings,
1063
- blocking_errors: blocking_errors.length > 0 ? blocking_errors : [],
1064
- can_apply: canApply,
1065
- prepared_call: preparedCall,
1066
- summary,
1067
- };
1068
- }
1069
- function parseGuardPatchOperation(opStr) {
1070
- const parts = opStr.trim().split(/\s+/);
1071
- if (parts.length < 2)
1072
- return null;
1073
- const [cmd, subcmd, ...rest] = parts;
1074
- if (cmd === "add" && subcmd === "table" && rest.length >= 4) {
1075
- return { type: "add_table", args: rest, raw: opStr };
1076
- }
1077
- if (cmd === "remove" && subcmd === "table" && rest.length >= 1) {
1078
- return { type: "remove_table", args: rest, raw: opStr };
1079
- }
1080
- if (cmd === "set" && subcmd === "table_value" && rest.length >= 2) {
1081
- return { type: "set_table_value", args: rest, raw: opStr };
1082
- }
1083
- if (cmd === "set" && subcmd === "table_name" && rest.length >= 2) {
1084
- return { type: "set_table_name", args: rest, raw: opStr };
1085
- }
1086
- if (cmd === "set" && subcmd === "table_submission" && rest.length >= 2) {
1087
- return { type: "set_table_submission", args: rest, raw: opStr };
1088
- }
1089
- if (cmd === "set" && subcmd === "root" && rest.length >= 1) {
1090
- return { type: "set_root", args: rest, raw: opStr };
1091
- }
1092
- if (cmd === "set" && subcmd === "rely" && rest.length >= 1) {
1093
- return { type: "set_rely", args: rest, raw: opStr };
1094
- }
1095
- return null;
1096
- }
1097
- function tryParseJSON(s) {
1098
- try {
1099
- return JSON.parse(s);
1100
- }
1101
- catch {
1102
- return undefined;
1103
- }
1104
- }
1105
- function applyGuardPatchOperation(op, context) {
1106
- switch (op.type) {
1107
- case "add_table": {
1108
- const [idStr, name, valueTypeStr, bSubStr, ...valueParts] = op.args;
1109
- const identifier = parseInt(idStr, 10);
1110
- if (isNaN(identifier) || identifier < 0) {
1111
- return { success: false, error: `Invalid table identifier: ${idStr} (must be a non-negative integer)` };
1112
- }
1113
- if (context.table.some(t => t.identifier === identifier)) {
1114
- return { success: false, error: `Table identifier ${identifier} already exists` };
1115
- }
1116
- const b_submission = bSubStr === "true";
1117
- const value_type = /^[0-9]+$/.test(valueTypeStr)
1118
- ? parseInt(valueTypeStr, 10)
1119
- : valueTypeStr;
1120
- let value = undefined;
1121
- if (valueParts.length > 0) {
1122
- const valueStr = valueParts.join(" ");
1123
- if (valueStr !== "none") {
1124
- value = tryParseJSON(valueStr);
1125
- if (value === undefined) {
1126
- value = valueStr;
1127
- }
1128
- }
1129
- }
1130
- context.table.push({
1131
- identifier,
1132
- name: name === "none" ? undefined : name,
1133
- value_type,
1134
- b_submission,
1135
- value,
1136
- });
1137
- return { success: true };
1138
- }
1139
- case "remove_table": {
1140
- const [idStr] = op.args;
1141
- const identifier = parseInt(idStr, 10);
1142
- if (isNaN(identifier)) {
1143
- return { success: false, error: `Invalid table identifier: ${idStr}` };
1144
- }
1145
- const idx = context.table.findIndex(t => t.identifier === identifier);
1146
- if (idx === -1) {
1147
- return { success: false, error: `Table identifier ${identifier} not found` };
1148
- }
1149
- context.table.splice(idx, 1);
1150
- return { success: true };
1151
- }
1152
- case "set_table_value": {
1153
- const [idStr, ...valueParts] = op.args;
1154
- const identifier = parseInt(idStr, 10);
1155
- if (isNaN(identifier)) {
1156
- return { success: false, error: `Invalid table identifier: ${idStr}` };
1157
- }
1158
- const entry = context.table.find(t => t.identifier === identifier);
1159
- if (!entry) {
1160
- return { success: false, error: `Table identifier ${identifier} not found` };
1161
- }
1162
- const valueStr = valueParts.join(" ");
1163
- if (valueStr === "none") {
1164
- entry.value = undefined;
1165
- }
1166
- else {
1167
- const parsed = tryParseJSON(valueStr);
1168
- entry.value = parsed !== undefined ? parsed : valueStr;
1169
- }
1170
- return { success: true };
1171
- }
1172
- case "set_table_name": {
1173
- const [idStr, name, ...rest] = op.args;
1174
- const identifier = parseInt(idStr, 10);
1175
- if (isNaN(identifier)) {
1176
- return { success: false, error: `Invalid table identifier: ${idStr}` };
1177
- }
1178
- const entry = context.table.find(t => t.identifier === identifier);
1179
- if (!entry) {
1180
- return { success: false, error: `Table identifier ${identifier} not found` };
1181
- }
1182
- const fullName = rest.length > 0 ? [name, ...rest].join(" ") : name;
1183
- entry.name = fullName === "none" ? undefined : fullName;
1184
- return { success: true };
1185
- }
1186
- case "set_table_submission": {
1187
- const [idStr, bSubStr] = op.args;
1188
- const identifier = parseInt(idStr, 10);
1189
- if (isNaN(identifier)) {
1190
- return { success: false, error: `Invalid table identifier: ${idStr}` };
1191
- }
1192
- const entry = context.table.find(t => t.identifier === identifier);
1193
- if (!entry) {
1194
- return { success: false, error: `Table identifier ${identifier} not found` };
1195
- }
1196
- if (bSubStr !== "true" && bSubStr !== "false") {
1197
- return { success: false, error: `Invalid b_submission value: ${bSubStr} (must be 'true' or 'false')` };
1198
- }
1199
- entry.b_submission = bSubStr === "true";
1200
- return { success: true };
1201
- }
1202
- case "set_root": {
1203
- const jsonStr = op.args.join(" ");
1204
- const newRoot = tryParseJSON(jsonStr);
1205
- if (newRoot === undefined || typeof newRoot !== "object" || newRoot === null) {
1206
- return { success: false, error: `Invalid root JSON: '${jsonStr.slice(0, 80)}' (must be a valid JSON object)` };
1207
- }
1208
- if (typeof newRoot.type !== "string") {
1209
- return { success: false, error: `Root JSON must have a 'type' field (string). Got: ${JSON.stringify(Object.keys(newRoot)).slice(0, 80)}` };
1210
- }
1211
- return { success: true, newRoot: newRoot };
1212
- }
1213
- case "set_rely": {
1214
- const [relyStr] = op.args;
1215
- if (relyStr === "none") {
1216
- context.rely = null;
1217
- return { success: true };
1218
- }
1219
- const guards = relyStr.split(",").map(s => s.trim()).filter(s => s.length > 0);
1220
- if (guards.length === 0) {
1221
- return { success: false, error: `Invalid rely value: '${relyStr}' (expected 'none' or comma-separated addresses)` };
1222
- }
1223
- context.rely = {
1224
- guards,
1225
- logic_or: context.rely?.logic_or ?? false,
1226
- };
1227
- return { success: true };
1228
- }
1229
- default:
1230
- return { success: false, error: `Unknown Guard patch operation type: ${op.type}` };
1231
- }
1232
- }
1233
- export async function handlePatchGuardTree(v) {
1234
- const projectId = await resolveProjectId(v);
1235
- const guardAddress = await resolveObjectAddress(v);
1236
- const operations = v.patch_operations ?? [];
1237
- if (operations.length === 0) {
1238
- throw new Error("'patch_operations' is required for patch_guard_tree (non-empty array)");
1239
- }
1240
- const project = await localProject.getProject(projectId);
1241
- if (!project)
1242
- throw new Error(`Project not found (id: ${projectId})`);
1243
- let guardName = null;
1244
- try {
1245
- const mark = await LocalMark.Instance().get(guardAddress);
1246
- guardName = mark?.name ?? null;
1247
- }
1248
- catch {
1249
- }
1250
- const network = (project.network ?? "testnet");
1251
- const current = await fetchCurrentGuard(guardAddress, network);
1252
- const oldRoot = JSON.parse(JSON.stringify(current.root));
1253
- const oldTable = current.table.map(t => ({ ...t, value: t.value !== undefined ? JSON.parse(JSON.stringify(t.value)) : undefined }));
1254
- const oldRely = current.rely ? { ...current.rely, guards: [...current.rely.guards] } : null;
1255
- const operationsFailed = [];
1256
- let operationsApplied = 0;
1257
- let newRoot = current.root;
1258
- for (const opStr of operations) {
1259
- const op = parseGuardPatchOperation(opStr);
1260
- if (!op) {
1261
- operationsFailed.push({
1262
- operation: opStr,
1263
- error: "Invalid Guard patch operation format. See patch_operations schema for supported formats.",
1264
- });
1265
- continue;
1266
- }
1267
- const result = applyGuardPatchOperation(op, {
1268
- root: newRoot,
1269
- table: current.table,
1270
- rely: current.rely,
1271
- });
1272
- if (result.success) {
1273
- operationsApplied++;
1274
- if (result.newRoot) {
1275
- newRoot = result.newRoot;
1276
- }
1277
- }
1278
- else {
1279
- operationsFailed.push({
1280
- operation: opStr,
1281
- error: result.error ?? "Unknown error",
1282
- });
1283
- }
1284
- }
1285
- if (current.rely && Array.isArray(current.rely.guards)) {
1286
- const resolved = [];
1287
- for (const g of current.rely.guards) {
1288
- if (/^0x[0-9a-fA-F]{32,64}$/.test(g)) {
1289
- resolved.push(g);
1290
- }
1291
- else {
1292
- try {
1293
- const mark = await LocalMark.Instance().get(g);
1294
- if (mark?.address) {
1295
- resolved.push(mark.address);
1296
- }
1297
- else {
1298
- resolved.push(g);
1299
- }
1300
- }
1301
- catch {
1302
- resolved.push(g);
1303
- }
1304
- }
1305
- }
1306
- current.rely.guards = resolved;
1307
- }
1308
- const diff = diffGuard(oldRoot, newRoot, oldTable, current.table);
1309
- const validation = validateGuard(newRoot, current.table);
1310
- const blocking_errors = [];
1311
- for (const fail of operationsFailed) {
1312
- blocking_errors.push({
1313
- id: "E-OP",
1314
- description: `Operation '${fail.operation}' failed: ${fail.error}`,
1315
- impact: "This operation was not applied. The patch cannot be executed on-chain until all operations succeed.",
1316
- });
1317
- }
1318
- for (const be of validation.blocking_errors) {
1319
- blocking_errors.push(be);
1320
- }
1321
- const canApply = blocking_errors.length === 0;
1322
- const preparedCall = canApply
1323
- ? prepareGuardCall(guardName, guardAddress, newRoot, current.table, current.rely)
1324
- : null;
1325
- const summary = `Guard patch: ${operationsApplied} applied, ${operationsFailed.length} failed. ${diff.summary}.`;
1326
- return {
1327
- action: "patch_guard_tree",
1328
- guard_address: guardAddress,
1329
- guard_name: guardName,
1330
- operations_applied: operationsApplied,
1331
- operations_failed: operationsFailed,
1332
- patched_root: newRoot,
1333
- patched_table: current.table,
1334
- patched_rely: current.rely,
1335
- diff,
1336
- warnings: validation.warnings,
1337
- blocking_errors: blocking_errors.length > 0 ? blocking_errors : [],
1338
- can_apply: canApply,
1339
- prepared_call: preparedCall,
1340
- summary,
1341
- };
1342
- }
1
+ import{randomUUID,createHash}from'node:crypto';import{LocalProject,LocalMark,query_objects}from'@wowok/wowok';import{fetchMachineNodes}from'./machine-nodes.js';import{parseMachineTreeIndented}from'../knowledge/machine-render.js';import{parseGuardTreeIndented,parseGuardTableJSON}from'../knowledge/guard-render.js';const PLAN_TTL_MS=0xa*0x3c*0x3e8,planStore=new Map();function cleanupExpiredPlans(){const a=Date['now']();for(const [b,c]of planStore){a>c['expires_at']&&planStore['delete'](b);}}const localProject=LocalProject['Instance']();async function resolveProjectId(a){if(a['project_id'])return a['project_id'];if(a['project']){const b=await localProject['getProjectByPrefix'](a['project']);if(!b)throw new Error('Project\x20not\x20found\x20by\x20prefix:\x20'+a['project']);return b['id'];}throw new Error('Either\x20\x27project_id\x27\x20or\x20\x27project\x27\x20(prefix)\x20is\x20required\x20for\x20this\x20action');}async function resolveObjectAddress(a){if(a['object_address']){const b=a['object_address'],c=/^0x[0-9a-fA-F]{32,64}$/['test'](b),d=b['startsWith']('draft:');if(!c&&!d)throw new Error('Invalid\x20object_address\x20format:\x20\x27'+b['slice'](0x0,0x28)+'\x27.\x20'+'Expected\x20a\x20valid\x20Sui\x20address\x20(0x\x20+\x2032-64\x20hex\x20chars)\x20or\x20\x27draft:<name>\x27\x20sentinel.');return b;}if(a['object_name_add']){const e=await LocalMark['Instance']()['get'](a['object_name_add']);if(e?.['address'])return e['address'];throw new Error('LocalMark\x20name\x20not\x20found:\x20'+a['object_name_add']);}throw new Error('Either\x20\x27object_address\x27\x20or\x20\x27object_name_add\x27\x20is\x20required');}function sha256(a){return createHash('sha256')['update'](a,'utf8')['digest']('hex');}function diffMachine(a,b,c,d){const f=[],g=[],h=[],i=new Set(a['map'](o=>o['name'])),j=new Set(c['map'](o=>o['name']));for(const n of j){if(!i['has'](n))f['push']('node:\x20'+n);}for(const o of i){if(!j['has'](o))g['push']('node:\x20'+o);}const k=new Map();for(const p of b)k['set'](p['from']+'->'+p['to'],p);const l=new Map();for(const q of d)l['set'](q['from']+'->'+q['to'],q);for(const [r,s]of l){if(!k['has'](r))f['push']('edge:\x20'+r);else{const t=k['get'](r);t['threshold']!==s['threshold']&&h['push']('edge\x20'+r+':\x20threshold\x20'+t['threshold']+'\x20->\x20'+s['threshold']);const u=new Set(t['forwards']['map'](w=>w['name'])),v=new Set(s['forwards']['map'](w=>w['name']));for(const w of v){if(!u['has'](w))f['push']('forward:\x20'+r+'\x20/\x20'+w);else{const x=t['forwards']['find'](A=>A['name']===w),y=s['forwards']['find'](A=>A['name']===w),z=[];if(x['guard']!==y['guard'])z['push']('guard\x20'+x['guard']+'\x20->\x20'+y['guard']);if(x['permission_index']!==y['permission_index'])z['push']('perm\x20'+x['permission_index']+'\x20->\x20'+y['permission_index']);if(x['named_operator']!==y['named_operator'])z['push']('op\x20'+x['named_operator']+'\x20->\x20'+y['named_operator']);if(x['weight']!==y['weight'])z['push']('weight\x20'+x['weight']+'\x20->\x20'+y['weight']);z['length']>0x0&&h['push']('forward\x20'+r+'\x20/\x20'+w+':\x20'+z['join'](',\x20'));}}for(const A of u){!v['has'](A)&&g['push']('forward:\x20'+r+'\x20/\x20'+A);}}}for(const B of k['keys']()){if(!l['has'](B))g['push']('edge:\x20'+B);}const m=f['length']+'\x20added,\x20'+g['length']+'\x20removed,\x20'+h['length']+'\x20modified';return{'added':f,'removed':g,'modified':h,'summary':m};}function diffGuard(a,b,c,d){const e=[],f=[],g=[];function h(l,m,n){if(!l&&m){e['push']('node:\x20'+n+'\x20('+m['type']+')');return;}if(l&&!m){f['push']('node:\x20'+n+'\x20('+l['type']+')');return;}if(!l||!m)return;if(l['type']!==m['type']){g['push']('node\x20'+n+':\x20type\x20'+l['type']+'\x20->\x20'+m['type']);return;}l['type']==='identifier'&&m['type']==='identifier'&&(l['identifier']!==m['identifier']&&g['push']('node\x20'+n+':\x20identifier\x20'+l['identifier']+'\x20->\x20'+m['identifier']));l['type']==='context'&&m['type']==='context'&&(l['context']!==m['context']&&g['push']('node\x20'+n+':\x20context\x20'+l['context']+'\x20->\x20'+m['context']));l['type']==='query'&&m['type']==='query'&&(l['query']!==m['query']&&g['push']('node\x20'+n+':\x20query\x20'+l['query']+'\x20->\x20'+m['query']));const o=getGuardChildren(l),p=getGuardChildren(m),q=Math['max'](o['length'],p['length']);for(let r=0x0;r<q;r++){h(o[r]?.['node'],p[r]?.['node'],n+'.'+(p[r]?.['label']??o[r]?.['label']??r));}}h(a,b,'root');const i=new Map(c['map'](l=>[l['identifier'],l])),j=new Map(d['map'](l=>[l['identifier'],l]));for(const [l,m]of j){if(!i['has'](l))e['push']('table:\x20id['+l+']');else{const n=i['get'](l),o=[];if(n['value_type']!==m['value_type'])o['push']('type\x20'+n['value_type']+'\x20->\x20'+m['value_type']);if(n['b_submission']!==m['b_submission'])o['push']('submission\x20'+n['b_submission']+'\x20->\x20'+m['b_submission']);if(JSON['stringify'](n['value'])!==JSON['stringify'](m['value']))o['push']('value\x20changed');if(o['length']>0x0)g['push']('table\x20id['+l+']:\x20'+o['join'](',\x20'));}}for(const p of i['keys']()){if(!j['has'](p))f['push']('table:\x20id['+p+']');}const k=e['length']+'\x20added,\x20'+f['length']+'\x20removed,\x20'+g['length']+'\x20modified';return{'added':e,'removed':f,'modified':g,'summary':k};}function getGuardChildren(a){const b=[];if(a['nodes'])a['nodes']['forEach']((d,e)=>b['push']({'node':d,'label':'child['+e+']'}));if(a['node'])b['push']({'node':a['node'],'label':'child'});if(a['nodeLeft'])b['push']({'node':a['nodeLeft'],'label':'left'});if(a['nodeRight'])b['push']({'node':a['nodeRight'],'label':'right'});if(a['parameters'])a['parameters']['forEach']((d,e)=>b['push']({'node':d,'label':'param['+e+']'}));if(a['historyIdx'])b['push']({'node':a['historyIdx'],'label':'historyIdx'});if(a['sessionIdx'])b['push']({'node':a['sessionIdx'],'label':'sessionIdx'});if(a['forwardIdx'])b['push']({'node':a['forwardIdx'],'label':'forwardIdx'});if(a['where'])b['push']({'node':a['where'],'label':'where'});if(a['find'])b['push']({'node':a['find'],'label':'find'});if(a['objectLeft'])b['push']({'node':a['objectLeft'],'label':'objLeft'});if(a['objectRight'])b['push']({'node':a['objectRight'],'label':'objRight'});if(a['recipient'])b['push']({'node':a['recipient'],'label':'recipient'});return b;}function validateMachine(a,b){const c=[],d=[],e=b['some'](i=>i['from']==='');!e&&d['push']({'id':'E-01','description':'No\x20entry\x20forward\x20found\x20(no\x20edge\x20with\x20from=\x27\x27).\x20Every\x20Machine\x20must\x20have\x20at\x20least\x20one\x20entry\x20forward.','impact':'The\x20Machine\x20cannot\x20start\x20—\x20no\x20way\x20to\x20create\x20the\x20first\x20Progress\x20entry.'});const f=new Set(a['map'](i=>i['name']));for(const i of b){i['from']&&!f['has'](i['from'])&&d['push']({'id':'E-02','description':'Edge\x20'+i['from']+'->'+i['to']+'\x20references\x20unknown\x20source\x20node\x20\x27'+i['from']+'\x27.','impact':'The\x20on-chain\x20Machine\x20will\x20reject\x20this\x20—\x20all\x20edge\x20endpoints\x20must\x20exist\x20as\x20nodes.'}),!f['has'](i['to'])&&d['push']({'id':'E-02','description':'Edge\x20'+i['from']+'->'+i['to']+'\x20references\x20unknown\x20target\x20node\x20\x27'+i['to']+'\x27.','impact':'The\x20on-chain\x20Machine\x20will\x20reject\x20this\x20—\x20all\x20edge\x20endpoints\x20must\x20exist\x20as\x20nodes.'});}a['length']>0xc8&&d['push']({'id':'E-03','description':'Node\x20count\x20'+a['length']+'\x20exceeds\x20on-chain\x20MAX_NODE_COUNT\x20(200).','impact':'The\x20on-chain\x20Machine\x20will\x20reject\x20this\x20—\x20split\x20the\x20workflow\x20into\x20multiple\x20Machines.'});const g=new Set(b['filter'](j=>j['from']!=='')['map'](j=>j['to'])),h=new Set(b['filter'](j=>j['from']==='')['map'](j=>j['to']));for(const j of a){!g['has'](j['name'])&&!h['has'](j['name'])&&c['push']({'id':'W-01','description':'Node\x20\x27'+j['name']+'\x27\x20has\x20no\x20incoming\x20edges\x20and\x20is\x20not\x20an\x20entry\x20node\x20(unreachable).','impact':'This\x20node\x20will\x20never\x20be\x20reached\x20during\x20workflow\x20execution.'});}for(const k of b){k['from']===k['to']&&k['from']!==''&&c['push']({'id':'W-02','description':'Self-loop\x20detected\x20on\x20node\x20\x27'+k['from']+'\x27\x20(revision\x20cycle).','impact':'This\x20is\x20intentional\x20for\x20revision\x20workflows,\x20but\x20ensure\x20there\x27s\x20an\x20exit\x20forward\x20to\x20break\x20the\x20cycle.'});}return{'warnings':c,'blocking_errors':d};}function validateGuard(a,b){const c=[],d=[];if(!a)return d['push']({'id':'E-01','description':'Guard\x20tree\x20has\x20no\x20root\x20node.','impact':'The\x20on-chain\x20Guard\x20will\x20reject\x20this\x20—\x20every\x20Guard\x20must\x20have\x20a\x20root\x20computation\x20node.'}),{'warnings':c,'blocking_errors':d};const e=new Set(b['map'](k=>k['identifier'])),f=new Set();function g(k){k['type']==='identifier'&&typeof k['identifier']==='number'&&f['add'](k['identifier']);for(const l of getGuardChildren(k)){g(l['node']);}}g(a);for(const k of f){!e['has'](k)&&d['push']({'id':'E-02','description':'Identifier\x20'+k+'\x20is\x20referenced\x20in\x20the\x20tree\x20but\x20not\x20defined\x20in\x20the\x20table.','impact':'The\x20on-chain\x20Guard\x20will\x20reject\x20this\x20—\x20all\x20identifier\x20references\x20must\x20have\x20a\x20table\x20entry.'});}b['length']>0x100&&d['push']({'id':'E-03','description':'Table\x20size\x20'+b['length']+'\x20exceeds\x20on-chain\x20MAX_TABLE_SIZE\x20(256).','impact':'The\x20on-chain\x20Guard\x20will\x20reject\x20this\x20—\x20reduce\x20the\x20number\x20of\x20table\x20entries.'});const h=b['filter'](l=>l['b_submission']);for(const l of h){if(!f['has'](l['identifier'])){const m=l['name']?'\x27'+l['name']+'\x27\x20(id='+l['identifier']+')':'id='+l['identifier'];c['push']({'id':'W-01','description':'Submission\x20slot\x20'+m+'\x20is\x20declared\x20in\x20the\x20table\x20but\x20never\x20referenced\x20by\x20any\x20identifier\x20node\x20in\x20the\x20tree.','impact':'This\x20slot\x20is\x20dead\x20—\x20submitting\x20a\x20value\x20for\x20it\x20has\x20no\x20effect\x20on\x20the\x20guard\x20result.\x20Remove\x20it\x20or\x20add\x20an\x20identifier\x20reference.'});}}for(const n of b){if(!f['has'](n['identifier'])){if(n['b_submission'])continue;const o=n['name']?'\x27'+n['name']+'\x27\x20(id='+n['identifier']+')':'id='+n['identifier'];c['push']({'id':'W-02','description':'Table\x20entry\x20'+o+'\x20is\x20declared\x20but\x20never\x20referenced\x20by\x20any\x20identifier\x20node\x20in\x20the\x20tree.','impact':'This\x20entry\x20is\x20orphaned\x20—\x20it\x20consumes\x20table\x20space\x20without\x20affecting\x20the\x20guard\x20result.\x20Remove\x20it\x20to\x20reduce\x20table\x20size.'});}}function i(p,q){if(q>0x10)return q;const r=getGuardChildren(p);if(r['length']===0x0)return q;return Math['max'](...r['map'](s=>i(s['node'],q+0x1)));}const j=i(a,0x1);return j>0x10&&c['push']({'id':'W-03','description':'Guard\x20tree\x20depth\x20'+j+'\x20exceeds\x2016\x20(heuristic\x20threshold\x20for\x20on-chain\x20recursion\x20safety).','impact':'Deep\x20trees\x20may\x20hit\x20on-chain\x20stack/gas\x20limits\x20or\x20fail\x20audit.\x20Consider\x20flattening\x20logic\x20(e.g.\x20split\x20into\x20multiple\x20guards\x20connected\x20via\x20rely)\x20or\x20simplifying\x20nested\x20computations.'}),{'warnings':c,'blocking_errors':d};}function prepareMachineCall(a,b,c,d){const e=new Map();for(const h of c){e['set'](h['name'],{'name':h['name'],'description':h['description']??null,'pairs':[]});}for(const i of d){!e['has'](i['to'])&&e['set'](i['to'],{'name':i['to'],'description':null,'pairs':[]}),e['get'](i['to'])['pairs']['push']({'prev_node':i['from'],'threshold':i['threshold'],'forwards':i['forwards']['map'](j=>({'name':j['name'],'weight':j['weight'],'namedOperator':j['named_operator']??'','permissionIndex':j['permission_index']??0x0,'guard':j['guard']?{'guard':j['guard']}:null,'retained_submission':j['retained_submission']??null}))});}const f=Array['from'](e['values']()),g=JSON['stringify'](f,null,0x2);return{'operation_type':'machine','data':{'namedNew':{'name':a??b},'node':{'json_or_markdown':g},'bReplace':!![]}};}function prepareGuardCall(a,b,c,d,e){const f={'namedNew':{'name':a??b},'root':{'type':'inline_json','json':JSON['stringify'](c,null,0x2)},'table':d['map'](g=>({'identifier':g['identifier'],'b_submission':g['b_submission'],'value_type':typeof g['value_type']==='string'?g['value_type']:g['value_type'],'value':g['value'],'name':g['name']}))};return e&&Array['isArray'](e['guards'])&&e['guards']['length']>0x0&&(f['rely']={'guards':e['guards'],'logic_or':e['logic_or']}),{'operation_type':'guard','data':f};}export async function handlePlanObjectEdit(a){cleanupExpiredPlans();const b=await resolveProjectId(a),c=await resolveObjectAddress(a),d=a['object_kind'],e=a['edit_format']??'tree_outline',f=a['edited_content'];if(!d)throw new Error('\x27object_kind\x27\x20is\x20required\x20for\x20plan_object_edit\x20(must\x20be\x20\x27machine\x27\x20or\x20\x27guard\x27)');if(!f)throw new Error('\x27edited_content\x27\x20is\x20required\x20for\x20plan_object_edit');const g=await localProject['getProject'](b);if(!g)throw new Error('Project\x20not\x20found\x20(id:\x20'+b+')');let h=null;try{const x=await LocalMark['Instance']()['get'](c);h=x?.['name']??null;}catch{}const i=g['network']??'testnet';let j;d==='machine'?j=parseMachineTreeIndented(f):j=parseGuardTreeIndented(f);if(!j['success']||!j['data']){const y={'plan_id':randomUUID(),'object_kind':d,'object_address':c,'object_name':h,'expected_hash':sha256(f),'edited_content':f,'edit_format':e,'diff':{'added':[],'removed':[],'modified':[],'summary':'parse\x20failed\x20—\x20no\x20diff\x20computed'},'warnings':[],'blocking_errors':[{'id':'E-PARSE','description':'Failed\x20to\x20parse\x20edited\x20content:\x20'+j['errors']['join'](';\x20'),'impact':'The\x20edited\x20content\x20is\x20malformed\x20and\x20cannot\x20be\x20applied.\x20Fix\x20the\x20syntax\x20and\x20try\x20again.'}],'can_apply':![],'prepared_call':null,'created_at':Date['now'](),'expires_at':Date['now']()+PLAN_TTL_MS,'summary':'Parse\x20failed\x20—\x20'+j['errors']['length']+'\x20error(s)'};return planStore['set'](y['plan_id'],y),{'action':'plan_object_edit','plan_id':y['plan_id'],'object_kind':y['object_kind'],'object_address':y['object_address'],'object_name':y['object_name'],'expected_hash':y['expected_hash'],'diff':y['diff'],'warnings':y['warnings'],'blocking_errors':y['blocking_errors'],'can_apply':y['can_apply'],'prepared_call':y['prepared_call'],'expires_at':new Date(y['expires_at'])['toISOString'](),'summary':y['summary']};}const k=sha256(JSON['stringify'](j['data'])+f);if(d==='machine'){const z=j['data']['nodes'],A=j['data']['edges'];let B=[],C=[];try{const I=await fetchCurrentMachine(c,i);B=I['nodes'],C=I['edges'];}catch{}const D=diffMachine(B,C,z,A),E=validateMachine(z,A),F=E['blocking_errors']['length']===0x0,G=F?prepareMachineCall(h,c,z,A):null,H={'plan_id':randomUUID(),'object_kind':d,'object_address':c,'object_name':h,'expected_hash':k,'edited_content':f,'edit_format':e,'diff':D,'warnings':E['warnings'],'blocking_errors':E['blocking_errors'],'can_apply':F,'prepared_call':G,'created_at':Date['now'](),'expires_at':Date['now']()+PLAN_TTL_MS,'summary':'Machine\x20edit:\x20'+D['summary']+'.\x20'+E['blocking_errors']['length']+'\x20blocking\x20error(s),\x20'+E['warnings']['length']+'\x20warning(s).'};return planStore['set'](H['plan_id'],H),{'action':'plan_object_edit','plan_id':H['plan_id'],'object_kind':H['object_kind'],'object_address':H['object_address'],'object_name':H['object_name'],'expected_hash':H['expected_hash'],'diff':H['diff'],'warnings':H['warnings'],'blocking_errors':H['blocking_errors'],'can_apply':H['can_apply'],'prepared_call':H['prepared_call'],'expires_at':new Date(H['expires_at'])['toISOString'](),'summary':H['summary']};}const l=j['data'];let m=[];const n=parseGuardTableJSON(f);if(n&&n['length']>0x0)m=n;else{const J=f['match'](/##\s*Table[^\n]*\n([\s\S]*?)(?=\n##\s|$)/i);if(J){const K=J[0x1]['split']('\x0a')['filter'](L=>L['trim']()['startsWith']('|\x20'));for(const L of K['slice'](0x2)){const M=L['split']('|')['map'](N=>N['trim']())['filter'](Boolean);M['length']>=0x4&&m['push']({'identifier':parseInt(M[0x0],0xa),'b_submission':M[0x1]==='true','value_type':M[0x2],'value':M[0x3]==='-'?undefined:M[0x3],'name':M[0x4]==='-'?undefined:M[0x4]});}}}let o=null,p=[],q=null;try{const N=await fetchCurrentGuard(c,i);o=N['root'],p=N['table'],q=N['rely'];}catch{}const r=diffGuard(o??l,l,p,m),s=validateGuard(l,m),t=s['blocking_errors']['length']===0x0,u=t?prepareGuardCall(h,c,l,m,q):null,w={'plan_id':randomUUID(),'object_kind':d,'object_address':c,'object_name':h,'expected_hash':k,'edited_content':f,'edit_format':e,'diff':r,'warnings':s['warnings'],'blocking_errors':s['blocking_errors'],'can_apply':t,'prepared_call':u,'created_at':Date['now'](),'expires_at':Date['now']()+PLAN_TTL_MS,'summary':'Guard\x20edit:\x20'+r['summary']+'.\x20'+s['blocking_errors']['length']+'\x20blocking\x20error(s),\x20'+s['warnings']['length']+'\x20warning(s).'};return planStore['set'](w['plan_id'],w),{'action':'plan_object_edit','plan_id':w['plan_id'],'object_kind':w['object_kind'],'object_address':w['object_address'],'object_name':w['object_name'],'expected_hash':w['expected_hash'],'diff':w['diff'],'warnings':w['warnings'],'blocking_errors':w['blocking_errors'],'can_apply':w['can_apply'],'prepared_call':w['prepared_call'],'expires_at':new Date(w['expires_at'])['toISOString'](),'summary':w['summary']};}export async function handleApplyObjectEdit(a){cleanupExpiredPlans();const b=a['plan_id'],c=a['expected_hash'];if(!b)throw new Error('\x27plan_id\x27\x20is\x20required\x20for\x20apply_object_edit');if(!c)throw new Error('\x27expected_hash\x27\x20is\x20required\x20for\x20apply_object_edit');const d=planStore['get'](b);if(!d)return{'action':'apply_object_edit','plan_id':b,'applied':![],'hash_match':![],'prepared_call':null,'error':'Plan\x20not\x20found\x20(id:\x20'+b+').\x20The\x20plan\x20may\x20have\x20expired\x20(10-minute\x20TTL)\x20or\x20never\x20existed.','next_step':'Re-run\x20plan_object_edit\x20to\x20create\x20a\x20new\x20plan.'};if(Date['now']()>d['expires_at'])return planStore['delete'](b),{'action':'apply_object_edit','plan_id':b,'applied':![],'hash_match':![],'prepared_call':null,'error':'Plan\x20expired\x20at\x20'+new Date(d['expires_at'])['toISOString']()+'.\x20Plans\x20have\x20a\x2010-minute\x20TTL.','next_step':'Re-run\x20plan_object_edit\x20to\x20create\x20a\x20new\x20plan.'};const e=d['expected_hash']===c;if(!e)return{'action':'apply_object_edit','plan_id':b,'applied':![],'hash_match':![],'prepared_call':null,'error':'Hash\x20mismatch\x20—\x20the\x20on-chain\x20state\x20may\x20have\x20changed\x20between\x20plan\x20and\x20apply,\x20or\x20the\x20edited_content\x20was\x20modified.\x20Expected:\x20'+d['expected_hash']+',\x20got:\x20'+c+'.','next_step':'Re-run\x20plan_object_edit\x20to\x20create\x20a\x20fresh\x20plan\x20based\x20on\x20the\x20current\x20on-chain\x20state.'};if(!d['can_apply'])return{'action':'apply_object_edit','plan_id':b,'applied':![],'hash_match':!![],'prepared_call':null,'error':'Plan\x20has\x20'+d['blocking_errors']['length']+'\x20blocking\x20error(s).\x20Fix\x20them\x20before\x20applying:\x20'+d['blocking_errors']['map'](f=>f['description'])['join'](';\x20'),'next_step':'Fix\x20the\x20blocking\x20errors\x20in\x20the\x20edited\x20content,\x20then\x20re-run\x20plan_object_edit.'};return{'action':'apply_object_edit','plan_id':b,'applied':!![],'hash_match':!![],'prepared_call':d['prepared_call'],'error':null,'next_step':'Pass\x20the\x20prepared_call\x20to\x20onchain_operations\x20to\x20execute\x20the\x20edit\x20on-chain.\x20Review\x20the\x20call\x20data\x20before\x20executing\x20—\x20it\x20will\x20modify\x20the\x20on-chain\x20object.'};}async function fetchCurrentMachine(a,b){const c=await fetchMachineNodes(a,b),d=new Map(),e=[];for(const f of c){const g=f['name'];if(!g)continue;!d['has'](g)&&d['set'](g,{'name':g,'description':null});const h=Array['isArray'](f['value'])?f['value']:[];for(const i of h){if(!i||typeof i!=='object')continue;const j=typeof i['prev_node']==='string'?i['prev_node']:'',k=g,l=typeof i['threshold']==='number'?i['threshold']:0x1,m=Array['isArray'](i['forwards'])?i['forwards']:[],n=m['map'](o=>({'name':o['name']??'','weight':o['weight']??0x1,'named_operator':o['namedOperator']??null,'permission_index':o['permissionIndex']??null,'guard':o['guard']?.['guard']??o['guard']??null,'retained_submission':o['retained_submission']??null}));e['push']({'from':j,'to':k,'threshold':l,'forwards':n});}}for(const o of e){if(!d['has'](o['from']))d['set'](o['from'],{'name':o['from'],'description':null});if(!d['has'](o['to']))d['set'](o['to'],{'name':o['to'],'description':null});}return{'nodes':Array['from'](d['values']()),'edges':e};}async function fetchCurrentGuard(a,b){const c=await query_objects({'objects':[a],'network':b}),d=c?.['objects']?.[0x0]??null;if(!d)throw new Error('Guard\x20'+a+'\x20not\x20found\x20on\x20'+b);const e=d['root']??d['data']?.['root']??null,f=d['table']??d['data']?.['table']??[],g=d['relies']??d['data']?.['relies']??null,h=d['relies_logic_and']??d['data']?.['relies_logic_and']??null;let i=null;return Array['isArray'](g)&&g['length']>0x0&&(i={'guards':g,'logic_or':typeof h==='boolean'?!h:undefined}),{'root':e,'table':Array['isArray'](f)?f['map'](j=>({'identifier':j['identifier'],'name':j['name'],'value_type':j['value_type'],'b_submission':j['b_submission'],'value':j['value']})):[],'rely':i};}function parsePatchOperation(a){const b=a['trim']()['split'](/\s+/);if(b['length']<0x2)return null;const [c,d,...e]=b;if(c==='add'&&d==='node'&&e['length']>=0x1)return{'type':'add_node','args':e,'raw':a};if(c==='remove'&&d==='node'&&e['length']>=0x1)return{'type':'remove_node','args':e,'raw':a};if(c==='add'&&d==='edge'&&e['length']>=0x2)return{'type':'add_edge','args':e,'raw':a};if(c==='remove'&&d==='edge'&&e['length']>=0x2)return{'type':'remove_edge','args':e,'raw':a};if(c==='add'&&d==='forward'&&e['length']>=0x3)return{'type':'add_forward','args':e,'raw':a};if(c==='remove'&&d==='forward'&&e['length']>=0x3)return{'type':'remove_forward','args':e,'raw':a};if(c==='set'&&d==='threshold'&&e['length']>=0x3)return{'type':'set_threshold','args':e,'raw':a};if(c==='set'&&d==='guard'&&e['length']>=0x4)return{'type':'set_guard','args':e,'raw':a};if(c==='set'&&d==='permission'&&e['length']>=0x4)return{'type':'set_permission','args':e,'raw':a};if(c==='set'&&d==='operator'&&e['length']>=0x4)return{'type':'set_operator','args':e,'raw':a};if(c==='set'&&d==='weight'&&e['length']>=0x4)return{'type':'set_weight','args':e,'raw':a};if(c==='set'&&d==='retained_submission'&&e['length']>=0x4)return{'type':'set_retained_submission','args':e,'raw':a};if(c==='set'&&d==='description'&&e['length']>=0x2)return{'type':'set_description','args':e,'raw':a};return null;}function applyPatchOperation(a,b,c){switch(a['type']){case'add_node':{const d=a['args'][0x0];if(b['some'](e=>e['name']===d))return{'success':![],'error':'Node\x20\x27'+d+'\x27\x20already\x20exists'};return b['push']({'name':d,'description':null}),{'success':!![]};}case'remove_node':{const e=a['args'][0x0],f=b['findIndex'](h=>h['name']===e);if(f===-0x1)return{'success':![],'error':'Node\x20\x27'+e+'\x27\x20not\x20found'};const g=c['some'](h=>h['from']===e||h['to']===e);if(g)return{'success':![],'error':'Node\x20\x27'+e+'\x27\x20has\x20edges\x20—\x20remove\x20them\x20first'};return b['splice'](f,0x1),{'success':!![]};}case'add_edge':{const [h,i]=a['args'];if(!b['some'](j=>j['name']===i))return{'success':![],'error':'Target\x20node\x20\x27'+i+'\x27\x20not\x20found'};if(h!==''&&!b['some'](j=>j['name']===h))return{'success':![],'error':'Source\x20node\x20\x27'+h+'\x27\x20not\x20found'};if(c['some'](j=>j['from']===h&&j['to']===i))return{'success':![],'error':'Edge\x20\x27'+h+'->'+i+'\x27\x20already\x20exists'};return c['push']({'from':h,'to':i,'threshold':0x1,'forwards':[]}),{'success':!![]};}case'remove_edge':{const [j,k]=a['args'],l=c['findIndex'](m=>m['from']===j&&m['to']===k);if(l===-0x1)return{'success':![],'error':'Edge\x20\x27'+j+'->'+k+'\x27\x20not\x20found'};return c['splice'](l,0x1),{'success':!![]};}case'add_forward':{const [m,n,o]=a['args'],p=c['find'](q=>q['from']===m&&q['to']===n);if(!p)return{'success':![],'error':'Edge\x20\x27'+m+'->'+n+'\x27\x20not\x20found'};if(p['forwards']['some'](q=>q['name']===o))return{'success':![],'error':'Forward\x20\x27'+o+'\x27\x20already\x20exists\x20on\x20edge\x20\x27'+m+'->'+n+'\x27'};return p['forwards']['push']({'name':o,'weight':0x1,'named_operator':null,'permission_index':null,'guard':null,'retained_submission':null}),{'success':!![]};}case'remove_forward':{const [q,r,s]=a['args'],t=c['find'](v=>v['from']===q&&v['to']===r);if(!t)return{'success':![],'error':'Edge\x20\x27'+q+'->'+r+'\x27\x20not\x20found'};const u=t['forwards']['findIndex'](v=>v['name']===s);if(u===-0x1)return{'success':![],'error':'Forward\x20\x27'+s+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+q+'->'+r+'\x27'};return t['forwards']['splice'](u,0x1),{'success':!![]};}case'set_threshold':{const [v,w,x]=a['args'],y=parseInt(x,0xa);if(isNaN(y)||y<0x1)return{'success':![],'error':'Invalid\x20threshold\x20value:\x20'+x};const z=c['find'](A=>A['from']===v&&A['to']===w);if(!z)return{'success':![],'error':'Edge\x20\x27'+v+'->'+w+'\x27\x20not\x20found'};return z['threshold']=y,{'success':!![]};}case'set_guard':{const [A,B,C,D]=a['args'],E=c['find'](G=>G['from']===A&&G['to']===B);if(!E)return{'success':![],'error':'Edge\x20\x27'+A+'->'+B+'\x27\x20not\x20found'};const F=E['forwards']['find'](G=>G['name']===C);if(!F)return{'success':![],'error':'Forward\x20\x27'+C+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+A+'->'+B+'\x27'};return F['guard']=D==='none'?null:D,{'success':!![]};}case'set_permission':{const [G,H,I,J]=a['args'],K=c['find'](N=>N['from']===G&&N['to']===H);if(!K)return{'success':![],'error':'Edge\x20\x27'+G+'->'+H+'\x27\x20not\x20found'};const L=K['forwards']['find'](N=>N['name']===I);if(!L)return{'success':![],'error':'Forward\x20\x27'+I+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+G+'->'+H+'\x27'};const M=parseInt(J,0xa);if(isNaN(M)||M<0x0)return{'success':![],'error':'Invalid\x20permission\x20index:\x20'+J+'\x20(must\x20be\x20a\x20non-negative\x20integer)'};return L['permission_index']=M,{'success':!![]};}case'set_operator':{const [N,O,P,...Q]=a['args'],R=Q['join']('\x20'),S=c['find'](U=>U['from']===N&&U['to']===O);if(!S)return{'success':![],'error':'Edge\x20\x27'+N+'->'+O+'\x27\x20not\x20found'};const T=S['forwards']['find'](U=>U['name']===P);if(!T)return{'success':![],'error':'Forward\x20\x27'+P+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+N+'->'+O+'\x27'};return R==='none'?T['named_operator']=null:T['named_operator']=R,{'success':!![]};}case'set_weight':{const [U,V,W,X]=a['args'],Y=c['find'](a1=>a1['from']===U&&a1['to']===V);if(!Y)return{'success':![],'error':'Edge\x20\x27'+U+'->'+V+'\x27\x20not\x20found'};const Z=Y['forwards']['find'](a1=>a1['name']===W);if(!Z)return{'success':![],'error':'Forward\x20\x27'+W+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+U+'->'+V+'\x27'};const a0=parseInt(X,0xa);if(isNaN(a0)||a0<0x1)return{'success':![],'error':'Invalid\x20weight:\x20'+X+'\x20(must\x20be\x20a\x20positive\x20integer)'};return Z['weight']=a0,{'success':!![]};}case'set_retained_submission':{const [a1,a2,a3,a4]=a['args'],a5=c['find'](a8=>a8['from']===a1&&a8['to']===a2);if(!a5)return{'success':![],'error':'Edge\x20\x27'+a1+'->'+a2+'\x27\x20not\x20found'};const a6=a5['forwards']['find'](a8=>a8['name']===a3);if(!a6)return{'success':![],'error':'Forward\x20\x27'+a3+'\x27\x20not\x20found\x20on\x20edge\x20\x27'+a1+'->'+a2+'\x27'};if(a4==='none')return a6['retained_submission']=null,{'success':!![]};const a7=a4['split'](',')['map'](a8=>{const a9=parseInt(a8['trim'](),0xa);if(isNaN(a9)||a9<0x0)return-0x1;return a9;});if(a7['some'](a8=>a8<0x0))return{'success':![],'error':'Invalid\x20retained_submission\x20indices:\x20'+a4+'\x20(must\x20be\x20comma-separated\x20non-negative\x20integers\x20or\x20\x27none\x27)'};return a6['retained_submission']=a7,{'success':!![]};}case'set_description':{const [a8,...a9]=a['args'],aa=b['find'](ac=>ac['name']===a8);if(!aa)return{'success':![],'error':'Node\x20\x27'+a8+'\x27\x20not\x20found'};const ab=a9['join']('\x20');return aa['description']=ab==='none'?null:ab,{'success':!![]};}default:return{'success':![],'error':'Unknown\x20operation\x20type:\x20'+a['type']};}}export async function handlePatchMachineNodes(a){const b=await resolveProjectId(a),c=await resolveObjectAddress(a),d=a['patch_operations']??[];if(d['length']===0x0)throw new Error('\x27patch_operations\x27\x20is\x20required\x20for\x20patch_machine_nodes\x20(non-empty\x20array)');const e=await localProject['getProject'](b);if(!e)throw new Error('Project\x20not\x20found\x20(id:\x20'+b+')');let f=null;try{const s=await LocalMark['Instance']()['get'](c);f=s?.['name']??null;}catch{}const g=e['network']??'testnet',h=await fetchCurrentMachine(c,g),i=h['nodes']['map'](t=>({...t})),j=h['edges']['map'](t=>({...t,'forwards':t['forwards']['map'](u=>({...u}))})),k=[];let l=0x0;for(const t of d){const u=parsePatchOperation(t);if(!u){k['push']({'operation':t,'error':'Invalid\x20operation\x20format.\x20See\x20patch_operations\x20schema\x20for\x20supported\x20formats.'});continue;}const w=applyPatchOperation(u,h['nodes'],h['edges']);w['success']?l++:k['push']({'operation':t,'error':w['error']??'Unknown\x20error'});}const m=diffMachine(i,j,h['nodes'],h['edges']),n=validateMachine(h['nodes'],h['edges']),o=[];for(const x of k){o['push']({'id':'E-OP','description':'Operation\x20\x27'+x['operation']+'\x27\x20failed:\x20'+x['error'],'impact':'This\x20operation\x20was\x20not\x20applied.\x20The\x20patch\x20cannot\x20be\x20executed\x20on-chain\x20until\x20all\x20operations\x20succeed.'});}for(const y of n['blocking_errors']){o['push'](y);}const p=o['length']===0x0,q=p?prepareMachineCall(f,c,h['nodes'],h['edges']):null,r='Patch:\x20'+l+'\x20applied,\x20'+k['length']+'\x20failed.\x20'+m['summary']+'.';return{'action':'patch_machine_nodes','machine_address':c,'machine_name':f,'operations_applied':l,'operations_failed':k,'patched_nodes':h['nodes'],'patched_edges':h['edges'],'diff':m,'warnings':n['warnings'],'blocking_errors':o['length']>0x0?o:[],'can_apply':p,'prepared_call':q,'summary':r};}function parseGuardPatchOperation(a){const b=a['trim']()['split'](/\s+/);if(b['length']<0x2)return null;const [c,d,...e]=b;if(c==='add'&&d==='table'&&e['length']>=0x4)return{'type':'add_table','args':e,'raw':a};if(c==='remove'&&d==='table'&&e['length']>=0x1)return{'type':'remove_table','args':e,'raw':a};if(c==='set'&&d==='table_value'&&e['length']>=0x2)return{'type':'set_table_value','args':e,'raw':a};if(c==='set'&&d==='table_name'&&e['length']>=0x2)return{'type':'set_table_name','args':e,'raw':a};if(c==='set'&&d==='table_submission'&&e['length']>=0x2)return{'type':'set_table_submission','args':e,'raw':a};if(c==='set'&&d==='root'&&e['length']>=0x1)return{'type':'set_root','args':e,'raw':a};if(c==='set'&&d==='rely'&&e['length']>=0x1)return{'type':'set_rely','args':e,'raw':a};return null;}function tryParseJSON(a){try{return JSON['parse'](a);}catch{return undefined;}}function applyGuardPatchOperation(a,b){switch(a['type']){case'add_table':{const [c,d,e,f,...g]=a['args'],h=parseInt(c,0xa);if(isNaN(h)||h<0x0)return{'success':![],'error':'Invalid\x20table\x20identifier:\x20'+c+'\x20(must\x20be\x20a\x20non-negative\x20integer)'};if(b['table']['some'](l=>l['identifier']===h))return{'success':![],'error':'Table\x20identifier\x20'+h+'\x20already\x20exists'};const i=f==='true',j=/^[0-9]+$/['test'](e)?parseInt(e,0xa):e;let k=undefined;if(g['length']>0x0){const l=g['join']('\x20');l!=='none'&&(k=tryParseJSON(l),k===undefined&&(k=l));}return b['table']['push']({'identifier':h,'name':d==='none'?undefined:d,'value_type':j,'b_submission':i,'value':k}),{'success':!![]};}case'remove_table':{const [m]=a['args'],n=parseInt(m,0xa);if(isNaN(n))return{'success':![],'error':'Invalid\x20table\x20identifier:\x20'+m};const o=b['table']['findIndex'](p=>p['identifier']===n);if(o===-0x1)return{'success':![],'error':'Table\x20identifier\x20'+n+'\x20not\x20found'};return b['table']['splice'](o,0x1),{'success':!![]};}case'set_table_value':{const [p,...q]=a['args'],r=parseInt(p,0xa);if(isNaN(r))return{'success':![],'error':'Invalid\x20table\x20identifier:\x20'+p};const s=b['table']['find'](u=>u['identifier']===r);if(!s)return{'success':![],'error':'Table\x20identifier\x20'+r+'\x20not\x20found'};const t=q['join']('\x20');if(t==='none')s['value']=undefined;else{const u=tryParseJSON(t);s['value']=u!==undefined?u:t;}return{'success':!![]};}case'set_table_name':{const [v,w,...x]=a['args'],y=parseInt(v,0xa);if(isNaN(y))return{'success':![],'error':'Invalid\x20table\x20identifier:\x20'+v};const z=b['table']['find'](B=>B['identifier']===y);if(!z)return{'success':![],'error':'Table\x20identifier\x20'+y+'\x20not\x20found'};const A=x['length']>0x0?[w,...x]['join']('\x20'):w;return z['name']=A==='none'?undefined:A,{'success':!![]};}case'set_table_submission':{const [B,C]=a['args'],D=parseInt(B,0xa);if(isNaN(D))return{'success':![],'error':'Invalid\x20table\x20identifier:\x20'+B};const E=b['table']['find'](F=>F['identifier']===D);if(!E)return{'success':![],'error':'Table\x20identifier\x20'+D+'\x20not\x20found'};if(C!=='true'&&C!=='false')return{'success':![],'error':'Invalid\x20b_submission\x20value:\x20'+C+'\x20(must\x20be\x20\x27true\x27\x20or\x20\x27false\x27)'};return E['b_submission']=C==='true',{'success':!![]};}case'set_root':{const F=a['args']['join']('\x20'),G=tryParseJSON(F);if(G===undefined||typeof G!=='object'||G===null)return{'success':![],'error':'Invalid\x20root\x20JSON:\x20\x27'+F['slice'](0x0,0x50)+'\x27\x20(must\x20be\x20a\x20valid\x20JSON\x20object)'};if(typeof G['type']!=='string')return{'success':![],'error':'Root\x20JSON\x20must\x20have\x20a\x20\x27type\x27\x20field\x20(string).\x20Got:\x20'+JSON['stringify'](Object['keys'](G))['slice'](0x0,0x50)};return{'success':!![],'newRoot':G};}case'set_rely':{const [H]=a['args'];if(H==='none')return b['rely']=null,{'success':!![]};const I=H['split'](',')['map'](J=>J['trim']())['filter'](J=>J['length']>0x0);if(I['length']===0x0)return{'success':![],'error':'Invalid\x20rely\x20value:\x20\x27'+H+'\x27\x20(expected\x20\x27none\x27\x20or\x20comma-separated\x20addresses)'};return b['rely']={'guards':I,'logic_or':b['rely']?.['logic_or']??![]},{'success':!![]};}default:return{'success':![],'error':'Unknown\x20Guard\x20patch\x20operation\x20type:\x20'+a['type']};}}export async function handlePatchGuardTree(a){const b=await resolveProjectId(a),c=await resolveObjectAddress(a),d=a['patch_operations']??[];if(d['length']===0x0)throw new Error('\x27patch_operations\x27\x20is\x20required\x20for\x20patch_guard_tree\x20(non-empty\x20array)');const e=await localProject['getProject'](b);if(!e)throw new Error('Project\x20not\x20found\x20(id:\x20'+b+')');let f=null;try{const w=await LocalMark['Instance']()['get'](c);f=w?.['name']??null;}catch{}const h=e['network']??'testnet',i=await fetchCurrentGuard(c,h),j=JSON['parse'](JSON['stringify'](i['root'])),k=i['table']['map'](x=>({...x,'value':x['value']!==undefined?JSON['parse'](JSON['stringify'](x['value'])):undefined})),l=i['rely']?{...i['rely'],'guards':[...i['rely']['guards']]}:null,m=[];let n=0x0,o=i['root'];for(const x of d){const y=parseGuardPatchOperation(x);if(!y){m['push']({'operation':x,'error':'Invalid\x20Guard\x20patch\x20operation\x20format.\x20See\x20patch_operations\x20schema\x20for\x20supported\x20formats.'});continue;}const z=applyGuardPatchOperation(y,{'root':o,'table':i['table'],'rely':i['rely']});z['success']?(n++,z['newRoot']&&(o=z['newRoot'])):m['push']({'operation':x,'error':z['error']??'Unknown\x20error'});}if(i['rely']&&Array['isArray'](i['rely']['guards'])){const A=[];for(const B of i['rely']['guards']){if(/^0x[0-9a-fA-F]{32,64}$/['test'](B))A['push'](B);else try{const C=await LocalMark['Instance']()['get'](B);C?.['address']?A['push'](C['address']):A['push'](B);}catch{A['push'](B);}}i['rely']['guards']=A;}const p=diffGuard(j,o,k,i['table']),q=validateGuard(o,i['table']),r=[];for(const D of m){r['push']({'id':'E-OP','description':'Operation\x20\x27'+D['operation']+'\x27\x20failed:\x20'+D['error'],'impact':'This\x20operation\x20was\x20not\x20applied.\x20The\x20patch\x20cannot\x20be\x20executed\x20on-chain\x20until\x20all\x20operations\x20succeed.'});}for(const E of q['blocking_errors']){r['push'](E);}const s=r['length']===0x0,t=s?prepareGuardCall(f,c,o,i['table'],i['rely']):null,u='Guard\x20patch:\x20'+n+'\x20applied,\x20'+m['length']+'\x20failed.\x20'+p['summary']+'.';return{'action':'patch_guard_tree','guard_address':c,'guard_name':f,'operations_applied':n,'operations_failed':m,'patched_root':o,'patched_table':i['table'],'patched_rely':i['rely'],'diff':p,'warnings':q['warnings'],'blocking_errors':r['length']>0x0?r:[],'can_apply':s,'prepared_call':t,'summary':u};}