@wowok/agent-mcp 2.7.0 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.d.ts +5 -1
  13. package/dist/customer/risk-assessment.js +1 -397
  14. package/dist/customer/types.js +1 -13
  15. package/dist/customer/user-preferences.js +1 -460
  16. package/dist/evaluation/arbitration-game.d.ts +23 -0
  17. package/dist/evaluation/arbitration-game.js +1 -0
  18. package/dist/evaluation/builtins/demand-match.d.ts +15 -0
  19. package/dist/evaluation/builtins/demand-match.js +1 -0
  20. package/dist/evaluation/builtins/index.d.ts +3 -0
  21. package/dist/evaluation/builtins/index.js +1 -0
  22. package/dist/evaluation/builtins/service-risk.d.ts +6 -0
  23. package/dist/evaluation/builtins/service-risk.js +1 -0
  24. package/dist/evaluation/capability.d.ts +50 -0
  25. package/dist/evaluation/capability.js +1 -0
  26. package/dist/evaluation/composer.d.ts +13 -0
  27. package/dist/evaluation/composer.js +1 -0
  28. package/dist/evaluation/engine.d.ts +18 -0
  29. package/dist/evaluation/engine.js +1 -0
  30. package/dist/evaluation/extract.d.ts +30 -0
  31. package/dist/evaluation/extract.js +1 -0
  32. package/dist/evaluation/game-strategy.d.ts +27 -0
  33. package/dist/evaluation/game-strategy.js +1 -0
  34. package/dist/evaluation/gap.d.ts +2 -0
  35. package/dist/evaluation/gap.js +1 -0
  36. package/dist/evaluation/index.d.ts +12 -0
  37. package/dist/evaluation/index.js +1 -0
  38. package/dist/evaluation/node-game.d.ts +62 -0
  39. package/dist/evaluation/node-game.js +1 -0
  40. package/dist/evaluation/region.d.ts +10 -0
  41. package/dist/evaluation/region.js +1 -0
  42. package/dist/evaluation/types.d.ts +77 -0
  43. package/dist/evaluation/types.js +1 -0
  44. package/dist/evaluation/user-injection.d.ts +6 -0
  45. package/dist/evaluation/user-injection.js +1 -0
  46. package/dist/examples/education-contact-create.json +40 -0
  47. package/dist/examples/freelance-contact-create.json +40 -0
  48. package/dist/examples/insurance-machine-create.json +1 -1
  49. package/dist/examples/insurance-service-allocators.json +1 -1
  50. package/dist/examples/machine-publish.json +1 -1
  51. package/dist/examples/rental-ziroom-service-create.json +1 -1
  52. package/dist/examples/retail-adv-guard-messenger-proof-create.json +1 -1
  53. package/dist/examples/retail-myshop-service-create.json +1 -1
  54. package/dist/examples/retail-myshop-service-customer-required.json +1 -1
  55. package/dist/examples/subscription-contact-create.json +40 -0
  56. package/dist/examples/threebody-machine-create.json +1 -1
  57. package/dist/examples/travel-machine-create.json +1 -1
  58. package/dist/examples/travel-service-create.json +1 -1
  59. package/dist/experience/experience-reuse.js +1 -103
  60. package/dist/experience/index.js +1 -5
  61. package/dist/experience/intent-distill.js +1 -83
  62. package/dist/experience/realtime-feedback.js +1 -94
  63. package/dist/experience/types.js +1 -1
  64. package/dist/experience/user-profile.js +1 -171
  65. package/dist/extensions/business-modules.js +1 -287
  66. package/dist/extensions/capability-manifest.js +1 -781
  67. package/dist/extensions/constraint-registry.js +1 -198
  68. package/dist/extensions/index.js +1 -6
  69. package/dist/extensions/metric-registry.js +1 -257
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.js +1 -717
  73. package/dist/extensions/types.js +1 -1
  74. package/dist/harness/auto-escalation.js +1 -68
  75. package/dist/harness/checkpoint.js +1 -129
  76. package/dist/harness/index.js +1 -78
  77. package/dist/harness/plan.js +1 -276
  78. package/dist/harness/recover.js +1 -139
  79. package/dist/harness/types.js +1 -1
  80. package/dist/harness/verify.js +1 -237
  81. package/dist/index.js +1 -273
  82. package/dist/intent/enrich.d.ts +1 -0
  83. package/dist/intent/enrich.js +1 -0
  84. package/dist/intent/index.d.ts +23 -0
  85. package/dist/intent/index.js +1 -0
  86. package/dist/intent/matcher.d.ts +2 -0
  87. package/dist/intent/matcher.js +1 -0
  88. package/dist/intent/store.d.ts +19 -0
  89. package/dist/intent/store.js +1 -0
  90. package/dist/intent/types.d.ts +33 -0
  91. package/dist/intent/types.js +1 -0
  92. package/dist/knowledge/acquisition-flywheel.js +1 -192
  93. package/dist/knowledge/allocation-confirm.js +1 -534
  94. package/dist/knowledge/allocation-context.js +1 -249
  95. package/dist/knowledge/allocation-ledger.js +1 -463
  96. package/dist/knowledge/allocation-puzzle.js +1 -298
  97. package/dist/knowledge/allocation-risk.js +1 -568
  98. package/dist/knowledge/allocation-templates.js +1 -970
  99. package/dist/knowledge/allocation-translation.js +1 -585
  100. package/dist/knowledge/arb-risk.js +1 -210
  101. package/dist/knowledge/arbitration-confirm.js +1 -559
  102. package/dist/knowledge/arbitration-context.js +1 -505
  103. package/dist/knowledge/arbitration-ledger.js +1 -521
  104. package/dist/knowledge/arbitration-puzzle.js +1 -304
  105. package/dist/knowledge/arbitration-risk.js +1 -433
  106. package/dist/knowledge/arbitration-templates.js +1 -276
  107. package/dist/knowledge/arbitration-translation.js +1 -487
  108. package/dist/knowledge/arbitration-trust.js +1 -117
  109. package/dist/knowledge/audit-rules.js +1 -141
  110. package/dist/knowledge/bridge-risk.js +1 -263
  111. package/dist/knowledge/contact-risk.js +1 -200
  112. package/dist/knowledge/contact-templates.d.ts +27 -0
  113. package/dist/knowledge/contact-templates.js +1 -0
  114. package/dist/knowledge/demand-confirm.js +1 -206
  115. package/dist/knowledge/demand-matching.js +1 -132
  116. package/dist/knowledge/demand-risk.js +1 -240
  117. package/dist/knowledge/demand-translation.js +1 -354
  118. package/dist/knowledge/deployment-scanner.js +1 -823
  119. package/dist/knowledge/dynamic-pricing.js +1 -87
  120. package/dist/knowledge/examples-scanner-cli.js +1 -26
  121. package/dist/knowledge/examples-scanner.js +1 -825
  122. package/dist/knowledge/flywheel-loop.js +1 -404
  123. package/dist/knowledge/fund-layer.js +1 -973
  124. package/dist/knowledge/glossary.js +1 -211
  125. package/dist/knowledge/guard-confirm.js +1 -406
  126. package/dist/knowledge/guard-context.js +1 -287
  127. package/dist/knowledge/guard-design-patterns.js +1 -360
  128. package/dist/knowledge/guard-ledger.js +1 -260
  129. package/dist/knowledge/guard-lint.js +1 -670
  130. package/dist/knowledge/guard-migration.js +1 -228
  131. package/dist/knowledge/guard-puzzle.js +1 -805
  132. package/dist/knowledge/guard-render.js +1 -700
  133. package/dist/knowledge/guard-risk.js +1 -1879
  134. package/dist/knowledge/guard-submission-prompt.js +1 -171
  135. package/dist/knowledge/guard-templates.js +1 -1105
  136. package/dist/knowledge/guard-translation.js +1 -1119
  137. package/dist/knowledge/index.js +1 -436
  138. package/dist/knowledge/industry-evolution.js +1 -323
  139. package/dist/knowledge/industry-generalizer.js +1 -381
  140. package/dist/knowledge/industry-registry.js +1 -174
  141. package/dist/knowledge/intent-metrics.d.ts +4 -3
  142. package/dist/knowledge/intent-metrics.js +1 -566
  143. package/dist/knowledge/machine-confirm.js +1 -559
  144. package/dist/knowledge/machine-context.js +1 -833
  145. package/dist/knowledge/machine-ledger.js +1 -338
  146. package/dist/knowledge/machine-puzzle.js +1 -494
  147. package/dist/knowledge/machine-render.js +1 -565
  148. package/dist/knowledge/machine-risk.js +1 -670
  149. package/dist/knowledge/machine-templates.js +1 -1597
  150. package/dist/knowledge/machine-topology.js +1 -234
  151. package/dist/knowledge/machine-translation.js +1 -513
  152. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  153. package/dist/knowledge/mcp-schema-audit.d.ts +1 -1
  154. package/dist/knowledge/mcp-schema-audit.js +1 -773
  155. package/dist/knowledge/onchain-constants.js +1 -35
  156. package/dist/knowledge/order-confirm.js +1 -573
  157. package/dist/knowledge/order-context.js +1 -390
  158. package/dist/knowledge/order-ledger.js +1 -341
  159. package/dist/knowledge/order-puzzle.js +1 -255
  160. package/dist/knowledge/order-risk.js +1 -653
  161. package/dist/knowledge/order-templates.js +1 -368
  162. package/dist/knowledge/order-translation.js +1 -550
  163. package/dist/knowledge/overrides-loader.js +1 -65
  164. package/dist/knowledge/passport-confirm.js +1 -531
  165. package/dist/knowledge/passport-context.js +1 -306
  166. package/dist/knowledge/passport-ledger.js +1 -282
  167. package/dist/knowledge/passport-puzzle.js +1 -333
  168. package/dist/knowledge/passport-risk.js +1 -450
  169. package/dist/knowledge/passport-templates.js +1 -568
  170. package/dist/knowledge/passport-translation.js +1 -516
  171. package/dist/knowledge/payment-risk.js +1 -249
  172. package/dist/knowledge/permission-confirm.js +1 -426
  173. package/dist/knowledge/permission-context.js +1 -224
  174. package/dist/knowledge/permission-ledger.js +1 -403
  175. package/dist/knowledge/permission-puzzle.js +1 -173
  176. package/dist/knowledge/permission-risk.js +1 -411
  177. package/dist/knowledge/permission-templates.js +1 -234
  178. package/dist/knowledge/permission-translation.js +1 -350
  179. package/dist/knowledge/personal-risk.js +1 -212
  180. package/dist/knowledge/process-model.js +1 -160
  181. package/dist/knowledge/progress-confirm.js +1 -456
  182. package/dist/knowledge/progress-context.js +1 -452
  183. package/dist/knowledge/progress-ledger.js +1 -330
  184. package/dist/knowledge/progress-puzzle.js +1 -219
  185. package/dist/knowledge/progress-risk.js +1 -461
  186. package/dist/knowledge/progress-templates.js +1 -228
  187. package/dist/knowledge/progress-translation.js +1 -405
  188. package/dist/knowledge/proof-confirm.js +1 -187
  189. package/dist/knowledge/proof-risk.js +1 -207
  190. package/dist/knowledge/proof-translation.js +1 -283
  191. package/dist/knowledge/registrar-risk.js +1 -217
  192. package/dist/knowledge/repository-confirm.js +1 -286
  193. package/dist/knowledge/repository-risk.js +1 -373
  194. package/dist/knowledge/repository-translation.js +1 -445
  195. package/dist/knowledge/reputation-rules.js +1 -99
  196. package/dist/knowledge/resource-risk.js +1 -157
  197. package/dist/knowledge/reward-confirm.js +1 -526
  198. package/dist/knowledge/reward-context.js +1 -504
  199. package/dist/knowledge/reward-ledger.js +1 -502
  200. package/dist/knowledge/reward-puzzle.js +1 -300
  201. package/dist/knowledge/reward-risk.js +1 -627
  202. package/dist/knowledge/reward-templates.js +1 -197
  203. package/dist/knowledge/reward-translation.js +1 -501
  204. package/dist/knowledge/safety-rules.js +1 -404
  205. package/dist/knowledge/scenario-modes.js +1 -321
  206. package/dist/knowledge/service-confirm.js +1 -807
  207. package/dist/knowledge/service-context.js +1 -403
  208. package/dist/knowledge/service-ledger.js +1 -609
  209. package/dist/knowledge/service-puzzle.js +1 -236
  210. package/dist/knowledge/service-risk.js +1 -615
  211. package/dist/knowledge/service-templates.js +1 -456
  212. package/dist/knowledge/service-translation.js +1 -622
  213. package/dist/knowledge/template-registry.d.ts +1 -1
  214. package/dist/knowledge/template-registry.js +1 -341
  215. package/dist/knowledge/tool-constraints.js +1 -195
  216. package/dist/knowledge/tools-reference.js +1 -155
  217. package/dist/knowledge/treasury-confirm.js +1 -512
  218. package/dist/knowledge/treasury-context.js +1 -363
  219. package/dist/knowledge/treasury-ledger.js +1 -300
  220. package/dist/knowledge/treasury-puzzle.js +1 -216
  221. package/dist/knowledge/treasury-risk.js +1 -440
  222. package/dist/knowledge/treasury-templates.js +1 -358
  223. package/dist/knowledge/treasury-translation.js +1 -498
  224. package/dist/knowledge/trust-metrics.js +1 -198
  225. package/dist/knowledge/util-risk.js +1 -135
  226. package/dist/loop-engineering/aggregate.js +1 -132
  227. package/dist/loop-engineering/context-collect.js +1 -83
  228. package/dist/loop-engineering/diagnose.js +1 -273
  229. package/dist/loop-engineering/improve.js +1 -405
  230. package/dist/loop-engineering/index.js +1 -4
  231. package/dist/loop-engineering/pipeline.js +1 -56
  232. package/dist/mode-market/index.js +1 -3
  233. package/dist/mode-market/registry.js +1 -124
  234. package/dist/mode-market/review.js +1 -214
  235. package/dist/mode-market/submission.js +1 -85
  236. package/dist/participation/collaborator-interest.d.ts +23 -0
  237. package/dist/participation/collaborator-interest.js +1 -0
  238. package/dist/participation/customer-interest.d.ts +25 -0
  239. package/dist/participation/customer-interest.js +1 -0
  240. package/dist/participation/merchant-interest.js +1 -100
  241. package/dist/participation/radar-core.d.ts +13 -3
  242. package/dist/participation/radar-core.js +1 -269
  243. package/dist/participation/supplier-interest.d.ts +25 -0
  244. package/dist/participation/supplier-interest.js +1 -0
  245. package/dist/persona/analyzer.d.ts +16 -0
  246. package/dist/persona/analyzer.js +1 -0
  247. package/dist/persona/bridge.d.ts +5 -0
  248. package/dist/persona/bridge.js +1 -0
  249. package/dist/persona/defaults.d.ts +4 -0
  250. package/dist/persona/defaults.js +1 -0
  251. package/dist/persona/experience-bridge.d.ts +3 -0
  252. package/dist/persona/experience-bridge.js +1 -0
  253. package/dist/persona/index.d.ts +18 -0
  254. package/dist/persona/index.js +1 -0
  255. package/dist/persona/model.d.ts +7 -0
  256. package/dist/persona/model.js +1 -0
  257. package/dist/persona/store.d.ts +19 -0
  258. package/dist/persona/store.js +1 -0
  259. package/dist/persona/types.d.ts +45 -0
  260. package/dist/persona/types.js +1 -0
  261. package/dist/project/business-puzzle.js +1 -383
  262. package/dist/project/context-assembly.js +1 -254
  263. package/dist/project/deployment-bridge.js +1 -120
  264. package/dist/project/deployment-doc.js +1 -1126
  265. package/dist/project/edit-planner.js +1 -1342
  266. package/dist/project/evaluation.js +1 -2011
  267. package/dist/project/game-theory.js +1 -177
  268. package/dist/project/graph-builder.js +1 -656
  269. package/dist/project/graph.js +1 -340
  270. package/dist/project/handlers.d.ts +5 -0
  271. package/dist/project/handlers.js +1 -1762
  272. package/dist/project/index.d.ts +1 -0
  273. package/dist/project/index.js +1 -301
  274. package/dist/project/intent-analyzer.js +1 -149
  275. package/dist/project/machine-nodes.js +1 -36
  276. package/dist/project/merchant-guide.js +1 -264
  277. package/dist/project/migration.js +1 -125
  278. package/dist/project/mode-actions.js +1 -309
  279. package/dist/project/namespace.js +1 -206
  280. package/dist/project/participation-radar.js +1 -428
  281. package/dist/project/pipeline-actions.js +1 -109
  282. package/dist/project/project-store.js +1 -422
  283. package/dist/project/query.js +1 -153
  284. package/dist/project/reverse-mapping.d.ts +34 -0
  285. package/dist/project/reverse-mapping.js +1 -0
  286. package/dist/project/risk-aggregator.js +1 -295
  287. package/dist/project/rollback-policy.js +1 -290
  288. package/dist/project/semantic-assembler.js +1 -345
  289. package/dist/project/semantic-graph.js +1 -245
  290. package/dist/project/stage-gate.js +1 -369
  291. package/dist/project/substep-trace.js +1 -332
  292. package/dist/project/task-tracker.js +1 -78
  293. package/dist/role/derivation.d.ts +18 -0
  294. package/dist/role/derivation.js +1 -0
  295. package/dist/role/index.d.ts +5 -0
  296. package/dist/role/index.js +1 -0
  297. package/dist/role/model.d.ts +8 -0
  298. package/dist/role/model.js +1 -0
  299. package/dist/role/resolution.d.ts +11 -0
  300. package/dist/role/resolution.js +1 -0
  301. package/dist/role/types.d.ts +11 -0
  302. package/dist/role/types.js +1 -0
  303. package/dist/rules.d.ts +2 -0
  304. package/dist/rules.js +1 -9
  305. package/dist/safety/confirm-gate.js +1 -88
  306. package/dist/safety/index.js +1 -3
  307. package/dist/safety/preview.js +1 -52
  308. package/dist/schema/call/allocation.js +1 -34
  309. package/dist/schema/call/arbitration.js +1 -113
  310. package/dist/schema/call/base.d.ts +15 -15
  311. package/dist/schema/call/base.js +1 -370
  312. package/dist/schema/call/bridge-handler.js +1 -265
  313. package/dist/schema/call/bridge.d.ts +7 -7
  314. package/dist/schema/call/bridge.js +1 -458
  315. package/dist/schema/call/contact.js +1 -37
  316. package/dist/schema/call/demand.js +1 -47
  317. package/dist/schema/call/guard.js +1 -161
  318. package/dist/schema/call/handler.js +1 -322
  319. package/dist/schema/call/index.js +1 -20
  320. package/dist/schema/call/machine.js +1 -193
  321. package/dist/schema/call/order.js +1 -35
  322. package/dist/schema/call/payment.js +1 -37
  323. package/dist/schema/call/permission-handler.js +1 -54
  324. package/dist/schema/call/permission.js +1 -105
  325. package/dist/schema/call/personal.js +1 -78
  326. package/dist/schema/call/progress.js +1 -47
  327. package/dist/schema/call/proof.js +1 -33
  328. package/dist/schema/call/repository.js +1 -77
  329. package/dist/schema/call/reward.js +1 -30
  330. package/dist/schema/call/semantic.js +1 -1657
  331. package/dist/schema/call/service.js +1 -178
  332. package/dist/schema/call/treasury.js +1 -71
  333. package/dist/schema/common/index.js +1 -407
  334. package/dist/schema/config/index.js +1 -68
  335. package/dist/schema/evaluation/index.d.ts +4436 -0
  336. package/dist/schema/evaluation/index.js +1 -0
  337. package/dist/schema/index.d.ts +4 -0
  338. package/dist/schema/index.js +1 -13
  339. package/dist/schema/intent-radar/index.d.ts +284 -0
  340. package/dist/schema/intent-radar/index.js +1 -0
  341. package/dist/schema/local/index.d.ts +21 -21
  342. package/dist/schema/local/index.js +1 -927
  343. package/dist/schema/local/wip.js +1 -187
  344. package/dist/schema/messenger/index.d.ts +7 -7
  345. package/dist/schema/messenger/index.js +1 -475
  346. package/dist/schema/operations.d.ts +7 -7
  347. package/dist/schema/operations.js +1 -520
  348. package/dist/schema/persona/index.d.ts +1985 -0
  349. package/dist/schema/persona/index.js +1 -0
  350. package/dist/schema/project/index.d.ts +96 -50
  351. package/dist/schema/project/index.js +1 -2057
  352. package/dist/schema/query/index.d.ts +423 -7
  353. package/dist/schema/query/index.js +1 -1640
  354. package/dist/schema/schema-query/index.js +1 -104
  355. package/dist/schema/schema-version.js +1 -76
  356. package/dist/schema/sync-layer4.d.ts +1 -1
  357. package/dist/schema/sync-layer4.js +1 -282
  358. package/dist/schema/task-status.d.ts +168 -0
  359. package/dist/schema/task-status.js +1 -0
  360. package/dist/schema/trust/index.js +1 -314
  361. package/dist/schema/utils/guard-parser.js +1 -419
  362. package/dist/schema/utils/guard-query-utils.js +1 -46
  363. package/dist/schema/utils/node-parser.js +1 -369
  364. package/dist/schema/utils/object-type-utils.js +1 -35
  365. package/dist/schema/utils/permission-index-utils.js +1 -7
  366. package/dist/schema/utils/permission-machine-check.js +1 -121
  367. package/dist/schema/utils/skills-recommendation.js +1 -77
  368. package/dist/schema-query/index.js +1 -810
  369. package/dist/schemas/account_operation.output.json +5 -2
  370. package/dist/schemas/bridge_operation.output.json +5 -2
  371. package/dist/schemas/evaluation_operation.output.json +782 -0
  372. package/dist/schemas/evaluation_operation.schema.json +990 -0
  373. package/dist/schemas/index.json +25 -1
  374. package/dist/schemas/intent_radar.output.json +232 -0
  375. package/dist/schemas/intent_radar.schema.json +138 -0
  376. package/dist/schemas/local_info_operation.output.json +5 -2
  377. package/dist/schemas/local_mark_operation.output.json +5 -2
  378. package/dist/schemas/messenger_operation.output.json +5 -2
  379. package/dist/schemas/onchain_events.output.json +5 -2
  380. package/dist/schemas/onchain_operations.output.json +5 -2
  381. package/dist/schemas/onchain_operations.schema.json +6 -6
  382. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  383. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  384. package/dist/schemas/onchain_operations_service.schema.json +3 -3
  385. package/dist/schemas/onchain_table_data.output.json +6 -3
  386. package/dist/schemas/persona_operation.output.json +392 -0
  387. package/dist/schemas/persona_operation.schema.json +250 -0
  388. package/dist/schemas/project_operation.output.json +28 -8
  389. package/dist/schemas/query_task_status.output.json +115 -0
  390. package/dist/schemas/query_task_status.schema.json +24 -0
  391. package/dist/schemas/query_toolkit.output.json +9 -6
  392. package/dist/schemas/trust_score.schema.json +1 -1
  393. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  394. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  395. package/dist/telemetry/index.js +1 -112
  396. package/dist/telemetry/redact.js +1 -23
  397. package/dist/telemetry/storage.js +1 -80
  398. package/dist/tools/handlers/bridge.js +1 -1
  399. package/dist/tools/handlers/config.js +1 -74
  400. package/dist/tools/handlers/evaluation.d.ts +2 -0
  401. package/dist/tools/handlers/evaluation.js +1 -0
  402. package/dist/tools/handlers/file-export.js +1 -90
  403. package/dist/tools/handlers/intent-radar.d.ts +2 -0
  404. package/dist/tools/handlers/intent-radar.js +1 -0
  405. package/dist/tools/handlers/local.js +1 -53
  406. package/dist/tools/handlers/messenger.js +1 -188
  407. package/dist/tools/handlers/onchain.js +1 -1082
  408. package/dist/tools/handlers/persona.d.ts +4 -0
  409. package/dist/tools/handlers/persona.js +1 -0
  410. package/dist/tools/handlers/project.js +1 -211
  411. package/dist/tools/handlers/query.js +1 -434
  412. package/dist/tools/handlers/schema-query.js +1 -176
  413. package/dist/tools/handlers/task-status.d.ts +0 -168
  414. package/dist/tools/handlers/task-status.js +1 -55
  415. package/dist/tools/handlers/trust.js +1 -380
  416. package/dist/tools/handlers/wip.js +1 -90
  417. package/dist/tools/index.js +1 -1306
  418. package/dist/tools/retry.js +1 -85
  419. package/dist/tools/rules-hook.js +1 -23
  420. package/dist/tools/shared.js +1 -130
  421. package/dist/tools/types.js +1 -1
  422. package/dist/tools/upgrade-check.d.ts +19 -0
  423. package/dist/tools/upgrade-check.js +1 -0
  424. package/dist/tools/wip-deploy-assist.d.ts +1 -1
  425. package/dist/tools/wip-deploy-assist.js +1 -278
  426. package/dist/tools/wrap.js +1 -500
  427. package/package.json +5 -3
@@ -1,2011 +1 @@
1
- import { IndustryModeRegistry } from "../extensions/registry.js";
2
- import { collectPermissionIndexes, checkPermissionAuthorization, } from "../schema/utils/permission-machine-check.js";
3
- const CRITICAL_BINDINGS = [
4
- { sourceType: "Service", targetType: "Machine", fieldName: "machine", critical: true },
5
- { sourceType: "Service", targetType: "Permission", fieldName: "permission", critical: true },
6
- { sourceType: "Service", targetType: "Guard", fieldName: "buy_guard", critical: false },
7
- { sourceType: "Service", targetType: "Allocation", fieldName: "order_allocators", critical: true },
8
- { sourceType: "Service", targetType: "Arbitration", fieldName: "arbitrations", critical: false },
9
- { sourceType: "Machine", targetType: "Permission", fieldName: "permission", critical: true },
10
- ];
11
- const MERCHANT_REQUIRED_ITEMS = [
12
- { id: "R1", objectType: "Permission", fieldName: "", required: true, description: "Governance — who can manage the service" },
13
- { id: "R2", objectType: "Service", fieldName: "", required: true, description: "Core offering — the service itself" },
14
- { id: "R3", objectType: "Machine", fieldName: "machine", required: true, description: "Workflow — order processing pipeline" },
15
- { id: "R4", objectType: "Guard", fieldName: "", required: true, description: "Purchase validation — Guard objects configured (binding to Service.buy_guard is optional)" },
16
- { id: "R5", objectType: "Allocation", fieldName: "order_allocators", required: true, description: "Order allocators template — inline Allocators on Service (independent Allocation objects are created per-order)" },
17
- { id: "R6", objectType: "Treasury", fieldName: "", required: true, description: "Compensation fund — independent Treasury object for buyer refund protection (industry-aware: optional for freelance)" },
18
- { id: "R7", objectType: "Arbitration", fieldName: "arbitrations", required: true, description: "Dispute resolution — arbitration configured (required when compensation_fund > 0 per service.move:494)" },
19
- { id: "R8", objectType: "Contact", fieldName: "", required: true, description: "Customer communication — contact info" },
20
- { id: "R9", objectType: "Progress", fieldName: "", required: false, description: "Order tracking — progress nodes" },
21
- { id: "R10", objectType: "Reward", fieldName: "rewards", required: false, description: "Customer incentives — reward claims" },
22
- { id: "R11", objectType: "Repository", fieldName: "repositories", required: false, description: "Documentation — published data" },
23
- { id: "R12", objectType: "Demand", fieldName: "", required: false, description: "Market discovery — demand signals" },
24
- ];
25
- function resolveRequiredItems(industry, compensationFundBalance = 0, hasAllocationEscrow = false) {
26
- let result = MERCHANT_REQUIRED_ITEMS;
27
- if (industry && industry !== "general") {
28
- let mode;
29
- try {
30
- mode = IndustryModeRegistry.Instance().getMode(industry);
31
- }
32
- catch {
33
- }
34
- if (mode) {
35
- const requireFund = mode.risk_constraints?.require_compensation_fund ?? true;
36
- if (!requireFund) {
37
- result = MERCHANT_REQUIRED_ITEMS.map(item => {
38
- if (item.id === "R6" || item.id === "R7") {
39
- return { ...item, required: false };
40
- }
41
- return item;
42
- });
43
- }
44
- }
45
- }
46
- if (hasAllocationEscrow && compensationFundBalance === 0) {
47
- result = result.map(item => {
48
- if (item.id === "R6") {
49
- return { ...item, required: false };
50
- }
51
- return item;
52
- });
53
- }
54
- if (compensationFundBalance > 0) {
55
- result = result.map(item => item.id === "R7" ? { ...item, required: true } : item);
56
- }
57
- return result;
58
- }
59
- const CONSUMER_DUE_DILIGENCE = [
60
- { id: "E1", check: "Service is published (bPublished=true)", severity: "critical", deduction: -30 },
61
- { id: "E2", check: "Service is not paused (bPaused=false)", severity: "warning", deduction: -20 },
62
- { id: "E3", check: "Machine has workflow nodes", severity: "warning", deduction: -15 },
63
- { id: "E4", check: "Service has buy_guard (purchase validation)", severity: "info", deduction: 0 },
64
- { id: "E5", check: "Service has compensation_fund (refund protection)", severity: "warning", deduction: -15 },
65
- { id: "E6", check: "Arbitration is configured (dispute resolution)", severity: "critical", deduction: -25 },
66
- { id: "E7", check: "Permission is present (governance)", severity: "warning", deduction: -10 },
67
- { id: "E8", check: "Contact is available (merchant reachable)", severity: "info", deduction: -5 },
68
- { id: "E9", check: "Repository has published data (transparency)", severity: "info", deduction: -5 },
69
- { id: "E10", check: "Reward is configured (customer incentives)", severity: "info", deduction: -3 },
70
- { id: "E11", check: "Service has description (offering clarity)", severity: "info", deduction: -5 },
71
- { id: "E12", check: "Registrar reputation is positive", severity: "warning", deduction: -10 },
72
- ];
73
- function clampScore(n) {
74
- return Math.max(0, Math.min(100, Math.round(n)));
75
- }
76
- function shortTypeName(objectType) {
77
- if (!objectType)
78
- return "unknown";
79
- const base = objectType.replace(/<.*>/, "").trim();
80
- const segments = base.split("::");
81
- const shortName = segments[segments.length - 1] || "unknown";
82
- if (shortName.length > 0 && shortName === shortName.toLowerCase()) {
83
- return shortName.charAt(0).toUpperCase() + shortName.slice(1);
84
- }
85
- return shortName;
86
- }
87
- function groupByType(objects) {
88
- const byType = new Map();
89
- for (const obj of objects) {
90
- const t = shortTypeName(obj.objectType);
91
- if (!byType.has(t))
92
- byType.set(t, []);
93
- byType.get(t).push(obj);
94
- }
95
- return byType;
96
- }
97
- function parseCacheData(cached) {
98
- if (!cached)
99
- return null;
100
- try {
101
- return JSON.parse(cached.data);
102
- }
103
- catch {
104
- return null;
105
- }
106
- }
107
- function isAddress(v) {
108
- return typeof v === "string" && v.startsWith("0x") && v.length >= 10;
109
- }
110
- function countArrayField(data, field) {
111
- const v = data[field];
112
- if (Array.isArray(v))
113
- return v.length;
114
- return 0;
115
- }
116
- export function getNumberField(data, field) {
117
- if (!data)
118
- return 0;
119
- const v = data[field];
120
- if (typeof v === "number" && Number.isFinite(v))
121
- return v;
122
- if (typeof v === "string") {
123
- const n = Number(v);
124
- if (Number.isFinite(n))
125
- return n;
126
- }
127
- return 0;
128
- }
129
- export function getMachineNodeCount(data) {
130
- if (!data)
131
- return 0;
132
- const nc = getNumberField(data, "node_count");
133
- if (nc > 0)
134
- return nc;
135
- const arrLen = countArrayField(data, "nodes");
136
- if (arrLen > 0)
137
- return arrLen;
138
- const nodesObj = data["nodes"];
139
- if (nodesObj && typeof nodesObj === "object") {
140
- const fieldsObj = nodesObj["fields"];
141
- if (fieldsObj && typeof fieldsObj === "object") {
142
- const sizeVal = getNumberField(fieldsObj, "size");
143
- if (sizeVal > 0)
144
- return sizeVal;
145
- }
146
- const directSize = getNumberField(nodesObj, "size");
147
- if (directSize > 0)
148
- return directSize;
149
- }
150
- return 0;
151
- }
152
- function extractMachineNodesFromCache(data) {
153
- if (!data)
154
- return [];
155
- const nodesArr = data["nodes"];
156
- if (Array.isArray(nodesArr)) {
157
- return nodesArr;
158
- }
159
- const config = data["config"];
160
- if (config && Array.isArray(config["nodes"])) {
161
- return config["nodes"];
162
- }
163
- const nodesObj = data["nodes"];
164
- if (nodesObj && typeof nodesObj === "object") {
165
- const fieldsObj = nodesObj["fields"];
166
- if (fieldsObj && Array.isArray(fieldsObj["contents"])) {
167
- return fieldsObj["contents"];
168
- }
169
- }
170
- return [];
171
- }
172
- function getBalanceValue(data, field) {
173
- if (!data)
174
- return 0;
175
- const v = data[field];
176
- if (v == null)
177
- return 0;
178
- if (typeof v === "number" && Number.isFinite(v))
179
- return v;
180
- if (typeof v === "string") {
181
- const n = Number(v);
182
- if (Number.isFinite(n))
183
- return n;
184
- }
185
- if (typeof v === "object") {
186
- const obj = v;
187
- const inner = obj.value ?? obj.fields;
188
- if (typeof inner === "number" && Number.isFinite(inner))
189
- return inner;
190
- if (typeof inner === "string") {
191
- const n = Number(inner);
192
- if (Number.isFinite(n))
193
- return n;
194
- }
195
- if (typeof inner === "object" && inner !== null) {
196
- const innerObj = inner;
197
- const val = innerObj.value;
198
- if (typeof val === "number" && Number.isFinite(val))
199
- return val;
200
- if (typeof val === "string") {
201
- const n = Number(val);
202
- if (Number.isFinite(n))
203
- return n;
204
- }
205
- }
206
- }
207
- return 0;
208
- }
209
- function getMaxSalePrice(data) {
210
- if (!data)
211
- return 0;
212
- const sales = data.sales;
213
- if (!Array.isArray(sales) || sales.length === 0)
214
- return 0;
215
- let max = 0;
216
- for (const sale of sales) {
217
- if (typeof sale !== "object" || sale === null)
218
- continue;
219
- const price = sale.price;
220
- let n = 0;
221
- if (typeof price === "number" && Number.isFinite(price)) {
222
- n = price;
223
- }
224
- else if (typeof price === "string") {
225
- const parsed = Number(price);
226
- if (Number.isFinite(parsed))
227
- n = parsed;
228
- }
229
- if (n > max)
230
- max = n;
231
- }
232
- return max;
233
- }
234
- function detectCircularRefs(edges, objectTypeMap) {
235
- const adj = new Map();
236
- for (const e of edges) {
237
- if (e.edgeSource === "potential")
238
- continue;
239
- if (!adj.has(e.sourceObject))
240
- adj.set(e.sourceObject, []);
241
- adj.get(e.sourceObject).push(e.targetObject);
242
- }
243
- const cycles = [];
244
- const visited = new Set();
245
- const recursionStack = new Set();
246
- const path = [];
247
- for (const startNode of adj.keys()) {
248
- if (visited.has(startNode))
249
- continue;
250
- const stack = [{
251
- node: startNode,
252
- nextNeighborIdx: 0,
253
- neighbors: adj.get(startNode) ?? [],
254
- }];
255
- visited.add(startNode);
256
- recursionStack.add(startNode);
257
- path.push(startNode);
258
- while (stack.length > 0) {
259
- const frame = stack[stack.length - 1];
260
- if (frame.nextNeighborIdx >= frame.neighbors.length) {
261
- stack.pop();
262
- path.pop();
263
- recursionStack.delete(frame.node);
264
- continue;
265
- }
266
- const neighbor = frame.neighbors[frame.nextNeighborIdx];
267
- frame.nextNeighborIdx++;
268
- if (!visited.has(neighbor)) {
269
- visited.add(neighbor);
270
- recursionStack.add(neighbor);
271
- path.push(neighbor);
272
- stack.push({
273
- node: neighbor,
274
- nextNeighborIdx: 0,
275
- neighbors: adj.get(neighbor) ?? [],
276
- });
277
- }
278
- else if (recursionStack.has(neighbor)) {
279
- const cycleStart = path.indexOf(neighbor);
280
- const cycle = path.slice(cycleStart).concat(neighbor);
281
- if (!isWoWokNormalFundCycle(cycle, objectTypeMap)) {
282
- cycles.push(cycle.join("→"));
283
- }
284
- }
285
- }
286
- }
287
- return cycles;
288
- }
289
- function isWoWokNormalFundCycle(cycle, objectTypeMap) {
290
- if (!objectTypeMap || cycle.length < 3)
291
- return false;
292
- const typesInCycle = new Set();
293
- for (const addr of cycle) {
294
- const type = objectTypeMap.get(addr);
295
- if (type) {
296
- typesInCycle.add(type);
297
- }
298
- else {
299
- return false;
300
- }
301
- }
302
- if (typesInCycle.size === 2 &&
303
- typesInCycle.has("Order") &&
304
- typesInCycle.has("Allocation")) {
305
- return true;
306
- }
307
- if (typesInCycle.size === 3 &&
308
- typesInCycle.has("Order") &&
309
- typesInCycle.has("Allocation") &&
310
- typesInCycle.has("Payment")) {
311
- return true;
312
- }
313
- const workflowTypes = ["Service", "Machine", "Progress", "Order"];
314
- const isWorkflowCycle = Array.from(typesInCycle).every(t => workflowTypes.includes(t));
315
- if (isWorkflowCycle && typesInCycle.size >= 2) {
316
- return true;
317
- }
318
- return false;
319
- }
320
- function adjustWeightsForPerspective(criterionScores, perspective) {
321
- if (perspective === "consumer") {
322
- return criterionScores.map(c => {
323
- if (c.name === "reputation" || c.name === "arbitration_coverage" || c.name === "consumer_diligence") {
324
- return { ...c, weight: c.weight * 1.4 };
325
- }
326
- if (c.name === "structural_risk" || c.name === "deployment_readiness") {
327
- return { ...c, weight: c.weight * 0.7 };
328
- }
329
- return c;
330
- });
331
- }
332
- if (perspective === "producer") {
333
- return criterionScores.map(c => {
334
- if (c.name === "structural_risk" || c.name === "deployment_readiness" || c.name === "binding_completeness") {
335
- return { ...c, weight: c.weight * 1.3 };
336
- }
337
- if (c.name === "consumer_diligence" || c.name === "transparency") {
338
- return { ...c, weight: c.weight * 0.7 };
339
- }
340
- return c;
341
- });
342
- }
343
- return criterionScores;
344
- }
345
- function normalizeWeights(criterionScores) {
346
- const total = criterionScores.reduce((sum, c) => sum + c.weight, 0);
347
- if (total === 0)
348
- return criterionScores;
349
- return criterionScores.map(c => ({ ...c, weight: c.weight / total }));
350
- }
351
- export const RISK_WEIGHTS = {
352
- structural_risk: 0.25,
353
- fund_safety: 0.2,
354
- operational_risk: 0.15,
355
- governance_risk: 0.1,
356
- graph_coherence: 0.2,
357
- mode_registry: 0.1,
358
- };
359
- export const TRUST_WEIGHTS = {
360
- reputation: 0.25,
361
- arbitration_coverage: 0.2,
362
- guard_quality: 0.2,
363
- transparency: 0.15,
364
- consumer_diligence: 0.2,
365
- };
366
- export const COMPLETENESS_WEIGHTS = {
367
- object_coverage: 0.3,
368
- binding_completeness: 0.25,
369
- workflow_rationality: 0.2,
370
- deployment_readiness: 0.25,
371
- };
372
- export const EXTENDED_DIMENSION_WEIGHTS = {
373
- escrow_quality: 0.15,
374
- proof_integrity: 0.1,
375
- arbitration_fairness: 0.15,
376
- fee_transparency: 0.1,
377
- timeout_protection: 0.1,
378
- supplier_visibility: 0.1,
379
- content_commitment: 0.1,
380
- reputation_verifiability: 0.1,
381
- permission_safety: 0.1,
382
- };
383
- export function finalizeCriterionScores(baseScores, perspective) {
384
- const criterionScores = normalizeWeights(adjustWeightsForPerspective(baseScores, perspective));
385
- const overall = clampScore(criterionScores.reduce((sum, c) => sum + c.score * c.weight, 0));
386
- return { criterionScores, overall };
387
- }
388
- function buildBindingIndex(edges) {
389
- const idx = new Map();
390
- for (const e of edges) {
391
- if (e.edgeSource === "potential")
392
- continue;
393
- if (!e.fieldName)
394
- continue;
395
- const key = `${e.sourceObject}#${e.fieldName}`;
396
- if (!idx.has(key))
397
- idx.set(key, new Set());
398
- idx.get(key).add(e.targetObject);
399
- }
400
- for (const e of edges) {
401
- if (e.edgeSource !== "potential")
402
- continue;
403
- if (!e.fieldName)
404
- continue;
405
- const key = `${e.sourceObject}#${e.fieldName}`;
406
- if (!idx.has(key) || idx.get(key).size === 0) {
407
- if (!idx.has(key))
408
- idx.set(key, new Set());
409
- idx.get(key).add(e.targetObject);
410
- }
411
- }
412
- return idx;
413
- }
414
- function evaluateIndustryPattern(project, objects, objectCache, edges) {
415
- const result = { strengths: [], findings: [], matched: false };
416
- const industryName = project.industry;
417
- if (!industryName || industryName === "general") {
418
- return result;
419
- }
420
- let mode;
421
- try {
422
- mode = IndustryModeRegistry.Instance().getMode(industryName);
423
- }
424
- catch {
425
- return result;
426
- }
427
- if (!mode)
428
- return result;
429
- const byType = groupByType(objects);
430
- const bindingIndex = buildBindingIndex(edges);
431
- let matchCount = 0;
432
- let totalChecks = 0;
433
- const expectedNodes = mode.machine_shape;
434
- if (expectedNodes.length > 0) {
435
- totalChecks++;
436
- const machines = byType.get("Machine") ?? [];
437
- if (machines.length > 0) {
438
- const machineObj = machines[0];
439
- const cached = parseCacheData(objectCache.get(machineObj.objectAddress));
440
- const nodeCount = getMachineNodeCount(cached);
441
- if (nodeCount > 0 && nodeCount >= expectedNodes.length) {
442
- matchCount++;
443
- result.strengths.push(`Industry pattern match: Machine has ${nodeCount} nodes, covering "${industryName}" mode's ${expectedNodes.length} expected node(s)`);
444
- }
445
- else if (nodeCount > 0) {
446
- result.findings.push({
447
- criterion: "industry_pattern",
448
- severity: "info",
449
- message: `Industry pattern: Machine has ${nodeCount} nodes, but "${industryName}" mode expects at least ${expectedNodes.length}`,
450
- deduction: 0,
451
- });
452
- }
453
- }
454
- }
455
- const expectedGuards = mode.guards;
456
- if (expectedGuards.length > 0) {
457
- totalChecks++;
458
- const guards = byType.get("Guard") ?? [];
459
- const minGuards = expectedGuards.length;
460
- const maxGuards = expectedGuards.length * 2;
461
- if (guards.length >= minGuards && guards.length <= maxGuards) {
462
- matchCount++;
463
- result.strengths.push(`Industry pattern match: ${guards.length} Guard(s) present, within "${industryName}" mode's expected range [${minGuards}-${maxGuards}]`);
464
- }
465
- else if (guards.length > 0 && guards.length < minGuards) {
466
- result.findings.push({
467
- criterion: "industry_pattern",
468
- severity: "info",
469
- message: `Industry pattern: ${guards.length} Guard(s) present, but "${industryName}" mode expects at least ${minGuards} (recommended range [${minGuards}-${maxGuards}])`,
470
- deduction: 0,
471
- });
472
- }
473
- else if (guards.length > maxGuards) {
474
- matchCount++;
475
- result.strengths.push(`Industry pattern match: ${guards.length} Guard(s) present, covering "${industryName}" mode's ${minGuards} expected guard(s)`);
476
- result.findings.push({
477
- criterion: "industry_pattern",
478
- severity: "info",
479
- message: `Industry pattern: ${guards.length} Guard(s) present, exceeds recommended max ${maxGuards}. Consider consolidating guards if some are redundant.`,
480
- deduction: 0,
481
- });
482
- }
483
- }
484
- const expectedAllocStrategy = mode.allocator;
485
- if (expectedAllocStrategy) {
486
- totalChecks++;
487
- const allocations = byType.get("Allocation") ?? [];
488
- const services4Alloc = byType.get("Service") ?? [];
489
- const serviceForAlloc = services4Alloc[0];
490
- const hasOrderAllocators = serviceForAlloc
491
- ? !!bindingIndex.get(`${serviceForAlloc.objectAddress}#order_allocators`)?.size
492
- : false;
493
- const expectsMultiple = mode.traits.multi_tier_allocation;
494
- if (hasOrderAllocators) {
495
- matchCount++;
496
- if (allocations.length > 0) {
497
- result.strengths.push(`Industry pattern match: Service.order_allocators bound + ${allocations.length} Allocation object(s) present (post-order) — matching "${industryName}" allocation pattern`);
498
- }
499
- else {
500
- result.strengths.push(`Industry pattern match: Service.order_allocators template bound — matching "${industryName}" allocation pattern (Allocation objects created per-order)`);
501
- }
502
- }
503
- else if (allocations.length > 0) {
504
- matchCount++;
505
- result.strengths.push(`Industry pattern match: ${allocations.length} Allocation object(s) present — matching "${industryName}" allocation pattern`);
506
- }
507
- else {
508
- result.findings.push({
509
- criterion: "industry_pattern",
510
- severity: "info",
511
- message: `Industry pattern: Service.order_allocators not bound and no Allocation objects — "${industryName}" mode expects ${expectsMultiple ? "multi-tier" : "single-tier"} allocation (Allocation objects are created per-order, so this is only a template-level gap)`,
512
- deduction: 0,
513
- });
514
- }
515
- }
516
- const requireCompensationFund = mode.risk_constraints?.require_compensation_fund ?? false;
517
- if (requireCompensationFund || mode.traits.deposit_required || mode.traits.trust_sensitivity !== "low") {
518
- totalChecks++;
519
- const treasuries = byType.get("Treasury") ?? [];
520
- const services4Treas = byType.get("Service") ?? [];
521
- const serviceForTreas = services4Treas[0];
522
- const serviceDataForTreas = serviceForTreas
523
- ? parseCacheData(objectCache.get(serviceForTreas.objectAddress))
524
- : null;
525
- const compensationBalance = serviceForTreas
526
- ? getBalanceValue(serviceDataForTreas, "compensation_fund")
527
- : 0;
528
- if (treasuries.length > 0 || compensationBalance > 0) {
529
- matchCount++;
530
- const parts = [];
531
- if (treasuries.length > 0)
532
- parts.push(`${treasuries.length} Treasury object(s)`);
533
- if (compensationBalance > 0)
534
- parts.push(`compensation_fund balance ${compensationBalance}`);
535
- result.strengths.push(`Industry pattern match: ${parts.join(" + ")} — matching "${industryName}" trust/deposit pattern`);
536
- }
537
- }
538
- result.matched = totalChecks > 0 && matchCount / totalChecks >= 0.6;
539
- if (result.matched) {
540
- result.strengths.push(`Industry pattern: project structure matches "${industryName}" mode (${matchCount}/${totalChecks} checks passed)`);
541
- }
542
- else if (totalChecks > 0) {
543
- result.findings.push({
544
- criterion: "industry_pattern",
545
- severity: "info",
546
- message: `Industry pattern: project partially matches "${industryName}" mode (${matchCount}/${totalChecks} checks passed)`,
547
- deduction: 0,
548
- });
549
- }
550
- if (industryName === "freelance") {
551
- const machines = byType.get("Machine") ?? [];
552
- for (const m of machines) {
553
- const mData = parseCacheData(objectCache.get(m.objectAddress));
554
- if (!mData)
555
- continue;
556
- const nodeCount = getMachineNodeCount(mData);
557
- if (nodeCount > 0) {
558
- result.findings.push({
559
- criterion: "industry_pattern",
560
- severity: "info",
561
- message: `ISSUE-P1-4: freelance project has a Machine with ${nodeCount} node(s). ` +
562
- `If the workflow includes a "delivered" state, 48h auto-accept requires ` +
563
- `an off-chain keeper (WoWok Guard does not support time-based triggers). ` +
564
- `Keeper should poll Progress objects in "delivered" state and call ` +
565
- `adminUnhold (permission 224) after 48h timeout.`,
566
- deduction: 0,
567
- });
568
- break;
569
- }
570
- }
571
- }
572
- return result;
573
- }
574
- function evaluateRisk(input) {
575
- const findings = [];
576
- const strengths = [];
577
- const { objects, edges, objectCache, project } = input;
578
- const byType = groupByType(objects);
579
- const services = byType.get("Service") ?? [];
580
- const bindingIndex = buildBindingIndex(edges);
581
- let structuralScore = 100;
582
- const serviceObj = services[0];
583
- const svcDataForStruct = serviceObj ? parseCacheData(objectCache.get(serviceObj.objectAddress)) : null;
584
- const compensationBalanceForStruct = serviceObj ? getBalanceValue(svcDataForStruct, "compensation_fund") : 0;
585
- if (serviceObj) {
586
- for (const expected of CRITICAL_BINDINGS) {
587
- if (expected.sourceType !== "Service")
588
- continue;
589
- const effectiveCritical = expected.fieldName === "arbitrations"
590
- ? (compensationBalanceForStruct > 0 ? true : expected.critical)
591
- : expected.critical;
592
- const key = `${serviceObj.objectAddress}#${expected.fieldName}`;
593
- const bindings = bindingIndex.get(key);
594
- if (!bindings || bindings.size === 0) {
595
- const deduction = effectiveCritical ? -25 : -10;
596
- structuralScore += deduction;
597
- findings.push({
598
- criterion: "structural_risk",
599
- severity: effectiveCritical ? "critical" : "warning",
600
- message: `Service missing ${expected.fieldName} binding (expected ${expected.targetType})${expected.fieldName === "arbitrations" ? (compensationBalanceForStruct > 0 ? " — required by contract when compensation_fund > 0 (service.move:494)" : " — optional when compensation_fund is 0") : ""}`,
601
- deduction,
602
- });
603
- }
604
- else {
605
- strengths.push(`Service has ${expected.fieldName} binding`);
606
- }
607
- }
608
- }
609
- else {
610
- structuralScore = 30;
611
- findings.push({
612
- criterion: "structural_risk",
613
- severity: "critical",
614
- message: "No Service object in project — project has no core",
615
- deduction: -70,
616
- });
617
- }
618
- structuralScore = clampScore(structuralScore);
619
- let fundScore = 100;
620
- const treasuries = byType.get("Treasury") ?? [];
621
- const allocations = byType.get("Allocation") ?? [];
622
- const serviceData = serviceObj ? parseCacheData(objectCache.get(serviceObj.objectAddress)) : null;
623
- const compensationBalance = serviceObj ? getBalanceValue(serviceData, "compensation_fund") : 0;
624
- const orderAllocatorsBinding = serviceObj
625
- ? bindingIndex.get(`${serviceObj.objectAddress}#order_allocators`)?.size ?? 0
626
- : 0;
627
- const hasAllocationEscrow = allocations.length > 0 && orderAllocatorsBinding > 0;
628
- let industryRequiresFund = true;
629
- if (project.industry && project.industry !== "general") {
630
- try {
631
- const mode = IndustryModeRegistry.Instance().getMode(project.industry);
632
- if (mode) {
633
- industryRequiresFund = mode.risk_constraints?.require_compensation_fund ?? true;
634
- }
635
- }
636
- catch { }
637
- }
638
- if (treasuries.length === 0 && compensationBalance === 0) {
639
- if (hasAllocationEscrow) {
640
- fundScore -= 5;
641
- strengths.push("Allocation escrow mode active — funds locked in contract, released by Guard verification");
642
- findings.push({
643
- criterion: "fund_safety",
644
- severity: "info",
645
- message: `Using Allocation escrow (${allocations.length} Allocation object(s) + order_allocators bound) — fund safety via Guard verification, no Treasury/compensation_fund needed`,
646
- deduction: -5,
647
- });
648
- }
649
- else if (industryRequiresFund) {
650
- fundScore -= 30;
651
- findings.push({
652
- criterion: "fund_safety",
653
- severity: "warning",
654
- message: "No Treasury object and Service.compensation_fund is empty — no refund fund for buyers",
655
- deduction: -30,
656
- });
657
- }
658
- else {
659
- fundScore -= 10;
660
- findings.push({
661
- criterion: "fund_safety",
662
- severity: "info",
663
- message: `No Treasury/compensation_fund — industry "${project.industry}" does not require refund fund (optional)`,
664
- deduction: -10,
665
- });
666
- }
667
- }
668
- else {
669
- if (treasuries.length > 0) {
670
- strengths.push(`${treasuries.length} Treasury object(s) present — independent fund holder`);
671
- }
672
- if (compensationBalance > 0) {
673
- strengths.push(`Service.compensation_fund has ${compensationBalance} units — inline refund fund active`);
674
- const maxSalePrice = getMaxSalePrice(serviceData);
675
- if (maxSalePrice > 0) {
676
- let coverageRatio = 5;
677
- if (project.industry && project.industry !== "general") {
678
- try {
679
- const mode = IndustryModeRegistry.Instance().getMode(project.industry);
680
- if (mode?.risk_constraints?.compensation_fund_coverage_ratio) {
681
- coverageRatio = mode.risk_constraints.compensation_fund_coverage_ratio;
682
- }
683
- }
684
- catch { }
685
- }
686
- const requiredThreshold = coverageRatio * maxSalePrice;
687
- if (compensationBalance < requiredThreshold) {
688
- fundScore -= 10;
689
- findings.push({
690
- criterion: "fund_safety",
691
- severity: "warning",
692
- message: `Service.compensation_fund balance (${compensationBalance}) is less than ${coverageRatio}× the max order amount (${maxSalePrice} → threshold ${requiredThreshold}). Refund coverage may be insufficient — top up via service.compensation_fund_add to avoid arbitration rulings exceeding the fund. (industry: ${project.industry ?? "general"}, ratio: ${coverageRatio}×)`,
693
- deduction: -10,
694
- });
695
- }
696
- else {
697
- findings.push({
698
- criterion: "fund_safety",
699
- severity: "info",
700
- message: `Service.compensation_fund balance (${compensationBalance}) covers ${coverageRatio}× the max order amount (${maxSalePrice}). Fund is sufficient for refund protection. (industry: ${project.industry ?? "general"}, ratio: ${coverageRatio}×)`,
701
- deduction: 0,
702
- });
703
- }
704
- }
705
- }
706
- else {
707
- findings.push({
708
- criterion: "fund_safety",
709
- severity: "info",
710
- message: "Treasury present but Service.compensation_fund balance is 0 — consider depositing refund fund",
711
- deduction: -5,
712
- });
713
- }
714
- }
715
- fundScore = clampScore(fundScore);
716
- let operationalScore = 100;
717
- if (serviceObj) {
718
- const data = parseCacheData(objectCache.get(serviceObj.objectAddress));
719
- if (data) {
720
- const paused = data.bPaused;
721
- const published = data.bPublished;
722
- if (published && paused) {
723
- operationalScore -= 25;
724
- findings.push({
725
- criterion: "operational_risk",
726
- severity: "warning",
727
- message: "Service is published but PAUSED — operations halted",
728
- deduction: -25,
729
- });
730
- }
731
- if (!published) {
732
- operationalScore -= 15;
733
- findings.push({
734
- criterion: "operational_risk",
735
- severity: "info",
736
- message: "Service not yet published — project not live",
737
- deduction: -15,
738
- });
739
- }
740
- }
741
- }
742
- const arbitrations = byType.get("Arbitration") ?? [];
743
- if (arbitrations.length === 0) {
744
- operationalScore -= 20;
745
- findings.push({
746
- criterion: "operational_risk",
747
- severity: "warning",
748
- message: "No Arbitration object — disputes cannot be resolved",
749
- deduction: -20,
750
- });
751
- }
752
- else {
753
- strengths.push(`${arbitrations.length} Arbitration object(s) configured`);
754
- }
755
- operationalScore = clampScore(operationalScore);
756
- let governanceScore = 100;
757
- const permissions = byType.get("Permission") ?? [];
758
- if (permissions.length === 0) {
759
- governanceScore -= 40;
760
- findings.push({
761
- criterion: "governance_risk",
762
- severity: "critical",
763
- message: "No Permission object — project is ungoverned",
764
- deduction: -40,
765
- });
766
- }
767
- if (serviceObj) {
768
- const data = parseCacheData(objectCache.get(serviceObj.objectAddress));
769
- if (data && !isAddress(data.um)) {
770
- governanceScore -= 5;
771
- findings.push({
772
- criterion: "governance_risk",
773
- severity: "info",
774
- message: "Service has no UM (manager) — UM is optional; set via um_set if management delegation needed",
775
- deduction: -5,
776
- });
777
- }
778
- }
779
- const machines = byType.get("Machine") ?? [];
780
- for (const machineObj of machines) {
781
- const meta = machineObj.metadata;
782
- const config = meta?.config;
783
- if (config?.entry_node_forward_hint) {
784
- const hint = config.entry_node_forward_hint;
785
- const exampleFwd = hint.example_forward;
786
- if (exampleFwd?.namedOperator === "") {
787
- strengths.push("Machine entry forward uses namedOperator='' (OrderHolder) — " +
788
- "correct for customer-operable nodes. namedOperator='' represents " +
789
- "the order holder, distinct from merchant's permission index.");
790
- }
791
- }
792
- const guardObjects = config?.guard_objects;
793
- if (guardObjects && guardObjects.length > 0) {
794
- strengths.push(`Machine has ${guardObjects.length} guard object reference(s) — ` +
795
- `forward-level permission validation configured`);
796
- }
797
- const cached = parseCacheData(objectCache.get(machineObj.objectAddress));
798
- const nodeCount = getMachineNodeCount(cached);
799
- if (nodeCount > 0 && !config) {
800
- findings.push({
801
- criterion: "governance_risk",
802
- severity: "info",
803
- message: `Machine has ${nodeCount} node(s). Verify each forward has at least one of ` +
804
- `namedOperator or permissionIndex. Key: namedOperator='' means OrderHolder ` +
805
- `(customer), NOT 'anyone'. Use non-empty namedOperator for specific roles, ` +
806
- `or permissionIndex for permission-based access. Both set = OR semantic ` +
807
- `(either can execute).`,
808
- deduction: 0,
809
- });
810
- }
811
- }
812
- const machinesForPermCheck = byType.get("Machine") ?? [];
813
- const permissionsForCheck = byType.get("Permission") ?? [];
814
- const permDataMap = new Map();
815
- for (const permObj of permissionsForCheck) {
816
- const cached = parseCacheData(objectCache.get(permObj.objectAddress));
817
- if (cached) {
818
- permDataMap.set(permObj.objectAddress, {
819
- address: permObj.objectAddress,
820
- entity_count: typeof cached.entity_count === "number" ? cached.entity_count : undefined,
821
- perm_remark: Array.isArray(cached.perm_remark) ? cached.perm_remark : undefined,
822
- owner: typeof cached.owner === "string" ? cached.owner : (typeof cached.builder === "string" ? cached.builder : undefined),
823
- admin: Array.isArray(cached.admin) ? cached.admin : undefined,
824
- });
825
- }
826
- }
827
- for (const machineObj of machinesForPermCheck) {
828
- const machinePermKey = `${machineObj.objectAddress}#permission`;
829
- const machinePermBindings = bindingIndex.get(machinePermKey);
830
- if (!machinePermBindings || machinePermBindings.size === 0)
831
- continue;
832
- let permAddress = null;
833
- for (const addr of machinePermBindings) {
834
- permAddress = addr;
835
- break;
836
- }
837
- if (!permAddress)
838
- continue;
839
- const permData = permDataMap.get(permAddress);
840
- if (!permData)
841
- continue;
842
- const machineCached = parseCacheData(objectCache.get(machineObj.objectAddress));
843
- if (!machineCached)
844
- continue;
845
- const machineNodes = extractMachineNodesFromCache(machineCached);
846
- if (machineNodes.length === 0)
847
- continue;
848
- const collection = collectPermissionIndexes(machineNodes);
849
- if (collection.requiredIndexes.length === 0)
850
- continue;
851
- const report = checkPermissionAuthorization(collection.requiredIndexes, permData);
852
- if (!report.allAuthorized) {
853
- governanceScore -= 25;
854
- findings.push({
855
- criterion: "governance_risk",
856
- severity: "critical",
857
- message: `Machine ${machineObj.objectAddress.slice(0, 8)} has forwards referencing ` +
858
- `un-authorized permission indexes: [${report.missingIndexes.join(", ")}]. ` +
859
- `These forwards can NEVER be executed — Progress will be permanently stuck. ` +
860
- `Grant entities for these indexes via permission.op="add perm by index" ` +
861
- `before publishing the Machine.`,
862
- deduction: -25,
863
- });
864
- }
865
- else {
866
- strengths.push(`Machine ${machineObj.objectAddress.slice(0, 8)}: all ${collection.requiredIndexes.length} ` +
867
- `permission index(es) are authorized`);
868
- }
869
- }
870
- if (serviceObj && arbitrations.length > 0) {
871
- const svcPermKey = `${serviceObj.objectAddress}#permission`;
872
- const svcPermBindings = bindingIndex.get(svcPermKey);
873
- const svcPermAddress = svcPermBindings && svcPermBindings.size > 0
874
- ? Array.from(svcPermBindings)[0]
875
- : null;
876
- const svcPermData = svcPermAddress ? permDataMap.get(svcPermAddress) : null;
877
- for (const arbObj of arbitrations) {
878
- const arbPermKey = `${arbObj.objectAddress}#permission`;
879
- const arbPermBindings = bindingIndex.get(arbPermKey);
880
- const arbPermAddress = arbPermBindings && arbPermBindings.size > 0
881
- ? Array.from(arbPermBindings)[0]
882
- : null;
883
- if (!svcPermAddress || !arbPermAddress)
884
- continue;
885
- if (svcPermAddress === arbPermAddress) {
886
- governanceScore -= 30;
887
- findings.push({
888
- criterion: "governance_risk",
889
- severity: "critical",
890
- message: `Arbitration ${arbObj.objectAddress.slice(0, 8)} and Service share the SAME ` +
891
- `Permission object (${svcPermAddress.slice(0, 8)}). This breaks dispute ` +
892
- `fairness — the merchant fully controls arbitration operations. ` +
893
- `Use a separate Permission object for Arbitration to ensure independent ` +
894
- `dispute resolution. (per arbitration.move: the permission field controls ` +
895
- `who can vote, confirm, and execute arbitration rulings)`,
896
- deduction: -30,
897
- });
898
- continue;
899
- }
900
- const arbPermData = permDataMap.get(arbPermAddress);
901
- if (svcPermData && arbPermData) {
902
- const svcOwner = svcPermData.owner?.toLowerCase();
903
- const arbOwner = arbPermData.owner?.toLowerCase();
904
- const svcAdmins = new Set((svcPermData.admin ?? []).map(a => a.toLowerCase()));
905
- const arbAdmins = new Set((arbPermData.admin ?? []).map(a => a.toLowerCase()));
906
- const ownerOverlap = svcOwner && arbOwner && svcOwner === arbOwner;
907
- const adminOverlap = [...svcAdmins].some(a => arbAdmins.has(a));
908
- if (ownerOverlap || adminOverlap) {
909
- const overlapType = ownerOverlap && adminOverlap
910
- ? "owner AND admin overlap"
911
- : ownerOverlap ? "same owner" : "admin overlap";
912
- governanceScore -= 20;
913
- findings.push({
914
- criterion: "governance_risk",
915
- severity: "warning",
916
- message: `Arbitration ${arbObj.objectAddress.slice(0, 8)} and Service have ` +
917
- `overlapping Permission control (${overlapType}). Even with separate ` +
918
- `Permission objects, shared control undermines dispute independence. ` +
919
- `For mainnet deployment, use a completely independent third-party ` +
920
- `Permission (different owner and admin list) for Arbitration. ` +
921
- `(testnet may tolerate this, but mainnet users should treat this as ` +
922
- `a critical trust factor)`,
923
- deduction: -20,
924
- });
925
- }
926
- else {
927
- strengths.push(`Arbitration ${arbObj.objectAddress.slice(0, 8)} has independent ` +
928
- `Permission (separate owner/admin) — trustworthy dispute resolution`);
929
- }
930
- }
931
- }
932
- }
933
- governanceScore = clampScore(governanceScore);
934
- let coherenceScore = 100;
935
- const objectAddresses = new Set();
936
- for (const o of objects) {
937
- if (o.objectAddress)
938
- objectAddresses.add(o.objectAddress);
939
- if (o.objectName) {
940
- objectAddresses.add(o.objectName);
941
- const shortType = shortTypeName(o.objectType).toLowerCase();
942
- objectAddresses.add(`${shortType}:${o.objectName}`);
943
- }
944
- }
945
- let danglingCount = 0;
946
- for (const e of edges) {
947
- if (e.edgeSource === "potential")
948
- continue;
949
- if (!objectAddresses.has(e.targetObject))
950
- danglingCount++;
951
- }
952
- if (danglingCount > 0) {
953
- const deduction = -Math.min(20, danglingCount * 3);
954
- coherenceScore += deduction;
955
- findings.push({
956
- criterion: "graph_coherence",
957
- severity: danglingCount >= 3 ? "warning" : "info",
958
- message: `${danglingCount} edge(s) point to objects outside the project — dangling references`,
959
- deduction,
960
- });
961
- }
962
- const objectTypeMap = new Map();
963
- for (const o of objects) {
964
- if (o.objectAddress) {
965
- objectTypeMap.set(o.objectAddress, shortTypeName(o.objectType));
966
- }
967
- }
968
- const cycles = detectCircularRefs(edges, objectTypeMap);
969
- if (cycles.length > 0) {
970
- coherenceScore -= 15;
971
- findings.push({
972
- criterion: "graph_coherence",
973
- severity: "warning",
974
- message: `${cycles.length} circular reference(s) detected: ${cycles.slice(0, 2).join("; ")}${cycles.length > 2 ? "..." : ""}`,
975
- deduction: -15,
976
- });
977
- }
978
- if (danglingCount === 0 && cycles.length === 0) {
979
- strengths.push("Graph is coherent — no dangling refs or cycles");
980
- }
981
- coherenceScore = clampScore(coherenceScore);
982
- let modeRegistryScore = 100;
983
- let modeRegistryRationale = "no industry declared — check skipped";
984
- if (!project.industry) {
985
- findings.push({
986
- criterion: "mode_registry",
987
- severity: "info",
988
- message: "Project has no industry tag — mode registry gates (metrics/constraints) not evaluated. Set project industry to enable.",
989
- deduction: 0,
990
- });
991
- }
992
- else {
993
- try {
994
- const modeEval = IndustryModeRegistry.Instance().evaluateMode(project.industry, project.description ?? project.name, {
995
- prefix: project.prefix,
996
- network: project.network === "mainnet" ? "mainnet" : "testnet",
997
- business_intent: project.description ?? undefined,
998
- industry: project.industry,
999
- version: project.currentVersion ?? undefined,
1000
- });
1001
- const modeNotFound = modeEval.unmet_conditions.some(c => c.includes("not found"));
1002
- if (modeNotFound) {
1003
- modeRegistryScore = 50;
1004
- modeRegistryRationale = `mode '${project.industry}' not registered`;
1005
- findings.push({
1006
- criterion: "mode_registry",
1007
- severity: "warning",
1008
- message: `Industry mode '${project.industry}' is not registered in the mode registry — cannot verify capability/conflict/constraint gates. Falling back to unverified mode.`,
1009
- deduction: -50,
1010
- });
1011
- }
1012
- else {
1013
- for (const v of modeEval.violated_constraints) {
1014
- modeRegistryScore -= 25;
1015
- findings.push({
1016
- criterion: "mode_registry",
1017
- severity: "critical",
1018
- message: `Mode '${project.industry}' hard constraint violated: ${v}`,
1019
- deduction: -25,
1020
- });
1021
- }
1022
- for (const c of modeEval.capability_conflicts) {
1023
- modeRegistryScore -= 20;
1024
- findings.push({
1025
- criterion: "mode_registry",
1026
- severity: "critical",
1027
- message: `Mode '${project.industry}' capability conflict: ${c}`,
1028
- deduction: -20,
1029
- });
1030
- }
1031
- for (const u of modeEval.unmet_conditions) {
1032
- modeRegistryScore -= 10;
1033
- findings.push({
1034
- criterion: "mode_registry",
1035
- severity: "warning",
1036
- message: `Mode '${project.industry}' soft constraint unmet: ${u}`,
1037
- deduction: -10,
1038
- });
1039
- }
1040
- modeRegistryScore = clampScore(modeRegistryScore);
1041
- modeRegistryRationale =
1042
- `metric risk ${modeEval.risk_score} / benefit ${modeEval.benefit_score} ` +
1043
- `(ratio ${modeEval.risk_benefit_ratio.toFixed(2)}); ` +
1044
- `${modeEval.violated_constraints.length} hard + ${modeEval.unmet_conditions.length} soft constraint issue(s), ` +
1045
- `${modeEval.capability_conflicts.length} capability conflict(s)`;
1046
- if (modeEval.applicable && modeEval.violated_constraints.length === 0 &&
1047
- modeEval.capability_conflicts.length === 0 && modeEval.unmet_conditions.length === 0) {
1048
- strengths.push(`Mode '${project.industry}' passes all mode-registry gates — ` +
1049
- `metric risk ${modeEval.risk_score} / benefit ${modeEval.benefit_score} ` +
1050
- `(risk-benefit ratio ${modeEval.risk_benefit_ratio.toFixed(2)})`);
1051
- }
1052
- }
1053
- }
1054
- catch {
1055
- modeRegistryRationale = "mode registry unavailable — check skipped";
1056
- }
1057
- }
1058
- modeRegistryScore = clampScore(modeRegistryScore);
1059
- const { criterionScores, overall } = finalizeCriterionScores([
1060
- { name: "structural_risk", score: structuralScore, weight: RISK_WEIGHTS.structural_risk, rationale: `${CRITICAL_BINDINGS.filter(b => b.sourceType === "Service").length} expected Service bindings checked` },
1061
- { name: "fund_safety", score: fundScore, weight: RISK_WEIGHTS.fund_safety, rationale: `Treasury + compensation_fund coverage` },
1062
- { name: "operational_risk", score: operationalScore, weight: RISK_WEIGHTS.operational_risk, rationale: `Service state + arbitration coverage` },
1063
- { name: "governance_risk", score: governanceScore, weight: RISK_WEIGHTS.governance_risk, rationale: `Permission + UM presence` },
1064
- { name: "graph_coherence", score: coherenceScore, weight: RISK_WEIGHTS.graph_coherence, rationale: `${danglingCount} dangling + ${cycles.length} circular refs` },
1065
- { name: "mode_registry", score: modeRegistryScore, weight: RISK_WEIGHTS.mode_registry, rationale: modeRegistryRationale },
1066
- ], project.perspective);
1067
- const criticalCount = findings.filter(f => f.severity === "critical").length;
1068
- const summary = criticalCount > 0
1069
- ? `HIGH RISK: ${criticalCount} critical issue(s). ${findings.length} total findings.`
1070
- : `Moderate risk: ${findings.length} finding(s), no critical issues.`;
1071
- return {
1072
- evaluationType: "risk",
1073
- score: overall,
1074
- summary,
1075
- criterionScores,
1076
- findings,
1077
- strengths,
1078
- needsLlm: false,
1079
- evaluatedAt: Date.now(),
1080
- };
1081
- }
1082
- function evaluateTrust(input) {
1083
- const findings = [];
1084
- const strengths = [];
1085
- const { objects, edges, objectCache, reputation, project } = input;
1086
- const byType = groupByType(objects);
1087
- const services = byType.get("Service") ?? [];
1088
- let reputationScore = 50;
1089
- if (reputation && reputation.size > 0 && services[0]) {
1090
- const rep = reputation.get(services[0].objectAddress);
1091
- if (rep) {
1092
- const total = rep.likes + rep.dislikes;
1093
- if (total > 0) {
1094
- const ratio = rep.likes / total;
1095
- reputationScore = clampScore(50 + (ratio - 0.5) * 100);
1096
- if (ratio >= 0.8) {
1097
- strengths.push(`Strong reputation: ${rep.likes} likes vs ${rep.dislikes} dislikes`);
1098
- }
1099
- else if (ratio < 0.4) {
1100
- findings.push({
1101
- criterion: "reputation",
1102
- severity: "warning",
1103
- message: `Poor reputation: ${rep.dislikes} dislikes vs ${rep.likes} likes`,
1104
- deduction: -20,
1105
- });
1106
- }
1107
- }
1108
- if (rep.affiliations >= 3) {
1109
- strengths.push(`${rep.affiliations} affiliations — trusted by other merchants`);
1110
- reputationScore = clampScore(reputationScore + 10);
1111
- }
1112
- }
1113
- }
1114
- else {
1115
- findings.push({
1116
- criterion: "reputation",
1117
- severity: "info",
1118
- message: "No Registrar reputation data — unknown merchant standing",
1119
- deduction: -10,
1120
- });
1121
- }
1122
- reputationScore = clampScore(reputationScore);
1123
- let arbitrationScore = 100;
1124
- const arbitrations = byType.get("Arbitration") ?? [];
1125
- if (arbitrations.length === 0) {
1126
- arbitrationScore = 30;
1127
- findings.push({
1128
- criterion: "arbitration_coverage",
1129
- severity: "critical",
1130
- message: "No Arbitration object — buyers have no dispute resolution path",
1131
- deduction: -70,
1132
- });
1133
- }
1134
- else {
1135
- strengths.push(`${arbitrations.length} Arbitration object(s) — dispute resolution available`);
1136
- }
1137
- arbitrationScore = clampScore(arbitrationScore);
1138
- let guardScore = 60;
1139
- const guards = byType.get("Guard") ?? [];
1140
- if (guards.length === 0) {
1141
- guardScore -= 20;
1142
- findings.push({
1143
- criterion: "guard_quality",
1144
- severity: "warning",
1145
- message: "No Guard objects — no validation rules",
1146
- deduction: -20,
1147
- });
1148
- }
1149
- else {
1150
- guardScore = 80;
1151
- strengths.push(`${guards.length} Guard object(s) — validation rules configured`);
1152
- }
1153
- if (services[0]) {
1154
- const bindingIndex = buildBindingIndex(edges);
1155
- const bgKey = `${services[0].objectAddress}#buy_guard`;
1156
- if (bindingIndex.get(bgKey)?.size) {
1157
- guardScore = clampScore(guardScore + 15);
1158
- strengths.push("Service has buy_guard bound — purchase validation active");
1159
- }
1160
- else if (guards.length > 0) {
1161
- strengths.push("Guard objects present (buy_guard binding optional)");
1162
- }
1163
- }
1164
- guardScore = clampScore(guardScore);
1165
- let transparencyScore = 60;
1166
- if (services[0]) {
1167
- const data = parseCacheData(objectCache.get(services[0].objectAddress));
1168
- if (data) {
1169
- const desc = data.description;
1170
- if (typeof desc === "string" && desc.length > 0) {
1171
- transparencyScore += 15;
1172
- strengths.push("Service has description");
1173
- }
1174
- else {
1175
- findings.push({
1176
- criterion: "transparency",
1177
- severity: "info",
1178
- message: "Service has no description — buyers cannot evaluate offering",
1179
- deduction: -10,
1180
- });
1181
- }
1182
- }
1183
- }
1184
- const repositories = byType.get("Repository") ?? [];
1185
- if (repositories.length > 0) {
1186
- transparencyScore = clampScore(transparencyScore + 10);
1187
- strengths.push(`${repositories.length} Repository object(s) — supporting data published`);
1188
- }
1189
- const contacts = byType.get("Contact") ?? [];
1190
- if (contacts.length > 0) {
1191
- transparencyScore = clampScore(transparencyScore + 10);
1192
- strengths.push("Contact information available");
1193
- }
1194
- else {
1195
- findings.push({
1196
- criterion: "transparency",
1197
- severity: "info",
1198
- message: "No Contact object — buyers cannot reach merchant",
1199
- deduction: -5,
1200
- });
1201
- }
1202
- transparencyScore = clampScore(transparencyScore);
1203
- let diligenceScore = 100;
1204
- const diligencePassed = [];
1205
- const bindingIndex2 = buildBindingIndex(edges);
1206
- const serviceObj2 = services[0];
1207
- if (serviceObj2) {
1208
- const svcData = parseCacheData(objectCache.get(serviceObj2.objectAddress));
1209
- for (const check of CONSUMER_DUE_DILIGENCE) {
1210
- let passed = false;
1211
- switch (check.id) {
1212
- case "E1":
1213
- passed = !!(svcData?.bPublished);
1214
- break;
1215
- case "E2":
1216
- passed = !!svcData && !svcData.bPaused;
1217
- break;
1218
- case "E3":
1219
- passed = (byType.get("Machine") ?? []).some(m => {
1220
- const d = parseCacheData(objectCache.get(m.objectAddress));
1221
- return d && (getNumberField(d, "node_count") > 0 || countArrayField(d, "nodes") > 0);
1222
- });
1223
- break;
1224
- case "E4":
1225
- passed = !!bindingIndex2.get(`${serviceObj2.objectAddress}#buy_guard`)?.size
1226
- || (byType.get("Guard") ?? []).length > 0;
1227
- break;
1228
- case "E5":
1229
- passed = getBalanceValue(svcData, "compensation_fund") > 0
1230
- || (byType.get("Treasury") ?? []).length > 0;
1231
- break;
1232
- case "E6":
1233
- passed = (byType.get("Arbitration") ?? []).length > 0;
1234
- break;
1235
- case "E7":
1236
- passed = (byType.get("Permission") ?? []).length > 0;
1237
- break;
1238
- case "E8":
1239
- passed = (byType.get("Contact") ?? []).length > 0;
1240
- break;
1241
- case "E9":
1242
- passed = (byType.get("Repository") ?? []).length > 0;
1243
- break;
1244
- case "E10":
1245
- passed = !!bindingIndex2.get(`${serviceObj2.objectAddress}#rewards`)?.size;
1246
- break;
1247
- case "E11":
1248
- passed = !!(svcData && typeof svcData.description === "string" && svcData.description.length > 0);
1249
- break;
1250
- case "E12":
1251
- if (reputation && reputation.size > 0) {
1252
- const rep = reputation.get(serviceObj2.objectAddress);
1253
- passed = !!rep && rep.likes >= rep.dislikes;
1254
- }
1255
- break;
1256
- }
1257
- if (passed) {
1258
- diligencePassed.push(check.id);
1259
- }
1260
- else {
1261
- let effectiveDeduction = check.deduction;
1262
- let effectiveSeverity = check.severity;
1263
- if (check.id === "E5" && project.industry && project.industry !== "general") {
1264
- try {
1265
- const mode = IndustryModeRegistry.Instance().getMode(project.industry);
1266
- if (mode && mode.risk_constraints?.require_compensation_fund === false) {
1267
- effectiveDeduction = -3;
1268
- effectiveSeverity = "info";
1269
- }
1270
- }
1271
- catch { }
1272
- }
1273
- diligenceScore += effectiveDeduction;
1274
- const detailSuffix = check.id === "E5" && effectiveDeduction !== check.deduction
1275
- ? " (industry does not require compensation_fund — reduced deduction)"
1276
- : "";
1277
- findings.push({
1278
- criterion: "consumer_diligence",
1279
- severity: effectiveSeverity,
1280
- message: `${check.id}: ${check.check} — FAIL: condition not met${detailSuffix} [severity: ${effectiveSeverity}]`,
1281
- deduction: effectiveDeduction,
1282
- });
1283
- }
1284
- }
1285
- const passRate = diligencePassed.length / CONSUMER_DUE_DILIGENCE.length;
1286
- if (passRate >= 0.8) {
1287
- strengths.push(`Consumer due diligence: ${diligencePassed.length}/${CONSUMER_DUE_DILIGENCE.length} checks passed`);
1288
- }
1289
- }
1290
- else {
1291
- diligenceScore = 20;
1292
- findings.push({
1293
- criterion: "consumer_diligence",
1294
- severity: "critical",
1295
- message: "No Service object — consumer due diligence cannot be performed",
1296
- deduction: -80,
1297
- });
1298
- }
1299
- diligenceScore = clampScore(diligenceScore);
1300
- const { criterionScores, overall } = finalizeCriterionScores([
1301
- { name: "reputation", score: reputationScore, weight: TRUST_WEIGHTS.reputation, rationale: `Registrar likes/dislikes + affiliations` },
1302
- { name: "arbitration_coverage", score: arbitrationScore, weight: TRUST_WEIGHTS.arbitration_coverage, rationale: `Dispute resolution availability` },
1303
- { name: "guard_quality", score: guardScore, weight: TRUST_WEIGHTS.guard_quality, rationale: `Validation rules + buy_guard binding` },
1304
- { name: "transparency", score: transparencyScore, weight: TRUST_WEIGHTS.transparency, rationale: `Description + Repository + Contact presence` },
1305
- { name: "consumer_diligence", score: diligenceScore, weight: TRUST_WEIGHTS.consumer_diligence, rationale: `${diligencePassed.length}/${CONSUMER_DUE_DILIGENCE.length} E-checks passed` },
1306
- ], project.perspective);
1307
- const summary = overall >= 70
1308
- ? `Trusted project (score ${overall}/100). ${strengths.length} strength(s).`
1309
- : `Limited trust signals (score ${overall}/100). ${findings.length} finding(s).`;
1310
- return {
1311
- evaluationType: "trust",
1312
- score: overall,
1313
- summary,
1314
- criterionScores,
1315
- findings,
1316
- strengths,
1317
- needsLlm: false,
1318
- evaluatedAt: Date.now(),
1319
- };
1320
- }
1321
- function evaluateCompleteness(input) {
1322
- const findings = [];
1323
- const strengths = [];
1324
- const { objects, edges, objectCache, project } = input;
1325
- const byType = groupByType(objects);
1326
- const services = byType.get("Service") ?? [];
1327
- const bindingIndex = buildBindingIndex(edges);
1328
- const svcObjForRequiredItems = services[0];
1329
- const svcDataForRequiredItems = svcObjForRequiredItems
1330
- ? parseCacheData(objectCache.get(svcObjForRequiredItems.objectAddress))
1331
- : null;
1332
- const compensationBalanceForItems = getBalanceValue(svcDataForRequiredItems, "compensation_fund");
1333
- const allocationsForItems = byType.get("Allocation") ?? [];
1334
- const orderAllocatorsBindingForItems = svcObjForRequiredItems
1335
- ? bindingIndex.get(`${svcObjForRequiredItems.objectAddress}#order_allocators`)?.size ?? 0
1336
- : 0;
1337
- const hasAllocationEscrowForItems = allocationsForItems.length > 0 && orderAllocatorsBindingForItems > 0;
1338
- const requiredItems = resolveRequiredItems(project.industry ?? undefined, compensationBalanceForItems, hasAllocationEscrowForItems);
1339
- const requiredCount = requiredItems.filter(r => r.required).length;
1340
- const optionalItems = requiredItems.filter(r => !r.required);
1341
- let requiredMet = 0;
1342
- let optionalMet = 0;
1343
- const missingRequired = [];
1344
- const missingOptional = [];
1345
- for (const item of requiredItems) {
1346
- const hasObject = (byType.get(item.objectType)?.length ?? 0) > 0;
1347
- const hasBinding = item.fieldName
1348
- ? !!bindingIndex.get(`${services[0]?.objectAddress ?? ""}#${item.fieldName}`)?.size
1349
- : hasObject;
1350
- if (item.required) {
1351
- if (hasBinding || (!item.fieldName && hasObject)) {
1352
- requiredMet++;
1353
- }
1354
- else {
1355
- missingRequired.push(`${item.id}(${item.objectType})`);
1356
- }
1357
- }
1358
- else {
1359
- if (hasBinding || (!item.fieldName && hasObject)) {
1360
- optionalMet++;
1361
- }
1362
- else {
1363
- missingOptional.push(`${item.id}(${item.objectType})`);
1364
- }
1365
- }
1366
- }
1367
- const requiredRatio = requiredMet / requiredCount;
1368
- const optionalRatio = optionalItems.length > 0 ? optionalMet / optionalItems.length : 1;
1369
- let coverageScore = clampScore(requiredRatio * 80 + optionalRatio * 20);
1370
- if (missingRequired.length > 0) {
1371
- findings.push({
1372
- criterion: "object_coverage",
1373
- severity: missingRequired.length >= 3 ? "critical" : "warning",
1374
- message: `Missing required items: ${missingRequired.join(", ")} — ${missingRequired.length}/${requiredCount} required items absent`,
1375
- deduction: -15 * missingRequired.length,
1376
- });
1377
- }
1378
- else {
1379
- strengths.push(`All ${requiredCount} required items present (R1-R8)`);
1380
- }
1381
- if (missingOptional.length > 0 && missingOptional.length === optionalItems.length) {
1382
- findings.push({
1383
- criterion: "object_coverage",
1384
- severity: "info",
1385
- message: `No optional items configured: ${missingOptional.join(", ")} — recommended for enhanced UX`,
1386
- deduction: -5,
1387
- });
1388
- }
1389
- else if (optionalMet > 0) {
1390
- strengths.push(`${optionalMet}/${optionalItems.length} optional items configured (R9-R12)`);
1391
- }
1392
- coverageScore = clampScore(coverageScore);
1393
- let bindingScore = 100;
1394
- if (services[0]) {
1395
- const serviceAddr = services[0].objectAddress;
1396
- const svcDataForBind = parseCacheData(objectCache.get(serviceAddr));
1397
- const compensationBalanceForBind = getBalanceValue(svcDataForBind, "compensation_fund");
1398
- let boundCount = 0;
1399
- let totalCount = 0;
1400
- for (const expected of CRITICAL_BINDINGS) {
1401
- if (expected.sourceType !== "Service")
1402
- continue;
1403
- totalCount++;
1404
- const effectiveCritical = expected.fieldName === "arbitrations"
1405
- ? (compensationBalanceForBind > 0 ? true : expected.critical)
1406
- : expected.critical;
1407
- const key = `${serviceAddr}#${expected.fieldName}`;
1408
- if (bindingIndex.get(key)?.size) {
1409
- boundCount++;
1410
- }
1411
- else {
1412
- const deduction = effectiveCritical ? -20 : -8;
1413
- bindingScore += deduction;
1414
- findings.push({
1415
- criterion: "binding_completeness",
1416
- severity: effectiveCritical ? "critical" : "warning",
1417
- message: `Service.${expected.fieldName} not bound (expected ${expected.targetType})${expected.fieldName === "arbitrations" ? (compensationBalanceForBind > 0 ? " — required by contract when compensation_fund > 0" : " — optional when compensation_fund is 0") : ""}`,
1418
- deduction,
1419
- });
1420
- }
1421
- }
1422
- if (boundCount === totalCount) {
1423
- strengths.push(`All ${totalCount} Service bindings established`);
1424
- }
1425
- }
1426
- else {
1427
- bindingScore = 0;
1428
- findings.push({
1429
- criterion: "binding_completeness",
1430
- severity: "critical",
1431
- message: "No Service object — cannot evaluate bindings",
1432
- deduction: -100,
1433
- });
1434
- }
1435
- bindingScore = clampScore(bindingScore);
1436
- let workflowScore = 80;
1437
- const machines = byType.get("Machine") ?? [];
1438
- if (machines.length === 0) {
1439
- workflowScore -= 20;
1440
- findings.push({
1441
- criterion: "workflow_rationality",
1442
- severity: "info",
1443
- message: "No Machine object — bind one before publishing (deploy-time requirement)",
1444
- deduction: -20,
1445
- });
1446
- }
1447
- else {
1448
- for (const m of machines) {
1449
- const data = parseCacheData(objectCache.get(m.objectAddress));
1450
- if (data) {
1451
- const nodeCount = getMachineNodeCount(data);
1452
- if (nodeCount > 0) {
1453
- strengths.push(`Machine has ${nodeCount} node(s)`);
1454
- }
1455
- else {
1456
- workflowScore -= 10;
1457
- findings.push({
1458
- criterion: "workflow_rationality",
1459
- severity: "info",
1460
- message: `Machine ${m.objectAddress.slice(0, 8)} has no nodes`,
1461
- deduction: -10,
1462
- });
1463
- }
1464
- }
1465
- }
1466
- }
1467
- const objectAddresses = new Set();
1468
- for (const o of objects) {
1469
- if (o.objectAddress)
1470
- objectAddresses.add(o.objectAddress);
1471
- if (o.objectName) {
1472
- objectAddresses.add(o.objectName);
1473
- const shortType = shortTypeName(o.objectType).toLowerCase();
1474
- objectAddresses.add(`${shortType}:${o.objectName}`);
1475
- }
1476
- }
1477
- let danglingCount = 0;
1478
- for (const e of edges) {
1479
- if (e.edgeSource === "potential")
1480
- continue;
1481
- if (!objectAddresses.has(e.targetObject))
1482
- danglingCount++;
1483
- }
1484
- if (danglingCount > 0) {
1485
- workflowScore = clampScore(workflowScore - Math.min(20, danglingCount * 2));
1486
- findings.push({
1487
- criterion: "workflow_rationality",
1488
- severity: "info",
1489
- message: `${danglingCount} edge(s) point to objects not in project — dangling references`,
1490
- deduction: -Math.min(20, danglingCount * 2),
1491
- });
1492
- }
1493
- workflowScore = clampScore(workflowScore);
1494
- let readinessScore = 100;
1495
- if (services[0]) {
1496
- const data = parseCacheData(objectCache.get(services[0].objectAddress));
1497
- if (data) {
1498
- const published = data.bPublished;
1499
- if (published) {
1500
- strengths.push("Service already published — deployment complete");
1501
- readinessScore = 100;
1502
- const machineAddr = data.machine;
1503
- if (typeof machineAddr === "string" && machineAddr.startsWith("0x")) {
1504
- const machineData = parseCacheData(objectCache.get(machineAddr));
1505
- if (machineData && machineData.bPublished === false) {
1506
- readinessScore -= 10;
1507
- findings.push({
1508
- criterion: "deployment_readiness",
1509
- severity: "info",
1510
- message: `Bound Machine ${machineAddr.slice(0, 8)} is not published — order_progress will fail (machine.move E_NOT_PUBLISHED)`,
1511
- deduction: -10,
1512
- });
1513
- }
1514
- }
1515
- }
1516
- else {
1517
- const hasMachine = bindingIndex.get(`${services[0].objectAddress}#machine`)?.size;
1518
- const hasPermission = bindingIndex.get(`${services[0].objectAddress}#permission`)?.size;
1519
- const hasOrderAllocators = bindingIndex.get(`${services[0].objectAddress}#order_allocators`)?.size;
1520
- const compensationBalanceForReady = getBalanceValue(data, "compensation_fund");
1521
- const hasArbitrations = bindingIndex.get(`${services[0].objectAddress}#arbitrations`)?.size;
1522
- if (!hasMachine) {
1523
- readinessScore -= 30;
1524
- findings.push({
1525
- criterion: "deployment_readiness",
1526
- severity: "critical",
1527
- message: "Service has no Machine — cannot publish",
1528
- deduction: -30,
1529
- });
1530
- }
1531
- if (!hasPermission) {
1532
- readinessScore -= 30;
1533
- findings.push({
1534
- criterion: "deployment_readiness",
1535
- severity: "critical",
1536
- message: "Service has no Permission — cannot publish",
1537
- deduction: -30,
1538
- });
1539
- }
1540
- if (!hasOrderAllocators) {
1541
- readinessScore -= 30;
1542
- findings.push({
1543
- criterion: "deployment_readiness",
1544
- severity: "critical",
1545
- message: "Service has no order_allocators — cannot publish (service.move:493 E_NO_ALLOCATOR)",
1546
- deduction: -30,
1547
- });
1548
- }
1549
- if (compensationBalanceForReady > 0 && !hasArbitrations) {
1550
- readinessScore -= 25;
1551
- findings.push({
1552
- criterion: "deployment_readiness",
1553
- severity: "critical",
1554
- message: `Service has compensation_fund (${compensationBalanceForReady}) but no arbitrations — cannot publish (service.move:495 E_ARBITRATION_NOT_SET_WITH_COMPENSATION_FUND)`,
1555
- deduction: -25,
1556
- });
1557
- }
1558
- if (hasMachine && hasPermission && hasOrderAllocators) {
1559
- if (compensationBalanceForReady > 0 && hasArbitrations) {
1560
- strengths.push("Service ready to publish (Machine + Permission + order_allocators + arbitrations bound)");
1561
- }
1562
- else if (compensationBalanceForReady === 0) {
1563
- strengths.push("Service ready to publish (Machine + Permission + order_allocators bound; arbitrations optional when compensation_fund is 0)");
1564
- }
1565
- }
1566
- }
1567
- }
1568
- }
1569
- else {
1570
- readinessScore = 0;
1571
- }
1572
- readinessScore = clampScore(readinessScore);
1573
- const { criterionScores, overall } = finalizeCriterionScores([
1574
- { name: "object_coverage", score: coverageScore, weight: COMPLETENESS_WEIGHTS.object_coverage, rationale: `R1-R8: ${requiredMet}/${requiredCount} required, R9-R12: ${optionalMet}/${optionalItems.length} optional` },
1575
- { name: "binding_completeness", score: bindingScore, weight: COMPLETENESS_WEIGHTS.binding_completeness, rationale: `Service critical bindings checked` },
1576
- { name: "workflow_rationality", score: workflowScore, weight: COMPLETENESS_WEIGHTS.workflow_rationality, rationale: `Machine nodes + dangling edges` },
1577
- { name: "deployment_readiness", score: readinessScore, weight: COMPLETENESS_WEIGHTS.deployment_readiness, rationale: `Service publishable state` },
1578
- ], project.perspective);
1579
- const criticalCount = findings.filter(f => f.severity === "critical").length;
1580
- const summary = criticalCount > 0
1581
- ? `Incomplete: ${criticalCount} critical gap(s). Not ready for deployment.`
1582
- : overall >= 80
1583
- ? `Complete project (score ${overall}/100). Ready for deployment.`
1584
- : `Partially complete (score ${overall}/100). ${findings.length} gap(s) to address.`;
1585
- const industryPattern = evaluateIndustryPattern(project, objects, objectCache, edges);
1586
- strengths.push(...industryPattern.strengths);
1587
- findings.push(...industryPattern.findings);
1588
- return {
1589
- evaluationType: "completeness",
1590
- score: overall,
1591
- summary,
1592
- criterionScores,
1593
- findings,
1594
- strengths,
1595
- needsLlm: false,
1596
- evaluatedAt: Date.now(),
1597
- };
1598
- }
1599
- function evaluateEscrowQuality(input) {
1600
- const { objects, edges, objectCache } = input;
1601
- const byType = groupByType(objects);
1602
- const services = byType.get("Service") ?? [];
1603
- const allocations = byType.get("Allocation") ?? [];
1604
- const bindingIndex = buildBindingIndex(edges);
1605
- let score = 50;
1606
- const findings = [];
1607
- if (services.length === 0) {
1608
- return { name: "escrow_quality", score: 0, weight: EXTENDED_DIMENSION_WEIGHTS.escrow_quality, rationale: "No Service object" };
1609
- }
1610
- const service = services[0];
1611
- const svcData = parseCacheData(objectCache.get(service.objectAddress));
1612
- const hasOrderAllocators = bindingIndex.get(`${service.objectAddress}#order_allocators`)?.size ?? 0;
1613
- if (hasOrderAllocators > 0 && allocations.length > 0) {
1614
- score = 90;
1615
- findings.push("On-chain escrow active: order_allocators bound + Allocation objects present");
1616
- }
1617
- else if (hasOrderAllocators > 0) {
1618
- score = 70;
1619
- findings.push("order_allocators template bound — escrow will activate per-order");
1620
- }
1621
- else if (svcData && getBalanceValue(svcData, "compensation_fund") > 0) {
1622
- score = 60;
1623
- findings.push("compensation_fund present but no Allocation escrow — funds held by merchant, not locked in contract");
1624
- }
1625
- else {
1626
- score = 20;
1627
- findings.push("No escrow mechanism — funds flow directly to merchant (high counterparty risk)");
1628
- }
1629
- return { name: "escrow_quality", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.escrow_quality, rationale: findings.join("; ") };
1630
- }
1631
- function evaluateProofIntegrity(input) {
1632
- const { objects, edges } = input;
1633
- const byType = groupByType(objects);
1634
- const repositories = byType.get("Repository") ?? [];
1635
- const guards = byType.get("Guard") ?? [];
1636
- const proofs = byType.get("Proof") ?? [];
1637
- let score = 50;
1638
- const parts = [];
1639
- if (repositories.length > 0) {
1640
- score += 20;
1641
- parts.push(`${repositories.length} Repository object(s)`);
1642
- }
1643
- if (guards.length > 0) {
1644
- score += 15;
1645
- parts.push(`${guards.length} Guard object(s)`);
1646
- }
1647
- if (proofs.length > 0) {
1648
- score += 15;
1649
- parts.push(`${proofs.length} Proof object(s)`);
1650
- }
1651
- if (repositories.length === 0 && guards.length === 0) {
1652
- score = 20;
1653
- parts.push("No on-chain proof mechanism — evidence can be tampered");
1654
- }
1655
- return { name: "proof_integrity", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.proof_integrity, rationale: parts.join(", ") || "No proof objects" };
1656
- }
1657
- function evaluateArbitrationFairness(input) {
1658
- const { objects, edges, objectCache } = input;
1659
- const byType = groupByType(objects);
1660
- const services = byType.get("Service") ?? [];
1661
- const arbitrations = byType.get("Arbitration") ?? [];
1662
- const bindingIndex = buildBindingIndex(edges);
1663
- if (arbitrations.length === 0) {
1664
- return { name: "arbitration_fairness", score: 0, weight: EXTENDED_DIMENSION_WEIGHTS.arbitration_fairness, rationale: "No Arbitration configured" };
1665
- }
1666
- let score = 50;
1667
- const issues = [];
1668
- const service = services[0];
1669
- if (!service) {
1670
- return { name: "arbitration_fairness", score: 30, weight: EXTENDED_DIMENSION_WEIGHTS.arbitration_fairness, rationale: "No Service to compare against" };
1671
- }
1672
- const svcPermKey = `${service.objectAddress}#permission`;
1673
- const svcPermAddr = bindingIndex.get(svcPermKey)?.values().next().value;
1674
- for (const arb of arbitrations) {
1675
- const arbPermKey = `${arb.objectAddress}#permission`;
1676
- const arbPermAddr = bindingIndex.get(arbPermKey)?.values().next().value;
1677
- if (!svcPermAddr || !arbPermAddr) {
1678
- score -= 10;
1679
- issues.push(`Arbitration ${arb.objectAddress.slice(0, 8)} missing permission binding`);
1680
- continue;
1681
- }
1682
- if (svcPermAddr === arbPermAddr) {
1683
- score = 10;
1684
- issues.push(`Arbitration ${arb.objectAddress.slice(0, 8)} shares SAME Permission as Service — NOT independent`);
1685
- }
1686
- else {
1687
- score += 30;
1688
- issues.push(`Arbitration ${arb.objectAddress.slice(0, 8)} has independent Permission`);
1689
- }
1690
- }
1691
- return { name: "arbitration_fairness", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.arbitration_fairness, rationale: issues.join("; ") };
1692
- }
1693
- function evaluateFeeTransparency(input) {
1694
- const { objects, edges, objectCache } = input;
1695
- const byType = groupByType(objects);
1696
- const allocations = byType.get("Allocation") ?? [];
1697
- const services = byType.get("Service") ?? [];
1698
- let score = 60;
1699
- const parts = [];
1700
- if (allocations.length > 0) {
1701
- score += 20;
1702
- parts.push(`${allocations.length} Allocation object(s) — fee distribution on-chain`);
1703
- }
1704
- const service = services[0];
1705
- if (service) {
1706
- const svcData = parseCacheData(objectCache.get(service.objectAddress));
1707
- if (svcData?.sales && Array.isArray(svcData.sales)) {
1708
- score += 10;
1709
- parts.push(`${svcData.sales.length} sale item(s) — pricing visible`);
1710
- }
1711
- if (svcData?.compensation_fund && getBalanceValue(svcData, "compensation_fund") > 0) {
1712
- score += 10;
1713
- parts.push("compensation_fund visible");
1714
- }
1715
- }
1716
- return { name: "fee_transparency", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.fee_transparency, rationale: parts.join(", ") || "Limited fee visibility" };
1717
- }
1718
- function evaluateTimeoutProtection(input) {
1719
- const { objects, objectCache } = input;
1720
- const byType = groupByType(objects);
1721
- const machines = byType.get("Machine") ?? [];
1722
- let score = 50;
1723
- const parts = [];
1724
- for (const machine of machines) {
1725
- const data = parseCacheData(objectCache.get(machine.objectAddress));
1726
- const nodeCount = getMachineNodeCount(data);
1727
- if (nodeCount > 0) {
1728
- const meta = machine.metadata;
1729
- const config = meta?.config;
1730
- if (config?.timeout_guard || config?.time_guard) {
1731
- score += 30;
1732
- parts.push("Machine has timeout guard configured");
1733
- }
1734
- else if (nodeCount >= 2) {
1735
- score += 10;
1736
- parts.push(`Machine has ${nodeCount} nodes — workflow structure present`);
1737
- }
1738
- }
1739
- }
1740
- if (machines.length === 0) {
1741
- score = 20;
1742
- parts.push("No Machine — no workflow timeout protection");
1743
- }
1744
- return { name: "timeout_protection", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.timeout_protection, rationale: parts.join("; ") || "No timeout mechanisms detected" };
1745
- }
1746
- function evaluateSupplierVisibility(input) {
1747
- const { objects } = input;
1748
- const byType = groupByType(objects);
1749
- const demands = byType.get("Demand") ?? [];
1750
- const allocations = byType.get("Allocation") ?? [];
1751
- let score = 60;
1752
- const parts = [];
1753
- if (demands.length > 0) {
1754
- score += 20;
1755
- parts.push(`${demands.length} Demand object(s) — supplier discovery on-chain`);
1756
- }
1757
- if (allocations.length > 0) {
1758
- score += 20;
1759
- parts.push(`${allocations.length} Allocation object(s) — supplier payments visible`);
1760
- }
1761
- if (demands.length === 0 && allocations.length === 0) {
1762
- score = 30;
1763
- parts.push("No Demand or Allocation — supplier relationships opaque");
1764
- }
1765
- return { name: "supplier_visibility", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.supplier_visibility, rationale: parts.join(", ") || "No supplier transparency" };
1766
- }
1767
- function evaluateContentCommitment(input) {
1768
- const { objects } = input;
1769
- const byType = groupByType(objects);
1770
- const repositories = byType.get("Repository") ?? [];
1771
- const guards = byType.get("Guard") ?? [];
1772
- let score = 50;
1773
- const parts = [];
1774
- if (repositories.length > 0) {
1775
- score += 25;
1776
- parts.push("Repository present — content hash commitments possible");
1777
- }
1778
- if (guards.length > 0) {
1779
- score += 25;
1780
- parts.push("Guard present — delivery verification possible");
1781
- }
1782
- return { name: "content_commitment", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.content_commitment, rationale: parts.join(", ") || "No content commitment mechanism" };
1783
- }
1784
- function evaluateReputationVerifiability(input) {
1785
- const { reputation, objects } = input;
1786
- const services = groupByType(objects).get("Service") ?? [];
1787
- let score = 40;
1788
- const parts = [];
1789
- if (reputation && reputation.size > 0 && services[0]) {
1790
- const rep = reputation.get(services[0].objectAddress);
1791
- if (rep) {
1792
- score += 30;
1793
- parts.push(`Registrar data: ${rep.likes} likes, ${rep.dislikes} dislikes, ${rep.affiliations} affiliations`);
1794
- }
1795
- }
1796
- if (services.length > 0) {
1797
- score += 10;
1798
- parts.push("Service object present — reputation can accumulate");
1799
- }
1800
- return { name: "reputation_verifiability", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.reputation_verifiability, rationale: parts.join(", ") || "No reputation data available" };
1801
- }
1802
- function evaluatePermissionSafety(input) {
1803
- const { objects, edges, objectCache } = input;
1804
- const byType = groupByType(objects);
1805
- const machines = byType.get("Machine") ?? [];
1806
- const permissions = byType.get("Permission") ?? [];
1807
- const bindingIndex = buildBindingIndex(edges);
1808
- let score = 60;
1809
- const issues = [];
1810
- if (machines.length === 0) {
1811
- return { name: "permission_safety", score: 50, weight: EXTENDED_DIMENSION_WEIGHTS.permission_safety, rationale: "No Machine to check" };
1812
- }
1813
- const permDataMap = new Map();
1814
- for (const permObj of permissions) {
1815
- const cached = parseCacheData(objectCache.get(permObj.objectAddress));
1816
- if (cached) {
1817
- permDataMap.set(permObj.objectAddress, {
1818
- address: permObj.objectAddress,
1819
- entity_count: typeof cached.entity_count === "number" ? cached.entity_count : undefined,
1820
- perm_remark: Array.isArray(cached.perm_remark) ? cached.perm_remark : undefined,
1821
- owner: typeof cached.owner === "string" ? cached.owner : undefined,
1822
- admin: Array.isArray(cached.admin) ? cached.admin : undefined,
1823
- });
1824
- }
1825
- }
1826
- for (const machine of machines) {
1827
- const permBindings = bindingIndex.get(`${machine.objectAddress}#permission`);
1828
- if (!permBindings || permBindings.size === 0)
1829
- continue;
1830
- const permAddr = permBindings.values().next().value;
1831
- const permData = permAddr ? permDataMap.get(permAddr) : null;
1832
- if (!permData)
1833
- continue;
1834
- const machineData = parseCacheData(objectCache.get(machine.objectAddress));
1835
- const nodes = extractMachineNodesFromCache(machineData);
1836
- if (nodes.length === 0)
1837
- continue;
1838
- const collection = collectPermissionIndexes(nodes);
1839
- if (collection.requiredIndexes.length === 0)
1840
- continue;
1841
- const report = checkPermissionAuthorization(collection.requiredIndexes, permData);
1842
- if (!report.allAuthorized) {
1843
- score -= 30;
1844
- issues.push(`Machine ${machine.objectAddress.slice(0, 8)} has unauthorized permission indexes: [${report.missingIndexes.join(", ")}]`);
1845
- }
1846
- else {
1847
- score += 20;
1848
- issues.push(`Machine ${machine.objectAddress.slice(0, 8)}: all ${collection.requiredIndexes.length} permission index(es) authorized`);
1849
- }
1850
- }
1851
- return { name: "permission_safety", score: clampScore(score), weight: EXTENDED_DIMENSION_WEIGHTS.permission_safety, rationale: issues.join("; ") || "Permission checks passed" };
1852
- }
1853
- function evaluateWorthBuyingStub(input, llmPrompt) {
1854
- const riskResult = evaluateRisk(input);
1855
- const trustResult = evaluateTrust(input);
1856
- const completenessResult = evaluateCompleteness(input);
1857
- const extendedDimensions = [
1858
- evaluateEscrowQuality(input),
1859
- evaluateProofIntegrity(input),
1860
- evaluateArbitrationFairness(input),
1861
- evaluateFeeTransparency(input),
1862
- evaluateTimeoutProtection(input),
1863
- evaluateSupplierVisibility(input),
1864
- evaluateContentCommitment(input),
1865
- evaluateReputationVerifiability(input),
1866
- evaluatePermissionSafety(input),
1867
- ];
1868
- const extendedSummary = extendedDimensions
1869
- .map(d => `${d.name}: ${d.score}/100 — ${d.rationale}`)
1870
- .join("\n");
1871
- const summaryLines = [
1872
- "=== RULE-BASED EVALUATION SUMMARY (F-08 enriched context) ===",
1873
- "",
1874
- `Risk: ${riskResult.score}/100 — ${riskResult.summary}`,
1875
- ...riskResult.findings.slice(0, 3).map(f => ` - [${f.severity}] ${f.message}`),
1876
- "",
1877
- `Trust: ${trustResult.score}/100 — ${trustResult.summary}`,
1878
- ...trustResult.findings.slice(0, 3).map(f => ` - [${f.severity}] ${f.message}`),
1879
- "",
1880
- `Completeness: ${completenessResult.score}/100 — ${completenessResult.summary}`,
1881
- ...completenessResult.findings.slice(0, 3).map(f => ` - [${f.severity}] ${f.message}`),
1882
- "",
1883
- "=== EXTENDED DIMENSIONS D16-D24 (GLM6/93) ===",
1884
- extendedSummary,
1885
- "",
1886
- "=== END RULE-BASED SUMMARY ===",
1887
- "",
1888
- ];
1889
- const enrichment = summaryLines.join("\n");
1890
- const enrichedPrompt = llmPrompt
1891
- ? `${llmPrompt}\n\n${enrichment}`
1892
- : `${enrichment}\nInstruction: Based on the rule-based summary above, ` +
1893
- "evaluate whether this project is worth buying. Return a 0-100 score " +
1894
- "and a brief rationale. Focus on buyer risk vs. value proposition.";
1895
- return {
1896
- evaluationType: "worth_buying",
1897
- score: 0,
1898
- summary: "Requires LLM evaluation — semantic prompt assembled with rule-based " +
1899
- "context (risk/trust/completeness + D16-D24 extended dimensions). " +
1900
- "Call save_evaluation with the LLM result.",
1901
- criterionScores: [],
1902
- findings: [],
1903
- strengths: [],
1904
- needsLlm: true,
1905
- llmPrompt: enrichedPrompt,
1906
- evaluatedAt: Date.now(),
1907
- };
1908
- }
1909
- function evaluateValueStub(_input, llmPrompt) {
1910
- return {
1911
- evaluationType: "value",
1912
- score: 0,
1913
- summary: "Requires LLM evaluation — semantic prompt assembled. Call save_evaluation with the LLM result.",
1914
- criterionScores: [],
1915
- findings: [],
1916
- strengths: [],
1917
- needsLlm: true,
1918
- llmPrompt,
1919
- evaluatedAt: Date.now(),
1920
- };
1921
- }
1922
- export function runEvaluation(input, evaluationType, llmPrompt) {
1923
- const filtered = filterTemplateObjects(input);
1924
- switch (evaluationType) {
1925
- case "risk":
1926
- return evaluateRisk(filtered);
1927
- case "trust":
1928
- return evaluateTrust(filtered);
1929
- case "completeness":
1930
- return evaluateCompleteness(filtered);
1931
- case "worth_buying":
1932
- return evaluateWorthBuyingStub(filtered, llmPrompt);
1933
- case "value":
1934
- return evaluateValueStub(filtered, llmPrompt);
1935
- default:
1936
- throw new Error(`Unknown evaluation type: ${evaluationType}`);
1937
- }
1938
- }
1939
- function filterTemplateObjects(input) {
1940
- const isDraftAddr = (addr) => {
1941
- if (!addr)
1942
- return true;
1943
- return addr.startsWith("draft:");
1944
- };
1945
- const isDraftObject = (o) => {
1946
- if (isDraftAddr(o.objectAddress))
1947
- return true;
1948
- const meta = o.metadata;
1949
- return !!(meta && meta.status === "draft");
1950
- };
1951
- const draftObjects = [];
1952
- const realObjects = [];
1953
- for (const o of input.objects) {
1954
- if (isDraftObject(o)) {
1955
- draftObjects.push(o);
1956
- }
1957
- else {
1958
- realObjects.push(o);
1959
- }
1960
- }
1961
- const realIds = new Set();
1962
- for (const o of realObjects) {
1963
- if (o.objectAddress)
1964
- realIds.add(o.objectAddress);
1965
- if (o.objectName) {
1966
- realIds.add(o.objectName);
1967
- const shortType = shortTypeName(o.objectType).toLowerCase();
1968
- realIds.add(`${shortType}:${o.objectName}`);
1969
- }
1970
- }
1971
- const draftIds = new Set();
1972
- for (const o of draftObjects) {
1973
- if (o.objectAddress)
1974
- draftIds.add(o.objectAddress);
1975
- if (o.objectName) {
1976
- draftIds.add(o.objectName);
1977
- const shortType = shortTypeName(o.objectType).toLowerCase();
1978
- draftIds.add(`${shortType}:${o.objectName}`);
1979
- }
1980
- }
1981
- const realEdges = input.edges.filter((e) => {
1982
- const meta = e.metadata;
1983
- if (meta && meta.blueprint === true)
1984
- return false;
1985
- const sourceIsDraft = isDraftAddr(e.sourceObject) || draftIds.has(e.sourceObject);
1986
- const targetIsDraft = isDraftAddr(e.targetObject) || draftIds.has(e.targetObject);
1987
- return !sourceIsDraft && !targetIsDraft;
1988
- });
1989
- return {
1990
- ...input,
1991
- objects: realObjects,
1992
- edges: realEdges,
1993
- };
1994
- }
1995
- export function compareProjects(entries, evaluationType) {
1996
- const ranking = [...entries].sort((a, b) => {
1997
- if (a.score === null && b.score === null)
1998
- return 0;
1999
- if (a.score === null)
2000
- return 1;
2001
- if (b.score === null)
2002
- return -1;
2003
- return b.score - a.score;
2004
- });
2005
- return {
2006
- evaluationType,
2007
- entries,
2008
- ranking,
2009
- bestProjectId: ranking[0]?.score !== null ? ranking[0]?.projectId ?? null : null,
2010
- };
2011
- }
1
+ import{IndustryModeRegistry}from'../extensions/registry.js';import{collectPermissionIndexes,checkPermissionAuthorization}from'../schema/utils/permission-machine-check.js';const CRITICAL_BINDINGS=[{'sourceType':'Service','targetType':'Machine','fieldName':'machine','critical':!![]},{'sourceType':'Service','targetType':'Permission','fieldName':'permission','critical':!![]},{'sourceType':'Service','targetType':'Guard','fieldName':'buy_guard','critical':![]},{'sourceType':'Service','targetType':'Allocation','fieldName':'order_allocators','critical':!![]},{'sourceType':'Service','targetType':'Arbitration','fieldName':'arbitrations','critical':![]},{'sourceType':'Machine','targetType':'Permission','fieldName':'permission','critical':!![]}],MERCHANT_REQUIRED_ITEMS=[{'id':'R1','objectType':'Permission','fieldName':'','required':!![],'description':'Governance\x20—\x20who\x20can\x20manage\x20the\x20service'},{'id':'R2','objectType':'Service','fieldName':'','required':!![],'description':'Core\x20offering\x20—\x20the\x20service\x20itself'},{'id':'R3','objectType':'Machine','fieldName':'machine','required':!![],'description':'Workflow\x20—\x20order\x20processing\x20pipeline'},{'id':'R4','objectType':'Guard','fieldName':'','required':!![],'description':'Purchase\x20validation\x20—\x20Guard\x20objects\x20configured\x20(binding\x20to\x20Service.buy_guard\x20is\x20optional)'},{'id':'R5','objectType':'Allocation','fieldName':'order_allocators','required':!![],'description':'Order\x20allocators\x20template\x20—\x20inline\x20Allocators\x20on\x20Service\x20(independent\x20Allocation\x20objects\x20are\x20created\x20per-order)'},{'id':'R6','objectType':'Treasury','fieldName':'','required':!![],'description':'Compensation\x20fund\x20—\x20independent\x20Treasury\x20object\x20for\x20buyer\x20refund\x20protection\x20(industry-aware:\x20optional\x20for\x20freelance)'},{'id':'R7','objectType':'Arbitration','fieldName':'arbitrations','required':!![],'description':'Dispute\x20resolution\x20—\x20arbitration\x20configured\x20(required\x20when\x20compensation_fund\x20>\x200\x20per\x20service.move:494)'},{'id':'R8','objectType':'Contact','fieldName':'','required':!![],'description':'Customer\x20communication\x20—\x20contact\x20info'},{'id':'R9','objectType':'Progress','fieldName':'','required':![],'description':'Order\x20tracking\x20—\x20progress\x20nodes'},{'id':'R10','objectType':'Reward','fieldName':'rewards','required':![],'description':'Customer\x20incentives\x20—\x20reward\x20claims'},{'id':'R11','objectType':'Repository','fieldName':'repositories','required':![],'description':'Documentation\x20—\x20published\x20data'},{'id':'R12','objectType':'Demand','fieldName':'','required':![],'description':'Market\x20discovery\x20—\x20demand\x20signals'}];function resolveRequiredItems(a,b=0x0,c=![]){let d=MERCHANT_REQUIRED_ITEMS;if(a&&a!=='general'){let e;try{e=IndustryModeRegistry['Instance']()['getMode'](a);}catch{}if(e){const f=e['risk_constraints']?.['require_compensation_fund']??!![];!f&&(d=MERCHANT_REQUIRED_ITEMS['map'](g=>{if(g['id']==='R6'||g['id']==='R7')return{...g,'required':![]};return g;}));}}return c&&b===0x0&&(d=d['map'](g=>{if(g['id']==='R6')return{...g,'required':![]};return g;})),b>0x0&&(d=d['map'](g=>g['id']==='R7'?{...g,'required':!![]}:g)),d;}const CONSUMER_DUE_DILIGENCE=[{'id':'E1','check':'Service\x20is\x20published\x20(bPublished=true)','severity':'critical','deduction':-0x1e},{'id':'E2','check':'Service\x20is\x20not\x20paused\x20(bPaused=false)','severity':'warning','deduction':-0x14},{'id':'E3','check':'Machine\x20has\x20workflow\x20nodes','severity':'warning','deduction':-0xf},{'id':'E4','check':'Service\x20has\x20buy_guard\x20(purchase\x20validation)','severity':'info','deduction':0x0},{'id':'E5','check':'Service\x20has\x20compensation_fund\x20(refund\x20protection)','severity':'warning','deduction':-0xf},{'id':'E6','check':'Arbitration\x20is\x20configured\x20(dispute\x20resolution)','severity':'critical','deduction':-0x19},{'id':'E7','check':'Permission\x20is\x20present\x20(governance)','severity':'warning','deduction':-0xa},{'id':'E8','check':'Contact\x20is\x20available\x20(merchant\x20reachable)','severity':'info','deduction':-0x5},{'id':'E9','check':'Repository\x20has\x20published\x20data\x20(transparency)','severity':'info','deduction':-0x5},{'id':'E10','check':'Reward\x20is\x20configured\x20(customer\x20incentives)','severity':'info','deduction':-0x3},{'id':'E11','check':'Service\x20has\x20description\x20(offering\x20clarity)','severity':'info','deduction':-0x5},{'id':'E12','check':'Registrar\x20reputation\x20is\x20positive','severity':'warning','deduction':-0xa}];function clampScore(a){return Math['max'](0x0,Math['min'](0x64,Math['round'](a)));}function shortTypeName(a){if(!a)return'unknown';const b=a['replace'](/<.*>/,'')['trim'](),c=b['split']('::'),d=c[c['length']-0x1]||'unknown';if(d['length']>0x0&&d===d['toLowerCase']())return d['charAt'](0x0)['toUpperCase']()+d['slice'](0x1);return d;}function groupByType(a){const b=new Map();for(const c of a){const d=shortTypeName(c['objectType']);if(!b['has'](d))b['set'](d,[]);b['get'](d)['push'](c);}return b;}function parseCacheData(a){if(!a)return null;try{return JSON['parse'](a['data']);}catch{return null;}}function isAddress(a){return typeof a==='string'&&a['startsWith']('0x')&&a['length']>=0xa;}function countArrayField(a,b){const c=a[b];if(Array['isArray'](c))return c['length'];return 0x0;}export function getNumberField(a,b){if(!a)return 0x0;const c=a[b];if(typeof c==='number'&&Number['isFinite'](c))return c;if(typeof c==='string'){const d=Number(c);if(Number['isFinite'](d))return d;}return 0x0;}export function getMachineNodeCount(a){if(!a)return 0x0;const b=getNumberField(a,'node_count');if(b>0x0)return b;const c=countArrayField(a,'nodes');if(c>0x0)return c;const d=a['nodes'];if(d&&typeof d==='object'){const e=d['fields'];if(e&&typeof e==='object'){const g=getNumberField(e,'size');if(g>0x0)return g;}const f=getNumberField(d,'size');if(f>0x0)return f;}return 0x0;}function extractMachineNodesFromCache(a){if(!a)return[];const b=a['nodes'];if(Array['isArray'](b))return b;const c=a['config'];if(c&&Array['isArray'](c['nodes']))return c['nodes'];const d=a['nodes'];if(d&&typeof d==='object'){const e=d['fields'];if(e&&Array['isArray'](e['contents']))return e['contents'];}return[];}function getBalanceValue(a,b){if(!a)return 0x0;const c=a[b];if(c==null)return 0x0;if(typeof c==='number'&&Number['isFinite'](c))return c;if(typeof c==='string'){const d=Number(c);if(Number['isFinite'](d))return d;}if(typeof c==='object'){const e=c,f=e['value']??e['fields'];if(typeof f==='number'&&Number['isFinite'](f))return f;if(typeof f==='string'){const g=Number(f);if(Number['isFinite'](g))return g;}if(typeof f==='object'&&f!==null){const h=f,i=h['value'];if(typeof i==='number'&&Number['isFinite'](i))return i;if(typeof i==='string'){const j=Number(i);if(Number['isFinite'](j))return j;}}}return 0x0;}function getMaxSalePrice(a){if(!a)return 0x0;const b=a['sales'];if(!Array['isArray'](b)||b['length']===0x0)return 0x0;let c=0x0;for(const d of b){if(typeof d!=='object'||d===null)continue;const e=d['price'];let f=0x0;if(typeof e==='number'&&Number['isFinite'](e))f=e;else{if(typeof e==='string'){const g=Number(e);if(Number['isFinite'](g))f=g;}}if(f>c)c=f;}return c;}function detectCircularRefs(a,b){const c=new Map();for(const i of a){if(i['edgeSource']==='potential')continue;if(!c['has'](i['sourceObject']))c['set'](i['sourceObject'],[]);c['get'](i['sourceObject'])['push'](i['targetObject']);}const d=[],f=new Set(),g=new Set(),h=[];for(const j of c['keys']()){if(f['has'](j))continue;const k=[{'node':j,'nextNeighborIdx':0x0,'neighbors':c['get'](j)??[]}];f['add'](j),g['add'](j),h['push'](j);while(k['length']>0x0){const l=k[k['length']-0x1];if(l['nextNeighborIdx']>=l['neighbors']['length']){k['pop'](),h['pop'](),g['delete'](l['node']);continue;}const m=l['neighbors'][l['nextNeighborIdx']];l['nextNeighborIdx']++;if(!f['has'](m))f['add'](m),g['add'](m),h['push'](m),k['push']({'node':m,'nextNeighborIdx':0x0,'neighbors':c['get'](m)??[]});else{if(g['has'](m)){const n=h['indexOf'](m),o=h['slice'](n)['concat'](m);!isWoWokNormalFundCycle(o,b)&&d['push'](o['join']('→'));}}}}return d;}function isWoWokNormalFundCycle(a,b){if(!b||a['length']<0x3)return![];const c=new Set();for(const f of a){const g=b['get'](f);if(g)c['add'](g);else return![];}if(c['size']===0x2&&c['has']('Order')&&c['has']('Allocation'))return!![];if(c['size']===0x3&&c['has']('Order')&&c['has']('Allocation')&&c['has']('Payment'))return!![];const d=['Service','Machine','Progress','Order'],e=Array['from'](c)['every'](h=>d['includes'](h));if(e&&c['size']>=0x2)return!![];return![];}function adjustWeightsForPerspective(a,b){if(b==='consumer')return a['map'](d=>{if(d['name']==='reputation'||d['name']==='arbitration_coverage'||d['name']==='consumer_diligence')return{...d,'weight':d['weight']*1.4};if(d['name']==='structural_risk'||d['name']==='deployment_readiness')return{...d,'weight':d['weight']*0.7};return d;});if(b==='producer')return a['map'](d=>{if(d['name']==='structural_risk'||d['name']==='deployment_readiness'||d['name']==='binding_completeness')return{...d,'weight':d['weight']*1.3};if(d['name']==='consumer_diligence'||d['name']==='transparency')return{...d,'weight':d['weight']*0.7};return d;});return a;}function normalizeWeights(a){const b=a['reduce']((d,e)=>d+e['weight'],0x0);if(b===0x0)return a;return a['map'](d=>({...d,'weight':d['weight']/b}));}export const RISK_WEIGHTS={'structural_risk':0.25,'fund_safety':0.2,'operational_risk':0.15,'governance_risk':0.1,'graph_coherence':0.2,'mode_registry':0.1};export const TRUST_WEIGHTS={'reputation':0.25,'arbitration_coverage':0.2,'guard_quality':0.2,'transparency':0.15,'consumer_diligence':0.2};export const COMPLETENESS_WEIGHTS={'object_coverage':0.3,'binding_completeness':0.25,'workflow_rationality':0.2,'deployment_readiness':0.25};export const EXTENDED_DIMENSION_WEIGHTS={'escrow_quality':0.15,'proof_integrity':0.1,'arbitration_fairness':0.15,'fee_transparency':0.1,'timeout_protection':0.1,'supplier_visibility':0.1,'content_commitment':0.1,'reputation_verifiability':0.1,'permission_safety':0.1};export function finalizeCriterionScores(a,b){const c=normalizeWeights(adjustWeightsForPerspective(a,b)),d=clampScore(c['reduce']((e,f)=>e+f['score']*f['weight'],0x0));return{'criterionScores':c,'overall':d};}function buildBindingIndex(a){const b=new Map();for(const c of a){if(c['edgeSource']==='potential')continue;if(!c['fieldName'])continue;const d=c['sourceObject']+'#'+c['fieldName'];if(!b['has'](d))b['set'](d,new Set());b['get'](d)['add'](c['targetObject']);}for(const f of a){if(f['edgeSource']!=='potential')continue;if(!f['fieldName'])continue;const g=f['sourceObject']+'#'+f['fieldName'];if(!b['has'](g)||b['get'](g)['size']===0x0){if(!b['has'](g))b['set'](g,new Set());b['get'](g)['add'](f['targetObject']);}}return b;}function evaluateIndustryPattern(a,b,c,d){const e={'strengths':[],'findings':[],'matched':![]},f=a['industry'];if(!f||f==='general')return e;let g;try{g=IndustryModeRegistry['Instance']()['getMode'](f);}catch{return e;}if(!g)return e;const h=groupByType(b),i=buildBindingIndex(d);let j=0x0,k=0x0;const l=g['machine_shape'];if(l['length']>0x0){k++;const q=h['get']('Machine')??[];if(q['length']>0x0){const r=q[0x0],s=parseCacheData(c['get'](r['objectAddress'])),t=getMachineNodeCount(s);if(t>0x0&&t>=l['length'])j++,e['strengths']['push']('Industry\x20pattern\x20match:\x20Machine\x20has\x20'+t+'\x20nodes,\x20covering\x20\x22'+f+'\x22\x20mode\x27s\x20'+l['length']+'\x20expected\x20node(s)');else t>0x0&&e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'Industry\x20pattern:\x20Machine\x20has\x20'+t+'\x20nodes,\x20but\x20\x22'+f+'\x22\x20mode\x20expects\x20at\x20least\x20'+l['length'],'deduction':0x0});}}const n=g['guards'];if(n['length']>0x0){k++;const u=h['get']('Guard')??[],v=n['length'],w=n['length']*0x2;if(u['length']>=v&&u['length']<=w)j++,e['strengths']['push']('Industry\x20pattern\x20match:\x20'+u['length']+'\x20Guard(s)\x20present,\x20within\x20\x22'+f+'\x22\x20mode\x27s\x20expected\x20range\x20['+v+'-'+w+']');else{if(u['length']>0x0&&u['length']<v)e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'Industry\x20pattern:\x20'+u['length']+'\x20Guard(s)\x20present,\x20but\x20\x22'+f+'\x22\x20mode\x20expects\x20at\x20least\x20'+v+'\x20(recommended\x20range\x20['+v+'-'+w+'])','deduction':0x0});else u['length']>w&&(j++,e['strengths']['push']('Industry\x20pattern\x20match:\x20'+u['length']+'\x20Guard(s)\x20present,\x20covering\x20\x22'+f+'\x22\x20mode\x27s\x20'+v+'\x20expected\x20guard(s)'),e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'Industry\x20pattern:\x20'+u['length']+'\x20Guard(s)\x20present,\x20exceeds\x20recommended\x20max\x20'+w+'.\x20Consider\x20consolidating\x20guards\x20if\x20some\x20are\x20redundant.','deduction':0x0}));}}const o=g['allocator'];if(o){k++;const x=h['get']('Allocation')??[],y=h['get']('Service')??[],z=y[0x0],A=z?!!i['get'](z['objectAddress']+'#order_allocators')?.['size']:![],B=g['traits']['multi_tier_allocation'];if(A)j++,x['length']>0x0?e['strengths']['push']('Industry\x20pattern\x20match:\x20Service.order_allocators\x20bound\x20+\x20'+x['length']+'\x20Allocation\x20object(s)\x20present\x20(post-order)\x20—\x20matching\x20\x22'+f+'\x22\x20allocation\x20pattern'):e['strengths']['push']('Industry\x20pattern\x20match:\x20Service.order_allocators\x20template\x20bound\x20—\x20matching\x20\x22'+f+'\x22\x20allocation\x20pattern\x20(Allocation\x20objects\x20created\x20per-order)');else x['length']>0x0?(j++,e['strengths']['push']('Industry\x20pattern\x20match:\x20'+x['length']+'\x20Allocation\x20object(s)\x20present\x20—\x20matching\x20\x22'+f+'\x22\x20allocation\x20pattern')):e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'Industry\x20pattern:\x20Service.order_allocators\x20not\x20bound\x20and\x20no\x20Allocation\x20objects\x20—\x20\x22'+f+'\x22\x20mode\x20expects\x20'+(B?'multi-tier':'single-tier')+'\x20allocation\x20(Allocation\x20objects\x20are\x20created\x20per-order,\x20so\x20this\x20is\x20only\x20a\x20template-level\x20gap)','deduction':0x0});}const p=g['risk_constraints']?.['require_compensation_fund']??![];if(p||g['traits']['deposit_required']||g['traits']['trust_sensitivity']!=='low'){k++;const C=h['get']('Treasury')??[],D=h['get']('Service')??[],E=D[0x0],F=E?parseCacheData(c['get'](E['objectAddress'])):null,G=E?getBalanceValue(F,'compensation_fund'):0x0;if(C['length']>0x0||G>0x0){j++;const H=[];if(C['length']>0x0)H['push'](C['length']+'\x20Treasury\x20object(s)');if(G>0x0)H['push']('compensation_fund\x20balance\x20'+G);e['strengths']['push']('Industry\x20pattern\x20match:\x20'+H['join']('\x20+\x20')+'\x20—\x20matching\x20\x22'+f+'\x22\x20trust/deposit\x20pattern');}}e['matched']=k>0x0&&j/k>=0.6;if(e['matched'])e['strengths']['push']('Industry\x20pattern:\x20project\x20structure\x20matches\x20\x22'+f+'\x22\x20mode\x20('+j+'/'+k+'\x20checks\x20passed)');else k>0x0&&e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'Industry\x20pattern:\x20project\x20partially\x20matches\x20\x22'+f+'\x22\x20mode\x20('+j+'/'+k+'\x20checks\x20passed)','deduction':0x0});if(f==='freelance'){const I=h['get']('Machine')??[];for(const J of I){const K=parseCacheData(c['get'](J['objectAddress']));if(!K)continue;const L=getMachineNodeCount(K);if(L>0x0){e['findings']['push']({'criterion':'industry_pattern','severity':'info','message':'ISSUE-P1-4:\x20freelance\x20project\x20has\x20a\x20Machine\x20with\x20'+L+'\x20node(s).\x20'+'If\x20the\x20workflow\x20includes\x20a\x20\x22delivered\x22\x20state,\x2048h\x20auto-accept\x20requires\x20'+'an\x20off-chain\x20keeper\x20(WoWok\x20Guard\x20does\x20not\x20support\x20time-based\x20triggers).\x20'+'Keeper\x20should\x20poll\x20Progress\x20objects\x20in\x20\x22delivered\x22\x20state\x20and\x20call\x20'+'adminUnhold\x20(permission\x20224)\x20after\x2048h\x20timeout.','deduction':0x0});break;}}}return e;}function evaluateRisk(a){const b=[],d=[],{objects:f,edges:g,objectCache:h,project:i}=a,j=groupByType(f),k=j['get']('Service')??[],l=buildBindingIndex(g);let m=0x64;const n=k[0x0],p=n?parseCacheData(h['get'](n['objectAddress'])):null,q=n?getBalanceValue(p,'compensation_fund'):0x0;if(n)for(const U of CRITICAL_BINDINGS){if(U['sourceType']!=='Service')continue;const V=U['fieldName']==='arbitrations'?q>0x0?!![]:U['critical']:U['critical'],W=n['objectAddress']+'#'+U['fieldName'],X=l['get'](W);if(!X||X['size']===0x0){const Y=V?-0x19:-0xa;m+=Y,b['push']({'criterion':'structural_risk','severity':V?'critical':'warning','message':'Service\x20missing\x20'+U['fieldName']+'\x20binding\x20(expected\x20'+U['targetType']+')'+(U['fieldName']==='arbitrations'?q>0x0?'\x20—\x20required\x20by\x20contract\x20when\x20compensation_fund\x20>\x200\x20(service.move:494)':'\x20—\x20optional\x20when\x20compensation_fund\x20is\x200':''),'deduction':Y});}else d['push']('Service\x20has\x20'+U['fieldName']+'\x20binding');}else m=0x1e,b['push']({'criterion':'structural_risk','severity':'critical','message':'No\x20Service\x20object\x20in\x20project\x20—\x20project\x20has\x20no\x20core','deduction':-0x46});m=clampScore(m);let r=0x64;const s=j['get']('Treasury')??[],t=j['get']('Allocation')??[],w=n?parseCacheData(h['get'](n['objectAddress'])):null,x=n?getBalanceValue(w,'compensation_fund'):0x0,y=n?l['get'](n['objectAddress']+'#order_allocators')?.['size']??0x0:0x0,z=t['length']>0x0&&y>0x0;let A=!![];if(i['industry']&&i['industry']!=='general')try{const Z=IndustryModeRegistry['Instance']()['getMode'](i['industry']);Z&&(A=Z['risk_constraints']?.['require_compensation_fund']??!![]);}catch{}if(s['length']===0x0&&x===0x0){if(z)r-=0x5,d['push']('Allocation\x20escrow\x20mode\x20active\x20—\x20funds\x20locked\x20in\x20contract,\x20released\x20by\x20Guard\x20verification'),b['push']({'criterion':'fund_safety','severity':'info','message':'Using\x20Allocation\x20escrow\x20('+t['length']+'\x20Allocation\x20object(s)\x20+\x20order_allocators\x20bound)\x20—\x20fund\x20safety\x20via\x20Guard\x20verification,\x20no\x20Treasury/compensation_fund\x20needed','deduction':-0x5});else A?(r-=0x1e,b['push']({'criterion':'fund_safety','severity':'warning','message':'No\x20Treasury\x20object\x20and\x20Service.compensation_fund\x20is\x20empty\x20—\x20no\x20refund\x20fund\x20for\x20buyers','deduction':-0x1e})):(r-=0xa,b['push']({'criterion':'fund_safety','severity':'info','message':'No\x20Treasury/compensation_fund\x20—\x20industry\x20\x22'+i['industry']+'\x22\x20does\x20not\x20require\x20refund\x20fund\x20(optional)','deduction':-0xa}));}else{s['length']>0x0&&d['push'](s['length']+'\x20Treasury\x20object(s)\x20present\x20—\x20independent\x20fund\x20holder');if(x>0x0){d['push']('Service.compensation_fund\x20has\x20'+x+'\x20units\x20—\x20inline\x20refund\x20fund\x20active');const a0=getMaxSalePrice(w);if(a0>0x0){let a1=0x5;if(i['industry']&&i['industry']!=='general')try{const a3=IndustryModeRegistry['Instance']()['getMode'](i['industry']);a3?.['risk_constraints']?.['compensation_fund_coverage_ratio']&&(a1=a3['risk_constraints']['compensation_fund_coverage_ratio']);}catch{}const a2=a1*a0;x<a2?(r-=0xa,b['push']({'criterion':'fund_safety','severity':'warning','message':'Service.compensation_fund\x20balance\x20('+x+')\x20is\x20less\x20than\x20'+a1+'×\x20the\x20max\x20order\x20amount\x20('+a0+'\x20→\x20threshold\x20'+a2+').\x20Refund\x20coverage\x20may\x20be\x20insufficient\x20—\x20top\x20up\x20via\x20service.compensation_fund_add\x20to\x20avoid\x20arbitration\x20rulings\x20exceeding\x20the\x20fund.\x20(industry:\x20'+(i['industry']??'general')+',\x20ratio:\x20'+a1+'×)','deduction':-0xa})):b['push']({'criterion':'fund_safety','severity':'info','message':'Service.compensation_fund\x20balance\x20('+x+')\x20covers\x20'+a1+'×\x20the\x20max\x20order\x20amount\x20('+a0+').\x20Fund\x20is\x20sufficient\x20for\x20refund\x20protection.\x20(industry:\x20'+(i['industry']??'general')+',\x20ratio:\x20'+a1+'×)','deduction':0x0});}}else b['push']({'criterion':'fund_safety','severity':'info','message':'Treasury\x20present\x20but\x20Service.compensation_fund\x20balance\x20is\x200\x20—\x20consider\x20depositing\x20refund\x20fund','deduction':-0x5});}r=clampScore(r);let B=0x64;if(n){const a4=parseCacheData(h['get'](n['objectAddress']));if(a4){const a5=a4['bPaused'],a6=a4['bPublished'];a6&&a5&&(B-=0x19,b['push']({'criterion':'operational_risk','severity':'warning','message':'Service\x20is\x20published\x20but\x20PAUSED\x20—\x20operations\x20halted','deduction':-0x19})),!a6&&(B-=0xf,b['push']({'criterion':'operational_risk','severity':'info','message':'Service\x20not\x20yet\x20published\x20—\x20project\x20not\x20live','deduction':-0xf}));}}const C=j['get']('Arbitration')??[];C['length']===0x0?(B-=0x14,b['push']({'criterion':'operational_risk','severity':'warning','message':'No\x20Arbitration\x20object\x20—\x20disputes\x20cannot\x20be\x20resolved','deduction':-0x14})):d['push'](C['length']+'\x20Arbitration\x20object(s)\x20configured');B=clampScore(B);let D=0x64;const E=j['get']('Permission')??[];E['length']===0x0&&(D-=0x28,b['push']({'criterion':'governance_risk','severity':'critical','message':'No\x20Permission\x20object\x20—\x20project\x20is\x20ungoverned','deduction':-0x28}));if(n){const a7=parseCacheData(h['get'](n['objectAddress']));a7&&!isAddress(a7['um'])&&(D-=0x5,b['push']({'criterion':'governance_risk','severity':'info','message':'Service\x20has\x20no\x20UM\x20(manager)\x20—\x20UM\x20is\x20optional;\x20set\x20via\x20um_set\x20if\x20management\x20delegation\x20needed','deduction':-0x5}));}const F=j['get']('Machine')??[];for(const a8 of F){const a9=a8['metadata'],aa=a9?.['config'];if(aa?.['entry_node_forward_hint']){const ae=aa['entry_node_forward_hint'],af=ae['example_forward'];af?.['namedOperator']===''&&d['push']('Machine\x20entry\x20forward\x20uses\x20namedOperator=\x27\x27\x20(OrderHolder)\x20—\x20'+'correct\x20for\x20customer-operable\x20nodes.\x20namedOperator=\x27\x27\x20represents\x20'+'the\x20order\x20holder,\x20distinct\x20from\x20merchant\x27s\x20permission\x20index.');}const ab=aa?.['guard_objects'];ab&&ab['length']>0x0&&d['push']('Machine\x20has\x20'+ab['length']+'\x20guard\x20object\x20reference(s)\x20—\x20'+'forward-level\x20permission\x20validation\x20configured');const ac=parseCacheData(h['get'](a8['objectAddress'])),ad=getMachineNodeCount(ac);ad>0x0&&!aa&&b['push']({'criterion':'governance_risk','severity':'info','message':'Machine\x20has\x20'+ad+'\x20node(s).\x20Verify\x20each\x20forward\x20has\x20at\x20least\x20one\x20of\x20'+'namedOperator\x20or\x20permissionIndex.\x20Key:\x20namedOperator=\x27\x27\x20means\x20OrderHolder\x20'+'(customer),\x20NOT\x20\x27anyone\x27.\x20Use\x20non-empty\x20namedOperator\x20for\x20specific\x20roles,\x20'+'or\x20permissionIndex\x20for\x20permission-based\x20access.\x20Both\x20set\x20=\x20OR\x20semantic\x20'+'(either\x20can\x20execute).','deduction':0x0});}const G=j['get']('Machine')??[],H=j['get']('Permission')??[],I=new Map();for(const ag of H){const ah=parseCacheData(h['get'](ag['objectAddress']));ah&&I['set'](ag['objectAddress'],{'address':ag['objectAddress'],'entity_count':typeof ah['entity_count']==='number'?ah['entity_count']:undefined,'perm_remark':Array['isArray'](ah['perm_remark'])?ah['perm_remark']:undefined,'owner':typeof ah['owner']==='string'?ah['owner']:typeof ah['builder']==='string'?ah['builder']:undefined,'admin':Array['isArray'](ah['admin'])?ah['admin']:undefined});}for(const ai of G){const aj=ai['objectAddress']+'#permission',ak=l['get'](aj);if(!ak||ak['size']===0x0)continue;let al=null;for(const ar of ak){al=ar;break;}if(!al)continue;const am=I['get'](al);if(!am)continue;const an=parseCacheData(h['get'](ai['objectAddress']));if(!an)continue;const ao=extractMachineNodesFromCache(an);if(ao['length']===0x0)continue;const ap=collectPermissionIndexes(ao);if(ap['requiredIndexes']['length']===0x0)continue;const aq=checkPermissionAuthorization(ap['requiredIndexes'],am);!aq['allAuthorized']?(D-=0x19,b['push']({'criterion':'governance_risk','severity':'critical','message':'Machine\x20'+ai['objectAddress']['slice'](0x0,0x8)+'\x20has\x20forwards\x20referencing\x20'+('un-authorized\x20permission\x20indexes:\x20['+aq['missingIndexes']['join'](',\x20')+'].\x20')+'These\x20forwards\x20can\x20NEVER\x20be\x20executed\x20—\x20Progress\x20will\x20be\x20permanently\x20stuck.\x20'+'Grant\x20entities\x20for\x20these\x20indexes\x20via\x20permission.op=\x22add\x20perm\x20by\x20index\x22\x20'+'before\x20publishing\x20the\x20Machine.','deduction':-0x19})):d['push']('Machine\x20'+ai['objectAddress']['slice'](0x0,0x8)+':\x20all\x20'+ap['requiredIndexes']['length']+'\x20'+'permission\x20index(es)\x20are\x20authorized');}if(n&&C['length']>0x0){const as=n['objectAddress']+'#permission',at=l['get'](as),au=at&&at['size']>0x0?Array['from'](at)[0x0]:null,av=au?I['get'](au):null;for(const aw of C){const ax=aw['objectAddress']+'#permission',ay=l['get'](ax),az=ay&&ay['size']>0x0?Array['from'](ay)[0x0]:null;if(!au||!az)continue;if(au===az){D-=0x1e,b['push']({'criterion':'governance_risk','severity':'critical','message':'Arbitration\x20'+aw['objectAddress']['slice'](0x0,0x8)+'\x20and\x20Service\x20share\x20the\x20SAME\x20'+('Permission\x20object\x20('+au['slice'](0x0,0x8)+').\x20This\x20breaks\x20dispute\x20')+'fairness\x20—\x20the\x20merchant\x20fully\x20controls\x20arbitration\x20operations.\x20'+'Use\x20a\x20separate\x20Permission\x20object\x20for\x20Arbitration\x20to\x20ensure\x20independent\x20'+'dispute\x20resolution.\x20(per\x20arbitration.move:\x20the\x20permission\x20field\x20controls\x20'+'who\x20can\x20vote,\x20confirm,\x20and\x20execute\x20arbitration\x20rulings)','deduction':-0x1e});continue;}const aA=I['get'](az);if(av&&aA){const aB=av['owner']?.['toLowerCase'](),aC=aA['owner']?.['toLowerCase'](),aD=new Set((av['admin']??[])['map'](aH=>aH['toLowerCase']())),aE=new Set((aA['admin']??[])['map'](aH=>aH['toLowerCase']())),aF=aB&&aC&&aB===aC,aG=[...aD]['some'](aH=>aE['has'](aH));if(aF||aG){const aH=aF&&aG?'owner\x20AND\x20admin\x20overlap':aF?'same\x20owner':'admin\x20overlap';D-=0x14,b['push']({'criterion':'governance_risk','severity':'warning','message':'Arbitration\x20'+aw['objectAddress']['slice'](0x0,0x8)+'\x20and\x20Service\x20have\x20'+('overlapping\x20Permission\x20control\x20('+aH+').\x20Even\x20with\x20separate\x20')+'Permission\x20objects,\x20shared\x20control\x20undermines\x20dispute\x20independence.\x20'+'For\x20mainnet\x20deployment,\x20use\x20a\x20completely\x20independent\x20third-party\x20'+'Permission\x20(different\x20owner\x20and\x20admin\x20list)\x20for\x20Arbitration.\x20'+'(testnet\x20may\x20tolerate\x20this,\x20but\x20mainnet\x20users\x20should\x20treat\x20this\x20as\x20'+'a\x20critical\x20trust\x20factor)','deduction':-0x14});}else d['push']('Arbitration\x20'+aw['objectAddress']['slice'](0x0,0x8)+'\x20has\x20independent\x20'+'Permission\x20(separate\x20owner/admin)\x20—\x20trustworthy\x20dispute\x20resolution');}}}D=clampScore(D);let J=0x64;const K=new Set();for(const aI of f){if(aI['objectAddress'])K['add'](aI['objectAddress']);if(aI['objectName']){K['add'](aI['objectName']);const aJ=shortTypeName(aI['objectType'])['toLowerCase']();K['add'](aJ+':'+aI['objectName']);}}let L=0x0;for(const aK of g){if(aK['edgeSource']==='potential')continue;if(!K['has'](aK['targetObject']))L++;}if(L>0x0){const aL=-Math['min'](0x14,L*0x3);J+=aL,b['push']({'criterion':'graph_coherence','severity':L>=0x3?'warning':'info','message':L+'\x20edge(s)\x20point\x20to\x20objects\x20outside\x20the\x20project\x20—\x20dangling\x20references','deduction':aL});}const M=new Map();for(const aM of f){aM['objectAddress']&&M['set'](aM['objectAddress'],shortTypeName(aM['objectType']));}const N=detectCircularRefs(g,M);N['length']>0x0&&(J-=0xf,b['push']({'criterion':'graph_coherence','severity':'warning','message':N['length']+'\x20circular\x20reference(s)\x20detected:\x20'+N['slice'](0x0,0x2)['join'](';\x20')+(N['length']>0x2?'...':''),'deduction':-0xf}));L===0x0&&N['length']===0x0&&d['push']('Graph\x20is\x20coherent\x20—\x20no\x20dangling\x20refs\x20or\x20cycles');J=clampScore(J);let O=0x64,P='no\x20industry\x20declared\x20—\x20check\x20skipped';if(!i['industry'])b['push']({'criterion':'mode_registry','severity':'info','message':'Project\x20has\x20no\x20industry\x20tag\x20—\x20mode\x20registry\x20gates\x20(metrics/constraints)\x20not\x20evaluated.\x20Set\x20project\x20industry\x20to\x20enable.','deduction':0x0});else try{const aN=IndustryModeRegistry['Instance']()['evaluateMode'](i['industry'],i['description']??i['name'],{'prefix':i['prefix'],'network':i['network']==='mainnet'?'mainnet':'testnet','business_intent':i['description']??undefined,'industry':i['industry'],'version':i['currentVersion']??undefined}),aO=aN['unmet_conditions']['some'](aP=>aP['includes']('not\x20found'));if(aO)O=0x32,P='mode\x20\x27'+i['industry']+'\x27\x20not\x20registered',b['push']({'criterion':'mode_registry','severity':'warning','message':'Industry\x20mode\x20\x27'+i['industry']+'\x27\x20is\x20not\x20registered\x20in\x20the\x20mode\x20registry\x20—\x20cannot\x20verify\x20capability/conflict/constraint\x20gates.\x20Falling\x20back\x20to\x20unverified\x20mode.','deduction':-0x32});else{for(const aP of aN['violated_constraints']){O-=0x19,b['push']({'criterion':'mode_registry','severity':'critical','message':'Mode\x20\x27'+i['industry']+'\x27\x20hard\x20constraint\x20violated:\x20'+aP,'deduction':-0x19});}for(const aQ of aN['capability_conflicts']){O-=0x14,b['push']({'criterion':'mode_registry','severity':'critical','message':'Mode\x20\x27'+i['industry']+'\x27\x20capability\x20conflict:\x20'+aQ,'deduction':-0x14});}for(const aR of aN['unmet_conditions']){O-=0xa,b['push']({'criterion':'mode_registry','severity':'warning','message':'Mode\x20\x27'+i['industry']+'\x27\x20soft\x20constraint\x20unmet:\x20'+aR,'deduction':-0xa});}O=clampScore(O),P='metric\x20risk\x20'+aN['risk_score']+'\x20/\x20benefit\x20'+aN['benefit_score']+'\x20'+('(ratio\x20'+aN['risk_benefit_ratio']['toFixed'](0x2)+');\x20')+(aN['violated_constraints']['length']+'\x20hard\x20+\x20'+aN['unmet_conditions']['length']+'\x20soft\x20constraint\x20issue(s),\x20')+(aN['capability_conflicts']['length']+'\x20capability\x20conflict(s)'),aN['applicable']&&aN['violated_constraints']['length']===0x0&&aN['capability_conflicts']['length']===0x0&&aN['unmet_conditions']['length']===0x0&&d['push']('Mode\x20\x27'+i['industry']+'\x27\x20passes\x20all\x20mode-registry\x20gates\x20—\x20'+('metric\x20risk\x20'+aN['risk_score']+'\x20/\x20benefit\x20'+aN['benefit_score']+'\x20')+('(risk-benefit\x20ratio\x20'+aN['risk_benefit_ratio']['toFixed'](0x2)+')'));}}catch{P='mode\x20registry\x20unavailable\x20—\x20check\x20skipped';}O=clampScore(O);const {criterionScores:Q,overall:R}=finalizeCriterionScores([{'name':'structural_risk','score':m,'weight':RISK_WEIGHTS['structural_risk'],'rationale':CRITICAL_BINDINGS['filter'](aS=>aS['sourceType']==='Service')['length']+'\x20expected\x20Service\x20bindings\x20checked'},{'name':'fund_safety','score':r,'weight':RISK_WEIGHTS['fund_safety'],'rationale':'Treasury\x20+\x20compensation_fund\x20coverage'},{'name':'operational_risk','score':B,'weight':RISK_WEIGHTS['operational_risk'],'rationale':'Service\x20state\x20+\x20arbitration\x20coverage'},{'name':'governance_risk','score':D,'weight':RISK_WEIGHTS['governance_risk'],'rationale':'Permission\x20+\x20UM\x20presence'},{'name':'graph_coherence','score':J,'weight':RISK_WEIGHTS['graph_coherence'],'rationale':L+'\x20dangling\x20+\x20'+N['length']+'\x20circular\x20refs'},{'name':'mode_registry','score':O,'weight':RISK_WEIGHTS['mode_registry'],'rationale':P}],i['perspective']),S=b['filter'](aS=>aS['severity']==='critical')['length'],T=S>0x0?'HIGH\x20RISK:\x20'+S+'\x20critical\x20issue(s).\x20'+b['length']+'\x20total\x20findings.':'Moderate\x20risk:\x20'+b['length']+'\x20finding(s),\x20no\x20critical\x20issues.';return{'evaluationType':'risk','score':R,'summary':T,'criterionScores':Q,'findings':b,'strengths':d,'needsLlm':![],'evaluatedAt':Date['now']()};}function evaluateTrust(a){const b=[],c=[],{objects:d,edges:e,objectCache:f,reputation:g,project:h}=a,i=groupByType(d),j=i['get']('Service')??[];let k=0x32;if(g&&g['size']>0x0&&j[0x0]){const z=g['get'](j[0x0]['objectAddress']);if(z){const A=z['likes']+z['dislikes'];if(A>0x0){const B=z['likes']/A;k=clampScore(0x32+(B-0.5)*0x64);if(B>=0.8)c['push']('Strong\x20reputation:\x20'+z['likes']+'\x20likes\x20vs\x20'+z['dislikes']+'\x20dislikes');else B<0.4&&b['push']({'criterion':'reputation','severity':'warning','message':'Poor\x20reputation:\x20'+z['dislikes']+'\x20dislikes\x20vs\x20'+z['likes']+'\x20likes','deduction':-0x14});}z['affiliations']>=0x3&&(c['push'](z['affiliations']+'\x20affiliations\x20—\x20trusted\x20by\x20other\x20merchants'),k=clampScore(k+0xa));}}else b['push']({'criterion':'reputation','severity':'info','message':'No\x20Registrar\x20reputation\x20data\x20—\x20unknown\x20merchant\x20standing','deduction':-0xa});k=clampScore(k);let l=0x64;const m=i['get']('Arbitration')??[];m['length']===0x0?(l=0x1e,b['push']({'criterion':'arbitration_coverage','severity':'critical','message':'No\x20Arbitration\x20object\x20—\x20buyers\x20have\x20no\x20dispute\x20resolution\x20path','deduction':-0x46})):c['push'](m['length']+'\x20Arbitration\x20object(s)\x20—\x20dispute\x20resolution\x20available');l=clampScore(l);let n=0x3c;const o=i['get']('Guard')??[];o['length']===0x0?(n-=0x14,b['push']({'criterion':'guard_quality','severity':'warning','message':'No\x20Guard\x20objects\x20—\x20no\x20validation\x20rules','deduction':-0x14})):(n=0x50,c['push'](o['length']+'\x20Guard\x20object(s)\x20—\x20validation\x20rules\x20configured'));if(j[0x0]){const C=buildBindingIndex(e),D=j[0x0]['objectAddress']+'#buy_guard';if(C['get'](D)?.['size'])n=clampScore(n+0xf),c['push']('Service\x20has\x20buy_guard\x20bound\x20—\x20purchase\x20validation\x20active');else o['length']>0x0&&c['push']('Guard\x20objects\x20present\x20(buy_guard\x20binding\x20optional)');}n=clampScore(n);let p=0x3c;if(j[0x0]){const E=parseCacheData(f['get'](j[0x0]['objectAddress']));if(E){const F=E['description'];typeof F==='string'&&F['length']>0x0?(p+=0xf,c['push']('Service\x20has\x20description')):b['push']({'criterion':'transparency','severity':'info','message':'Service\x20has\x20no\x20description\x20—\x20buyers\x20cannot\x20evaluate\x20offering','deduction':-0xa});}}const q=i['get']('Repository')??[];q['length']>0x0&&(p=clampScore(p+0xa),c['push'](q['length']+'\x20Repository\x20object(s)\x20—\x20supporting\x20data\x20published'));const r=i['get']('Contact')??[];r['length']>0x0?(p=clampScore(p+0xa),c['push']('Contact\x20information\x20available')):b['push']({'criterion':'transparency','severity':'info','message':'No\x20Contact\x20object\x20—\x20buyers\x20cannot\x20reach\x20merchant','deduction':-0x5});p=clampScore(p);let s=0x64;const t=[],u=buildBindingIndex(e),v=j[0x0];if(v){const G=parseCacheData(f['get'](v['objectAddress']));for(const I of CONSUMER_DUE_DILIGENCE){let J=![];switch(I['id']){case'E1':J=!!G?.['bPublished'];break;case'E2':J=!!G&&!G['bPaused'];break;case'E3':J=(i['get']('Machine')??[])['some'](K=>{const L=parseCacheData(f['get'](K['objectAddress']));return L&&(getNumberField(L,'node_count')>0x0||countArrayField(L,'nodes')>0x0);});break;case'E4':J=!!u['get'](v['objectAddress']+'#buy_guard')?.['size']||(i['get']('Guard')??[])['length']>0x0;break;case'E5':J=getBalanceValue(G,'compensation_fund')>0x0||(i['get']('Treasury')??[])['length']>0x0;break;case'E6':J=(i['get']('Arbitration')??[])['length']>0x0;break;case'E7':J=(i['get']('Permission')??[])['length']>0x0;break;case'E8':J=(i['get']('Contact')??[])['length']>0x0;break;case'E9':J=(i['get']('Repository')??[])['length']>0x0;break;case'E10':J=!!u['get'](v['objectAddress']+'#rewards')?.['size'];break;case'E11':J=!!(G&&typeof G['description']==='string'&&G['description']['length']>0x0);break;case'E12':if(g&&g['size']>0x0){const K=g['get'](v['objectAddress']);J=!!K&&K['likes']>=K['dislikes'];}break;}if(J)t['push'](I['id']);else{let L=I['deduction'],M=I['severity'];if(I['id']==='E5'&&h['industry']&&h['industry']!=='general')try{const O=IndustryModeRegistry['Instance']()['getMode'](h['industry']);O&&O['risk_constraints']?.['require_compensation_fund']===![]&&(L=-0x3,M='info');}catch{}s+=L;const N=I['id']==='E5'&&L!==I['deduction']?'\x20(industry\x20does\x20not\x20require\x20compensation_fund\x20—\x20reduced\x20deduction)':'';b['push']({'criterion':'consumer_diligence','severity':M,'message':I['id']+':\x20'+I['check']+'\x20—\x20FAIL:\x20condition\x20not\x20met'+N+'\x20[severity:\x20'+M+']','deduction':L});}}const H=t['length']/CONSUMER_DUE_DILIGENCE['length'];H>=0.8&&c['push']('Consumer\x20due\x20diligence:\x20'+t['length']+'/'+CONSUMER_DUE_DILIGENCE['length']+'\x20checks\x20passed');}else s=0x14,b['push']({'criterion':'consumer_diligence','severity':'critical','message':'No\x20Service\x20object\x20—\x20consumer\x20due\x20diligence\x20cannot\x20be\x20performed','deduction':-0x50});s=clampScore(s);const {criterionScores:w,overall:x}=finalizeCriterionScores([{'name':'reputation','score':k,'weight':TRUST_WEIGHTS['reputation'],'rationale':'Registrar\x20likes/dislikes\x20+\x20affiliations'},{'name':'arbitration_coverage','score':l,'weight':TRUST_WEIGHTS['arbitration_coverage'],'rationale':'Dispute\x20resolution\x20availability'},{'name':'guard_quality','score':n,'weight':TRUST_WEIGHTS['guard_quality'],'rationale':'Validation\x20rules\x20+\x20buy_guard\x20binding'},{'name':'transparency','score':p,'weight':TRUST_WEIGHTS['transparency'],'rationale':'Description\x20+\x20Repository\x20+\x20Contact\x20presence'},{'name':'consumer_diligence','score':s,'weight':TRUST_WEIGHTS['consumer_diligence'],'rationale':t['length']+'/'+CONSUMER_DUE_DILIGENCE['length']+'\x20E-checks\x20passed'}],h['perspective']),y=x>=0x46?'Trusted\x20project\x20(score\x20'+x+'/100).\x20'+c['length']+'\x20strength(s).':'Limited\x20trust\x20signals\x20(score\x20'+x+'/100).\x20'+b['length']+'\x20finding(s).';return{'evaluationType':'trust','score':x,'summary':y,'criterionScores':w,'findings':b,'strengths':c,'needsLlm':![],'evaluatedAt':Date['now']()};}function evaluateCompleteness(a){const b=[],c=[],{objects:d,edges:f,objectCache:g,project:h}=a,i=groupByType(d),j=i['get']('Service')??[],k=buildBindingIndex(f),l=j[0x0],n=l?parseCacheData(g['get'](l['objectAddress'])):null,p=getBalanceValue(n,'compensation_fund'),q=i['get']('Allocation')??[],r=l?k['get'](l['objectAddress']+'#order_allocators')?.['size']??0x0:0x0,s=q['length']>0x0&&r>0x0,t=resolveRequiredItems(h['industry']??undefined,p,s),u=t['filter'](O=>O['required'])['length'],v=t['filter'](O=>!O['required']);let w=0x0,x=0x0;const y=[],z=[];for(const O of t){const P=(i['get'](O['objectType'])?.['length']??0x0)>0x0,Q=O['fieldName']?!!k['get']((j[0x0]?.['objectAddress']??'')+'#'+O['fieldName'])?.['size']:P;O['required']?Q||!O['fieldName']&&P?w++:y['push'](O['id']+'('+O['objectType']+')'):Q||!O['fieldName']&&P?x++:z['push'](O['id']+'('+O['objectType']+')');}const A=w/u,B=v['length']>0x0?x/v['length']:0x1;let C=clampScore(A*0x50+B*0x14);y['length']>0x0?b['push']({'criterion':'object_coverage','severity':y['length']>=0x3?'critical':'warning','message':'Missing\x20required\x20items:\x20'+y['join'](',\x20')+'\x20—\x20'+y['length']+'/'+u+'\x20required\x20items\x20absent','deduction':-0xf*y['length']}):c['push']('All\x20'+u+'\x20required\x20items\x20present\x20(R1-R8)');if(z['length']>0x0&&z['length']===v['length'])b['push']({'criterion':'object_coverage','severity':'info','message':'No\x20optional\x20items\x20configured:\x20'+z['join'](',\x20')+'\x20—\x20recommended\x20for\x20enhanced\x20UX','deduction':-0x5});else x>0x0&&c['push'](x+'/'+v['length']+'\x20optional\x20items\x20configured\x20(R9-R12)');C=clampScore(C);let D=0x64;if(j[0x0]){const R=j[0x0]['objectAddress'],S=parseCacheData(g['get'](R)),T=getBalanceValue(S,'compensation_fund');let U=0x0,V=0x0;for(const W of CRITICAL_BINDINGS){if(W['sourceType']!=='Service')continue;V++;const X=W['fieldName']==='arbitrations'?T>0x0?!![]:W['critical']:W['critical'],Y=R+'#'+W['fieldName'];if(k['get'](Y)?.['size'])U++;else{const Z=X?-0x14:-0x8;D+=Z,b['push']({'criterion':'binding_completeness','severity':X?'critical':'warning','message':'Service.'+W['fieldName']+'\x20not\x20bound\x20(expected\x20'+W['targetType']+')'+(W['fieldName']==='arbitrations'?T>0x0?'\x20—\x20required\x20by\x20contract\x20when\x20compensation_fund\x20>\x200':'\x20—\x20optional\x20when\x20compensation_fund\x20is\x200':''),'deduction':Z});}}U===V&&c['push']('All\x20'+V+'\x20Service\x20bindings\x20established');}else D=0x0,b['push']({'criterion':'binding_completeness','severity':'critical','message':'No\x20Service\x20object\x20—\x20cannot\x20evaluate\x20bindings','deduction':-0x64});D=clampScore(D);let E=0x50;const F=i['get']('Machine')??[];if(F['length']===0x0)E-=0x14,b['push']({'criterion':'workflow_rationality','severity':'info','message':'No\x20Machine\x20object\x20—\x20bind\x20one\x20before\x20publishing\x20(deploy-time\x20requirement)','deduction':-0x14});else for(const a0 of F){const a1=parseCacheData(g['get'](a0['objectAddress']));if(a1){const a2=getMachineNodeCount(a1);a2>0x0?c['push']('Machine\x20has\x20'+a2+'\x20node(s)'):(E-=0xa,b['push']({'criterion':'workflow_rationality','severity':'info','message':'Machine\x20'+a0['objectAddress']['slice'](0x0,0x8)+'\x20has\x20no\x20nodes','deduction':-0xa}));}}const G=new Set();for(const a3 of d){if(a3['objectAddress'])G['add'](a3['objectAddress']);if(a3['objectName']){G['add'](a3['objectName']);const a4=shortTypeName(a3['objectType'])['toLowerCase']();G['add'](a4+':'+a3['objectName']);}}let H=0x0;for(const a5 of f){if(a5['edgeSource']==='potential')continue;if(!G['has'](a5['targetObject']))H++;}H>0x0&&(E=clampScore(E-Math['min'](0x14,H*0x2)),b['push']({'criterion':'workflow_rationality','severity':'info','message':H+'\x20edge(s)\x20point\x20to\x20objects\x20not\x20in\x20project\x20—\x20dangling\x20references','deduction':-Math['min'](0x14,H*0x2)}));E=clampScore(E);let I=0x64;if(j[0x0]){const a6=parseCacheData(g['get'](j[0x0]['objectAddress']));if(a6){const a7=a6['bPublished'];if(a7){c['push']('Service\x20already\x20published\x20—\x20deployment\x20complete'),I=0x64;const a8=a6['machine'];if(typeof a8==='string'&&a8['startsWith']('0x')){const a9=parseCacheData(g['get'](a8));a9&&a9['bPublished']===![]&&(I-=0xa,b['push']({'criterion':'deployment_readiness','severity':'info','message':'Bound\x20Machine\x20'+a8['slice'](0x0,0x8)+'\x20is\x20not\x20published\x20—\x20order_progress\x20will\x20fail\x20(machine.move\x20E_NOT_PUBLISHED)','deduction':-0xa}));}}else{const aa=k['get'](j[0x0]['objectAddress']+'#machine')?.['size'],ab=k['get'](j[0x0]['objectAddress']+'#permission')?.['size'],ac=k['get'](j[0x0]['objectAddress']+'#order_allocators')?.['size'],ad=getBalanceValue(a6,'compensation_fund'),ae=k['get'](j[0x0]['objectAddress']+'#arbitrations')?.['size'];!aa&&(I-=0x1e,b['push']({'criterion':'deployment_readiness','severity':'critical','message':'Service\x20has\x20no\x20Machine\x20—\x20cannot\x20publish','deduction':-0x1e}));!ab&&(I-=0x1e,b['push']({'criterion':'deployment_readiness','severity':'critical','message':'Service\x20has\x20no\x20Permission\x20—\x20cannot\x20publish','deduction':-0x1e}));!ac&&(I-=0x1e,b['push']({'criterion':'deployment_readiness','severity':'critical','message':'Service\x20has\x20no\x20order_allocators\x20—\x20cannot\x20publish\x20(service.move:493\x20E_NO_ALLOCATOR)','deduction':-0x1e}));ad>0x0&&!ae&&(I-=0x19,b['push']({'criterion':'deployment_readiness','severity':'critical','message':'Service\x20has\x20compensation_fund\x20('+ad+')\x20but\x20no\x20arbitrations\x20—\x20cannot\x20publish\x20(service.move:495\x20E_ARBITRATION_NOT_SET_WITH_COMPENSATION_FUND)','deduction':-0x19}));if(aa&&ab&&ac){if(ad>0x0&&ae)c['push']('Service\x20ready\x20to\x20publish\x20(Machine\x20+\x20Permission\x20+\x20order_allocators\x20+\x20arbitrations\x20bound)');else ad===0x0&&c['push']('Service\x20ready\x20to\x20publish\x20(Machine\x20+\x20Permission\x20+\x20order_allocators\x20bound;\x20arbitrations\x20optional\x20when\x20compensation_fund\x20is\x200)');}}}}else I=0x0;I=clampScore(I);const {criterionScores:J,overall:K}=finalizeCriterionScores([{'name':'object_coverage','score':C,'weight':COMPLETENESS_WEIGHTS['object_coverage'],'rationale':'R1-R8:\x20'+w+'/'+u+'\x20required,\x20R9-R12:\x20'+x+'/'+v['length']+'\x20optional'},{'name':'binding_completeness','score':D,'weight':COMPLETENESS_WEIGHTS['binding_completeness'],'rationale':'Service\x20critical\x20bindings\x20checked'},{'name':'workflow_rationality','score':E,'weight':COMPLETENESS_WEIGHTS['workflow_rationality'],'rationale':'Machine\x20nodes\x20+\x20dangling\x20edges'},{'name':'deployment_readiness','score':I,'weight':COMPLETENESS_WEIGHTS['deployment_readiness'],'rationale':'Service\x20publishable\x20state'}],h['perspective']),L=b['filter'](af=>af['severity']==='critical')['length'],M=L>0x0?'Incomplete:\x20'+L+'\x20critical\x20gap(s).\x20Not\x20ready\x20for\x20deployment.':K>=0x50?'Complete\x20project\x20(score\x20'+K+'/100).\x20Ready\x20for\x20deployment.':'Partially\x20complete\x20(score\x20'+K+'/100).\x20'+b['length']+'\x20gap(s)\x20to\x20address.',N=evaluateIndustryPattern(h,d,g,f);return c['push'](...N['strengths']),b['push'](...N['findings']),{'evaluationType':'completeness','score':K,'summary':M,'criterionScores':J,'findings':b,'strengths':c,'needsLlm':![],'evaluatedAt':Date['now']()};}function evaluateEscrowQuality(a){const {objects:b,edges:c,objectCache:d}=a,e=groupByType(b),f=e['get']('Service')??[],g=e['get']('Allocation')??[],h=buildBindingIndex(c);let i=0x32;const j=[];if(f['length']===0x0)return{'name':'escrow_quality','score':0x0,'weight':EXTENDED_DIMENSION_WEIGHTS['escrow_quality'],'rationale':'No\x20Service\x20object'};const k=f[0x0],l=parseCacheData(d['get'](k['objectAddress'])),m=h['get'](k['objectAddress']+'#order_allocators')?.['size']??0x0;if(m>0x0&&g['length']>0x0)i=0x5a,j['push']('On-chain\x20escrow\x20active:\x20order_allocators\x20bound\x20+\x20Allocation\x20objects\x20present');else{if(m>0x0)i=0x46,j['push']('order_allocators\x20template\x20bound\x20—\x20escrow\x20will\x20activate\x20per-order');else l&&getBalanceValue(l,'compensation_fund')>0x0?(i=0x3c,j['push']('compensation_fund\x20present\x20but\x20no\x20Allocation\x20escrow\x20—\x20funds\x20held\x20by\x20merchant,\x20not\x20locked\x20in\x20contract')):(i=0x14,j['push']('No\x20escrow\x20mechanism\x20—\x20funds\x20flow\x20directly\x20to\x20merchant\x20(high\x20counterparty\x20risk)'));}return{'name':'escrow_quality','score':clampScore(i),'weight':EXTENDED_DIMENSION_WEIGHTS['escrow_quality'],'rationale':j['join'](';\x20')};}function evaluateProofIntegrity(a){const {objects:b,edges:c}=a,d=groupByType(b),e=d['get']('Repository')??[],f=d['get']('Guard')??[],g=d['get']('Proof')??[];let h=0x32;const i=[];return e['length']>0x0&&(h+=0x14,i['push'](e['length']+'\x20Repository\x20object(s)')),f['length']>0x0&&(h+=0xf,i['push'](f['length']+'\x20Guard\x20object(s)')),g['length']>0x0&&(h+=0xf,i['push'](g['length']+'\x20Proof\x20object(s)')),e['length']===0x0&&f['length']===0x0&&(h=0x14,i['push']('No\x20on-chain\x20proof\x20mechanism\x20—\x20evidence\x20can\x20be\x20tampered')),{'name':'proof_integrity','score':clampScore(h),'weight':EXTENDED_DIMENSION_WEIGHTS['proof_integrity'],'rationale':i['join'](',\x20')||'No\x20proof\x20objects'};}function evaluateArbitrationFairness(a){const {objects:b,edges:c,objectCache:d}=a,e=groupByType(b),f=e['get']('Service')??[],g=e['get']('Arbitration')??[],h=buildBindingIndex(c);if(g['length']===0x0)return{'name':'arbitration_fairness','score':0x0,'weight':EXTENDED_DIMENSION_WEIGHTS['arbitration_fairness'],'rationale':'No\x20Arbitration\x20configured'};let i=0x32;const j=[],k=f[0x0];if(!k)return{'name':'arbitration_fairness','score':0x1e,'weight':EXTENDED_DIMENSION_WEIGHTS['arbitration_fairness'],'rationale':'No\x20Service\x20to\x20compare\x20against'};const l=k['objectAddress']+'#permission',m=h['get'](l)?.['values']()['next']()['value'];for(const n of g){const o=n['objectAddress']+'#permission',p=h['get'](o)?.['values']()['next']()['value'];if(!m||!p){i-=0xa,j['push']('Arbitration\x20'+n['objectAddress']['slice'](0x0,0x8)+'\x20missing\x20permission\x20binding');continue;}m===p?(i=0xa,j['push']('Arbitration\x20'+n['objectAddress']['slice'](0x0,0x8)+'\x20shares\x20SAME\x20Permission\x20as\x20Service\x20—\x20NOT\x20independent')):(i+=0x1e,j['push']('Arbitration\x20'+n['objectAddress']['slice'](0x0,0x8)+'\x20has\x20independent\x20Permission'));}return{'name':'arbitration_fairness','score':clampScore(i),'weight':EXTENDED_DIMENSION_WEIGHTS['arbitration_fairness'],'rationale':j['join'](';\x20')};}function evaluateFeeTransparency(a){const {objects:b,edges:c,objectCache:d}=a,e=groupByType(b),f=e['get']('Allocation')??[],g=e['get']('Service')??[];let h=0x3c;const i=[];f['length']>0x0&&(h+=0x14,i['push'](f['length']+'\x20Allocation\x20object(s)\x20—\x20fee\x20distribution\x20on-chain'));const j=g[0x0];if(j){const k=parseCacheData(d['get'](j['objectAddress']));k?.['sales']&&Array['isArray'](k['sales'])&&(h+=0xa,i['push'](k['sales']['length']+'\x20sale\x20item(s)\x20—\x20pricing\x20visible')),k?.['compensation_fund']&&getBalanceValue(k,'compensation_fund')>0x0&&(h+=0xa,i['push']('compensation_fund\x20visible'));}return{'name':'fee_transparency','score':clampScore(h),'weight':EXTENDED_DIMENSION_WEIGHTS['fee_transparency'],'rationale':i['join'](',\x20')||'Limited\x20fee\x20visibility'};}function evaluateTimeoutProtection(a){const {objects:b,objectCache:c}=a,d=groupByType(b),e=d['get']('Machine')??[];let f=0x32;const g=[];for(const h of e){const i=parseCacheData(c['get'](h['objectAddress'])),j=getMachineNodeCount(i);if(j>0x0){const k=h['metadata'],l=k?.['config'];if(l?.['timeout_guard']||l?.['time_guard'])f+=0x1e,g['push']('Machine\x20has\x20timeout\x20guard\x20configured');else j>=0x2&&(f+=0xa,g['push']('Machine\x20has\x20'+j+'\x20nodes\x20—\x20workflow\x20structure\x20present'));}}return e['length']===0x0&&(f=0x14,g['push']('No\x20Machine\x20—\x20no\x20workflow\x20timeout\x20protection')),{'name':'timeout_protection','score':clampScore(f),'weight':EXTENDED_DIMENSION_WEIGHTS['timeout_protection'],'rationale':g['join'](';\x20')||'No\x20timeout\x20mechanisms\x20detected'};}function evaluateSupplierVisibility(a){const {objects:b}=a,c=groupByType(b),d=c['get']('Demand')??[],e=c['get']('Allocation')??[];let f=0x3c;const g=[];return d['length']>0x0&&(f+=0x14,g['push'](d['length']+'\x20Demand\x20object(s)\x20—\x20supplier\x20discovery\x20on-chain')),e['length']>0x0&&(f+=0x14,g['push'](e['length']+'\x20Allocation\x20object(s)\x20—\x20supplier\x20payments\x20visible')),d['length']===0x0&&e['length']===0x0&&(f=0x1e,g['push']('No\x20Demand\x20or\x20Allocation\x20—\x20supplier\x20relationships\x20opaque')),{'name':'supplier_visibility','score':clampScore(f),'weight':EXTENDED_DIMENSION_WEIGHTS['supplier_visibility'],'rationale':g['join'](',\x20')||'No\x20supplier\x20transparency'};}function evaluateContentCommitment(a){const {objects:b}=a,c=groupByType(b),d=c['get']('Repository')??[],e=c['get']('Guard')??[];let f=0x32;const g=[];return d['length']>0x0&&(f+=0x19,g['push']('Repository\x20present\x20—\x20content\x20hash\x20commitments\x20possible')),e['length']>0x0&&(f+=0x19,g['push']('Guard\x20present\x20—\x20delivery\x20verification\x20possible')),{'name':'content_commitment','score':clampScore(f),'weight':EXTENDED_DIMENSION_WEIGHTS['content_commitment'],'rationale':g['join'](',\x20')||'No\x20content\x20commitment\x20mechanism'};}function evaluateReputationVerifiability(a){const {reputation:b,objects:c}=a,d=groupByType(c)['get']('Service')??[];let e=0x28;const f=[];if(b&&b['size']>0x0&&d[0x0]){const g=b['get'](d[0x0]['objectAddress']);g&&(e+=0x1e,f['push']('Registrar\x20data:\x20'+g['likes']+'\x20likes,\x20'+g['dislikes']+'\x20dislikes,\x20'+g['affiliations']+'\x20affiliations'));}return d['length']>0x0&&(e+=0xa,f['push']('Service\x20object\x20present\x20—\x20reputation\x20can\x20accumulate')),{'name':'reputation_verifiability','score':clampScore(e),'weight':EXTENDED_DIMENSION_WEIGHTS['reputation_verifiability'],'rationale':f['join'](',\x20')||'No\x20reputation\x20data\x20available'};}function evaluatePermissionSafety(a){const {objects:b,edges:c,objectCache:d}=a,e=groupByType(b),f=e['get']('Machine')??[],g=e['get']('Permission')??[],h=buildBindingIndex(c);let i=0x3c;const j=[];if(f['length']===0x0)return{'name':'permission_safety','score':0x32,'weight':EXTENDED_DIMENSION_WEIGHTS['permission_safety'],'rationale':'No\x20Machine\x20to\x20check'};const k=new Map();for(const l of g){const m=parseCacheData(d['get'](l['objectAddress']));m&&k['set'](l['objectAddress'],{'address':l['objectAddress'],'entity_count':typeof m['entity_count']==='number'?m['entity_count']:undefined,'perm_remark':Array['isArray'](m['perm_remark'])?m['perm_remark']:undefined,'owner':typeof m['owner']==='string'?m['owner']:undefined,'admin':Array['isArray'](m['admin'])?m['admin']:undefined});}for(const n of f){const o=h['get'](n['objectAddress']+'#permission');if(!o||o['size']===0x0)continue;const p=o['values']()['next']()['value'],q=p?k['get'](p):null;if(!q)continue;const r=parseCacheData(d['get'](n['objectAddress'])),s=extractMachineNodesFromCache(r);if(s['length']===0x0)continue;const t=collectPermissionIndexes(s);if(t['requiredIndexes']['length']===0x0)continue;const u=checkPermissionAuthorization(t['requiredIndexes'],q);!u['allAuthorized']?(i-=0x1e,j['push']('Machine\x20'+n['objectAddress']['slice'](0x0,0x8)+'\x20has\x20unauthorized\x20permission\x20indexes:\x20['+u['missingIndexes']['join'](',\x20')+']')):(i+=0x14,j['push']('Machine\x20'+n['objectAddress']['slice'](0x0,0x8)+':\x20all\x20'+t['requiredIndexes']['length']+'\x20permission\x20index(es)\x20authorized'));}return{'name':'permission_safety','score':clampScore(i),'weight':EXTENDED_DIMENSION_WEIGHTS['permission_safety'],'rationale':j['join'](';\x20')||'Permission\x20checks\x20passed'};}function evaluateWorthBuyingStub(a,b){const c=evaluateRisk(a),d=evaluateTrust(a),e=evaluateCompleteness(a),f=[evaluateEscrowQuality(a),evaluateProofIntegrity(a),evaluateArbitrationFairness(a),evaluateFeeTransparency(a),evaluateTimeoutProtection(a),evaluateSupplierVisibility(a),evaluateContentCommitment(a),evaluateReputationVerifiability(a),evaluatePermissionSafety(a)],g=f['map'](k=>k['name']+':\x20'+k['score']+'/100\x20—\x20'+k['rationale'])['join']('\x0a'),h=['===\x20RULE-BASED\x20EVALUATION\x20SUMMARY\x20(F-08\x20enriched\x20context)\x20===','','Risk:\x20'+c['score']+'/100\x20—\x20'+c['summary'],...c['findings']['slice'](0x0,0x3)['map'](k=>'\x20\x20-\x20['+k['severity']+']\x20'+k['message']),'','Trust:\x20'+d['score']+'/100\x20—\x20'+d['summary'],...d['findings']['slice'](0x0,0x3)['map'](k=>'\x20\x20-\x20['+k['severity']+']\x20'+k['message']),'','Completeness:\x20'+e['score']+'/100\x20—\x20'+e['summary'],...e['findings']['slice'](0x0,0x3)['map'](k=>'\x20\x20-\x20['+k['severity']+']\x20'+k['message']),'','===\x20EXTENDED\x20DIMENSIONS\x20D16-D24\x20(GLM6/93)\x20===',g,'','===\x20END\x20RULE-BASED\x20SUMMARY\x20===',''],i=h['join']('\x0a'),j=b?b+'\x0a\x0a'+i:i+'\x0aInstruction:\x20Based\x20on\x20the\x20rule-based\x20summary\x20above,\x20'+'evaluate\x20whether\x20this\x20project\x20is\x20worth\x20buying.\x20Return\x20a\x200-100\x20score\x20'+'and\x20a\x20brief\x20rationale.\x20Focus\x20on\x20buyer\x20risk\x20vs.\x20value\x20proposition.';return{'evaluationType':'worth_buying','score':0x0,'summary':'Requires\x20LLM\x20evaluation\x20—\x20semantic\x20prompt\x20assembled\x20with\x20rule-based\x20'+'context\x20(risk/trust/completeness\x20+\x20D16-D24\x20extended\x20dimensions).\x20'+'Call\x20save_evaluation\x20with\x20the\x20LLM\x20result.','criterionScores':[],'findings':[],'strengths':[],'needsLlm':!![],'llmPrompt':j,'evaluatedAt':Date['now']()};}function evaluateValueStub(a,b){return{'evaluationType':'value','score':0x0,'summary':'Requires\x20LLM\x20evaluation\x20—\x20semantic\x20prompt\x20assembled.\x20Call\x20save_evaluation\x20with\x20the\x20LLM\x20result.','criterionScores':[],'findings':[],'strengths':[],'needsLlm':!![],'llmPrompt':b,'evaluatedAt':Date['now']()};}export function runEvaluation(a,b,c){const d=filterTemplateObjects(a);switch(b){case'risk':return evaluateRisk(d);case'trust':return evaluateTrust(d);case'completeness':return evaluateCompleteness(d);case'worth_buying':return evaluateWorthBuyingStub(d,c);case'value':return evaluateValueStub(d,c);default:throw new Error('Unknown\x20evaluation\x20type:\x20'+b);}}function filterTemplateObjects(a){const b=i=>{if(!i)return!![];return i['startsWith']('draft:');},c=i=>{if(b(i['objectAddress']))return!![];const j=i['metadata'];return!!(j&&j['status']==='draft');},d=[],e=[];for(const i of a['objects']){c(i)?d['push'](i):e['push'](i);}const f=new Set();for(const j of e){if(j['objectAddress'])f['add'](j['objectAddress']);if(j['objectName']){f['add'](j['objectName']);const k=shortTypeName(j['objectType'])['toLowerCase']();f['add'](k+':'+j['objectName']);}}const g=new Set();for(const l of d){if(l['objectAddress'])g['add'](l['objectAddress']);if(l['objectName']){g['add'](l['objectName']);const m=shortTypeName(l['objectType'])['toLowerCase']();g['add'](m+':'+l['objectName']);}}const h=a['edges']['filter'](n=>{const p=n['metadata'];if(p&&p['blueprint']===!![])return![];const q=b(n['sourceObject'])||g['has'](n['sourceObject']),r=b(n['targetObject'])||g['has'](n['targetObject']);return!q&&!r;});return{...a,'objects':e,'edges':h};}export function compareProjects(a,b){const c=[...a]['sort']((d,e)=>{if(d['score']===null&&e['score']===null)return 0x0;if(d['score']===null)return 0x1;if(e['score']===null)return-0x1;return e['score']-d['score'];});return{'evaluationType':b,'entries':a,'ranking':c,'bestProjectId':c[0x0]?.['score']!==null?c[0x0]?.['projectId']??null:null};}