@wowok/agent-mcp 2.7.1 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.js +1 -397
  13. package/dist/customer/types.js +1 -13
  14. package/dist/customer/user-preferences.js +1 -460
  15. package/dist/evaluation/arbitration-game.d.ts +9 -2
  16. package/dist/evaluation/arbitration-game.js +1 -48
  17. package/dist/evaluation/builtins/demand-match.js +1 -153
  18. package/dist/evaluation/builtins/index.js +1 -10
  19. package/dist/evaluation/builtins/service-risk.js +1 -55
  20. package/dist/evaluation/capability.js +1 -13
  21. package/dist/evaluation/composer.js +1 -40
  22. package/dist/evaluation/engine.js +1 -175
  23. package/dist/evaluation/extract.js +1 -115
  24. package/dist/evaluation/game-strategy.d.ts +27 -0
  25. package/dist/evaluation/game-strategy.js +1 -0
  26. package/dist/evaluation/gap.js +1 -100
  27. package/dist/evaluation/index.d.ts +1 -0
  28. package/dist/evaluation/index.js +1 -11
  29. package/dist/evaluation/node-game.d.ts +31 -3
  30. package/dist/evaluation/node-game.js +1 -57
  31. package/dist/evaluation/region.js +1 -36
  32. package/dist/evaluation/types.d.ts +1 -0
  33. package/dist/evaluation/types.js +1 -1
  34. package/dist/evaluation/user-injection.js +1 -27
  35. package/dist/experience/experience-reuse.js +1 -103
  36. package/dist/experience/index.js +1 -5
  37. package/dist/experience/intent-distill.js +1 -83
  38. package/dist/experience/realtime-feedback.js +1 -94
  39. package/dist/experience/types.js +1 -1
  40. package/dist/experience/user-profile.js +1 -171
  41. package/dist/extensions/business-modules.js +1 -287
  42. package/dist/extensions/capability-manifest.js +1 -781
  43. package/dist/extensions/constraint-registry.js +1 -198
  44. package/dist/extensions/index.js +1 -6
  45. package/dist/extensions/metric-registry.js +1 -257
  46. package/dist/extensions/mode-evaluator.js +1 -170
  47. package/dist/extensions/modes.js +1 -499
  48. package/dist/extensions/registry.js +1 -717
  49. package/dist/extensions/types.js +1 -1
  50. package/dist/harness/auto-escalation.js +1 -68
  51. package/dist/harness/checkpoint.js +1 -129
  52. package/dist/harness/index.js +1 -78
  53. package/dist/harness/plan.js +1 -315
  54. package/dist/harness/recover.js +1 -139
  55. package/dist/harness/types.js +1 -1
  56. package/dist/harness/verify.js +1 -237
  57. package/dist/index.js +1 -273
  58. package/dist/intent/enrich.js +1 -67
  59. package/dist/intent/index.js +1 -60
  60. package/dist/intent/matcher.js +1 -81
  61. package/dist/intent/store.js +1 -55
  62. package/dist/intent/types.js +1 -10
  63. package/dist/knowledge/acquisition-flywheel.js +1 -192
  64. package/dist/knowledge/allocation-confirm.js +1 -534
  65. package/dist/knowledge/allocation-context.js +1 -249
  66. package/dist/knowledge/allocation-ledger.js +1 -463
  67. package/dist/knowledge/allocation-puzzle.js +1 -298
  68. package/dist/knowledge/allocation-risk.js +1 -568
  69. package/dist/knowledge/allocation-templates.js +1 -970
  70. package/dist/knowledge/allocation-translation.js +1 -585
  71. package/dist/knowledge/arb-risk.js +1 -210
  72. package/dist/knowledge/arbitration-confirm.js +1 -559
  73. package/dist/knowledge/arbitration-context.js +1 -505
  74. package/dist/knowledge/arbitration-ledger.js +1 -521
  75. package/dist/knowledge/arbitration-puzzle.js +1 -304
  76. package/dist/knowledge/arbitration-risk.js +1 -423
  77. package/dist/knowledge/arbitration-templates.js +1 -276
  78. package/dist/knowledge/arbitration-translation.js +1 -487
  79. package/dist/knowledge/arbitration-trust.js +1 -117
  80. package/dist/knowledge/audit-rules.js +1 -141
  81. package/dist/knowledge/bridge-risk.js +1 -263
  82. package/dist/knowledge/contact-risk.js +1 -200
  83. package/dist/knowledge/contact-templates.js +1 -60
  84. package/dist/knowledge/demand-confirm.js +1 -206
  85. package/dist/knowledge/demand-matching.js +1 -132
  86. package/dist/knowledge/demand-risk.js +1 -240
  87. package/dist/knowledge/demand-translation.js +1 -354
  88. package/dist/knowledge/deployment-scanner.js +1 -823
  89. package/dist/knowledge/dynamic-pricing.js +1 -87
  90. package/dist/knowledge/examples-scanner-cli.js +1 -26
  91. package/dist/knowledge/examples-scanner.js +1 -843
  92. package/dist/knowledge/flywheel-loop.js +1 -404
  93. package/dist/knowledge/fund-layer.js +1 -973
  94. package/dist/knowledge/glossary.js +1 -211
  95. package/dist/knowledge/guard-confirm.js +1 -406
  96. package/dist/knowledge/guard-context.js +1 -287
  97. package/dist/knowledge/guard-design-patterns.js +1 -360
  98. package/dist/knowledge/guard-ledger.js +1 -260
  99. package/dist/knowledge/guard-lint.js +1 -670
  100. package/dist/knowledge/guard-migration.js +1 -228
  101. package/dist/knowledge/guard-puzzle.js +1 -805
  102. package/dist/knowledge/guard-render.js +1 -700
  103. package/dist/knowledge/guard-risk.js +1 -1879
  104. package/dist/knowledge/guard-submission-prompt.js +1 -171
  105. package/dist/knowledge/guard-templates.js +1 -1105
  106. package/dist/knowledge/guard-translation.js +1 -1119
  107. package/dist/knowledge/index.js +1 -436
  108. package/dist/knowledge/industry-evolution.js +1 -323
  109. package/dist/knowledge/industry-generalizer.js +1 -381
  110. package/dist/knowledge/industry-registry.js +1 -174
  111. package/dist/knowledge/intent-metrics.d.ts +4 -3
  112. package/dist/knowledge/intent-metrics.js +1 -566
  113. package/dist/knowledge/machine-confirm.js +1 -559
  114. package/dist/knowledge/machine-context.js +1 -833
  115. package/dist/knowledge/machine-ledger.js +1 -338
  116. package/dist/knowledge/machine-puzzle.js +1 -494
  117. package/dist/knowledge/machine-render.js +1 -565
  118. package/dist/knowledge/machine-risk.js +1 -669
  119. package/dist/knowledge/machine-templates.js +1 -1597
  120. package/dist/knowledge/machine-topology.js +1 -234
  121. package/dist/knowledge/machine-translation.js +1 -513
  122. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  123. package/dist/knowledge/mcp-schema-audit.js +1 -777
  124. package/dist/knowledge/onchain-constants.js +1 -35
  125. package/dist/knowledge/order-confirm.js +1 -573
  126. package/dist/knowledge/order-context.js +1 -390
  127. package/dist/knowledge/order-ledger.js +1 -341
  128. package/dist/knowledge/order-puzzle.js +1 -255
  129. package/dist/knowledge/order-risk.js +1 -653
  130. package/dist/knowledge/order-templates.js +1 -368
  131. package/dist/knowledge/order-translation.js +1 -550
  132. package/dist/knowledge/overrides-loader.js +1 -65
  133. package/dist/knowledge/passport-confirm.js +1 -531
  134. package/dist/knowledge/passport-context.js +1 -306
  135. package/dist/knowledge/passport-ledger.js +1 -282
  136. package/dist/knowledge/passport-puzzle.js +1 -333
  137. package/dist/knowledge/passport-risk.js +1 -450
  138. package/dist/knowledge/passport-templates.js +1 -568
  139. package/dist/knowledge/passport-translation.js +1 -516
  140. package/dist/knowledge/payment-risk.js +1 -249
  141. package/dist/knowledge/permission-confirm.js +1 -426
  142. package/dist/knowledge/permission-context.js +1 -224
  143. package/dist/knowledge/permission-ledger.js +1 -403
  144. package/dist/knowledge/permission-puzzle.js +1 -173
  145. package/dist/knowledge/permission-risk.js +1 -411
  146. package/dist/knowledge/permission-templates.js +1 -234
  147. package/dist/knowledge/permission-translation.js +1 -350
  148. package/dist/knowledge/personal-risk.js +1 -212
  149. package/dist/knowledge/process-model.js +1 -160
  150. package/dist/knowledge/progress-confirm.js +1 -456
  151. package/dist/knowledge/progress-context.js +1 -452
  152. package/dist/knowledge/progress-ledger.js +1 -330
  153. package/dist/knowledge/progress-puzzle.js +1 -219
  154. package/dist/knowledge/progress-risk.js +1 -461
  155. package/dist/knowledge/progress-templates.js +1 -228
  156. package/dist/knowledge/progress-translation.js +1 -405
  157. package/dist/knowledge/proof-confirm.js +1 -187
  158. package/dist/knowledge/proof-risk.js +1 -207
  159. package/dist/knowledge/proof-translation.js +1 -283
  160. package/dist/knowledge/registrar-risk.js +1 -217
  161. package/dist/knowledge/repository-confirm.js +1 -286
  162. package/dist/knowledge/repository-risk.js +1 -373
  163. package/dist/knowledge/repository-translation.js +1 -445
  164. package/dist/knowledge/reputation-rules.js +1 -99
  165. package/dist/knowledge/resource-risk.js +1 -157
  166. package/dist/knowledge/reward-confirm.js +1 -526
  167. package/dist/knowledge/reward-context.js +1 -504
  168. package/dist/knowledge/reward-ledger.js +1 -502
  169. package/dist/knowledge/reward-puzzle.js +1 -300
  170. package/dist/knowledge/reward-risk.js +1 -627
  171. package/dist/knowledge/reward-templates.js +1 -197
  172. package/dist/knowledge/reward-translation.js +1 -501
  173. package/dist/knowledge/safety-rules.js +1 -404
  174. package/dist/knowledge/scenario-modes.js +1 -321
  175. package/dist/knowledge/service-confirm.js +1 -807
  176. package/dist/knowledge/service-context.js +1 -403
  177. package/dist/knowledge/service-ledger.js +1 -609
  178. package/dist/knowledge/service-puzzle.js +1 -236
  179. package/dist/knowledge/service-risk.js +1 -651
  180. package/dist/knowledge/service-templates.js +1 -456
  181. package/dist/knowledge/service-translation.js +1 -622
  182. package/dist/knowledge/template-registry.js +1 -353
  183. package/dist/knowledge/tool-constraints.js +1 -195
  184. package/dist/knowledge/tools-reference.js +1 -178
  185. package/dist/knowledge/treasury-confirm.js +1 -512
  186. package/dist/knowledge/treasury-context.js +1 -363
  187. package/dist/knowledge/treasury-ledger.js +1 -300
  188. package/dist/knowledge/treasury-puzzle.js +1 -216
  189. package/dist/knowledge/treasury-risk.js +1 -440
  190. package/dist/knowledge/treasury-templates.js +1 -358
  191. package/dist/knowledge/treasury-translation.js +1 -498
  192. package/dist/knowledge/trust-metrics.js +1 -198
  193. package/dist/knowledge/util-risk.js +1 -135
  194. package/dist/loop-engineering/aggregate.js +1 -132
  195. package/dist/loop-engineering/context-collect.js +1 -83
  196. package/dist/loop-engineering/diagnose.js +1 -273
  197. package/dist/loop-engineering/improve.js +1 -405
  198. package/dist/loop-engineering/index.js +1 -4
  199. package/dist/loop-engineering/pipeline.js +1 -56
  200. package/dist/mode-market/index.js +1 -3
  201. package/dist/mode-market/registry.js +1 -124
  202. package/dist/mode-market/review.js +1 -214
  203. package/dist/mode-market/submission.js +1 -85
  204. package/dist/participation/collaborator-interest.d.ts +23 -0
  205. package/dist/participation/collaborator-interest.js +1 -0
  206. package/dist/participation/customer-interest.d.ts +25 -0
  207. package/dist/participation/customer-interest.js +1 -0
  208. package/dist/participation/merchant-interest.js +1 -100
  209. package/dist/participation/radar-core.d.ts +13 -3
  210. package/dist/participation/radar-core.js +1 -269
  211. package/dist/participation/supplier-interest.d.ts +25 -0
  212. package/dist/participation/supplier-interest.js +1 -0
  213. package/dist/persona/analyzer.js +1 -66
  214. package/dist/persona/bridge.js +1 -86
  215. package/dist/persona/defaults.js +1 -195
  216. package/dist/persona/experience-bridge.js +1 -23
  217. package/dist/persona/index.js +1 -71
  218. package/dist/persona/model.js +1 -111
  219. package/dist/persona/store.js +1 -62
  220. package/dist/persona/types.d.ts +3 -1
  221. package/dist/persona/types.js +1 -5
  222. package/dist/project/business-puzzle.js +1 -383
  223. package/dist/project/context-assembly.js +1 -254
  224. package/dist/project/deployment-bridge.js +1 -120
  225. package/dist/project/deployment-doc.js +1 -1126
  226. package/dist/project/edit-planner.js +1 -1342
  227. package/dist/project/evaluation.js +1 -2011
  228. package/dist/project/game-theory.js +1 -177
  229. package/dist/project/graph-builder.js +1 -656
  230. package/dist/project/graph.js +1 -340
  231. package/dist/project/handlers.js +1 -1784
  232. package/dist/project/index.d.ts +1 -0
  233. package/dist/project/index.js +1 -301
  234. package/dist/project/intent-analyzer.js +1 -149
  235. package/dist/project/machine-nodes.js +1 -36
  236. package/dist/project/merchant-guide.js +1 -264
  237. package/dist/project/migration.js +1 -125
  238. package/dist/project/mode-actions.js +1 -309
  239. package/dist/project/namespace.js +1 -206
  240. package/dist/project/participation-radar.js +1 -428
  241. package/dist/project/pipeline-actions.js +1 -109
  242. package/dist/project/project-store.js +1 -422
  243. package/dist/project/query.js +1 -153
  244. package/dist/project/reverse-mapping.d.ts +34 -0
  245. package/dist/project/reverse-mapping.js +1 -0
  246. package/dist/project/risk-aggregator.js +1 -295
  247. package/dist/project/rollback-policy.js +1 -290
  248. package/dist/project/semantic-assembler.js +1 -345
  249. package/dist/project/semantic-graph.js +1 -292
  250. package/dist/project/stage-gate.js +1 -369
  251. package/dist/project/substep-trace.js +1 -332
  252. package/dist/project/task-tracker.js +1 -78
  253. package/dist/role/derivation.d.ts +18 -0
  254. package/dist/role/derivation.js +1 -0
  255. package/dist/role/index.d.ts +5 -0
  256. package/dist/role/index.js +1 -0
  257. package/dist/role/model.d.ts +8 -0
  258. package/dist/role/model.js +1 -0
  259. package/dist/role/resolution.d.ts +11 -0
  260. package/dist/role/resolution.js +1 -0
  261. package/dist/role/types.d.ts +11 -0
  262. package/dist/role/types.js +1 -0
  263. package/dist/rules.js +1 -52
  264. package/dist/safety/confirm-gate.js +1 -88
  265. package/dist/safety/index.js +1 -3
  266. package/dist/safety/preview.js +1 -52
  267. package/dist/schema/call/allocation.js +1 -34
  268. package/dist/schema/call/arbitration.js +1 -113
  269. package/dist/schema/call/base.d.ts +15 -15
  270. package/dist/schema/call/base.js +1 -370
  271. package/dist/schema/call/bridge-handler.js +1 -265
  272. package/dist/schema/call/bridge.d.ts +7 -7
  273. package/dist/schema/call/bridge.js +1 -458
  274. package/dist/schema/call/contact.js +1 -37
  275. package/dist/schema/call/demand.js +1 -47
  276. package/dist/schema/call/guard.js +1 -161
  277. package/dist/schema/call/handler.js +1 -322
  278. package/dist/schema/call/index.js +1 -20
  279. package/dist/schema/call/machine.js +1 -193
  280. package/dist/schema/call/order.js +1 -35
  281. package/dist/schema/call/payment.js +1 -37
  282. package/dist/schema/call/permission-handler.js +1 -54
  283. package/dist/schema/call/permission.js +1 -105
  284. package/dist/schema/call/personal.js +1 -78
  285. package/dist/schema/call/progress.js +1 -47
  286. package/dist/schema/call/proof.js +1 -33
  287. package/dist/schema/call/repository.js +1 -77
  288. package/dist/schema/call/reward.js +1 -30
  289. package/dist/schema/call/semantic.js +1 -1679
  290. package/dist/schema/call/service.js +1 -184
  291. package/dist/schema/call/treasury.js +1 -71
  292. package/dist/schema/common/index.js +1 -407
  293. package/dist/schema/config/index.js +1 -68
  294. package/dist/schema/evaluation/index.d.ts +213 -16
  295. package/dist/schema/evaluation/index.js +1 -356
  296. package/dist/schema/index.js +1 -17
  297. package/dist/schema/intent-radar/index.d.ts +13 -13
  298. package/dist/schema/intent-radar/index.js +1 -89
  299. package/dist/schema/local/index.d.ts +21 -21
  300. package/dist/schema/local/index.js +1 -927
  301. package/dist/schema/local/wip.js +1 -187
  302. package/dist/schema/messenger/index.d.ts +7 -7
  303. package/dist/schema/messenger/index.js +1 -475
  304. package/dist/schema/operations.d.ts +7 -7
  305. package/dist/schema/operations.js +1 -520
  306. package/dist/schema/persona/index.d.ts +54 -54
  307. package/dist/schema/persona/index.js +1 -148
  308. package/dist/schema/project/index.d.ts +94 -48
  309. package/dist/schema/project/index.js +1 -2057
  310. package/dist/schema/query/index.d.ts +423 -7
  311. package/dist/schema/query/index.js +1 -1646
  312. package/dist/schema/schema-query/index.js +1 -104
  313. package/dist/schema/schema-version.js +1 -76
  314. package/dist/schema/sync-layer4.js +1 -286
  315. package/dist/schema/task-status.js +1 -36
  316. package/dist/schema/trust/index.js +1 -314
  317. package/dist/schema/utils/guard-parser.js +1 -419
  318. package/dist/schema/utils/guard-query-utils.js +1 -46
  319. package/dist/schema/utils/node-parser.js +1 -369
  320. package/dist/schema/utils/object-type-utils.js +1 -35
  321. package/dist/schema/utils/permission-index-utils.js +1 -7
  322. package/dist/schema/utils/permission-machine-check.js +1 -121
  323. package/dist/schema/utils/skills-recommendation.js +1 -77
  324. package/dist/schema-query/index.js +1 -810
  325. package/dist/schemas/account_operation.output.json +5 -2
  326. package/dist/schemas/bridge_operation.output.json +5 -2
  327. package/dist/schemas/evaluation_operation.output.json +112 -7
  328. package/dist/schemas/evaluation_operation.schema.json +93 -6
  329. package/dist/schemas/index.json +1 -1
  330. package/dist/schemas/intent_radar.output.json +4 -1
  331. package/dist/schemas/intent_radar.schema.json +4 -1
  332. package/dist/schemas/local_info_operation.output.json +5 -2
  333. package/dist/schemas/local_mark_operation.output.json +5 -2
  334. package/dist/schemas/messenger_operation.output.json +5 -2
  335. package/dist/schemas/onchain_events.output.json +5 -2
  336. package/dist/schemas/onchain_operations.output.json +5 -2
  337. package/dist/schemas/onchain_operations.schema.json +4 -4
  338. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  339. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  340. package/dist/schemas/onchain_operations_service.schema.json +1 -1
  341. package/dist/schemas/onchain_table_data.output.json +6 -3
  342. package/dist/schemas/persona_operation.output.json +4 -1
  343. package/dist/schemas/persona_operation.schema.json +4 -1
  344. package/dist/schemas/project_operation.output.json +28 -8
  345. package/dist/schemas/query_toolkit.output.json +8 -5
  346. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  347. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  348. package/dist/telemetry/index.js +1 -112
  349. package/dist/telemetry/redact.js +1 -23
  350. package/dist/telemetry/storage.js +1 -80
  351. package/dist/tools/handlers/bridge.js +1 -1
  352. package/dist/tools/handlers/config.js +1 -74
  353. package/dist/tools/handlers/evaluation.js +1 -123
  354. package/dist/tools/handlers/file-export.js +1 -90
  355. package/dist/tools/handlers/intent-radar.js +1 -76
  356. package/dist/tools/handlers/local.js +1 -53
  357. package/dist/tools/handlers/messenger.js +1 -188
  358. package/dist/tools/handlers/onchain.js +1 -1180
  359. package/dist/tools/handlers/persona.js +1 -89
  360. package/dist/tools/handlers/project.js +1 -211
  361. package/dist/tools/handlers/query.js +1 -434
  362. package/dist/tools/handlers/schema-query.js +1 -176
  363. package/dist/tools/handlers/task-status.js +1 -26
  364. package/dist/tools/handlers/trust.js +1 -380
  365. package/dist/tools/handlers/wip.js +1 -90
  366. package/dist/tools/index.js +1 -1382
  367. package/dist/tools/retry.js +1 -85
  368. package/dist/tools/rules-hook.js +1 -23
  369. package/dist/tools/shared.js +1 -130
  370. package/dist/tools/types.js +1 -1
  371. package/dist/tools/upgrade-check.d.ts +19 -0
  372. package/dist/tools/upgrade-check.js +1 -0
  373. package/dist/tools/wip-deploy-assist.js +1 -306
  374. package/dist/tools/wrap.js +1 -500
  375. package/package.json +4 -2
@@ -1,534 +1 @@
1
- import { MAX_ALLOCATOR_COUNT, ALLOCATION_MAX_SHARING_COUNT, RATE_TOTAL_FULL, ALLOCATION_ERROR_CODES, isSignerRecipient, isEntityRecipient, } from "./allocation-ledger.js";
2
- import { assessAllocationRisks, } from "./allocation-risk.js";
3
- export const ALLOCATION_PUBLISH_CHECKLIST = [
4
- { id: "C-A-01", description: "Allocator count <= MAX_ALLOCATOR_COUNT (100)", passed: false, message: "" },
5
- { id: "C-A-02", description: "Sharing count per Allocator <= MAX_SHARING_COUNT (100)", passed: false, message: "" },
6
- { id: "C-A-03", description: "At most 1 Surplus sharing per Allocator (EMULTIPLE_SURPLUS)", passed: false, message: "" },
7
- { id: "C-A-04", description: "Pure Rate mode sum(rates) == 10000 (ERATE_NOT_10000) OR Rate+Surplus sum <= 10000 (ERATE_EXCEEDS_10000)", passed: false, message: "" },
8
- { id: "C-A-05", description: "Pure Amount mode sum(fix) >= threshold (EAMOUNT_BELOW_THRESHOLD)", passed: false, message: "" },
9
- { id: "C-A-06", description: "Amount sum(fix) <= max when max is set (EAMOUNT_EXCEEDS_MAX)", passed: false, message: "" },
10
- { id: "C-A-07", description: "allocators[].guard unique within the same Allocators (F-A-14)", passed: false, message: "" },
11
- { id: "C-A-08", description: "Guard addresses valid (0x prefix, length >= 40)", passed: false, message: "" },
12
- { id: "C-A-09", description: "Entity addresses valid (0x prefix, length >= 40)", passed: false, message: "" },
13
- { id: "C-A-10", description: "Signer recipients have Guard Signer binding (R-A-2-01 CRITICAL theft risk)", passed: false, message: "" },
14
- { id: "C-A-11", description: "payment_info present (required at alloc() time — ENO_PAYMENT_INFO)", passed: false, message: "" },
15
- { id: "C-A-12", description: "coin type matches type_parameter (EINSUFFICIENT_BALANCE if mismatch)", passed: false, message: "" },
16
- ];
17
- function isValidAddress(s) {
18
- return typeof s === "string" && s.startsWith("0x") && s.length >= 40;
19
- }
20
- function runStaticChecklist(input) {
21
- const items = ALLOCATION_PUBLISH_CHECKLIST.map(c => ({ ...c }));
22
- const data = input.allocation_json;
23
- const isCreate = data.object !== null &&
24
- data.object !== undefined &&
25
- typeof data.object === "object" &&
26
- !Array.isArray(data.object);
27
- if (!isCreate) {
28
- for (const item of items)
29
- item.passed = true;
30
- if (typeof data.object === "string") {
31
- const objValid = isValidAddress(data.object);
32
- items.find(i => i.id === "C-A-08").passed = objValid;
33
- items.find(i => i.id === "C-A-08").message = objValid ? "" : `Allocation object address ${data.object} invalid`;
34
- }
35
- if (data.alloc_by_guard !== undefined) {
36
- const guardValid = isValidAddress(data.alloc_by_guard);
37
- items.find(i => i.id === "C-A-09").passed = guardValid;
38
- items.find(i => i.id === "C-A-09").message = guardValid ? "" : `alloc_by_guard address ${data.alloc_by_guard} invalid`;
39
- }
40
- return { all_passed: items.every(i => i.passed), items };
41
- }
42
- const allocatorsData = data.allocators;
43
- if (!allocatorsData) {
44
- for (const item of items) {
45
- if (item.id.startsWith("C-A-0")) {
46
- item.passed = false;
47
- item.message = "Missing required field: allocators";
48
- }
49
- else {
50
- item.passed = true;
51
- }
52
- }
53
- return { all_passed: false, items };
54
- }
55
- const allocators = allocatorsData.allocators;
56
- const ca01 = items.find(i => i.id === "C-A-01");
57
- ca01.passed = allocators.length <= MAX_ALLOCATOR_COUNT;
58
- ca01.message = ca01.passed ? "" : `Allocator count ${allocators.length} > ${MAX_ALLOCATOR_COUNT}`;
59
- let ca02Ok = true;
60
- let ca02Msg = "";
61
- for (let i = 0; i < allocators.length; i++) {
62
- if (allocators[i].sharing.length > ALLOCATION_MAX_SHARING_COUNT) {
63
- ca02Ok = false;
64
- ca02Msg = `Allocator ${i} sharing count ${allocators[i].sharing.length} > ${ALLOCATION_MAX_SHARING_COUNT}`;
65
- break;
66
- }
67
- }
68
- const ca02 = items.find(i => i.id === "C-A-02");
69
- ca02.passed = ca02Ok;
70
- ca02.message = ca02Msg;
71
- let ca03Ok = true;
72
- let ca03Msg = "";
73
- for (let i = 0; i < allocators.length; i++) {
74
- const surplusCount = allocators[i].sharing.filter(s => s.mode === "Surplus").length;
75
- if (surplusCount > 1) {
76
- ca03Ok = false;
77
- ca03Msg = `Allocator ${i} has ${surplusCount} Surplus (max 1 allowed)`;
78
- break;
79
- }
80
- }
81
- const ca03 = items.find(i => i.id === "C-A-03");
82
- ca03.passed = ca03Ok;
83
- ca03.message = ca03Msg;
84
- let ca04Ok = true;
85
- let ca04Msg = "";
86
- for (let i = 0; i < allocators.length; i++) {
87
- const a = allocators[i];
88
- const rateSum = a.sharing
89
- .filter(s => s.mode === "Rate")
90
- .reduce((sum, s) => sum + Number(s.sharing), 0);
91
- const hasSurplus = a.sharing.some(s => s.mode === "Surplus");
92
- const hasRate = a.sharing.some(s => s.mode === "Rate");
93
- if (hasRate && !hasSurplus && rateSum !== RATE_TOTAL_FULL) {
94
- ca04Ok = false;
95
- ca04Msg = `Allocator ${i} pure Rate sum ${rateSum} != ${RATE_TOTAL_FULL}`;
96
- break;
97
- }
98
- if (hasRate && hasSurplus && rateSum > RATE_TOTAL_FULL) {
99
- ca04Ok = false;
100
- ca04Msg = `Allocator ${i} Rate+Surplus sum ${rateSum} > ${RATE_TOTAL_FULL}`;
101
- break;
102
- }
103
- }
104
- const ca04 = items.find(i => i.id === "C-A-04");
105
- ca04.passed = ca04Ok;
106
- ca04.message = ca04Msg;
107
- let ca05Ok = true;
108
- let ca05Msg = "";
109
- const threshold = Number(allocatorsData.threshold);
110
- for (let i = 0; i < allocators.length; i++) {
111
- const a = allocators[i];
112
- const hasRate = a.sharing.some(s => s.mode === "Rate");
113
- const hasSurplus = a.sharing.some(s => s.mode === "Surplus");
114
- const amountSum = a.sharing
115
- .filter(s => s.mode === "Amount")
116
- .reduce((sum, s) => sum + Number(s.sharing), 0);
117
- if (!hasRate && !hasSurplus && amountSum > 0 && amountSum < threshold) {
118
- ca05Ok = false;
119
- ca05Msg = `Allocator ${i} pure Amount sum ${amountSum} < threshold ${threshold}`;
120
- break;
121
- }
122
- }
123
- const ca05 = items.find(i => i.id === "C-A-05");
124
- ca05.passed = ca05Ok;
125
- ca05.message = ca05Msg;
126
- let ca06Ok = true;
127
- let ca06Msg = "";
128
- for (let i = 0; i < allocators.length; i++) {
129
- const a = allocators[i];
130
- if (a.max == null)
131
- continue;
132
- const amountSum = a.sharing
133
- .filter(s => s.mode === "Amount")
134
- .reduce((sum, s) => sum + Number(s.sharing), 0);
135
- if (amountSum > Number(a.max)) {
136
- ca06Ok = false;
137
- ca06Msg = `Allocator ${i} Amount sum ${amountSum} > max ${Number(a.max)}`;
138
- break;
139
- }
140
- }
141
- const ca06 = items.find(i => i.id === "C-A-06");
142
- ca06.passed = ca06Ok;
143
- ca06.message = ca06Msg;
144
- const guardSet = new Set();
145
- let ca07Ok = true;
146
- let ca07Msg = "";
147
- for (let i = 0; i < allocators.length; i++) {
148
- if (guardSet.has(allocators[i].guard)) {
149
- ca07Ok = false;
150
- ca07Msg = `Allocator ${i} guard ${allocators[i].guard} duplicates an earlier Allocator (F-A-14)`;
151
- break;
152
- }
153
- guardSet.add(allocators[i].guard);
154
- }
155
- const ca07 = items.find(i => i.id === "C-A-07");
156
- ca07.passed = ca07Ok;
157
- ca07.message = ca07Msg;
158
- let ca08Ok = true;
159
- let ca08Msg = "";
160
- for (let i = 0; i < allocators.length; i++) {
161
- if (!isValidAddress(allocators[i].guard)) {
162
- ca08Ok = false;
163
- ca08Msg = `Allocator ${i} guard address ${allocators[i].guard} invalid`;
164
- break;
165
- }
166
- }
167
- const ca08 = items.find(i => i.id === "C-A-08");
168
- ca08.passed = ca08Ok;
169
- ca08.message = ca08Msg;
170
- let ca09Ok = true;
171
- let ca09Msg = "";
172
- outer: for (let i = 0; i < allocators.length; i++) {
173
- for (let j = 0; j < allocators[i].sharing.length; j++) {
174
- const s = allocators[i].sharing[j];
175
- if (isEntityRecipient(s.who)) {
176
- const addr = s.who.Entity;
177
- if (!isValidAddress(addr)) {
178
- ca09Ok = false;
179
- ca09Msg = `Allocator ${i} sharing ${j} Entity address ${addr} invalid`;
180
- break outer;
181
- }
182
- }
183
- }
184
- }
185
- const ca09 = items.find(i => i.id === "C-A-09");
186
- ca09.passed = ca09Ok;
187
- ca09.message = ca09Msg;
188
- let ca10Ok = true;
189
- let ca10Msg = "";
190
- for (let i = 0; i < allocators.length; i++) {
191
- const a = allocators[i];
192
- const hasSigner = a.sharing.some(s => isSignerRecipient(s.who));
193
- if (!hasSigner)
194
- continue;
195
- const bound = input.guard_signer_bindings?.[a.guard] === true;
196
- if (!bound) {
197
- ca10Ok = false;
198
- ca10Msg = `Allocator ${i} (guard=${a.guard}) has Signer recipient but no Guard Signer binding — R-A-2-01 CRITICAL theft risk`;
199
- break;
200
- }
201
- }
202
- const ca10 = items.find(i => i.id === "C-A-10");
203
- ca10.passed = ca10Ok;
204
- ca10.message = ca10Msg;
205
- const ca11 = items.find(i => i.id === "C-A-11");
206
- ca11.passed = data.payment_info !== undefined && data.payment_info !== null;
207
- ca11.message = ca11.passed ? "" : "payment_info missing — required at alloc() time (ENO_PAYMENT_INFO=9)";
208
- const ca12 = items.find(i => i.id === "C-A-12");
209
- const obj = data.object;
210
- if (obj.type_parameter && data.coin) {
211
- ca12.passed = true;
212
- ca12.message = "";
213
- }
214
- else if (!obj.type_parameter) {
215
- ca12.passed = false;
216
- ca12.message = "type_parameter missing on object";
217
- }
218
- else {
219
- ca12.passed = false;
220
- ca12.message = "coin missing — required for create";
221
- }
222
- return {
223
- all_passed: items.every(i => i.passed),
224
- items,
225
- };
226
- }
227
- function adaptRiskAssessment(input, _checklist) {
228
- const ctx = {
229
- object: typeof input.allocation_json.object === "string" ? input.allocation_json.object : null,
230
- allocators_config: input.allocation_json.allocators,
231
- operation_type: input.operation_type ?? "create",
232
- has_payment_info: input.allocation_json.payment_info !== undefined,
233
- host_service_published: true,
234
- referenced_treasuries_permissions: input.referenced_treasuries_permissions,
235
- guard_signer_bindings: input.guard_signer_bindings,
236
- passport_identifier_types: input.passport_identifier_types,
237
- guard_conditions_mutually_exclusive: input.guard_conditions_mutually_exclusive,
238
- bound_order: input.bound_order,
239
- order_already_has_allocation: input.order_already_has_allocation,
240
- };
241
- return assessAllocationRisks(ctx);
242
- }
243
- export const ALLOCATION_CONFIRMATION_QUESTIONS = [
244
- {
245
- id: "QA1",
246
- question: "Are all Treasury / Entity recipient addresses correctly verified as trusted parties?",
247
- requires_explicit_yes: true,
248
- },
249
- {
250
- id: "QA2",
251
- question: "If using multiple Allocators (caller-specified guard), are Guard conditions mutually exclusive to prevent caller confusion or silent lockup (alloc_by_guard silently returns on no match)?",
252
- requires_explicit_yes: true,
253
- related_risk_ids: ["R-A-4-02"],
254
- },
255
- {
256
- id: "QA3",
257
- question: "⚠️ If using sharing.who=Signer: is the Guard Signer binding verified (context(Signer)==authorized)? Signer without Guard binding = CRITICAL theft risk.",
258
- requires_explicit_yes: true,
259
- related_risk_ids: ["R-A-2-01"],
260
- },
261
- {
262
- id: "QA4",
263
- question: "If using Amount+Surplus hybrid (refund-first): is threshold set to refund amount (fix) to ensure balance covers the Amount distribution?",
264
- requires_explicit_yes: true,
265
- related_risk_ids: ["R-A-1-03"],
266
- },
267
- {
268
- id: "QA5",
269
- question: "Is payment_info correctly configured? alloc() will abort with ENO_PAYMENT_INFO (9) if missing.",
270
- requires_explicit_yes: true,
271
- related_risk_ids: ["R-A-5-02"],
272
- },
273
- {
274
- id: "QA6",
275
- question: "Has the Allocation been tested on testnet? Allocation is a 'passive object' — once created, allocators cannot be reconfigured.",
276
- requires_explicit_yes: false,
277
- },
278
- ];
279
- function processUserConfirmation(input, assessment) {
280
- const questions = [...ALLOCATION_CONFIRMATION_QUESTIONS];
281
- const hasSignerRecipient = input.allocation_json.allocators?.allocators.some(a => a.sharing.some(s => isSignerRecipient(s.who))) ?? false;
282
- if (!hasSignerRecipient) {
283
- const idx = questions.findIndex(q => q.id === "QA3");
284
- if (idx >= 0)
285
- questions.splice(idx, 1);
286
- }
287
- const allocatorCount = input.allocation_json.allocators?.allocators.length ?? 0;
288
- if (allocatorCount <= 1) {
289
- const idx = questions.findIndex(q => q.id === "QA2");
290
- if (idx >= 0)
291
- questions.splice(idx, 1);
292
- }
293
- const hasAmountSurplusHybrid = input.allocation_json.allocators?.allocators.some(a => a.sharing.some(s => s.mode === "Amount") && a.sharing.some(s => s.mode === "Surplus")) ?? false;
294
- if (!hasAmountSurplusHybrid) {
295
- const idx = questions.findIndex(q => q.id === "QA4");
296
- if (idx >= 0)
297
- questions.splice(idx, 1);
298
- }
299
- if (input.skip_user_confirmation) {
300
- return {
301
- questions_asked: questions,
302
- responses: questions.map(q => ({ question_id: q.id, response: "yes" })),
303
- all_confirmed: true,
304
- };
305
- }
306
- return {
307
- questions_asked: questions,
308
- responses: [],
309
- all_confirmed: false,
310
- };
311
- }
312
- function verifyEnvironment(input) {
313
- const checks = [];
314
- if (typeof input.allocation_json.object === "string") {
315
- checks.push({
316
- name: "object_exists",
317
- passed: true,
318
- message: `Allocation object ${input.allocation_json.object} assumed to exist`,
319
- });
320
- }
321
- if (input.allocation_json.alloc_by_guard) {
322
- const guard = input.allocation_json.alloc_by_guard;
323
- const allocators = input.allocation_json.allocators?.allocators ?? [];
324
- const valid = isValidAddress(guard);
325
- checks.push({
326
- name: "alloc_by_guard_valid",
327
- passed: valid,
328
- message: valid
329
- ? `Guard ${guard} address valid (SDK will verify it exists in allocators[].guard)`
330
- : `Guard ${guard} address invalid`,
331
- });
332
- }
333
- if (input.operation_type === "create") {
334
- checks.push({
335
- name: "signer_authorized",
336
- passed: true,
337
- message: "Signer must hold SERVICE_ORDER_ALLOCATOR=313 permission (or ARBITRATION_FEES_ALLOC=365 for arbitration fees)",
338
- });
339
- }
340
- if (input.bound_order) {
341
- const alreadyHas = input.order_already_has_allocation === true;
342
- checks.push({
343
- name: "order_allocation_1to1",
344
- passed: !alreadyHas,
345
- message: alreadyHas
346
- ? `Order ${input.bound_order} already has an Allocation — E_ALLOCATION_ALREADY_SPECIFIED will abort`
347
- : `Order ${input.bound_order} has no Allocation — 1:1 constraint satisfied`,
348
- });
349
- }
350
- checks.push({
351
- name: "testnet_test_recommended",
352
- passed: true,
353
- message: "Allocation is a 'passive object' — strongly recommend testnet test before mainnet deployment",
354
- });
355
- const allPassed = checks.every(c => c.passed);
356
- return { passed: allPassed, checks };
357
- }
358
- export const ALLOCATION_CONFIRM_VERSION = "1.0.0";
359
- export function runAllocationConfirmGate(input) {
360
- const layersPassed = [];
361
- const layersFailed = [];
362
- const checklist = runStaticChecklist(input);
363
- if (!checklist.all_passed) {
364
- layersFailed.push("L1_checklist");
365
- return {
366
- status: "blocked_checklist",
367
- checklist_result: checklist,
368
- confirmation_text: generateConfirmationText(input, checklist),
369
- block_reason: `Checklist failed: ${checklist.items.filter(i => !i.passed).map(i => i.id).join(", ")}`,
370
- decision_record: {
371
- timestamp: new Date().toISOString(),
372
- gate_version: ALLOCATION_CONFIRM_VERSION,
373
- final_status: "blocked_checklist",
374
- layers_passed: layersPassed,
375
- layers_failed: layersFailed,
376
- },
377
- };
378
- }
379
- layersPassed.push("L1_checklist");
380
- const assessment = adaptRiskAssessment(input, checklist);
381
- if (assessment.blocks_publish) {
382
- layersFailed.push("L2_risk");
383
- return {
384
- status: "blocked_risk",
385
- checklist_result: checklist,
386
- risk_result: assessment,
387
- confirmation_text: generateConfirmationText(input, checklist, assessment),
388
- block_reason: `CRITICAL risks: ${assessment.risks.filter(r => r.level === "CRITICAL").map(r => r.id).join(", ")}`,
389
- decision_record: {
390
- timestamp: new Date().toISOString(),
391
- gate_version: ALLOCATION_CONFIRM_VERSION,
392
- final_status: "blocked_risk",
393
- layers_passed: layersPassed,
394
- layers_failed: layersFailed,
395
- },
396
- };
397
- }
398
- layersPassed.push("L2_risk");
399
- const userConf = processUserConfirmation(input, assessment);
400
- if (!userConf.all_confirmed) {
401
- }
402
- layersPassed.push("L3_user");
403
- if (input.skip_environment_check) {
404
- layersPassed.push("L4_environment");
405
- }
406
- else {
407
- const env = verifyEnvironment(input);
408
- if (!env.passed) {
409
- layersFailed.push("L4_environment");
410
- return {
411
- status: "blocked_environment",
412
- checklist_result: checklist,
413
- risk_result: assessment,
414
- user_confirmation: userConf,
415
- environment_result: env,
416
- confirmation_text: generateConfirmationText(input, checklist, assessment),
417
- block_reason: `Environment check failed: ${env.checks.filter(c => !c.passed).map(c => c.name).join(", ")}`,
418
- decision_record: {
419
- timestamp: new Date().toISOString(),
420
- gate_version: ALLOCATION_CONFIRM_VERSION,
421
- final_status: "blocked_environment",
422
- layers_passed: layersPassed,
423
- layers_failed: layersFailed,
424
- },
425
- };
426
- }
427
- layersPassed.push("L4_environment");
428
- }
429
- return {
430
- status: "approved",
431
- checklist_result: checklist,
432
- risk_result: assessment,
433
- user_confirmation: userConf,
434
- confirmation_text: generateConfirmationText(input, checklist, assessment),
435
- decision_record: {
436
- timestamp: new Date().toISOString(),
437
- gate_version: ALLOCATION_CONFIRM_VERSION,
438
- final_status: "approved",
439
- layers_passed: layersPassed,
440
- layers_failed: layersFailed,
441
- },
442
- };
443
- }
444
- function generateConfirmationText(input, checklist, assessment) {
445
- const lines = [];
446
- const data = input.allocation_json;
447
- lines.push("═══ Allocation Confirmation ═══");
448
- lines.push("");
449
- const isCreate = data.object !== null &&
450
- data.object !== undefined &&
451
- typeof data.object === "object";
452
- if (isCreate) {
453
- const obj = data.object;
454
- lines.push(`Allocation: NEW '${obj.name}' (${obj.type_parameter ?? "<missing>"})`);
455
- }
456
- else if (typeof data.object === "string") {
457
- lines.push(`Allocation: OPERATE ${data.object}`);
458
- }
459
- lines.push("");
460
- lines.push("─ Checklist ──────────────────");
461
- for (const item of checklist.items) {
462
- const mark = item.passed ? "✓" : "✗";
463
- lines.push(` ${mark} ${item.id}: ${item.description}${item.message ? " — " + item.message : ""}`);
464
- }
465
- lines.push("");
466
- if (assessment) {
467
- lines.push("─ Risk Assessment ──────────────────");
468
- lines.push(`Overall: ${assessment.overall_risk}`);
469
- lines.push(`Detected: ${assessment.risks.length} risk(s)`);
470
- for (const r of assessment.risks) {
471
- lines.push(` [${r.level}] ${r.id}: ${r.title}`);
472
- }
473
- lines.push("");
474
- }
475
- lines.push("─ Operations ──────────────────");
476
- if (isCreate && data.allocators) {
477
- lines.push(`- Description: ${data.allocators.description}`);
478
- lines.push(`- Threshold: ${data.allocators.threshold}`);
479
- lines.push(`- Allocators: ${data.allocators.allocators.length}`);
480
- data.allocators.allocators.forEach((a, i) => {
481
- const surplusCount = a.sharing.filter(s => s.mode === "Surplus").length;
482
- const rateSum = a.sharing.filter(s => s.mode === "Rate").reduce((sum, s) => sum + Number(s.sharing), 0);
483
- const amountSum = a.sharing.filter(s => s.mode === "Amount").reduce((sum, s) => sum + Number(s.sharing), 0);
484
- lines.push(` [${i}] guard=${a.guard}, sharing=${a.sharing.length} (Rate sum=${rateSum}, Amount sum=${amountSum}, Surplus=${surplusCount}), max=${a.max ?? "null"}`);
485
- });
486
- }
487
- if (data.received_coins) {
488
- lines.push(`- Receive: ${data.received_coins.received.length} CoinWrapper deposit(s)`);
489
- }
490
- if (data.alloc_by_guard) {
491
- lines.push(`- Alloc by Guard: ${data.alloc_by_guard}`);
492
- }
493
- lines.push("");
494
- lines.push("─ Error Code Reference ──────────────────");
495
- lines.push(` EALLOCATORS_EMPTY=${ALLOCATION_ERROR_CODES.EALLOCATORS_EMPTY}, ENO_ALLOCATOR=${ALLOCATION_ERROR_CODES.ENO_ALLOCATOR}, ERATE_NOT_10000=${ALLOCATION_ERROR_CODES.ERATE_NOT_10000}`);
496
- lines.push(` EMULTIPLE_SURPLUS=${ALLOCATION_ERROR_CODES.EMULTIPLE_SURPLUS}, ERATE_EXCEEDS_10000=${ALLOCATION_ERROR_CODES.ERATE_EXCEEDS_10000}, EINSUFFICIENT_BALANCE=${ALLOCATION_ERROR_CODES.EINSUFFICIENT_BALANCE}`);
497
- lines.push(` ENO_PAYMENT_INFO=${ALLOCATION_ERROR_CODES.ENO_PAYMENT_INFO}, ESHARING_COUNT_EXCEEDED=${ALLOCATION_ERROR_CODES.ESHARING_COUNT_EXCEEDED}, EAMOUNT_BELOW_THRESHOLD=${ALLOCATION_ERROR_CODES.EAMOUNT_BELOW_THRESHOLD}`);
498
- lines.push(` EAMOUNT_EXCEEDS_MAX=${ALLOCATION_ERROR_CODES.EAMOUNT_EXCEEDS_MAX}, EALLOCATOR_COUNT_EXCEEDED=${ALLOCATION_ERROR_CODES.EALLOCATOR_COUNT_EXCEEDED}`);
499
- lines.push("");
500
- return lines.join("\n");
501
- }
502
- export function progressiveAllocationCheck(input) {
503
- const checklist = runStaticChecklist(input);
504
- if (!checklist.all_passed) {
505
- return {
506
- stage: "checklist",
507
- status: "fail",
508
- message: `Checklist failed: ${checklist.items.filter(i => !i.passed).map(i => i.id).join(", ")}`,
509
- next_action: "Fix failing checklist items (C-A-XX)",
510
- };
511
- }
512
- const assessment = adaptRiskAssessment(input, checklist);
513
- if (assessment.blocks_publish) {
514
- return {
515
- stage: "risk",
516
- status: "fail",
517
- message: `CRITICAL risks: ${assessment.risks.filter(r => r.level === "CRITICAL").map(r => r.id).join(", ")}`,
518
- next_action: "Resolve CRITICAL risks (R-A-1-01 empty allocators, R-A-2-01 Signer theft) before proceeding",
519
- };
520
- }
521
- if (assessment.needs_human_review) {
522
- return {
523
- stage: "confirmation",
524
- status: "pending",
525
- message: "Human review required for HIGH risks",
526
- next_action: "Confirm risk acceptance (QA1 ~ QA6)",
527
- };
528
- }
529
- return {
530
- stage: "complete",
531
- status: "pass",
532
- message: "All checks passed",
533
- };
534
- }
1
+ import{MAX_ALLOCATOR_COUNT,ALLOCATION_MAX_SHARING_COUNT,RATE_TOTAL_FULL,ALLOCATION_ERROR_CODES,isSignerRecipient,isEntityRecipient}from'./allocation-ledger.js';import{assessAllocationRisks}from'./allocation-risk.js';export const ALLOCATION_PUBLISH_CHECKLIST=[{'id':'C-A-01','description':'Allocator\x20count\x20<=\x20MAX_ALLOCATOR_COUNT\x20(100)','passed':![],'message':''},{'id':'C-A-02','description':'Sharing\x20count\x20per\x20Allocator\x20<=\x20MAX_SHARING_COUNT\x20(100)','passed':![],'message':''},{'id':'C-A-03','description':'At\x20most\x201\x20Surplus\x20sharing\x20per\x20Allocator\x20(EMULTIPLE_SURPLUS)','passed':![],'message':''},{'id':'C-A-04','description':'Pure\x20Rate\x20mode\x20sum(rates)\x20==\x2010000\x20(ERATE_NOT_10000)\x20OR\x20Rate+Surplus\x20sum\x20<=\x2010000\x20(ERATE_EXCEEDS_10000)','passed':![],'message':''},{'id':'C-A-05','description':'Pure\x20Amount\x20mode\x20sum(fix)\x20>=\x20threshold\x20(EAMOUNT_BELOW_THRESHOLD)','passed':![],'message':''},{'id':'C-A-06','description':'Amount\x20sum(fix)\x20<=\x20max\x20when\x20max\x20is\x20set\x20(EAMOUNT_EXCEEDS_MAX)','passed':![],'message':''},{'id':'C-A-07','description':'allocators[].guard\x20unique\x20within\x20the\x20same\x20Allocators\x20(F-A-14)','passed':![],'message':''},{'id':'C-A-08','description':'Guard\x20addresses\x20valid\x20(0x\x20prefix,\x20length\x20>=\x2040)','passed':![],'message':''},{'id':'C-A-09','description':'Entity\x20addresses\x20valid\x20(0x\x20prefix,\x20length\x20>=\x2040)','passed':![],'message':''},{'id':'C-A-10','description':'Signer\x20recipients\x20have\x20Guard\x20Signer\x20binding\x20(R-A-2-01\x20CRITICAL\x20theft\x20risk)','passed':![],'message':''},{'id':'C-A-11','description':'payment_info\x20present\x20(required\x20at\x20alloc()\x20time\x20—\x20ENO_PAYMENT_INFO)','passed':![],'message':''},{'id':'C-A-12','description':'coin\x20type\x20matches\x20type_parameter\x20(EINSUFFICIENT_BALANCE\x20if\x20mismatch)','passed':![],'message':''}];function isValidAddress(a){return typeof a==='string'&&a['startsWith']('0x')&&a['length']>=0x28;}function runStaticChecklist(b){const c=ALLOCATION_PUBLISH_CHECKLIST['map'](R=>({...R})),d=b['allocation_json'],e=d['object']!==null&&d['object']!==undefined&&typeof d['object']==='object'&&!Array['isArray'](d['object']);if(!e){for(const R of c)R['passed']=!![];if(typeof d['object']==='string'){const S=isValidAddress(d['object']);c['find'](T=>T['id']==='C-A-08')['passed']=S,c['find'](T=>T['id']==='C-A-08')['message']=S?'':'Allocation\x20object\x20address\x20'+d['object']+'\x20invalid';}if(d['alloc_by_guard']!==undefined){const T=isValidAddress(d['alloc_by_guard']);c['find'](U=>U['id']==='C-A-09')['passed']=T,c['find'](U=>U['id']==='C-A-09')['message']=T?'':'alloc_by_guard\x20address\x20'+d['alloc_by_guard']+'\x20invalid';}return{'all_passed':c['every'](U=>U['passed']),'items':c};}const f=d['allocators'];if(!f){for(const U of c){U['id']['startsWith']('C-A-0')?(U['passed']=![],U['message']='Missing\x20required\x20field:\x20allocators'):U['passed']=!![];}return{'all_passed':![],'items':c};}const g=f['allocators'],h=c['find'](V=>V['id']==='C-A-01');h['passed']=g['length']<=MAX_ALLOCATOR_COUNT,h['message']=h['passed']?'':'Allocator\x20count\x20'+g['length']+'\x20>\x20'+MAX_ALLOCATOR_COUNT;let k=!![],l='';for(let V=0x0;V<g['length'];V++){if(g[V]['sharing']['length']>ALLOCATION_MAX_SHARING_COUNT){k=![],l='Allocator\x20'+V+'\x20sharing\x20count\x20'+g[V]['sharing']['length']+'\x20>\x20'+ALLOCATION_MAX_SHARING_COUNT;break;}}const m=c['find'](W=>W['id']==='C-A-02');m['passed']=k,m['message']=l;let n=!![],o='';for(let W=0x0;W<g['length'];W++){const X=g[W]['sharing']['filter'](Y=>Y['mode']==='Surplus')['length'];if(X>0x1){n=![],o='Allocator\x20'+W+'\x20has\x20'+X+'\x20Surplus\x20(max\x201\x20allowed)';break;}}const p=c['find'](Y=>Y['id']==='C-A-03');p['passed']=n,p['message']=o;let q=!![],r='';for(let Y=0x0;Y<g['length'];Y++){const Z=g[Y],a0=Z['sharing']['filter'](a3=>a3['mode']==='Rate')['reduce']((a3,a4)=>a3+Number(a4['sharing']),0x0),a1=Z['sharing']['some'](a3=>a3['mode']==='Surplus'),a2=Z['sharing']['some'](a3=>a3['mode']==='Rate');if(a2&&!a1&&a0!==RATE_TOTAL_FULL){q=![],r='Allocator\x20'+Y+'\x20pure\x20Rate\x20sum\x20'+a0+'\x20!=\x20'+RATE_TOTAL_FULL;break;}if(a2&&a1&&a0>RATE_TOTAL_FULL){q=![],r='Allocator\x20'+Y+'\x20Rate+Surplus\x20sum\x20'+a0+'\x20>\x20'+RATE_TOTAL_FULL;break;}}const t=c['find'](a3=>a3['id']==='C-A-04');t['passed']=q,t['message']=r;let u=!![],v='';const w=Number(f['threshold']);for(let a3=0x0;a3<g['length'];a3++){const a4=g[a3],a5=a4['sharing']['some'](a8=>a8['mode']==='Rate'),a6=a4['sharing']['some'](a8=>a8['mode']==='Surplus'),a7=a4['sharing']['filter'](a8=>a8['mode']==='Amount')['reduce']((a8,a9)=>a8+Number(a9['sharing']),0x0);if(!a5&&!a6&&a7>0x0&&a7<w){u=![],v='Allocator\x20'+a3+'\x20pure\x20Amount\x20sum\x20'+a7+'\x20<\x20threshold\x20'+w;break;}}const x=c['find'](a8=>a8['id']==='C-A-05');x['passed']=u,x['message']=v;let y=!![],z='';for(let a8=0x0;a8<g['length'];a8++){const a9=g[a8];if(a9['max']==null)continue;const aa=a9['sharing']['filter'](ab=>ab['mode']==='Amount')['reduce']((ab,ac)=>ab+Number(ac['sharing']),0x0);if(aa>Number(a9['max'])){y=![],z='Allocator\x20'+a8+'\x20Amount\x20sum\x20'+aa+'\x20>\x20max\x20'+Number(a9['max']);break;}}const A=c['find'](ab=>ab['id']==='C-A-06');A['passed']=y,A['message']=z;const B=new Set();let C=!![],D='';for(let ab=0x0;ab<g['length'];ab++){if(B['has'](g[ab]['guard'])){C=![],D='Allocator\x20'+ab+'\x20guard\x20'+g[ab]['guard']+'\x20duplicates\x20an\x20earlier\x20Allocator\x20(F-A-14)';break;}B['add'](g[ab]['guard']);}const E=c['find'](ac=>ac['id']==='C-A-07');E['passed']=C,E['message']=D;let F=!![],G='';for(let ac=0x0;ac<g['length'];ac++){if(!isValidAddress(g[ac]['guard'])){F=![],G='Allocator\x20'+ac+'\x20guard\x20address\x20'+g[ac]['guard']+'\x20invalid';break;}}const H=c['find'](ad=>ad['id']==='C-A-08');H['passed']=F,H['message']=G;let I=!![],J='';al:for(let ad=0x0;ad<g['length'];ad++){for(let ae=0x0;ae<g[ad]['sharing']['length'];ae++){const af=g[ad]['sharing'][ae];if(isEntityRecipient(af['who'])){const ag=af['who']['Entity'];if(!isValidAddress(ag)){I=![],J='Allocator\x20'+ad+'\x20sharing\x20'+ae+'\x20Entity\x20address\x20'+ag+'\x20invalid';break al;}}}}const K=c['find'](ah=>ah['id']==='C-A-09');K['passed']=I,K['message']=J;let L=!![],M='';for(let ah=0x0;ah<g['length'];ah++){const ai=g[ah],aj=ai['sharing']['some'](al=>isSignerRecipient(al['who']));if(!aj)continue;const ak=b['guard_signer_bindings']?.[ai['guard']]===!![];if(!ak){L=![],M='Allocator\x20'+ah+'\x20(guard='+ai['guard']+')\x20has\x20Signer\x20recipient\x20but\x20no\x20Guard\x20Signer\x20binding\x20—\x20R-A-2-01\x20CRITICAL\x20theft\x20risk';break;}}const N=c['find'](al=>al['id']==='C-A-10');N['passed']=L,N['message']=M;const O=c['find'](al=>al['id']==='C-A-11');O['passed']=d['payment_info']!==undefined&&d['payment_info']!==null,O['message']=O['passed']?'':'payment_info\x20missing\x20—\x20required\x20at\x20alloc()\x20time\x20(ENO_PAYMENT_INFO=9)';const P=c['find'](al=>al['id']==='C-A-12'),Q=d['object'];if(Q['type_parameter']&&d['coin'])P['passed']=!![],P['message']='';else!Q['type_parameter']?(P['passed']=![],P['message']='type_parameter\x20missing\x20on\x20object'):(P['passed']=![],P['message']='coin\x20missing\x20—\x20required\x20for\x20create');return{'all_passed':c['every'](al=>al['passed']),'items':c};}function adaptRiskAssessment(a,b){const c={'object':typeof a['allocation_json']['object']==='string'?a['allocation_json']['object']:null,'allocators_config':a['allocation_json']['allocators'],'operation_type':a['operation_type']??'create','has_payment_info':a['allocation_json']['payment_info']!==undefined,'host_service_published':!![],'referenced_treasuries_permissions':a['referenced_treasuries_permissions'],'guard_signer_bindings':a['guard_signer_bindings'],'passport_identifier_types':a['passport_identifier_types'],'guard_conditions_mutually_exclusive':a['guard_conditions_mutually_exclusive'],'bound_order':a['bound_order'],'order_already_has_allocation':a['order_already_has_allocation']};return assessAllocationRisks(c);}export const ALLOCATION_CONFIRMATION_QUESTIONS=[{'id':'QA1','question':'Are\x20all\x20Treasury\x20/\x20Entity\x20recipient\x20addresses\x20correctly\x20verified\x20as\x20trusted\x20parties?','requires_explicit_yes':!![]},{'id':'QA2','question':'If\x20using\x20multiple\x20Allocators\x20(caller-specified\x20guard),\x20are\x20Guard\x20conditions\x20mutually\x20exclusive\x20to\x20prevent\x20caller\x20confusion\x20or\x20silent\x20lockup\x20(alloc_by_guard\x20silently\x20returns\x20on\x20no\x20match)?','requires_explicit_yes':!![],'related_risk_ids':['R-A-4-02']},{'id':'QA3','question':'⚠️\x20If\x20using\x20sharing.who=Signer:\x20is\x20the\x20Guard\x20Signer\x20binding\x20verified\x20(context(Signer)==authorized)?\x20Signer\x20without\x20Guard\x20binding\x20=\x20CRITICAL\x20theft\x20risk.','requires_explicit_yes':!![],'related_risk_ids':['R-A-2-01']},{'id':'QA4','question':'If\x20using\x20Amount+Surplus\x20hybrid\x20(refund-first):\x20is\x20threshold\x20set\x20to\x20refund\x20amount\x20(fix)\x20to\x20ensure\x20balance\x20covers\x20the\x20Amount\x20distribution?','requires_explicit_yes':!![],'related_risk_ids':['R-A-1-03']},{'id':'QA5','question':'Is\x20payment_info\x20correctly\x20configured?\x20alloc()\x20will\x20abort\x20with\x20ENO_PAYMENT_INFO\x20(9)\x20if\x20missing.','requires_explicit_yes':!![],'related_risk_ids':['R-A-5-02']},{'id':'QA6','question':'Has\x20the\x20Allocation\x20been\x20tested\x20on\x20testnet?\x20Allocation\x20is\x20a\x20\x27passive\x20object\x27\x20—\x20once\x20created,\x20allocators\x20cannot\x20be\x20reconfigured.','requires_explicit_yes':![]}];function processUserConfirmation(a,b){const c=[...ALLOCATION_CONFIRMATION_QUESTIONS],d=a['allocation_json']['allocators']?.['allocators']['some'](g=>g['sharing']['some'](h=>isSignerRecipient(h['who'])))??![];if(!d){const g=c['findIndex'](h=>h['id']==='QA3');if(g>=0x0)c['splice'](g,0x1);}const e=a['allocation_json']['allocators']?.['allocators']['length']??0x0;if(e<=0x1){const h=c['findIndex'](i=>i['id']==='QA2');if(h>=0x0)c['splice'](h,0x1);}const f=a['allocation_json']['allocators']?.['allocators']['some'](i=>i['sharing']['some'](j=>j['mode']==='Amount')&&i['sharing']['some'](j=>j['mode']==='Surplus'))??![];if(!f){const i=c['findIndex'](j=>j['id']==='QA4');if(i>=0x0)c['splice'](i,0x1);}if(a['skip_user_confirmation'])return{'questions_asked':c,'responses':c['map'](j=>({'question_id':j['id'],'response':'yes'})),'all_confirmed':!![]};return{'questions_asked':c,'responses':[],'all_confirmed':![]};}function verifyEnvironment(a){const b=[];typeof a['allocation_json']['object']==='string'&&b['push']({'name':'object_exists','passed':!![],'message':'Allocation\x20object\x20'+a['allocation_json']['object']+'\x20assumed\x20to\x20exist'});if(a['allocation_json']['alloc_by_guard']){const d=a['allocation_json']['alloc_by_guard'],e=a['allocation_json']['allocators']?.['allocators']??[],f=isValidAddress(d);b['push']({'name':'alloc_by_guard_valid','passed':f,'message':f?'Guard\x20'+d+'\x20address\x20valid\x20(SDK\x20will\x20verify\x20it\x20exists\x20in\x20allocators[].guard)':'Guard\x20'+d+'\x20address\x20invalid'});}a['operation_type']==='create'&&b['push']({'name':'signer_authorized','passed':!![],'message':'Signer\x20must\x20hold\x20SERVICE_ORDER_ALLOCATOR=313\x20permission\x20(or\x20ARBITRATION_FEES_ALLOC=365\x20for\x20arbitration\x20fees)'});if(a['bound_order']){const g=a['order_already_has_allocation']===!![];b['push']({'name':'order_allocation_1to1','passed':!g,'message':g?'Order\x20'+a['bound_order']+'\x20already\x20has\x20an\x20Allocation\x20—\x20E_ALLOCATION_ALREADY_SPECIFIED\x20will\x20abort':'Order\x20'+a['bound_order']+'\x20has\x20no\x20Allocation\x20—\x201:1\x20constraint\x20satisfied'});}b['push']({'name':'testnet_test_recommended','passed':!![],'message':'Allocation\x20is\x20a\x20\x27passive\x20object\x27\x20—\x20strongly\x20recommend\x20testnet\x20test\x20before\x20mainnet\x20deployment'});const c=b['every'](h=>h['passed']);return{'passed':c,'checks':b};}export const ALLOCATION_CONFIRM_VERSION='1.0.0';export function runAllocationConfirmGate(a){const b=[],c=[],d=runStaticChecklist(a);if(!d['all_passed'])return c['push']('L1_checklist'),{'status':'blocked_checklist','checklist_result':d,'confirmation_text':generateConfirmationText(a,d),'block_reason':'Checklist\x20failed:\x20'+d['items']['filter'](g=>!g['passed'])['map'](g=>g['id'])['join'](',\x20'),'decision_record':{'timestamp':new Date()['toISOString'](),'gate_version':ALLOCATION_CONFIRM_VERSION,'final_status':'blocked_checklist','layers_passed':b,'layers_failed':c}};b['push']('L1_checklist');const e=adaptRiskAssessment(a,d);if(e['blocks_publish'])return c['push']('L2_risk'),{'status':'blocked_risk','checklist_result':d,'risk_result':e,'confirmation_text':generateConfirmationText(a,d,e),'block_reason':'CRITICAL\x20risks:\x20'+e['risks']['filter'](g=>g['level']==='CRITICAL')['map'](g=>g['id'])['join'](',\x20'),'decision_record':{'timestamp':new Date()['toISOString'](),'gate_version':ALLOCATION_CONFIRM_VERSION,'final_status':'blocked_risk','layers_passed':b,'layers_failed':c}};b['push']('L2_risk');const f=processUserConfirmation(a,e);if(!f['all_confirmed']){}b['push']('L3_user');if(a['skip_environment_check'])b['push']('L4_environment');else{const g=verifyEnvironment(a);if(!g['passed'])return c['push']('L4_environment'),{'status':'blocked_environment','checklist_result':d,'risk_result':e,'user_confirmation':f,'environment_result':g,'confirmation_text':generateConfirmationText(a,d,e),'block_reason':'Environment\x20check\x20failed:\x20'+g['checks']['filter'](h=>!h['passed'])['map'](h=>h['name'])['join'](',\x20'),'decision_record':{'timestamp':new Date()['toISOString'](),'gate_version':ALLOCATION_CONFIRM_VERSION,'final_status':'blocked_environment','layers_passed':b,'layers_failed':c}};b['push']('L4_environment');}return{'status':'approved','checklist_result':d,'risk_result':e,'user_confirmation':f,'confirmation_text':generateConfirmationText(a,d,e),'decision_record':{'timestamp':new Date()['toISOString'](),'gate_version':ALLOCATION_CONFIRM_VERSION,'final_status':'approved','layers_passed':b,'layers_failed':c}};}function generateConfirmationText(a,b,c){const d=[],e=a['allocation_json'];d['push']('═══\x20Allocation\x20Confirmation\x20═══'),d['push']('');const f=e['object']!==null&&e['object']!==undefined&&typeof e['object']==='object';if(f){const g=e['object'];d['push']('Allocation:\x20NEW\x20\x27'+g['name']+'\x27\x20('+(g['type_parameter']??'<missing>')+')');}else typeof e['object']==='string'&&d['push']('Allocation:\x20OPERATE\x20'+e['object']);d['push'](''),d['push']('─\x20Checklist\x20──────────────────');for(const h of b['items']){const i=h['passed']?'✓':'✗';d['push']('\x20\x20'+i+'\x20'+h['id']+':\x20'+h['description']+(h['message']?'\x20—\x20'+h['message']:''));}d['push']('');if(c){d['push']('─\x20Risk\x20Assessment\x20──────────────────'),d['push']('Overall:\x20'+c['overall_risk']),d['push']('Detected:\x20'+c['risks']['length']+'\x20risk(s)');for(const j of c['risks']){d['push']('\x20\x20['+j['level']+']\x20'+j['id']+':\x20'+j['title']);}d['push']('');}return d['push']('─\x20Operations\x20──────────────────'),f&&e['allocators']&&(d['push']('-\x20Description:\x20'+e['allocators']['description']),d['push']('-\x20Threshold:\x20'+e['allocators']['threshold']),d['push']('-\x20Allocators:\x20'+e['allocators']['allocators']['length']),e['allocators']['allocators']['forEach']((k,l)=>{const m=k['sharing']['filter'](p=>p['mode']==='Surplus')['length'],n=k['sharing']['filter'](p=>p['mode']==='Rate')['reduce']((p,q)=>p+Number(q['sharing']),0x0),o=k['sharing']['filter'](p=>p['mode']==='Amount')['reduce']((p,q)=>p+Number(q['sharing']),0x0);d['push']('\x20\x20['+l+']\x20guard='+k['guard']+',\x20sharing='+k['sharing']['length']+'\x20(Rate\x20sum='+n+',\x20Amount\x20sum='+o+',\x20Surplus='+m+'),\x20max='+(k['max']??'null'));})),e['received_coins']&&d['push']('-\x20Receive:\x20'+e['received_coins']['received']['length']+'\x20CoinWrapper\x20deposit(s)'),e['alloc_by_guard']&&d['push']('-\x20Alloc\x20by\x20Guard:\x20'+e['alloc_by_guard']),d['push'](''),d['push']('─\x20Error\x20Code\x20Reference\x20──────────────────'),d['push']('\x20\x20EALLOCATORS_EMPTY='+ALLOCATION_ERROR_CODES['EALLOCATORS_EMPTY']+',\x20ENO_ALLOCATOR='+ALLOCATION_ERROR_CODES['ENO_ALLOCATOR']+',\x20ERATE_NOT_10000='+ALLOCATION_ERROR_CODES['ERATE_NOT_10000']),d['push']('\x20\x20EMULTIPLE_SURPLUS='+ALLOCATION_ERROR_CODES['EMULTIPLE_SURPLUS']+',\x20ERATE_EXCEEDS_10000='+ALLOCATION_ERROR_CODES['ERATE_EXCEEDS_10000']+',\x20EINSUFFICIENT_BALANCE='+ALLOCATION_ERROR_CODES['EINSUFFICIENT_BALANCE']),d['push']('\x20\x20ENO_PAYMENT_INFO='+ALLOCATION_ERROR_CODES['ENO_PAYMENT_INFO']+',\x20ESHARING_COUNT_EXCEEDED='+ALLOCATION_ERROR_CODES['ESHARING_COUNT_EXCEEDED']+',\x20EAMOUNT_BELOW_THRESHOLD='+ALLOCATION_ERROR_CODES['EAMOUNT_BELOW_THRESHOLD']),d['push']('\x20\x20EAMOUNT_EXCEEDS_MAX='+ALLOCATION_ERROR_CODES['EAMOUNT_EXCEEDS_MAX']+',\x20EALLOCATOR_COUNT_EXCEEDED='+ALLOCATION_ERROR_CODES['EALLOCATOR_COUNT_EXCEEDED']),d['push'](''),d['join']('\x0a');}export function progressiveAllocationCheck(a){const b=runStaticChecklist(a);if(!b['all_passed'])return{'stage':'checklist','status':'fail','message':'Checklist\x20failed:\x20'+b['items']['filter'](d=>!d['passed'])['map'](d=>d['id'])['join'](',\x20'),'next_action':'Fix\x20failing\x20checklist\x20items\x20(C-A-XX)'};const c=adaptRiskAssessment(a,b);if(c['blocks_publish'])return{'stage':'risk','status':'fail','message':'CRITICAL\x20risks:\x20'+c['risks']['filter'](d=>d['level']==='CRITICAL')['map'](d=>d['id'])['join'](',\x20'),'next_action':'Resolve\x20CRITICAL\x20risks\x20(R-A-1-01\x20empty\x20allocators,\x20R-A-2-01\x20Signer\x20theft)\x20before\x20proceeding'};if(c['needs_human_review'])return{'stage':'confirmation','status':'pending','message':'Human\x20review\x20required\x20for\x20HIGH\x20risks','next_action':'Confirm\x20risk\x20acceptance\x20(QA1\x20~\x20QA6)'};return{'stage':'complete','status':'pass','message':'All\x20checks\x20passed'};}