@wowok/agent-mcp 2.7.1 → 2.7.3

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 (597) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/account-events.d.ts +32 -0
  4. package/dist/customer/account-events.js +1 -0
  5. package/dist/customer/customer-advice.d.ts +1 -0
  6. package/dist/customer/customer-advice.js +1 -130
  7. package/dist/customer/index.js +1 -11
  8. package/dist/customer/industry-risks.js +1 -438
  9. package/dist/customer/info-puzzle.js +1 -681
  10. package/dist/customer/order-monitor.js +1 -328
  11. package/dist/customer/order-strategy.d.ts +1 -1
  12. package/dist/customer/order-strategy.js +1 -373
  13. package/dist/customer/post-purchase.js +1 -351
  14. package/dist/customer/preorder-compare.js +1 -34
  15. package/dist/customer/reminder-system.d.ts +2 -0
  16. package/dist/customer/reminder-system.js +1 -316
  17. package/dist/customer/risk-assessment.d.ts +1 -0
  18. package/dist/customer/risk-assessment.js +1 -397
  19. package/dist/customer/types.d.ts +2 -0
  20. package/dist/customer/types.js +1 -13
  21. package/dist/customer/user-preferences.js +1 -460
  22. package/dist/evaluation/arbitration-game.d.ts +9 -2
  23. package/dist/evaluation/arbitration-game.js +1 -48
  24. package/dist/evaluation/builtins/arbitration-score.d.ts +41 -0
  25. package/dist/evaluation/builtins/arbitration-score.js +1 -0
  26. package/dist/evaluation/builtins/demand-match.js +1 -153
  27. package/dist/evaluation/builtins/index.d.ts +1 -0
  28. package/dist/evaluation/builtins/index.js +1 -10
  29. package/dist/evaluation/builtins/service-risk.js +1 -55
  30. package/dist/evaluation/capability.js +1 -13
  31. package/dist/evaluation/category-match-rules.d.ts +30 -0
  32. package/dist/evaluation/category-match-rules.js +1 -0
  33. package/dist/evaluation/composer.js +1 -40
  34. package/dist/evaluation/engine.js +1 -175
  35. package/dist/evaluation/extract.js +1 -115
  36. package/dist/evaluation/game-strategy.d.ts +27 -0
  37. package/dist/evaluation/game-strategy.js +1 -0
  38. package/dist/evaluation/gap.js +1 -100
  39. package/dist/evaluation/index.d.ts +2 -0
  40. package/dist/evaluation/index.js +1 -11
  41. package/dist/evaluation/location-match.d.ts +42 -0
  42. package/dist/evaluation/location-match.js +1 -0
  43. package/dist/evaluation/node-game.d.ts +31 -3
  44. package/dist/evaluation/node-game.js +1 -57
  45. package/dist/evaluation/path-reasoning.d.ts +35 -0
  46. package/dist/evaluation/path-reasoning.js +1 -0
  47. package/dist/evaluation/region.d.ts +6 -0
  48. package/dist/evaluation/region.js +1 -36
  49. package/dist/evaluation/types.d.ts +18 -0
  50. package/dist/evaluation/types.js +1 -1
  51. package/dist/evaluation/user-injection.js +1 -27
  52. package/dist/experience/experience-reuse.js +1 -103
  53. package/dist/experience/index.js +1 -5
  54. package/dist/experience/intent-distill.js +1 -83
  55. package/dist/experience/realtime-feedback.js +1 -94
  56. package/dist/experience/types.js +1 -1
  57. package/dist/experience/user-profile.d.ts +1 -1
  58. package/dist/experience/user-profile.js +1 -171
  59. package/dist/extensions/business-modules.js +1 -287
  60. package/dist/extensions/capability-manifest.js +1 -781
  61. package/dist/extensions/constraint-registry.js +1 -198
  62. package/dist/extensions/index.d.ts +6 -0
  63. package/dist/extensions/index.js +1 -6
  64. package/dist/extensions/industry-layers.d.ts +75 -0
  65. package/dist/extensions/industry-layers.js +1 -0
  66. package/dist/extensions/industry-pack.d.ts +105 -0
  67. package/dist/extensions/industry-pack.js +1 -0
  68. package/dist/extensions/metric-registry.js +1 -257
  69. package/dist/extensions/mode-evaluator.d.ts +1 -1
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.d.ts +1 -0
  73. package/dist/extensions/registry.js +1 -717
  74. package/dist/extensions/types.js +1 -1
  75. package/dist/graph/base.d.ts +8 -0
  76. package/dist/graph/base.js +1 -0
  77. package/dist/harness/auto-escalation.js +1 -68
  78. package/dist/harness/checkpoint.js +1 -129
  79. package/dist/harness/index.d.ts +1 -0
  80. package/dist/harness/index.js +1 -78
  81. package/dist/harness/plan.d.ts +2 -0
  82. package/dist/harness/plan.js +1 -315
  83. package/dist/harness/recover.d.ts +1 -1
  84. package/dist/harness/recover.js +1 -139
  85. package/dist/harness/types.d.ts +2 -3
  86. package/dist/harness/types.js +1 -1
  87. package/dist/harness/verify.js +1 -237
  88. package/dist/index.js +1 -273
  89. package/dist/intent/enrich.js +1 -67
  90. package/dist/intent/index.js +1 -60
  91. package/dist/intent/matcher.js +1 -81
  92. package/dist/intent/store.js +1 -55
  93. package/dist/intent/types.js +1 -10
  94. package/dist/knowledge/acquisition-flywheel.js +1 -192
  95. package/dist/knowledge/allocation-confirm.js +1 -534
  96. package/dist/knowledge/allocation-context.js +1 -249
  97. package/dist/knowledge/allocation-ledger.js +1 -463
  98. package/dist/knowledge/allocation-puzzle.js +1 -298
  99. package/dist/knowledge/allocation-risk.js +1 -568
  100. package/dist/knowledge/allocation-templates.js +1 -970
  101. package/dist/knowledge/allocation-translation.js +1 -585
  102. package/dist/knowledge/anti-cheat.d.ts +37 -0
  103. package/dist/knowledge/anti-cheat.js +1 -0
  104. package/dist/knowledge/arb-confirm.d.ts +28 -0
  105. package/dist/knowledge/arb-confirm.js +1 -0
  106. package/dist/knowledge/arb-risk.js +1 -210
  107. package/dist/knowledge/arb-translation.d.ts +48 -0
  108. package/dist/knowledge/arb-translation.js +1 -0
  109. package/dist/knowledge/arbitration-confirm.js +1 -559
  110. package/dist/knowledge/arbitration-context.js +1 -505
  111. package/dist/knowledge/arbitration-ledger.js +1 -521
  112. package/dist/knowledge/arbitration-puzzle.js +1 -304
  113. package/dist/knowledge/arbitration-risk.js +1 -423
  114. package/dist/knowledge/arbitration-templates.js +1 -276
  115. package/dist/knowledge/arbitration-translation.js +1 -487
  116. package/dist/knowledge/audit-rules.js +1 -141
  117. package/dist/knowledge/bridge-confirm.d.ts +26 -0
  118. package/dist/knowledge/bridge-confirm.js +1 -0
  119. package/dist/knowledge/bridge-risk.js +1 -263
  120. package/dist/knowledge/bridge-translation.d.ts +37 -0
  121. package/dist/knowledge/bridge-translation.js +1 -0
  122. package/dist/knowledge/contact-confirm.d.ts +27 -0
  123. package/dist/knowledge/contact-confirm.js +1 -0
  124. package/dist/knowledge/contact-risk.js +1 -200
  125. package/dist/knowledge/contact-templates.js +1 -60
  126. package/dist/knowledge/contact-translation.d.ts +39 -0
  127. package/dist/knowledge/contact-translation.js +1 -0
  128. package/dist/knowledge/demand-confirm.js +1 -206
  129. package/dist/knowledge/demand-context.d.ts +17 -0
  130. package/dist/knowledge/demand-context.js +1 -0
  131. package/dist/knowledge/demand-ledger.d.ts +26 -0
  132. package/dist/knowledge/demand-ledger.js +1 -0
  133. package/dist/knowledge/demand-matching.js +1 -132
  134. package/dist/knowledge/demand-puzzle.d.ts +29 -0
  135. package/dist/knowledge/demand-puzzle.js +1 -0
  136. package/dist/knowledge/demand-risk.js +1 -240
  137. package/dist/knowledge/demand-templates.d.ts +12 -0
  138. package/dist/knowledge/demand-templates.js +1 -0
  139. package/dist/knowledge/demand-translation.js +1 -354
  140. package/dist/knowledge/deployment-scanner.js +1 -823
  141. package/dist/knowledge/dynamic-pricing.js +1 -87
  142. package/dist/knowledge/evidence-review.d.ts +12 -0
  143. package/dist/knowledge/evidence-review.js +1 -0
  144. package/dist/knowledge/examples-scanner-cli.js +1 -26
  145. package/dist/knowledge/examples-scanner.js +1 -843
  146. package/dist/knowledge/flywheel-loop.d.ts +0 -1
  147. package/dist/knowledge/flywheel-loop.js +1 -404
  148. package/dist/knowledge/fund-layer.js +1 -973
  149. package/dist/knowledge/glossary.js +1 -211
  150. package/dist/knowledge/guard-confirm.js +1 -406
  151. package/dist/knowledge/guard-context.js +1 -287
  152. package/dist/knowledge/guard-design-patterns.js +1 -360
  153. package/dist/knowledge/guard-ledger.js +1 -260
  154. package/dist/knowledge/guard-lint.js +1 -670
  155. package/dist/knowledge/guard-migration.d.ts +1 -1
  156. package/dist/knowledge/guard-migration.js +1 -228
  157. package/dist/knowledge/guard-puzzle.js +1 -805
  158. package/dist/knowledge/guard-render.js +1 -700
  159. package/dist/knowledge/guard-risk.js +1 -1879
  160. package/dist/knowledge/guard-submission-prompt.js +1 -171
  161. package/dist/knowledge/guard-templates.js +1 -1105
  162. package/dist/knowledge/guard-translation.js +1 -1119
  163. package/dist/knowledge/index.d.ts +71 -3
  164. package/dist/knowledge/index.js +1 -436
  165. package/dist/knowledge/industry-evolution.js +1 -323
  166. package/dist/knowledge/industry-generalizer.js +1 -381
  167. package/dist/knowledge/industry-registry.js +1 -174
  168. package/dist/knowledge/intent-metrics.d.ts +4 -3
  169. package/dist/knowledge/intent-metrics.js +1 -566
  170. package/dist/knowledge/machine-confirm.js +1 -559
  171. package/dist/knowledge/machine-context.js +1 -833
  172. package/dist/knowledge/machine-ledger.js +1 -338
  173. package/dist/knowledge/machine-puzzle.js +1 -494
  174. package/dist/knowledge/machine-render.js +1 -565
  175. package/dist/knowledge/machine-risk.js +1 -669
  176. package/dist/knowledge/machine-templates.js +1 -1597
  177. package/dist/knowledge/machine-topology.js +1 -234
  178. package/dist/knowledge/machine-translation.js +1 -513
  179. package/dist/knowledge/market-metrics.d.ts +12 -0
  180. package/dist/knowledge/market-metrics.js +1 -0
  181. package/dist/knowledge/market-operations.d.ts +46 -0
  182. package/dist/knowledge/market-operations.js +1 -0
  183. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  184. package/dist/knowledge/mcp-schema-audit.d.ts +22 -22
  185. package/dist/knowledge/mcp-schema-audit.js +1 -777
  186. package/dist/knowledge/onchain-constants.js +1 -35
  187. package/dist/knowledge/order-confirm.js +1 -573
  188. package/dist/knowledge/order-context.js +1 -390
  189. package/dist/knowledge/order-ledger.js +1 -341
  190. package/dist/knowledge/order-puzzle.js +1 -255
  191. package/dist/knowledge/order-risk.js +1 -653
  192. package/dist/knowledge/order-templates.js +1 -368
  193. package/dist/knowledge/order-translation.js +1 -550
  194. package/dist/knowledge/overrides-loader.js +1 -65
  195. package/dist/knowledge/passport-confirm.js +1 -531
  196. package/dist/knowledge/passport-context.js +1 -306
  197. package/dist/knowledge/passport-ledger.js +1 -282
  198. package/dist/knowledge/passport-puzzle.js +1 -333
  199. package/dist/knowledge/passport-risk.js +1 -450
  200. package/dist/knowledge/passport-templates.js +1 -568
  201. package/dist/knowledge/passport-translation.js +1 -516
  202. package/dist/knowledge/payment-confirm.d.ts +26 -0
  203. package/dist/knowledge/payment-confirm.js +1 -0
  204. package/dist/knowledge/payment-risk.js +1 -249
  205. package/dist/knowledge/payment-translation.d.ts +37 -0
  206. package/dist/knowledge/payment-translation.js +1 -0
  207. package/dist/knowledge/permission-confirm.js +1 -426
  208. package/dist/knowledge/permission-context.js +1 -224
  209. package/dist/knowledge/permission-ledger.d.ts +11 -0
  210. package/dist/knowledge/permission-ledger.js +1 -403
  211. package/dist/knowledge/permission-puzzle.js +1 -173
  212. package/dist/knowledge/permission-risk.js +1 -411
  213. package/dist/knowledge/permission-templates.js +1 -234
  214. package/dist/knowledge/permission-translation.js +1 -350
  215. package/dist/knowledge/personal-confirm.d.ts +29 -0
  216. package/dist/knowledge/personal-confirm.js +1 -0
  217. package/dist/knowledge/personal-risk.js +1 -212
  218. package/dist/knowledge/personal-translation.d.ts +37 -0
  219. package/dist/knowledge/personal-translation.js +1 -0
  220. package/dist/knowledge/process-model.d.ts +1 -11
  221. package/dist/knowledge/process-model.js +1 -160
  222. package/dist/knowledge/progress-confirm.js +1 -456
  223. package/dist/knowledge/progress-context.js +1 -452
  224. package/dist/knowledge/progress-ledger.js +1 -330
  225. package/dist/knowledge/progress-puzzle.js +1 -219
  226. package/dist/knowledge/progress-risk.js +1 -461
  227. package/dist/knowledge/progress-templates.js +1 -228
  228. package/dist/knowledge/progress-translation.js +1 -405
  229. package/dist/knowledge/proof-confirm.js +1 -187
  230. package/dist/knowledge/proof-context.d.ts +17 -0
  231. package/dist/knowledge/proof-context.js +1 -0
  232. package/dist/knowledge/proof-ledger.d.ts +34 -0
  233. package/dist/knowledge/proof-ledger.js +1 -0
  234. package/dist/knowledge/proof-puzzle.d.ts +35 -0
  235. package/dist/knowledge/proof-puzzle.js +1 -0
  236. package/dist/knowledge/proof-risk.js +1 -207
  237. package/dist/knowledge/proof-templates.d.ts +22 -0
  238. package/dist/knowledge/proof-templates.js +1 -0
  239. package/dist/knowledge/proof-translation.js +1 -283
  240. package/dist/knowledge/registrar-confirm.d.ts +26 -0
  241. package/dist/knowledge/registrar-confirm.js +1 -0
  242. package/dist/knowledge/registrar-risk.js +1 -217
  243. package/dist/knowledge/registrar-translation.d.ts +37 -0
  244. package/dist/knowledge/registrar-translation.js +1 -0
  245. package/dist/knowledge/repository-confirm.js +1 -286
  246. package/dist/knowledge/repository-context.d.ts +12 -0
  247. package/dist/knowledge/repository-context.js +1 -0
  248. package/dist/knowledge/repository-ledger.d.ts +25 -0
  249. package/dist/knowledge/repository-ledger.js +1 -0
  250. package/dist/knowledge/repository-puzzle.d.ts +30 -0
  251. package/dist/knowledge/repository-puzzle.js +1 -0
  252. package/dist/knowledge/repository-risk.js +1 -373
  253. package/dist/knowledge/repository-templates.d.ts +14 -0
  254. package/dist/knowledge/repository-templates.js +1 -0
  255. package/dist/knowledge/repository-translation.js +1 -445
  256. package/dist/knowledge/reputation-rules.js +1 -99
  257. package/dist/knowledge/resource-confirm.d.ts +25 -0
  258. package/dist/knowledge/resource-confirm.js +1 -0
  259. package/dist/knowledge/resource-risk.js +1 -157
  260. package/dist/knowledge/resource-translation.d.ts +37 -0
  261. package/dist/knowledge/resource-translation.js +1 -0
  262. package/dist/knowledge/reward-confirm.js +1 -526
  263. package/dist/knowledge/reward-context.d.ts +2 -2
  264. package/dist/knowledge/reward-context.js +1 -504
  265. package/dist/knowledge/reward-ledger.js +1 -502
  266. package/dist/knowledge/reward-puzzle.js +1 -300
  267. package/dist/knowledge/reward-risk.js +1 -627
  268. package/dist/knowledge/reward-templates.js +1 -197
  269. package/dist/knowledge/reward-translation.js +1 -501
  270. package/dist/knowledge/safety-rules.d.ts +1 -0
  271. package/dist/knowledge/safety-rules.js +1 -404
  272. package/dist/knowledge/scenario-modes.js +1 -321
  273. package/dist/knowledge/service-confirm.js +1 -807
  274. package/dist/knowledge/service-context.js +1 -403
  275. package/dist/knowledge/service-ledger.js +1 -609
  276. package/dist/knowledge/service-puzzle.js +1 -236
  277. package/dist/knowledge/service-risk.d.ts +1 -1
  278. package/dist/knowledge/service-risk.js +1 -651
  279. package/dist/knowledge/service-templates.js +1 -456
  280. package/dist/knowledge/service-translation.js +1 -622
  281. package/dist/knowledge/template-registry.js +1 -353
  282. package/dist/knowledge/tool-constraints.js +1 -195
  283. package/dist/knowledge/tools-reference.js +1 -178
  284. package/dist/knowledge/treasury-confirm.js +1 -512
  285. package/dist/knowledge/treasury-context.js +1 -363
  286. package/dist/knowledge/treasury-ledger.js +1 -300
  287. package/dist/knowledge/treasury-puzzle.js +1 -216
  288. package/dist/knowledge/treasury-risk.js +1 -440
  289. package/dist/knowledge/treasury-templates.js +1 -358
  290. package/dist/knowledge/treasury-translation.js +1 -498
  291. package/dist/knowledge/trust-metrics.js +1 -198
  292. package/dist/knowledge/universal-template.d.ts +22 -0
  293. package/dist/knowledge/universal-template.js +1 -0
  294. package/dist/knowledge/util-confirm.d.ts +24 -0
  295. package/dist/knowledge/util-confirm.js +1 -0
  296. package/dist/knowledge/util-risk.js +1 -135
  297. package/dist/knowledge/util-translation.d.ts +38 -0
  298. package/dist/knowledge/util-translation.js +1 -0
  299. package/dist/knowledge/workflow-guidance.d.ts +116 -0
  300. package/dist/knowledge/workflow-guidance.js +1 -0
  301. package/dist/loop-engineering/aggregate.js +1 -132
  302. package/dist/loop-engineering/context-collect.js +1 -83
  303. package/dist/loop-engineering/diagnose.js +1 -273
  304. package/dist/loop-engineering/improve.js +1 -405
  305. package/dist/loop-engineering/index.js +1 -4
  306. package/dist/loop-engineering/pipeline.js +1 -56
  307. package/dist/mode-market/index.js +1 -3
  308. package/dist/mode-market/registry.js +1 -124
  309. package/dist/mode-market/review.js +1 -214
  310. package/dist/mode-market/submission.js +1 -85
  311. package/dist/participation/collaborator-interest.d.ts +23 -0
  312. package/dist/participation/collaborator-interest.js +1 -0
  313. package/dist/participation/customer-interest.d.ts +25 -0
  314. package/dist/participation/customer-interest.js +1 -0
  315. package/dist/participation/employee-kpi.d.ts +25 -0
  316. package/dist/participation/employee-kpi.js +1 -0
  317. package/dist/participation/employee-store.d.ts +16 -0
  318. package/dist/participation/employee-store.js +1 -0
  319. package/dist/participation/index.d.ts +2 -0
  320. package/dist/participation/index.js +1 -0
  321. package/dist/participation/merchant-interest.js +1 -100
  322. package/dist/participation/radar-core.d.ts +13 -3
  323. package/dist/participation/radar-core.js +1 -269
  324. package/dist/participation/supplier-interest.d.ts +25 -0
  325. package/dist/participation/supplier-interest.js +1 -0
  326. package/dist/persona/analyzer.js +1 -66
  327. package/dist/persona/bridge.js +1 -86
  328. package/dist/persona/defaults.js +1 -195
  329. package/dist/persona/experience-bridge.js +1 -23
  330. package/dist/persona/index.d.ts +9 -2
  331. package/dist/persona/index.js +1 -71
  332. package/dist/persona/local-region.d.ts +20 -0
  333. package/dist/persona/local-region.js +1 -0
  334. package/dist/persona/model.js +1 -111
  335. package/dist/persona/overrides.d.ts +10 -0
  336. package/dist/persona/overrides.js +1 -0
  337. package/dist/persona/pack-personae.d.ts +11 -0
  338. package/dist/persona/pack-personae.js +1 -0
  339. package/dist/persona/store.js +1 -62
  340. package/dist/persona/strategy-intent.d.ts +20 -0
  341. package/dist/persona/strategy-intent.js +1 -0
  342. package/dist/persona/types.d.ts +6 -2
  343. package/dist/persona/types.js +1 -5
  344. package/dist/project/business-puzzle.d.ts +1 -1
  345. package/dist/project/business-puzzle.js +1 -383
  346. package/dist/project/context-assembly.js +1 -254
  347. package/dist/project/deployment-bridge.js +1 -120
  348. package/dist/project/deployment-doc.js +1 -1126
  349. package/dist/project/edit-planner.js +1 -1342
  350. package/dist/project/evaluation.d.ts +37 -1
  351. package/dist/project/evaluation.js +1 -2011
  352. package/dist/project/game-theory.js +1 -177
  353. package/dist/project/graph-builder.js +1 -656
  354. package/dist/project/graph.d.ts +3 -6
  355. package/dist/project/graph.js +1 -340
  356. package/dist/project/handlers.d.ts +33 -2
  357. package/dist/project/handlers.js +1 -1784
  358. package/dist/project/index.d.ts +2 -0
  359. package/dist/project/index.js +1 -301
  360. package/dist/project/intent-analyzer.js +1 -149
  361. package/dist/project/machine-nodes.js +1 -36
  362. package/dist/project/merchant-guide.d.ts +19 -0
  363. package/dist/project/merchant-guide.js +1 -264
  364. package/dist/project/migration.js +1 -125
  365. package/dist/project/mode-actions.js +1 -309
  366. package/dist/project/namespace.js +1 -206
  367. package/dist/project/participation-radar.js +1 -428
  368. package/dist/project/pipeline-actions.js +1 -109
  369. package/dist/project/project-store.js +1 -422
  370. package/dist/project/query.js +1 -153
  371. package/dist/project/reverse-mapping.d.ts +34 -0
  372. package/dist/project/reverse-mapping.js +1 -0
  373. package/dist/project/risk-aggregator.js +1 -295
  374. package/dist/project/rollback-policy.js +1 -290
  375. package/dist/project/semantic-assembler.js +1 -345
  376. package/dist/project/semantic-graph.d.ts +3 -5
  377. package/dist/project/semantic-graph.js +1 -292
  378. package/dist/project/stage-gate.js +1 -369
  379. package/dist/project/substep-trace.js +1 -332
  380. package/dist/project/task-tracker.js +1 -78
  381. package/dist/project/workflow-design-assessment.d.ts +24 -0
  382. package/dist/project/workflow-design-assessment.js +1 -0
  383. package/dist/role/derivation.d.ts +18 -0
  384. package/dist/role/derivation.js +1 -0
  385. package/dist/role/index.d.ts +5 -0
  386. package/dist/role/index.js +1 -0
  387. package/dist/role/model.d.ts +8 -0
  388. package/dist/role/model.js +1 -0
  389. package/dist/role/resolution.d.ts +11 -0
  390. package/dist/role/resolution.js +1 -0
  391. package/dist/role/types.d.ts +11 -0
  392. package/dist/role/types.js +1 -0
  393. package/dist/rules.js +1 -52
  394. package/dist/safety/confirm-gate.d.ts +1 -1
  395. package/dist/safety/confirm-gate.js +1 -88
  396. package/dist/safety/index.js +1 -3
  397. package/dist/safety/preview.js +1 -52
  398. package/dist/schema/call/allocation.d.ts +186 -1385
  399. package/dist/schema/call/allocation.js +1 -34
  400. package/dist/schema/call/arbitration.d.ts +272 -1871
  401. package/dist/schema/call/arbitration.js +1 -113
  402. package/dist/schema/call/base.d.ts +1831 -9076
  403. package/dist/schema/call/base.js +1 -370
  404. package/dist/schema/call/bridge.d.ts +911 -3171
  405. package/dist/schema/call/bridge.js +1 -458
  406. package/dist/schema/call/contact.d.ts +135 -931
  407. package/dist/schema/call/contact.js +1 -37
  408. package/dist/schema/call/demand.d.ts +164 -1194
  409. package/dist/schema/call/demand.js +1 -47
  410. package/dist/schema/call/guard.d.ts +298 -1140
  411. package/dist/schema/call/guard.js +1 -161
  412. package/dist/schema/call/handler.js +1 -322
  413. package/dist/schema/call/index.js +1 -20
  414. package/dist/schema/call/machine.d.ts +459 -5403
  415. package/dist/schema/call/machine.js +1 -193
  416. package/dist/schema/call/order.d.ts +137 -844
  417. package/dist/schema/call/order.js +1 -35
  418. package/dist/schema/call/payment.d.ts +74 -561
  419. package/dist/schema/call/payment.js +1 -37
  420. package/dist/schema/call/permission-handler.js +1 -54
  421. package/dist/schema/call/permission.d.ts +335 -2791
  422. package/dist/schema/call/permission.js +1 -105
  423. package/dist/schema/call/personal.d.ts +227 -1814
  424. package/dist/schema/call/personal.js +1 -78
  425. package/dist/schema/call/progress.d.ts +140 -843
  426. package/dist/schema/call/progress.js +1 -47
  427. package/dist/schema/call/proof.d.ts +42 -258
  428. package/dist/schema/call/proof.js +1 -33
  429. package/dist/schema/call/repository.d.ts +324 -2222
  430. package/dist/schema/call/repository.js +1 -77
  431. package/dist/schema/call/reward.d.ts +153 -1183
  432. package/dist/schema/call/reward.js +1 -30
  433. package/dist/schema/call/semantic.js +1 -1679
  434. package/dist/schema/call/service.d.ts +376 -3431
  435. package/dist/schema/call/service.js +1 -184
  436. package/dist/schema/call/treasury.d.ts +252 -2158
  437. package/dist/schema/call/treasury.js +1 -71
  438. package/dist/schema/common/index.d.ts +222 -697
  439. package/dist/schema/common/index.js +1 -407
  440. package/dist/schema/config/index.d.ts +18 -161
  441. package/dist/schema/config/index.js +1 -68
  442. package/dist/schema/employee/index.d.ts +99 -0
  443. package/dist/schema/employee/index.js +1 -0
  444. package/dist/schema/evaluation/index.d.ts +1062 -3748
  445. package/dist/schema/evaluation/index.js +1 -356
  446. package/dist/schema/index.d.ts +3 -0
  447. package/dist/schema/index.js +1 -17
  448. package/dist/schema/industry-pack/index.d.ts +132 -0
  449. package/dist/schema/industry-pack/index.js +1 -0
  450. package/dist/schema/intent-radar/index.d.ts +92 -245
  451. package/dist/schema/intent-radar/index.js +1 -89
  452. package/dist/schema/local/index.d.ts +2045 -18080
  453. package/dist/schema/local/index.js +1 -927
  454. package/dist/schema/local/wip.d.ts +61 -651
  455. package/dist/schema/local/wip.js +1 -187
  456. package/dist/schema/messenger/index.d.ts +949 -5557
  457. package/dist/schema/messenger/index.js +1 -475
  458. package/dist/schema/operations.d.ts +2969 -26518
  459. package/dist/schema/operations.js +1 -520
  460. package/dist/schema/persona/index.d.ts +469 -1820
  461. package/dist/schema/persona/index.js +1 -148
  462. package/dist/schema/project/index.d.ts +1027 -8408
  463. package/dist/schema/project/index.js +1 -2057
  464. package/dist/schema/query/index.d.ts +12041 -75261
  465. package/dist/schema/query/index.js +1 -1646
  466. package/dist/schema/schema-query/index.d.ts +35 -98
  467. package/dist/schema/schema-query/index.js +1 -104
  468. package/dist/schema/schema-version.js +1 -76
  469. package/dist/schema/task-status.d.ts +26 -132
  470. package/dist/schema/task-status.js +1 -36
  471. package/dist/schema/trust/index.d.ts +194 -1290
  472. package/dist/schema/trust/index.js +1 -314
  473. package/dist/schema/utils/guard-parser.js +1 -419
  474. package/dist/schema/utils/guard-query-utils.js +1 -46
  475. package/dist/schema/utils/node-parser.js +1 -369
  476. package/dist/schema/utils/object-type-utils.js +1 -35
  477. package/dist/schema/utils/permission-index-utils.js +1 -7
  478. package/dist/schema/utils/permission-machine-check.js +1 -121
  479. package/dist/schema/utils/skills-recommendation.d.ts +1 -0
  480. package/dist/schema/utils/skills-recommendation.js +1 -77
  481. package/dist/schema/workspace/index.d.ts +69 -0
  482. package/dist/schema/workspace/index.js +1 -0
  483. package/dist/schema-query-impl/index.js +1 -0
  484. package/dist/schemas/account_operation.output.json +3147 -1652
  485. package/dist/schemas/account_operation.schema.json +225 -218
  486. package/dist/schemas/bridge_operation.output.json +1168 -650
  487. package/dist/schemas/bridge_operation.schema.json +736 -504
  488. package/dist/schemas/config_operation.output.json +185 -179
  489. package/dist/schemas/config_operation.schema.json +21 -26
  490. package/dist/schemas/employee_operation.output.json +207 -0
  491. package/dist/schemas/employee_operation.schema.json +176 -0
  492. package/dist/schemas/evaluation_operation.output.json +2329 -557
  493. package/dist/schemas/evaluation_operation.schema.json +2939 -720
  494. package/dist/schemas/guard2file.output.json +58 -64
  495. package/dist/schemas/guard2file.schema.json +79 -81
  496. package/dist/schemas/index.json +29 -11
  497. package/dist/schemas/industry_pack_operation.output.json +594 -0
  498. package/dist/schemas/industry_pack_operation.schema.json +55 -0
  499. package/dist/schemas/intent_radar.output.json +275 -200
  500. package/dist/schemas/intent_radar.schema.json +124 -123
  501. package/dist/schemas/local_info_operation.output.json +1174 -657
  502. package/dist/schemas/local_info_operation.schema.json +119 -125
  503. package/dist/schemas/local_mark_operation.output.json +1239 -689
  504. package/dist/schemas/local_mark_operation.schema.json +91 -96
  505. package/dist/schemas/machineNode2file.output.json +63 -69
  506. package/dist/schemas/machineNode2file.schema.json +79 -81
  507. package/dist/schemas/messenger_operation.output.json +2722 -1528
  508. package/dist/schemas/messenger_operation.schema.json +1482 -1264
  509. package/dist/schemas/onchain_events.output.json +2590 -975
  510. package/dist/schemas/onchain_events.schema.json +117 -99
  511. package/dist/schemas/onchain_operations.output.json +3957 -2309
  512. package/dist/schemas/onchain_operations.schema.json +20799 -9285
  513. package/dist/schemas/onchain_operations_allocation.schema.json +172 -108
  514. package/dist/schemas/onchain_operations_arbitration.schema.json +233 -146
  515. package/dist/schemas/onchain_operations_contact.schema.json +129 -90
  516. package/dist/schemas/onchain_operations_demand.schema.json +170 -112
  517. package/dist/schemas/onchain_operations_gen_passport.schema.json +61 -646
  518. package/dist/schemas/onchain_operations_gen_proof.schema.json +40 -172
  519. package/dist/schemas/onchain_operations_guard.schema.json +3765 -294
  520. package/dist/schemas/onchain_operations_machine.schema.json +537 -164
  521. package/dist/schemas/onchain_operations_order.schema.json +126 -96
  522. package/dist/schemas/onchain_operations_payment.schema.json +82 -67
  523. package/dist/schemas/onchain_operations_permission.schema.json +331 -93
  524. package/dist/schemas/onchain_operations_personal.schema.json +636 -96
  525. package/dist/schemas/onchain_operations_progress.schema.json +125 -92
  526. package/dist/schemas/onchain_operations_proof.schema.json +76 -69
  527. package/dist/schemas/onchain_operations_repository.schema.json +636 -249
  528. package/dist/schemas/onchain_operations_reward.schema.json +218 -108
  529. package/dist/schemas/onchain_operations_service.schema.json +679 -221
  530. package/dist/schemas/onchain_operations_treasury.schema.json +401 -135
  531. package/dist/schemas/onchain_table_data.output.json +6018 -2430
  532. package/dist/schemas/onchain_table_data.schema.json +544 -430
  533. package/dist/schemas/persona_operation.output.json +1568 -265
  534. package/dist/schemas/persona_operation.schema.json +346 -202
  535. package/dist/schemas/project_operation.output.json +6957 -5147
  536. package/dist/schemas/project_operation.schema.json +1050 -1020
  537. package/dist/schemas/query_task_status.output.json +195 -99
  538. package/dist/schemas/query_task_status.schema.json +12 -18
  539. package/dist/schemas/query_toolkit.output.json +18870 -14566
  540. package/dist/schemas/query_toolkit.schema.json +614 -522
  541. package/dist/schemas/schema_query.output.json +127 -129
  542. package/dist/schemas/schema_query.schema.json +64 -69
  543. package/dist/schemas/trust_score.output.json +678 -587
  544. package/dist/schemas/trust_score.schema.json +289 -277
  545. package/dist/schemas/wip_file.output.json +116 -124
  546. package/dist/schemas/wip_file.schema.json +142 -143
  547. package/dist/schemas/workspace_operation.output.json +277 -0
  548. package/dist/schemas/workspace_operation.schema.json +45 -0
  549. package/dist/schemas/wowok_buildin_info.output.json +1693 -723
  550. package/dist/schemas/wowok_buildin_info.schema.json +576 -512
  551. package/dist/telemetry/index.js +1 -112
  552. package/dist/telemetry/redact.js +1 -23
  553. package/dist/telemetry/storage.js +1 -80
  554. package/dist/tools/handlers/bridge.d.ts +8 -1
  555. package/dist/tools/handlers/bridge.js +1 -1
  556. package/dist/tools/handlers/config.js +1 -74
  557. package/dist/tools/handlers/employee.d.ts +2 -0
  558. package/dist/tools/handlers/employee.js +1 -0
  559. package/dist/tools/handlers/evaluation.js +1 -123
  560. package/dist/tools/handlers/file-export.js +1 -90
  561. package/dist/tools/handlers/industry-pack.d.ts +2 -0
  562. package/dist/tools/handlers/industry-pack.js +1 -0
  563. package/dist/tools/handlers/intent-radar.js +1 -76
  564. package/dist/tools/handlers/local.js +1 -53
  565. package/dist/tools/handlers/messenger.js +1 -188
  566. package/dist/tools/handlers/onchain.js +1 -1180
  567. package/dist/tools/handlers/persona.js +1 -89
  568. package/dist/tools/handlers/project.js +1 -211
  569. package/dist/tools/handlers/query.js +1 -434
  570. package/dist/tools/handlers/schema-query.js +1 -176
  571. package/dist/tools/handlers/task-status.js +1 -26
  572. package/dist/tools/handlers/trust.js +1 -380
  573. package/dist/tools/handlers/wip.js +1 -90
  574. package/dist/tools/handlers/workspace.d.ts +2 -0
  575. package/dist/tools/handlers/workspace.js +1 -0
  576. package/dist/tools/index.d.ts +2 -1
  577. package/dist/tools/index.js +1 -1382
  578. package/dist/tools/retry.js +1 -85
  579. package/dist/tools/rules-hook.d.ts +1 -1
  580. package/dist/tools/rules-hook.js +1 -23
  581. package/dist/tools/shared.d.ts +1 -1
  582. package/dist/tools/shared.js +1 -130
  583. package/dist/tools/types.d.ts +2 -1
  584. package/dist/tools/types.js +1 -1
  585. package/dist/tools/upgrade-check.d.ts +19 -0
  586. package/dist/tools/upgrade-check.js +1 -0
  587. package/dist/tools/wip-deploy-assist.js +1 -306
  588. package/dist/tools/wrap.js +1 -500
  589. package/package.json +7 -6
  590. package/dist/knowledge/arbitration-trust.d.ts +0 -24
  591. package/dist/knowledge/arbitration-trust.js +0 -117
  592. package/dist/schema/call/bridge-handler.d.ts +0 -8
  593. package/dist/schema/call/bridge-handler.js +0 -265
  594. package/dist/schema/sync-layer4.d.ts +0 -21
  595. package/dist/schema/sync-layer4.js +0 -286
  596. package/dist/schema-query/index.js +0 -810
  597. /package/dist/{schema-query → schema-query-impl}/index.d.ts +0 -0
@@ -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 u=await LocalMark['Instance']()['get'](c);f=u?.['name']??null;}catch{}const h=e['network']??'testnet',i=await fetchCurrentGuard(c,h),j=JSON['parse'](JSON['stringify'](i['root'])),k=i['table']['map'](w=>({...w,'value':w['value']!==undefined?JSON['parse'](JSON['stringify'](w['value'])):undefined})),l=[];let m=0x0,n=i['root'];for(const w of d){const x=parseGuardPatchOperation(w);if(!x){l['push']({'operation':w,'error':'Invalid\x20Guard\x20patch\x20operation\x20format.\x20See\x20patch_operations\x20schema\x20for\x20supported\x20formats.'});continue;}const y=applyGuardPatchOperation(x,{'root':n,'table':i['table'],'rely':i['rely']});y['success']?(m++,y['newRoot']&&(n=y['newRoot'])):l['push']({'operation':w,'error':y['error']??'Unknown\x20error'});}if(i['rely']&&Array['isArray'](i['rely']['guards'])){const z=[];for(const A of i['rely']['guards']){if(/^0x[0-9a-fA-F]{32,64}$/['test'](A))z['push'](A);else try{const B=await LocalMark['Instance']()['get'](A);B?.['address']?z['push'](B['address']):z['push'](A);}catch{z['push'](A);}}i['rely']['guards']=z;}const o=diffGuard(j,n,k,i['table']),p=validateGuard(n,i['table']),q=[];for(const C of l){q['push']({'id':'E-OP','description':'Operation\x20\x27'+C['operation']+'\x27\x20failed:\x20'+C['error'],'impact':'This\x20operation\x20was\x20not\x20applied.\x20The\x20patch\x20cannot\x20be\x20executed\x20on-chain\x20until\x20all\x20operations\x20succeed.'});}for(const D of p['blocking_errors']){q['push'](D);}const r=q['length']===0x0,s=r?prepareGuardCall(f,c,n,i['table'],i['rely']):null,t='Guard\x20patch:\x20'+m+'\x20applied,\x20'+l['length']+'\x20failed.\x20'+o['summary']+'.';return{'action':'patch_guard_tree','guard_address':c,'guard_name':f,'operations_applied':m,'operations_failed':l,'patched_root':n,'patched_table':i['table'],'patched_rely':i['rely'],'diff':o,'warnings':p['warnings'],'blocking_errors':q['length']>0x0?q:[],'can_apply':r,'prepared_call':s,'summary':t};}