@wowok/agent-mcp 2.7.1 → 2.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/account-events.d.ts +32 -0
  4. package/dist/customer/account-events.js +1 -0
  5. package/dist/customer/customer-advice.d.ts +1 -0
  6. package/dist/customer/customer-advice.js +1 -130
  7. package/dist/customer/index.js +1 -11
  8. package/dist/customer/industry-risks.js +1 -438
  9. package/dist/customer/info-puzzle.js +1 -681
  10. package/dist/customer/order-monitor.js +1 -328
  11. package/dist/customer/order-strategy.d.ts +1 -1
  12. package/dist/customer/order-strategy.js +1 -373
  13. package/dist/customer/post-purchase.js +1 -351
  14. package/dist/customer/preorder-compare.js +1 -34
  15. package/dist/customer/reminder-system.d.ts +2 -0
  16. package/dist/customer/reminder-system.js +1 -316
  17. package/dist/customer/risk-assessment.d.ts +1 -0
  18. package/dist/customer/risk-assessment.js +1 -397
  19. package/dist/customer/types.d.ts +2 -0
  20. package/dist/customer/types.js +1 -13
  21. package/dist/customer/user-preferences.js +1 -460
  22. package/dist/evaluation/arbitration-game.d.ts +9 -2
  23. package/dist/evaluation/arbitration-game.js +1 -48
  24. package/dist/evaluation/builtins/arbitration-score.d.ts +41 -0
  25. package/dist/evaluation/builtins/arbitration-score.js +1 -0
  26. package/dist/evaluation/builtins/demand-match.js +1 -153
  27. package/dist/evaluation/builtins/index.d.ts +1 -0
  28. package/dist/evaluation/builtins/index.js +1 -10
  29. package/dist/evaluation/builtins/service-risk.js +1 -55
  30. package/dist/evaluation/capability.js +1 -13
  31. package/dist/evaluation/category-match-rules.d.ts +30 -0
  32. package/dist/evaluation/category-match-rules.js +1 -0
  33. package/dist/evaluation/composer.js +1 -40
  34. package/dist/evaluation/engine.js +1 -175
  35. package/dist/evaluation/extract.js +1 -115
  36. package/dist/evaluation/game-strategy.d.ts +27 -0
  37. package/dist/evaluation/game-strategy.js +1 -0
  38. package/dist/evaluation/gap.js +1 -100
  39. package/dist/evaluation/index.d.ts +2 -0
  40. package/dist/evaluation/index.js +1 -11
  41. package/dist/evaluation/location-match.d.ts +42 -0
  42. package/dist/evaluation/location-match.js +1 -0
  43. package/dist/evaluation/node-game.d.ts +31 -3
  44. package/dist/evaluation/node-game.js +1 -57
  45. package/dist/evaluation/path-reasoning.d.ts +35 -0
  46. package/dist/evaluation/path-reasoning.js +1 -0
  47. package/dist/evaluation/region.d.ts +6 -0
  48. package/dist/evaluation/region.js +1 -36
  49. package/dist/evaluation/types.d.ts +18 -0
  50. package/dist/evaluation/types.js +1 -1
  51. package/dist/evaluation/user-injection.js +1 -27
  52. package/dist/experience/experience-reuse.js +1 -103
  53. package/dist/experience/index.js +1 -5
  54. package/dist/experience/intent-distill.js +1 -83
  55. package/dist/experience/realtime-feedback.js +1 -94
  56. package/dist/experience/types.js +1 -1
  57. package/dist/experience/user-profile.d.ts +1 -1
  58. package/dist/experience/user-profile.js +1 -171
  59. package/dist/extensions/business-modules.js +1 -287
  60. package/dist/extensions/capability-manifest.js +1 -781
  61. package/dist/extensions/constraint-registry.js +1 -198
  62. package/dist/extensions/index.d.ts +6 -0
  63. package/dist/extensions/index.js +1 -6
  64. package/dist/extensions/industry-layers.d.ts +75 -0
  65. package/dist/extensions/industry-layers.js +1 -0
  66. package/dist/extensions/industry-pack.d.ts +105 -0
  67. package/dist/extensions/industry-pack.js +1 -0
  68. package/dist/extensions/metric-registry.js +1 -257
  69. package/dist/extensions/mode-evaluator.d.ts +1 -1
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.d.ts +1 -0
  73. package/dist/extensions/registry.js +1 -717
  74. package/dist/extensions/types.js +1 -1
  75. package/dist/graph/base.d.ts +8 -0
  76. package/dist/graph/base.js +1 -0
  77. package/dist/harness/auto-escalation.js +1 -68
  78. package/dist/harness/checkpoint.js +1 -129
  79. package/dist/harness/index.d.ts +1 -0
  80. package/dist/harness/index.js +1 -78
  81. package/dist/harness/plan.d.ts +2 -0
  82. package/dist/harness/plan.js +1 -315
  83. package/dist/harness/recover.d.ts +1 -1
  84. package/dist/harness/recover.js +1 -139
  85. package/dist/harness/types.d.ts +2 -3
  86. package/dist/harness/types.js +1 -1
  87. package/dist/harness/verify.js +1 -237
  88. package/dist/index.js +1 -273
  89. package/dist/intent/enrich.js +1 -67
  90. package/dist/intent/index.js +1 -60
  91. package/dist/intent/matcher.js +1 -81
  92. package/dist/intent/store.js +1 -55
  93. package/dist/intent/types.js +1 -10
  94. package/dist/knowledge/acquisition-flywheel.js +1 -192
  95. package/dist/knowledge/allocation-confirm.js +1 -534
  96. package/dist/knowledge/allocation-context.js +1 -249
  97. package/dist/knowledge/allocation-ledger.js +1 -463
  98. package/dist/knowledge/allocation-puzzle.js +1 -298
  99. package/dist/knowledge/allocation-risk.js +1 -568
  100. package/dist/knowledge/allocation-templates.js +1 -970
  101. package/dist/knowledge/allocation-translation.js +1 -585
  102. package/dist/knowledge/anti-cheat.d.ts +37 -0
  103. package/dist/knowledge/anti-cheat.js +1 -0
  104. package/dist/knowledge/arb-confirm.d.ts +28 -0
  105. package/dist/knowledge/arb-confirm.js +1 -0
  106. package/dist/knowledge/arb-risk.js +1 -210
  107. package/dist/knowledge/arb-translation.d.ts +48 -0
  108. package/dist/knowledge/arb-translation.js +1 -0
  109. package/dist/knowledge/arbitration-confirm.js +1 -559
  110. package/dist/knowledge/arbitration-context.js +1 -505
  111. package/dist/knowledge/arbitration-ledger.js +1 -521
  112. package/dist/knowledge/arbitration-puzzle.js +1 -304
  113. package/dist/knowledge/arbitration-risk.js +1 -423
  114. package/dist/knowledge/arbitration-templates.js +1 -276
  115. package/dist/knowledge/arbitration-translation.js +1 -487
  116. package/dist/knowledge/audit-rules.js +1 -141
  117. package/dist/knowledge/bridge-confirm.d.ts +26 -0
  118. package/dist/knowledge/bridge-confirm.js +1 -0
  119. package/dist/knowledge/bridge-risk.js +1 -263
  120. package/dist/knowledge/bridge-translation.d.ts +37 -0
  121. package/dist/knowledge/bridge-translation.js +1 -0
  122. package/dist/knowledge/contact-confirm.d.ts +27 -0
  123. package/dist/knowledge/contact-confirm.js +1 -0
  124. package/dist/knowledge/contact-risk.js +1 -200
  125. package/dist/knowledge/contact-templates.js +1 -60
  126. package/dist/knowledge/contact-translation.d.ts +39 -0
  127. package/dist/knowledge/contact-translation.js +1 -0
  128. package/dist/knowledge/demand-confirm.js +1 -206
  129. package/dist/knowledge/demand-context.d.ts +17 -0
  130. package/dist/knowledge/demand-context.js +1 -0
  131. package/dist/knowledge/demand-ledger.d.ts +26 -0
  132. package/dist/knowledge/demand-ledger.js +1 -0
  133. package/dist/knowledge/demand-matching.js +1 -132
  134. package/dist/knowledge/demand-puzzle.d.ts +29 -0
  135. package/dist/knowledge/demand-puzzle.js +1 -0
  136. package/dist/knowledge/demand-risk.js +1 -240
  137. package/dist/knowledge/demand-templates.d.ts +12 -0
  138. package/dist/knowledge/demand-templates.js +1 -0
  139. package/dist/knowledge/demand-translation.js +1 -354
  140. package/dist/knowledge/deployment-scanner.js +1 -823
  141. package/dist/knowledge/dynamic-pricing.js +1 -87
  142. package/dist/knowledge/evidence-review.d.ts +12 -0
  143. package/dist/knowledge/evidence-review.js +1 -0
  144. package/dist/knowledge/examples-scanner-cli.js +1 -26
  145. package/dist/knowledge/examples-scanner.js +1 -843
  146. package/dist/knowledge/flywheel-loop.d.ts +0 -1
  147. package/dist/knowledge/flywheel-loop.js +1 -404
  148. package/dist/knowledge/fund-layer.js +1 -973
  149. package/dist/knowledge/glossary.js +1 -211
  150. package/dist/knowledge/guard-confirm.js +1 -406
  151. package/dist/knowledge/guard-context.js +1 -287
  152. package/dist/knowledge/guard-design-patterns.js +1 -360
  153. package/dist/knowledge/guard-ledger.js +1 -260
  154. package/dist/knowledge/guard-lint.js +1 -670
  155. package/dist/knowledge/guard-migration.d.ts +1 -1
  156. package/dist/knowledge/guard-migration.js +1 -228
  157. package/dist/knowledge/guard-puzzle.js +1 -805
  158. package/dist/knowledge/guard-render.js +1 -700
  159. package/dist/knowledge/guard-risk.js +1 -1879
  160. package/dist/knowledge/guard-submission-prompt.js +1 -171
  161. package/dist/knowledge/guard-templates.js +1 -1105
  162. package/dist/knowledge/guard-translation.js +1 -1119
  163. package/dist/knowledge/index.d.ts +71 -3
  164. package/dist/knowledge/index.js +1 -436
  165. package/dist/knowledge/industry-evolution.js +1 -323
  166. package/dist/knowledge/industry-generalizer.js +1 -381
  167. package/dist/knowledge/industry-registry.js +1 -174
  168. package/dist/knowledge/intent-metrics.d.ts +4 -3
  169. package/dist/knowledge/intent-metrics.js +1 -566
  170. package/dist/knowledge/machine-confirm.js +1 -559
  171. package/dist/knowledge/machine-context.js +1 -833
  172. package/dist/knowledge/machine-ledger.js +1 -338
  173. package/dist/knowledge/machine-puzzle.js +1 -494
  174. package/dist/knowledge/machine-render.js +1 -565
  175. package/dist/knowledge/machine-risk.js +1 -669
  176. package/dist/knowledge/machine-templates.js +1 -1597
  177. package/dist/knowledge/machine-topology.js +1 -234
  178. package/dist/knowledge/machine-translation.js +1 -513
  179. package/dist/knowledge/market-metrics.d.ts +12 -0
  180. package/dist/knowledge/market-metrics.js +1 -0
  181. package/dist/knowledge/market-operations.d.ts +46 -0
  182. package/dist/knowledge/market-operations.js +1 -0
  183. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  184. package/dist/knowledge/mcp-schema-audit.d.ts +22 -22
  185. package/dist/knowledge/mcp-schema-audit.js +1 -777
  186. package/dist/knowledge/onchain-constants.js +1 -35
  187. package/dist/knowledge/order-confirm.js +1 -573
  188. package/dist/knowledge/order-context.js +1 -390
  189. package/dist/knowledge/order-ledger.js +1 -341
  190. package/dist/knowledge/order-puzzle.js +1 -255
  191. package/dist/knowledge/order-risk.js +1 -653
  192. package/dist/knowledge/order-templates.js +1 -368
  193. package/dist/knowledge/order-translation.js +1 -550
  194. package/dist/knowledge/overrides-loader.js +1 -65
  195. package/dist/knowledge/passport-confirm.js +1 -531
  196. package/dist/knowledge/passport-context.js +1 -306
  197. package/dist/knowledge/passport-ledger.js +1 -282
  198. package/dist/knowledge/passport-puzzle.js +1 -333
  199. package/dist/knowledge/passport-risk.js +1 -450
  200. package/dist/knowledge/passport-templates.js +1 -568
  201. package/dist/knowledge/passport-translation.js +1 -516
  202. package/dist/knowledge/payment-confirm.d.ts +26 -0
  203. package/dist/knowledge/payment-confirm.js +1 -0
  204. package/dist/knowledge/payment-risk.js +1 -249
  205. package/dist/knowledge/payment-translation.d.ts +37 -0
  206. package/dist/knowledge/payment-translation.js +1 -0
  207. package/dist/knowledge/permission-confirm.js +1 -426
  208. package/dist/knowledge/permission-context.js +1 -224
  209. package/dist/knowledge/permission-ledger.d.ts +11 -0
  210. package/dist/knowledge/permission-ledger.js +1 -403
  211. package/dist/knowledge/permission-puzzle.js +1 -173
  212. package/dist/knowledge/permission-risk.js +1 -411
  213. package/dist/knowledge/permission-templates.js +1 -234
  214. package/dist/knowledge/permission-translation.js +1 -350
  215. package/dist/knowledge/personal-confirm.d.ts +29 -0
  216. package/dist/knowledge/personal-confirm.js +1 -0
  217. package/dist/knowledge/personal-risk.js +1 -212
  218. package/dist/knowledge/personal-translation.d.ts +37 -0
  219. package/dist/knowledge/personal-translation.js +1 -0
  220. package/dist/knowledge/process-model.d.ts +1 -11
  221. package/dist/knowledge/process-model.js +1 -160
  222. package/dist/knowledge/progress-confirm.js +1 -456
  223. package/dist/knowledge/progress-context.js +1 -452
  224. package/dist/knowledge/progress-ledger.js +1 -330
  225. package/dist/knowledge/progress-puzzle.js +1 -219
  226. package/dist/knowledge/progress-risk.js +1 -461
  227. package/dist/knowledge/progress-templates.js +1 -228
  228. package/dist/knowledge/progress-translation.js +1 -405
  229. package/dist/knowledge/proof-confirm.js +1 -187
  230. package/dist/knowledge/proof-context.d.ts +17 -0
  231. package/dist/knowledge/proof-context.js +1 -0
  232. package/dist/knowledge/proof-ledger.d.ts +34 -0
  233. package/dist/knowledge/proof-ledger.js +1 -0
  234. package/dist/knowledge/proof-puzzle.d.ts +35 -0
  235. package/dist/knowledge/proof-puzzle.js +1 -0
  236. package/dist/knowledge/proof-risk.js +1 -207
  237. package/dist/knowledge/proof-templates.d.ts +22 -0
  238. package/dist/knowledge/proof-templates.js +1 -0
  239. package/dist/knowledge/proof-translation.js +1 -283
  240. package/dist/knowledge/registrar-confirm.d.ts +26 -0
  241. package/dist/knowledge/registrar-confirm.js +1 -0
  242. package/dist/knowledge/registrar-risk.js +1 -217
  243. package/dist/knowledge/registrar-translation.d.ts +37 -0
  244. package/dist/knowledge/registrar-translation.js +1 -0
  245. package/dist/knowledge/repository-confirm.js +1 -286
  246. package/dist/knowledge/repository-context.d.ts +12 -0
  247. package/dist/knowledge/repository-context.js +1 -0
  248. package/dist/knowledge/repository-ledger.d.ts +25 -0
  249. package/dist/knowledge/repository-ledger.js +1 -0
  250. package/dist/knowledge/repository-puzzle.d.ts +30 -0
  251. package/dist/knowledge/repository-puzzle.js +1 -0
  252. package/dist/knowledge/repository-risk.js +1 -373
  253. package/dist/knowledge/repository-templates.d.ts +14 -0
  254. package/dist/knowledge/repository-templates.js +1 -0
  255. package/dist/knowledge/repository-translation.js +1 -445
  256. package/dist/knowledge/reputation-rules.js +1 -99
  257. package/dist/knowledge/resource-confirm.d.ts +25 -0
  258. package/dist/knowledge/resource-confirm.js +1 -0
  259. package/dist/knowledge/resource-risk.js +1 -157
  260. package/dist/knowledge/resource-translation.d.ts +37 -0
  261. package/dist/knowledge/resource-translation.js +1 -0
  262. package/dist/knowledge/reward-confirm.js +1 -526
  263. package/dist/knowledge/reward-context.d.ts +2 -2
  264. package/dist/knowledge/reward-context.js +1 -504
  265. package/dist/knowledge/reward-ledger.js +1 -502
  266. package/dist/knowledge/reward-puzzle.js +1 -300
  267. package/dist/knowledge/reward-risk.js +1 -627
  268. package/dist/knowledge/reward-templates.js +1 -197
  269. package/dist/knowledge/reward-translation.js +1 -501
  270. package/dist/knowledge/safety-rules.d.ts +1 -0
  271. package/dist/knowledge/safety-rules.js +1 -404
  272. package/dist/knowledge/scenario-modes.js +1 -321
  273. package/dist/knowledge/service-confirm.js +1 -807
  274. package/dist/knowledge/service-context.js +1 -403
  275. package/dist/knowledge/service-ledger.js +1 -609
  276. package/dist/knowledge/service-puzzle.js +1 -236
  277. package/dist/knowledge/service-risk.d.ts +1 -1
  278. package/dist/knowledge/service-risk.js +1 -651
  279. package/dist/knowledge/service-templates.js +1 -456
  280. package/dist/knowledge/service-translation.js +1 -622
  281. package/dist/knowledge/template-registry.js +1 -353
  282. package/dist/knowledge/tool-constraints.js +1 -195
  283. package/dist/knowledge/tools-reference.js +1 -178
  284. package/dist/knowledge/treasury-confirm.js +1 -512
  285. package/dist/knowledge/treasury-context.js +1 -363
  286. package/dist/knowledge/treasury-ledger.js +1 -300
  287. package/dist/knowledge/treasury-puzzle.js +1 -216
  288. package/dist/knowledge/treasury-risk.js +1 -440
  289. package/dist/knowledge/treasury-templates.js +1 -358
  290. package/dist/knowledge/treasury-translation.js +1 -498
  291. package/dist/knowledge/trust-metrics.js +1 -198
  292. package/dist/knowledge/universal-template.d.ts +22 -0
  293. package/dist/knowledge/universal-template.js +1 -0
  294. package/dist/knowledge/util-confirm.d.ts +24 -0
  295. package/dist/knowledge/util-confirm.js +1 -0
  296. package/dist/knowledge/util-risk.js +1 -135
  297. package/dist/knowledge/util-translation.d.ts +38 -0
  298. package/dist/knowledge/util-translation.js +1 -0
  299. package/dist/knowledge/workflow-guidance.d.ts +116 -0
  300. package/dist/knowledge/workflow-guidance.js +1 -0
  301. package/dist/loop-engineering/aggregate.js +1 -132
  302. package/dist/loop-engineering/context-collect.js +1 -83
  303. package/dist/loop-engineering/diagnose.js +1 -273
  304. package/dist/loop-engineering/improve.js +1 -405
  305. package/dist/loop-engineering/index.js +1 -4
  306. package/dist/loop-engineering/pipeline.js +1 -56
  307. package/dist/mode-market/index.js +1 -3
  308. package/dist/mode-market/registry.js +1 -124
  309. package/dist/mode-market/review.js +1 -214
  310. package/dist/mode-market/submission.js +1 -85
  311. package/dist/participation/collaborator-interest.d.ts +23 -0
  312. package/dist/participation/collaborator-interest.js +1 -0
  313. package/dist/participation/customer-interest.d.ts +25 -0
  314. package/dist/participation/customer-interest.js +1 -0
  315. package/dist/participation/employee-kpi.d.ts +25 -0
  316. package/dist/participation/employee-kpi.js +1 -0
  317. package/dist/participation/employee-store.d.ts +16 -0
  318. package/dist/participation/employee-store.js +1 -0
  319. package/dist/participation/index.d.ts +2 -0
  320. package/dist/participation/index.js +1 -0
  321. package/dist/participation/merchant-interest.js +1 -100
  322. package/dist/participation/radar-core.d.ts +13 -3
  323. package/dist/participation/radar-core.js +1 -269
  324. package/dist/participation/supplier-interest.d.ts +25 -0
  325. package/dist/participation/supplier-interest.js +1 -0
  326. package/dist/persona/analyzer.js +1 -66
  327. package/dist/persona/bridge.js +1 -86
  328. package/dist/persona/defaults.js +1 -195
  329. package/dist/persona/experience-bridge.js +1 -23
  330. package/dist/persona/index.d.ts +9 -2
  331. package/dist/persona/index.js +1 -71
  332. package/dist/persona/local-region.d.ts +20 -0
  333. package/dist/persona/local-region.js +1 -0
  334. package/dist/persona/model.js +1 -111
  335. package/dist/persona/overrides.d.ts +10 -0
  336. package/dist/persona/overrides.js +1 -0
  337. package/dist/persona/pack-personae.d.ts +11 -0
  338. package/dist/persona/pack-personae.js +1 -0
  339. package/dist/persona/store.js +1 -62
  340. package/dist/persona/strategy-intent.d.ts +20 -0
  341. package/dist/persona/strategy-intent.js +1 -0
  342. package/dist/persona/types.d.ts +6 -2
  343. package/dist/persona/types.js +1 -5
  344. package/dist/project/business-puzzle.d.ts +1 -1
  345. package/dist/project/business-puzzle.js +1 -383
  346. package/dist/project/context-assembly.js +1 -254
  347. package/dist/project/deployment-bridge.js +1 -120
  348. package/dist/project/deployment-doc.js +1 -1126
  349. package/dist/project/edit-planner.js +1 -1342
  350. package/dist/project/evaluation.d.ts +37 -1
  351. package/dist/project/evaluation.js +1 -2011
  352. package/dist/project/game-theory.js +1 -177
  353. package/dist/project/graph-builder.js +1 -656
  354. package/dist/project/graph.d.ts +3 -6
  355. package/dist/project/graph.js +1 -340
  356. package/dist/project/handlers.d.ts +33 -2
  357. package/dist/project/handlers.js +1 -1784
  358. package/dist/project/index.d.ts +2 -0
  359. package/dist/project/index.js +1 -301
  360. package/dist/project/intent-analyzer.js +1 -149
  361. package/dist/project/machine-nodes.js +1 -36
  362. package/dist/project/merchant-guide.d.ts +19 -0
  363. package/dist/project/merchant-guide.js +1 -264
  364. package/dist/project/migration.js +1 -125
  365. package/dist/project/mode-actions.js +1 -309
  366. package/dist/project/namespace.js +1 -206
  367. package/dist/project/participation-radar.js +1 -428
  368. package/dist/project/pipeline-actions.js +1 -109
  369. package/dist/project/project-store.js +1 -422
  370. package/dist/project/query.js +1 -153
  371. package/dist/project/reverse-mapping.d.ts +34 -0
  372. package/dist/project/reverse-mapping.js +1 -0
  373. package/dist/project/risk-aggregator.js +1 -295
  374. package/dist/project/rollback-policy.js +1 -290
  375. package/dist/project/semantic-assembler.js +1 -345
  376. package/dist/project/semantic-graph.d.ts +3 -5
  377. package/dist/project/semantic-graph.js +1 -292
  378. package/dist/project/stage-gate.js +1 -369
  379. package/dist/project/substep-trace.js +1 -332
  380. package/dist/project/task-tracker.js +1 -78
  381. package/dist/project/workflow-design-assessment.d.ts +24 -0
  382. package/dist/project/workflow-design-assessment.js +1 -0
  383. package/dist/role/derivation.d.ts +18 -0
  384. package/dist/role/derivation.js +1 -0
  385. package/dist/role/index.d.ts +5 -0
  386. package/dist/role/index.js +1 -0
  387. package/dist/role/model.d.ts +8 -0
  388. package/dist/role/model.js +1 -0
  389. package/dist/role/resolution.d.ts +11 -0
  390. package/dist/role/resolution.js +1 -0
  391. package/dist/role/types.d.ts +11 -0
  392. package/dist/role/types.js +1 -0
  393. package/dist/rules.js +1 -52
  394. package/dist/safety/confirm-gate.d.ts +1 -1
  395. package/dist/safety/confirm-gate.js +1 -88
  396. package/dist/safety/index.js +1 -3
  397. package/dist/safety/preview.js +1 -52
  398. package/dist/schema/call/allocation.d.ts +186 -1385
  399. package/dist/schema/call/allocation.js +1 -34
  400. package/dist/schema/call/arbitration.d.ts +272 -1871
  401. package/dist/schema/call/arbitration.js +1 -113
  402. package/dist/schema/call/base.d.ts +1831 -9076
  403. package/dist/schema/call/base.js +1 -370
  404. package/dist/schema/call/bridge.d.ts +911 -3171
  405. package/dist/schema/call/bridge.js +1 -458
  406. package/dist/schema/call/contact.d.ts +135 -931
  407. package/dist/schema/call/contact.js +1 -37
  408. package/dist/schema/call/demand.d.ts +164 -1194
  409. package/dist/schema/call/demand.js +1 -47
  410. package/dist/schema/call/guard.d.ts +298 -1140
  411. package/dist/schema/call/guard.js +1 -161
  412. package/dist/schema/call/handler.js +1 -322
  413. package/dist/schema/call/index.js +1 -20
  414. package/dist/schema/call/machine.d.ts +459 -5403
  415. package/dist/schema/call/machine.js +1 -193
  416. package/dist/schema/call/order.d.ts +137 -844
  417. package/dist/schema/call/order.js +1 -35
  418. package/dist/schema/call/payment.d.ts +74 -561
  419. package/dist/schema/call/payment.js +1 -37
  420. package/dist/schema/call/permission-handler.js +1 -54
  421. package/dist/schema/call/permission.d.ts +335 -2791
  422. package/dist/schema/call/permission.js +1 -105
  423. package/dist/schema/call/personal.d.ts +227 -1814
  424. package/dist/schema/call/personal.js +1 -78
  425. package/dist/schema/call/progress.d.ts +140 -843
  426. package/dist/schema/call/progress.js +1 -47
  427. package/dist/schema/call/proof.d.ts +42 -258
  428. package/dist/schema/call/proof.js +1 -33
  429. package/dist/schema/call/repository.d.ts +324 -2222
  430. package/dist/schema/call/repository.js +1 -77
  431. package/dist/schema/call/reward.d.ts +153 -1183
  432. package/dist/schema/call/reward.js +1 -30
  433. package/dist/schema/call/semantic.js +1 -1679
  434. package/dist/schema/call/service.d.ts +376 -3431
  435. package/dist/schema/call/service.js +1 -184
  436. package/dist/schema/call/treasury.d.ts +252 -2158
  437. package/dist/schema/call/treasury.js +1 -71
  438. package/dist/schema/common/index.d.ts +222 -697
  439. package/dist/schema/common/index.js +1 -407
  440. package/dist/schema/config/index.d.ts +18 -161
  441. package/dist/schema/config/index.js +1 -68
  442. package/dist/schema/employee/index.d.ts +99 -0
  443. package/dist/schema/employee/index.js +1 -0
  444. package/dist/schema/evaluation/index.d.ts +1062 -3748
  445. package/dist/schema/evaluation/index.js +1 -356
  446. package/dist/schema/index.d.ts +3 -0
  447. package/dist/schema/index.js +1 -17
  448. package/dist/schema/industry-pack/index.d.ts +132 -0
  449. package/dist/schema/industry-pack/index.js +1 -0
  450. package/dist/schema/intent-radar/index.d.ts +92 -245
  451. package/dist/schema/intent-radar/index.js +1 -89
  452. package/dist/schema/local/index.d.ts +2045 -18080
  453. package/dist/schema/local/index.js +1 -927
  454. package/dist/schema/local/wip.d.ts +61 -651
  455. package/dist/schema/local/wip.js +1 -187
  456. package/dist/schema/messenger/index.d.ts +949 -5557
  457. package/dist/schema/messenger/index.js +1 -475
  458. package/dist/schema/operations.d.ts +2969 -26518
  459. package/dist/schema/operations.js +1 -520
  460. package/dist/schema/persona/index.d.ts +469 -1820
  461. package/dist/schema/persona/index.js +1 -148
  462. package/dist/schema/project/index.d.ts +1027 -8408
  463. package/dist/schema/project/index.js +1 -2057
  464. package/dist/schema/query/index.d.ts +12041 -75261
  465. package/dist/schema/query/index.js +1 -1646
  466. package/dist/schema/schema-query/index.d.ts +35 -98
  467. package/dist/schema/schema-query/index.js +1 -104
  468. package/dist/schema/schema-version.js +1 -76
  469. package/dist/schema/task-status.d.ts +26 -132
  470. package/dist/schema/task-status.js +1 -36
  471. package/dist/schema/trust/index.d.ts +194 -1290
  472. package/dist/schema/trust/index.js +1 -314
  473. package/dist/schema/utils/guard-parser.js +1 -419
  474. package/dist/schema/utils/guard-query-utils.js +1 -46
  475. package/dist/schema/utils/node-parser.js +1 -369
  476. package/dist/schema/utils/object-type-utils.js +1 -35
  477. package/dist/schema/utils/permission-index-utils.js +1 -7
  478. package/dist/schema/utils/permission-machine-check.js +1 -121
  479. package/dist/schema/utils/skills-recommendation.d.ts +1 -0
  480. package/dist/schema/utils/skills-recommendation.js +1 -77
  481. package/dist/schema/workspace/index.d.ts +69 -0
  482. package/dist/schema/workspace/index.js +1 -0
  483. package/dist/schema-query-impl/index.js +1 -0
  484. package/dist/schemas/account_operation.output.json +3147 -1652
  485. package/dist/schemas/account_operation.schema.json +225 -218
  486. package/dist/schemas/bridge_operation.output.json +1168 -650
  487. package/dist/schemas/bridge_operation.schema.json +736 -504
  488. package/dist/schemas/config_operation.output.json +185 -179
  489. package/dist/schemas/config_operation.schema.json +21 -26
  490. package/dist/schemas/employee_operation.output.json +207 -0
  491. package/dist/schemas/employee_operation.schema.json +176 -0
  492. package/dist/schemas/evaluation_operation.output.json +2329 -557
  493. package/dist/schemas/evaluation_operation.schema.json +2939 -720
  494. package/dist/schemas/guard2file.output.json +58 -64
  495. package/dist/schemas/guard2file.schema.json +79 -81
  496. package/dist/schemas/index.json +29 -11
  497. package/dist/schemas/industry_pack_operation.output.json +594 -0
  498. package/dist/schemas/industry_pack_operation.schema.json +55 -0
  499. package/dist/schemas/intent_radar.output.json +275 -200
  500. package/dist/schemas/intent_radar.schema.json +124 -123
  501. package/dist/schemas/local_info_operation.output.json +1174 -657
  502. package/dist/schemas/local_info_operation.schema.json +119 -125
  503. package/dist/schemas/local_mark_operation.output.json +1239 -689
  504. package/dist/schemas/local_mark_operation.schema.json +91 -96
  505. package/dist/schemas/machineNode2file.output.json +63 -69
  506. package/dist/schemas/machineNode2file.schema.json +79 -81
  507. package/dist/schemas/messenger_operation.output.json +2722 -1528
  508. package/dist/schemas/messenger_operation.schema.json +1482 -1264
  509. package/dist/schemas/onchain_events.output.json +2590 -975
  510. package/dist/schemas/onchain_events.schema.json +117 -99
  511. package/dist/schemas/onchain_operations.output.json +3957 -2309
  512. package/dist/schemas/onchain_operations.schema.json +20799 -9285
  513. package/dist/schemas/onchain_operations_allocation.schema.json +172 -108
  514. package/dist/schemas/onchain_operations_arbitration.schema.json +233 -146
  515. package/dist/schemas/onchain_operations_contact.schema.json +129 -90
  516. package/dist/schemas/onchain_operations_demand.schema.json +170 -112
  517. package/dist/schemas/onchain_operations_gen_passport.schema.json +61 -646
  518. package/dist/schemas/onchain_operations_gen_proof.schema.json +40 -172
  519. package/dist/schemas/onchain_operations_guard.schema.json +3765 -294
  520. package/dist/schemas/onchain_operations_machine.schema.json +537 -164
  521. package/dist/schemas/onchain_operations_order.schema.json +126 -96
  522. package/dist/schemas/onchain_operations_payment.schema.json +82 -67
  523. package/dist/schemas/onchain_operations_permission.schema.json +331 -93
  524. package/dist/schemas/onchain_operations_personal.schema.json +636 -96
  525. package/dist/schemas/onchain_operations_progress.schema.json +125 -92
  526. package/dist/schemas/onchain_operations_proof.schema.json +76 -69
  527. package/dist/schemas/onchain_operations_repository.schema.json +636 -249
  528. package/dist/schemas/onchain_operations_reward.schema.json +218 -108
  529. package/dist/schemas/onchain_operations_service.schema.json +679 -221
  530. package/dist/schemas/onchain_operations_treasury.schema.json +401 -135
  531. package/dist/schemas/onchain_table_data.output.json +6018 -2430
  532. package/dist/schemas/onchain_table_data.schema.json +544 -430
  533. package/dist/schemas/persona_operation.output.json +1568 -265
  534. package/dist/schemas/persona_operation.schema.json +346 -202
  535. package/dist/schemas/project_operation.output.json +6957 -5147
  536. package/dist/schemas/project_operation.schema.json +1050 -1020
  537. package/dist/schemas/query_task_status.output.json +195 -99
  538. package/dist/schemas/query_task_status.schema.json +12 -18
  539. package/dist/schemas/query_toolkit.output.json +18870 -14566
  540. package/dist/schemas/query_toolkit.schema.json +614 -522
  541. package/dist/schemas/schema_query.output.json +127 -129
  542. package/dist/schemas/schema_query.schema.json +64 -69
  543. package/dist/schemas/trust_score.output.json +678 -587
  544. package/dist/schemas/trust_score.schema.json +289 -277
  545. package/dist/schemas/wip_file.output.json +116 -124
  546. package/dist/schemas/wip_file.schema.json +142 -143
  547. package/dist/schemas/workspace_operation.output.json +277 -0
  548. package/dist/schemas/workspace_operation.schema.json +45 -0
  549. package/dist/schemas/wowok_buildin_info.output.json +1693 -723
  550. package/dist/schemas/wowok_buildin_info.schema.json +576 -512
  551. package/dist/telemetry/index.js +1 -112
  552. package/dist/telemetry/redact.js +1 -23
  553. package/dist/telemetry/storage.js +1 -80
  554. package/dist/tools/handlers/bridge.d.ts +8 -1
  555. package/dist/tools/handlers/bridge.js +1 -1
  556. package/dist/tools/handlers/config.js +1 -74
  557. package/dist/tools/handlers/employee.d.ts +2 -0
  558. package/dist/tools/handlers/employee.js +1 -0
  559. package/dist/tools/handlers/evaluation.js +1 -123
  560. package/dist/tools/handlers/file-export.js +1 -90
  561. package/dist/tools/handlers/industry-pack.d.ts +2 -0
  562. package/dist/tools/handlers/industry-pack.js +1 -0
  563. package/dist/tools/handlers/intent-radar.js +1 -76
  564. package/dist/tools/handlers/local.js +1 -53
  565. package/dist/tools/handlers/messenger.js +1 -188
  566. package/dist/tools/handlers/onchain.js +1 -1180
  567. package/dist/tools/handlers/persona.js +1 -89
  568. package/dist/tools/handlers/project.js +1 -211
  569. package/dist/tools/handlers/query.js +1 -434
  570. package/dist/tools/handlers/schema-query.js +1 -176
  571. package/dist/tools/handlers/task-status.js +1 -26
  572. package/dist/tools/handlers/trust.js +1 -380
  573. package/dist/tools/handlers/wip.js +1 -90
  574. package/dist/tools/handlers/workspace.d.ts +2 -0
  575. package/dist/tools/handlers/workspace.js +1 -0
  576. package/dist/tools/index.d.ts +2 -1
  577. package/dist/tools/index.js +1 -1382
  578. package/dist/tools/retry.js +1 -85
  579. package/dist/tools/rules-hook.d.ts +1 -1
  580. package/dist/tools/rules-hook.js +1 -23
  581. package/dist/tools/shared.d.ts +1 -1
  582. package/dist/tools/shared.js +1 -130
  583. package/dist/tools/types.d.ts +2 -1
  584. package/dist/tools/types.js +1 -1
  585. package/dist/tools/upgrade-check.d.ts +19 -0
  586. package/dist/tools/upgrade-check.js +1 -0
  587. package/dist/tools/wip-deploy-assist.js +1 -306
  588. package/dist/tools/wrap.js +1 -500
  589. package/package.json +7 -6
  590. package/dist/knowledge/arbitration-trust.d.ts +0 -24
  591. package/dist/knowledge/arbitration-trust.js +0 -117
  592. package/dist/schema/call/bridge-handler.d.ts +0 -8
  593. package/dist/schema/call/bridge-handler.js +0 -265
  594. package/dist/schema/sync-layer4.d.ts +0 -21
  595. package/dist/schema/sync-layer4.js +0 -286
  596. package/dist/schema-query/index.js +0 -810
  597. /package/dist/{schema-query → schema-query-impl}/index.d.ts +0 -0
@@ -1,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';import{getEvaluationEngine}from'../evaluation/engine.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;}export function extractProjectEvaluationFacts(a){const {project:b,objects:c,edges:d,objectCache:f,reputation:g}=a,h=groupByType(c),i=buildBindingIndex(d),j=h['get']('Service')??[],k=j[0x0],l=k?parseCacheData(f['get'](k['objectAddress'])):null,m=k?getBalanceValue(l,'compensation_fund'):0x0,n=getMaxSalePrice(l),p=h['get']('Treasury')??[],q=h['get']('Allocation')??[],r=h['get']('Permission')??[],s=h['get']('Machine')??[],t=h['get']('Arbitration')??[],u=h['get']('Repository')??[],v=h['get']('Contact')??[],w=h['get']('Guard')??[],x=h['get']('Proof')??[],y=h['get']('Demand')??[],z=new Set();for(const I of c){if(I['objectAddress'])z['add'](I['objectAddress']);if(I['objectName']){z['add'](I['objectName']);const J=shortTypeName(I['objectType'])['toLowerCase']();z['add'](J+':'+I['objectName']);}}let A=0x0;for(const K of d){if(K['edgeSource']==='potential')continue;if(!z['has'](K['targetObject']))A++;}const B=new Map();for(const L of c){if(L['objectAddress'])B['set'](L['objectAddress'],shortTypeName(L['objectType']));}const C=detectCircularRefs(d,B),D=k?i['get'](k['objectAddress']+'#order_allocators')?.['size']??0x0:0x0,E=q['length']>0x0&&D>0x0;let F=!![],G=0x5;if(b['industry']&&b['industry']!=='general')try{const M=IndustryModeRegistry['Instance']()['getMode'](b['industry']);M&&(F=M['risk_constraints']?.['require_compensation_fund']??!![],M['risk_constraints']?.['compensation_fund_coverage_ratio']&&(G=M['risk_constraints']['compensation_fund_coverage_ratio']));}catch{}const H=new Map();for(const N of r){const O=parseCacheData(f['get'](N['objectAddress']));O&&H['set'](N['objectAddress'],{'address':N['objectAddress'],'entity_count':typeof O['entity_count']==='number'?O['entity_count']:undefined,'perm_remark':Array['isArray'](O['perm_remark'])?O['perm_remark']:undefined,'owner':typeof O['owner']==='string'?O['owner']:typeof O['builder']==='string'?O['builder']:undefined,'admin':Array['isArray'](O['admin'])?O['admin']:undefined});}return{'input':a,'project':b,'objects':c,'edges':d,'byType':h,'bindingIndex':i,'objectCache':f,'reputation':g,'serviceObj':k,'serviceData':l,'compensationBalance':m,'maxSalePrice':n,'treasuries':p,'allocations':q,'permissions':r,'machines':s,'arbitrations':t,'repositories':u,'contacts':v,'guards':w,'proofs':x,'demands':y,'danglingCount':A,'cycles':C,'hasAllocationEscrow':E,'orderAllocatorsBinding':D,'industryRequiresFund':F,'coverageRatio':G,'permDataMap':H};}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=[],e=extractProjectEvaluationFacts(a),{objects:f,edges:g,objectCache:h,project:i}=e,j=e['bindingIndex'];let k=0x64;const l=e['serviceObj'],m=e['compensationBalance'];if(l)for(const O of CRITICAL_BINDINGS){if(O['sourceType']!=='Service')continue;const P=O['fieldName']==='arbitrations'?m>0x0?!![]:O['critical']:O['critical'],Q=l['objectAddress']+'#'+O['fieldName'],R=j['get'](Q);if(!R||R['size']===0x0){const S=P?-0x19:-0xa;k+=S,b['push']({'criterion':'structural_risk','severity':P?'critical':'warning','message':'Service\x20missing\x20'+O['fieldName']+'\x20binding\x20(expected\x20'+O['targetType']+')'+(O['fieldName']==='arbitrations'?m>0x0?'\x20—\x20required\x20by\x20contract\x20when\x20compensation_fund\x20>\x200\x20(service.move:494)':'\x20—\x20optional\x20when\x20compensation_fund\x20is\x200':''),'deduction':S});}else d['push']('Service\x20has\x20'+O['fieldName']+'\x20binding');}else k=0x1e,b['push']({'criterion':'structural_risk','severity':'critical','message':'No\x20Service\x20object\x20in\x20project\x20—\x20project\x20has\x20no\x20core','deduction':-0x46});k=clampScore(k);let n=0x64;const o=e['treasuries'],p=e['allocations'],q=e['serviceData'],r=e['compensationBalance'],s=e['orderAllocatorsBinding'],t=e['hasAllocationEscrow'],w=e['industryRequiresFund'];if(o['length']===0x0&&r===0x0){if(t)n-=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('+p['length']+'\x20Allocation\x20object(s)\x20+\x20order_allocators\x20bound)\x20—\x20fund\x20safety\x20via\x20Guard\x20verification,\x20no\x20Treasury/compensation_fund\x20needed','deduction':-0x5});else w?(n-=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})):(n-=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{o['length']>0x0&&d['push'](o['length']+'\x20Treasury\x20object(s)\x20present\x20—\x20independent\x20fund\x20holder');if(r>0x0){d['push']('Service.compensation_fund\x20has\x20'+r+'\x20units\x20—\x20inline\x20refund\x20fund\x20active');const T=e['maxSalePrice'];if(T>0x0){const U=e['coverageRatio'],V=U*T;r<V?(n-=0xa,b['push']({'criterion':'fund_safety','severity':'warning','message':'Service.compensation_fund\x20balance\x20('+r+')\x20is\x20less\x20than\x20'+U+'×\x20the\x20max\x20order\x20amount\x20('+T+'\x20→\x20threshold\x20'+V+').\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'+U+'×)','deduction':-0xa})):b['push']({'criterion':'fund_safety','severity':'info','message':'Service.compensation_fund\x20balance\x20('+r+')\x20covers\x20'+U+'×\x20the\x20max\x20order\x20amount\x20('+T+').\x20Fund\x20is\x20sufficient\x20for\x20refund\x20protection.\x20(industry:\x20'+(i['industry']??'general')+',\x20ratio:\x20'+U+'×)','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});}n=clampScore(n);let x=0x64;if(l){const W=e['serviceData'];if(W){const X=W['bPaused'],Y=W['bPublished'];Y&&X&&(x-=0x19,b['push']({'criterion':'operational_risk','severity':'warning','message':'Service\x20is\x20published\x20but\x20PAUSED\x20—\x20operations\x20halted','deduction':-0x19})),!Y&&(x-=0xf,b['push']({'criterion':'operational_risk','severity':'info','message':'Service\x20not\x20yet\x20published\x20—\x20project\x20not\x20live','deduction':-0xf}));}}const y=e['arbitrations'];y['length']===0x0?(x-=0x14,b['push']({'criterion':'operational_risk','severity':'warning','message':'No\x20Arbitration\x20object\x20—\x20disputes\x20cannot\x20be\x20resolved','deduction':-0x14})):d['push'](y['length']+'\x20Arbitration\x20object(s)\x20configured');x=clampScore(x);let z=0x64;const A=e['permissions'];A['length']===0x0&&(z-=0x28,b['push']({'criterion':'governance_risk','severity':'critical','message':'No\x20Permission\x20object\x20—\x20project\x20is\x20ungoverned','deduction':-0x28}));if(l){const Z=e['serviceData'];Z&&!isAddress(Z['um'])&&(z-=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 B=e['machines'];for(const a0 of B){const a1=a0['metadata'],a2=a1?.['config'];if(a2?.['entry_node_forward_hint']){const a6=a2['entry_node_forward_hint'],a7=a6['example_forward'];a7?.['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 a3=a2?.['guard_objects'];a3&&a3['length']>0x0&&d['push']('Machine\x20has\x20'+a3['length']+'\x20guard\x20object\x20reference(s)\x20—\x20'+'forward-level\x20permission\x20validation\x20configured');const a4=parseCacheData(h['get'](a0['objectAddress'])),a5=getMachineNodeCount(a4);a5>0x0&&!a2&&b['push']({'criterion':'governance_risk','severity':'info','message':'Machine\x20has\x20'+a5+'\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 C=e['machines'],D=e['permissions'],E=e['permDataMap'];for(const a8 of C){const a9=a8['objectAddress']+'#permission',aa=j['get'](a9);if(!aa||aa['size']===0x0)continue;let ab=null;for(const ah of aa){ab=ah;break;}if(!ab)continue;const ac=E['get'](ab);if(!ac)continue;const ad=parseCacheData(h['get'](a8['objectAddress']));if(!ad)continue;const ae=extractMachineNodesFromCache(ad);if(ae['length']===0x0)continue;const af=collectPermissionIndexes(ae);if(af['requiredIndexes']['length']===0x0)continue;const ag=checkPermissionAuthorization(af['requiredIndexes'],ac);!ag['allAuthorized']?(z-=0x19,b['push']({'criterion':'governance_risk','severity':'critical','message':'Machine\x20'+a8['objectAddress']['slice'](0x0,0x8)+'\x20has\x20forwards\x20referencing\x20'+('un-authorized\x20permission\x20indexes:\x20['+ag['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'+a8['objectAddress']['slice'](0x0,0x8)+':\x20all\x20'+af['requiredIndexes']['length']+'\x20'+'permission\x20index(es)\x20are\x20authorized');}if(l&&y['length']>0x0){const ai=l['objectAddress']+'#permission',aj=j['get'](ai),ak=aj&&aj['size']>0x0?Array['from'](aj)[0x0]:null,al=ak?E['get'](ak):null;for(const am of y){const an=am['objectAddress']+'#permission',ao=j['get'](an),ap=ao&&ao['size']>0x0?Array['from'](ao)[0x0]:null;if(!ak||!ap)continue;if(ak===ap){z-=0x1e,b['push']({'criterion':'governance_risk','severity':'critical','message':'Arbitration\x20'+am['objectAddress']['slice'](0x0,0x8)+'\x20and\x20Service\x20share\x20the\x20SAME\x20'+('Permission\x20object\x20('+ak['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 aq=E['get'](ap);if(al&&aq){const ar=al['owner']?.['toLowerCase'](),as=aq['owner']?.['toLowerCase'](),at=new Set((al['admin']??[])['map'](ax=>ax['toLowerCase']())),au=new Set((aq['admin']??[])['map'](ax=>ax['toLowerCase']())),av=ar&&as&&ar===as,aw=[...at]['some'](ax=>au['has'](ax));if(av||aw){const ax=av&&aw?'owner\x20AND\x20admin\x20overlap':av?'same\x20owner':'admin\x20overlap';z-=0x14,b['push']({'criterion':'governance_risk','severity':'warning','message':'Arbitration\x20'+am['objectAddress']['slice'](0x0,0x8)+'\x20and\x20Service\x20have\x20'+('overlapping\x20Permission\x20control\x20('+ax+').\x20Even\x20with\x20separate\x20')+'Permission\x20objects,\x20shared\x20control\x20undermines\x20dispute\x20independence.\x20'+'The\x20contract\x20only\x20enforces\x20different\x20Permission\x20object\x20addresses\x20'+'(E_ARBITRATION_PERMISSION_CONFLICT)\x20—\x20it\x20does\x20NOT\x20check\x20who\x20controls\x20'+'each\x20Permission,\x20so\x20this\x20governance\x20risk\x20exists\x20on\x20ANY\x20network.\x20'+'Use\x20a\x20completely\x20independent\x20third-party\x20Permission\x20(different\x20owner\x20'+'and\x20admin\x20list)\x20for\x20Arbitration.','deduction':-0x14});}else d['push']('Arbitration\x20'+am['objectAddress']['slice'](0x0,0x8)+'\x20has\x20independent\x20'+'Permission\x20(separate\x20owner/admin)\x20—\x20trustworthy\x20dispute\x20resolution');}}}z=clampScore(z);let F=0x64;const G=e['danglingCount'],H=e['cycles'];if(G>0x0){const ay=-Math['min'](0x14,G*0x3);F+=ay,b['push']({'criterion':'graph_coherence','severity':G>=0x3?'warning':'info','message':G+'\x20edge(s)\x20point\x20to\x20objects\x20outside\x20the\x20project\x20—\x20dangling\x20references','deduction':ay});}H['length']>0x0&&(F-=0xf,b['push']({'criterion':'graph_coherence','severity':'warning','message':H['length']+'\x20circular\x20reference(s)\x20detected:\x20'+H['slice'](0x0,0x2)['join'](';\x20')+(H['length']>0x2?'...':''),'deduction':-0xf}));G===0x0&&H['length']===0x0&&d['push']('Graph\x20is\x20coherent\x20—\x20no\x20dangling\x20refs\x20or\x20cycles');F=clampScore(F);let I=0x64,J='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 az=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}),aA=az['unmet_conditions']['some'](aB=>aB['includes']('not\x20found'));if(aA)I=0x32,J='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 aB of az['violated_constraints']){I-=0x19,b['push']({'criterion':'mode_registry','severity':'critical','message':'Mode\x20\x27'+i['industry']+'\x27\x20hard\x20constraint\x20violated:\x20'+aB,'deduction':-0x19});}for(const aC of az['capability_conflicts']){I-=0x14,b['push']({'criterion':'mode_registry','severity':'critical','message':'Mode\x20\x27'+i['industry']+'\x27\x20capability\x20conflict:\x20'+aC,'deduction':-0x14});}for(const aD of az['unmet_conditions']){I-=0xa,b['push']({'criterion':'mode_registry','severity':'warning','message':'Mode\x20\x27'+i['industry']+'\x27\x20soft\x20constraint\x20unmet:\x20'+aD,'deduction':-0xa});}I=clampScore(I),J='metric\x20risk\x20'+az['risk_score']+'\x20/\x20benefit\x20'+az['benefit_score']+'\x20'+('(ratio\x20'+az['risk_benefit_ratio']['toFixed'](0x2)+');\x20')+(az['violated_constraints']['length']+'\x20hard\x20+\x20'+az['unmet_conditions']['length']+'\x20soft\x20constraint\x20issue(s),\x20')+(az['capability_conflicts']['length']+'\x20capability\x20conflict(s)'),az['applicable']&&az['violated_constraints']['length']===0x0&&az['capability_conflicts']['length']===0x0&&az['unmet_conditions']['length']===0x0&&d['push']('Mode\x20\x27'+i['industry']+'\x27\x20passes\x20all\x20mode-registry\x20gates\x20—\x20'+('metric\x20risk\x20'+az['risk_score']+'\x20/\x20benefit\x20'+az['benefit_score']+'\x20')+('(risk-benefit\x20ratio\x20'+az['risk_benefit_ratio']['toFixed'](0x2)+')'));}}catch{J='mode\x20registry\x20unavailable\x20—\x20check\x20skipped';}I=clampScore(I);const {criterionScores:K,overall:L}=finalizeCriterionScores([{'name':'structural_risk','score':k,'weight':RISK_WEIGHTS['structural_risk'],'rationale':CRITICAL_BINDINGS['filter'](aE=>aE['sourceType']==='Service')['length']+'\x20expected\x20Service\x20bindings\x20checked'},{'name':'fund_safety','score':n,'weight':RISK_WEIGHTS['fund_safety'],'rationale':'Treasury\x20+\x20compensation_fund\x20coverage'},{'name':'operational_risk','score':x,'weight':RISK_WEIGHTS['operational_risk'],'rationale':'Service\x20state\x20+\x20arbitration\x20coverage'},{'name':'governance_risk','score':z,'weight':RISK_WEIGHTS['governance_risk'],'rationale':'Permission\x20+\x20UM\x20presence'},{'name':'graph_coherence','score':F,'weight':RISK_WEIGHTS['graph_coherence'],'rationale':G+'\x20dangling\x20+\x20'+H['length']+'\x20circular\x20refs'},{'name':'mode_registry','score':I,'weight':RISK_WEIGHTS['mode_registry'],'rationale':J}],i['perspective']),M=b['filter'](aE=>aE['severity']==='critical')['length'],N=M>0x0?'HIGH\x20RISK:\x20'+M+'\x20critical\x20issue(s).\x20'+b['length']+'\x20total\x20findings.':'Moderate\x20risk:\x20'+b['length']+'\x20finding(s),\x20no\x20critical\x20issues.';return{'evaluationType':'risk','score':L,'summary':N,'criterionScores':K,'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 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 runEvaluationInternal(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'value':return evaluateValueStub(d,c);default:throw new Error('Unknown\x20evaluation\x20type:\x20'+b);}}const PROJECT_EVALUATION_TYPES=['risk','trust','completeness','worth_buying','value'];function makeProjectRule(a){return{'id':'project_'+a,'description':'Project-level\x20'+a+'\x20evaluation\x20(rule-based\x20or\x20LLM-assisted)','dimension':a,'weight':0x1,'evaluation_ids':['project_'+a],'evaluate':b=>{const c=b['entities']['projectEvaluation'],d=b['entities']['llmPrompt'],e=runEvaluationInternal(c,a,d);return b['facts']['criterionScores']=e['criterionScores'],b['facts']['findings']=e['findings'],b['facts']['strengths']=e['strengths'],b['facts']['needsLlm']=e['needsLlm'],b['facts']['llmPrompt']=e['llmPrompt'],{'score':e['score'],'weight':0x1,'reason':e['summary'],'red_flag':e['findings']?.['some'](g=>g['severity']==='critical')??![]};}};}const RISK_CRITERIA=['structural_risk','fund_safety','operational_risk','governance_risk','graph_coherence','mode_registry'],TRUST_CRITERIA=['reputation','arbitration_coverage','guard_quality','transparency','consumer_diligence'],COMPLETENESS_CRITERIA=['object_coverage','binding_completeness','workflow_rationality','deployment_readiness'];function registerRuleBasedProjectEvaluation(a,b,c,d){const e='__project_'+b+'_result';a['registerDataSource']({'id':'project_'+b+'_facts','description':'Extract\x20project\x20facts\x20+\x20run\x20the\x20'+b+'\x20criterion\x20computer\x20(perspective\x20via\x20UserInjection)','evaluation_ids':['project_'+b],'extract':f=>{const g=f['entities']['projectEvaluation'],h=f['injection']?.['preferences']?.['perspective'],i=h&&h!==g['project']['perspective']?{...g,'project':{...g['project'],'perspective':h}}:g,j=d(i);return f['facts'][e]=j,f['facts']['criterionScores']=j['criterionScores'],f['facts']['findings']=j['findings'],f['facts']['strengths']=j['strengths'],f['facts']['needsLlm']=j['needsLlm'],{};}});for(const f of c){a['registerRule']({'id':'project_'+b+'_'+f,'description':'Project\x20'+b+'\x20criterion:\x20'+f,'dimension':b,'weight':0x1,'evaluation_ids':['project_'+b],'evaluate':g=>{const h=g['facts'][e];if(!h)return null;const i=h['criterionScores']['find'](j=>j['name']===f);if(!i)return null;return{'score':i['score'],'weight':i['weight'],'reason':i['rationale']};}});}}function registerWorthBuyingEvaluation(a){a['registerDataSource']({'id':'project_worth_buying_facts','description':'Run\x20risk/trust/completeness\x20via\x20the\x20kernel\x20+\x20D16-D24\x20enrichment\x20+\x20build\x20LLM\x20prompt','evaluation_ids':['project_worth_buying'],'extract':async b=>{const c=b['entities']['projectEvaluation'],d=b['entities']['llmPrompt'],e={'projectEvaluation':c},[f,g,h]=await Promise['all']([a['evaluate']('project_risk',e,b['injection']),a['evaluate']('project_trust',e,b['injection']),a['evaluate']('project_completeness',e,b['injection'])]),i=[evaluateEscrowQuality(c),evaluateProofIntegrity(c),evaluateArbitrationFairness(c),evaluateFeeTransparency(c),evaluateTimeoutProtection(c),evaluateSupplierVisibility(c),evaluateContentCommitment(c),evaluateReputationVerifiability(c),evaluatePermissionSafety(c)],j=i['map'](m=>m['name']+':\x20'+m['score']+'/100\x20—\x20'+m['rationale'])['join']('\x0a'),k=['===\x20RULE-BASED\x20EVALUATION\x20SUMMARY\x20(F-08\x20enriched\x20context)\x20===','','Risk:\x20'+f['total']+'/100\x20—\x20'+f['summary'],...(f['findings']??[])['slice'](0x0,0x3)['map'](m=>'\x20\x20-\x20['+m['severity']+']\x20'+m['message']),'','Trust:\x20'+g['total']+'/100\x20—\x20'+g['summary'],...(g['findings']??[])['slice'](0x0,0x3)['map'](m=>'\x20\x20-\x20['+m['severity']+']\x20'+m['message']),'','Completeness:\x20'+h['total']+'/100\x20—\x20'+h['summary'],...(h['findings']??[])['slice'](0x0,0x3)['map'](m=>'\x20\x20-\x20['+m['severity']+']\x20'+m['message']),'','===\x20EXTENDED\x20DIMENSIONS\x20D16-D24\x20(GLM6/93)\x20===',j,'','===\x20END\x20RULE-BASED\x20SUMMARY\x20===',''],l=k['join']('\x0a');return b['facts']['needsLlm']=!![],b['facts']['llmPrompt']=d?d+'\x0a\x0a'+l:l+'\x0aInstruction:\x20Based\x20on\x20the\x20rule-based\x20summary\x20above,\x20evaluate\x20whether\x20this\x20project\x20is\x20worth\x20buying.\x20Return\x20a\x200-100\x20score\x20and\x20a\x20brief\x20rationale.\x20Focus\x20on\x20buyer\x20risk\x20vs.\x20value\x20proposition.',b['facts']['summary']='Requires\x20LLM\x20evaluation\x20—\x20semantic\x20prompt\x20assembled\x20with\x20rule-based\x20context\x20(risk/trust/completeness\x20+\x20D16-D24\x20extended\x20dimensions).\x20Call\x20save_evaluation\x20with\x20the\x20LLM\x20result.',{};}});}export function registerProjectEvaluations(a=getEvaluationEngine()){registerRuleBasedProjectEvaluation(a,'risk',RISK_CRITERIA,evaluateRisk),registerRuleBasedProjectEvaluation(a,'trust',TRUST_CRITERIA,evaluateTrust),registerRuleBasedProjectEvaluation(a,'completeness',COMPLETENESS_CRITERIA,evaluateCompleteness),registerWorthBuyingEvaluation(a);for(const b of PROJECT_EVALUATION_TYPES){if(b==='risk'||b==='trust'||b==='completeness'||b==='worth_buying')continue;a['registerRule'](makeProjectRule(b));}}registerProjectEvaluations();export async function runEvaluation(a,b,c,d){const e=filterTemplateObjects(a),f=getEvaluationEngine(),g=await f['evaluate']('project_'+b,{'projectEvaluation':e,'llmPrompt':c},d);return{'evaluationType':b,'score':g['total'],'summary':g['summary'],'criterionScores':g['criterionScores']??[],'findings':g['findings']??[],'strengths':g['strengths']??[],'needsLlm':g['needsLlm']??![],'llmPrompt':g['llmPrompt'],'evaluatedAt':Date['now']()};}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};}