@wowok/agent-mcp 2.7.1 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.js +1 -397
  13. package/dist/customer/types.js +1 -13
  14. package/dist/customer/user-preferences.js +1 -460
  15. package/dist/evaluation/arbitration-game.d.ts +9 -2
  16. package/dist/evaluation/arbitration-game.js +1 -48
  17. package/dist/evaluation/builtins/demand-match.js +1 -153
  18. package/dist/evaluation/builtins/index.js +1 -10
  19. package/dist/evaluation/builtins/service-risk.js +1 -55
  20. package/dist/evaluation/capability.js +1 -13
  21. package/dist/evaluation/composer.js +1 -40
  22. package/dist/evaluation/engine.js +1 -175
  23. package/dist/evaluation/extract.js +1 -115
  24. package/dist/evaluation/game-strategy.d.ts +27 -0
  25. package/dist/evaluation/game-strategy.js +1 -0
  26. package/dist/evaluation/gap.js +1 -100
  27. package/dist/evaluation/index.d.ts +1 -0
  28. package/dist/evaluation/index.js +1 -11
  29. package/dist/evaluation/node-game.d.ts +31 -3
  30. package/dist/evaluation/node-game.js +1 -57
  31. package/dist/evaluation/region.js +1 -36
  32. package/dist/evaluation/types.d.ts +1 -0
  33. package/dist/evaluation/types.js +1 -1
  34. package/dist/evaluation/user-injection.js +1 -27
  35. package/dist/experience/experience-reuse.js +1 -103
  36. package/dist/experience/index.js +1 -5
  37. package/dist/experience/intent-distill.js +1 -83
  38. package/dist/experience/realtime-feedback.js +1 -94
  39. package/dist/experience/types.js +1 -1
  40. package/dist/experience/user-profile.js +1 -171
  41. package/dist/extensions/business-modules.js +1 -287
  42. package/dist/extensions/capability-manifest.js +1 -781
  43. package/dist/extensions/constraint-registry.js +1 -198
  44. package/dist/extensions/index.js +1 -6
  45. package/dist/extensions/metric-registry.js +1 -257
  46. package/dist/extensions/mode-evaluator.js +1 -170
  47. package/dist/extensions/modes.js +1 -499
  48. package/dist/extensions/registry.js +1 -717
  49. package/dist/extensions/types.js +1 -1
  50. package/dist/harness/auto-escalation.js +1 -68
  51. package/dist/harness/checkpoint.js +1 -129
  52. package/dist/harness/index.js +1 -78
  53. package/dist/harness/plan.js +1 -315
  54. package/dist/harness/recover.js +1 -139
  55. package/dist/harness/types.js +1 -1
  56. package/dist/harness/verify.js +1 -237
  57. package/dist/index.js +1 -273
  58. package/dist/intent/enrich.js +1 -67
  59. package/dist/intent/index.js +1 -60
  60. package/dist/intent/matcher.js +1 -81
  61. package/dist/intent/store.js +1 -55
  62. package/dist/intent/types.js +1 -10
  63. package/dist/knowledge/acquisition-flywheel.js +1 -192
  64. package/dist/knowledge/allocation-confirm.js +1 -534
  65. package/dist/knowledge/allocation-context.js +1 -249
  66. package/dist/knowledge/allocation-ledger.js +1 -463
  67. package/dist/knowledge/allocation-puzzle.js +1 -298
  68. package/dist/knowledge/allocation-risk.js +1 -568
  69. package/dist/knowledge/allocation-templates.js +1 -970
  70. package/dist/knowledge/allocation-translation.js +1 -585
  71. package/dist/knowledge/arb-risk.js +1 -210
  72. package/dist/knowledge/arbitration-confirm.js +1 -559
  73. package/dist/knowledge/arbitration-context.js +1 -505
  74. package/dist/knowledge/arbitration-ledger.js +1 -521
  75. package/dist/knowledge/arbitration-puzzle.js +1 -304
  76. package/dist/knowledge/arbitration-risk.js +1 -423
  77. package/dist/knowledge/arbitration-templates.js +1 -276
  78. package/dist/knowledge/arbitration-translation.js +1 -487
  79. package/dist/knowledge/arbitration-trust.js +1 -117
  80. package/dist/knowledge/audit-rules.js +1 -141
  81. package/dist/knowledge/bridge-risk.js +1 -263
  82. package/dist/knowledge/contact-risk.js +1 -200
  83. package/dist/knowledge/contact-templates.js +1 -60
  84. package/dist/knowledge/demand-confirm.js +1 -206
  85. package/dist/knowledge/demand-matching.js +1 -132
  86. package/dist/knowledge/demand-risk.js +1 -240
  87. package/dist/knowledge/demand-translation.js +1 -354
  88. package/dist/knowledge/deployment-scanner.js +1 -823
  89. package/dist/knowledge/dynamic-pricing.js +1 -87
  90. package/dist/knowledge/examples-scanner-cli.js +1 -26
  91. package/dist/knowledge/examples-scanner.js +1 -843
  92. package/dist/knowledge/flywheel-loop.js +1 -404
  93. package/dist/knowledge/fund-layer.js +1 -973
  94. package/dist/knowledge/glossary.js +1 -211
  95. package/dist/knowledge/guard-confirm.js +1 -406
  96. package/dist/knowledge/guard-context.js +1 -287
  97. package/dist/knowledge/guard-design-patterns.js +1 -360
  98. package/dist/knowledge/guard-ledger.js +1 -260
  99. package/dist/knowledge/guard-lint.js +1 -670
  100. package/dist/knowledge/guard-migration.js +1 -228
  101. package/dist/knowledge/guard-puzzle.js +1 -805
  102. package/dist/knowledge/guard-render.js +1 -700
  103. package/dist/knowledge/guard-risk.js +1 -1879
  104. package/dist/knowledge/guard-submission-prompt.js +1 -171
  105. package/dist/knowledge/guard-templates.js +1 -1105
  106. package/dist/knowledge/guard-translation.js +1 -1119
  107. package/dist/knowledge/index.js +1 -436
  108. package/dist/knowledge/industry-evolution.js +1 -323
  109. package/dist/knowledge/industry-generalizer.js +1 -381
  110. package/dist/knowledge/industry-registry.js +1 -174
  111. package/dist/knowledge/intent-metrics.d.ts +4 -3
  112. package/dist/knowledge/intent-metrics.js +1 -566
  113. package/dist/knowledge/machine-confirm.js +1 -559
  114. package/dist/knowledge/machine-context.js +1 -833
  115. package/dist/knowledge/machine-ledger.js +1 -338
  116. package/dist/knowledge/machine-puzzle.js +1 -494
  117. package/dist/knowledge/machine-render.js +1 -565
  118. package/dist/knowledge/machine-risk.js +1 -669
  119. package/dist/knowledge/machine-templates.js +1 -1597
  120. package/dist/knowledge/machine-topology.js +1 -234
  121. package/dist/knowledge/machine-translation.js +1 -513
  122. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  123. package/dist/knowledge/mcp-schema-audit.js +1 -777
  124. package/dist/knowledge/onchain-constants.js +1 -35
  125. package/dist/knowledge/order-confirm.js +1 -573
  126. package/dist/knowledge/order-context.js +1 -390
  127. package/dist/knowledge/order-ledger.js +1 -341
  128. package/dist/knowledge/order-puzzle.js +1 -255
  129. package/dist/knowledge/order-risk.js +1 -653
  130. package/dist/knowledge/order-templates.js +1 -368
  131. package/dist/knowledge/order-translation.js +1 -550
  132. package/dist/knowledge/overrides-loader.js +1 -65
  133. package/dist/knowledge/passport-confirm.js +1 -531
  134. package/dist/knowledge/passport-context.js +1 -306
  135. package/dist/knowledge/passport-ledger.js +1 -282
  136. package/dist/knowledge/passport-puzzle.js +1 -333
  137. package/dist/knowledge/passport-risk.js +1 -450
  138. package/dist/knowledge/passport-templates.js +1 -568
  139. package/dist/knowledge/passport-translation.js +1 -516
  140. package/dist/knowledge/payment-risk.js +1 -249
  141. package/dist/knowledge/permission-confirm.js +1 -426
  142. package/dist/knowledge/permission-context.js +1 -224
  143. package/dist/knowledge/permission-ledger.js +1 -403
  144. package/dist/knowledge/permission-puzzle.js +1 -173
  145. package/dist/knowledge/permission-risk.js +1 -411
  146. package/dist/knowledge/permission-templates.js +1 -234
  147. package/dist/knowledge/permission-translation.js +1 -350
  148. package/dist/knowledge/personal-risk.js +1 -212
  149. package/dist/knowledge/process-model.js +1 -160
  150. package/dist/knowledge/progress-confirm.js +1 -456
  151. package/dist/knowledge/progress-context.js +1 -452
  152. package/dist/knowledge/progress-ledger.js +1 -330
  153. package/dist/knowledge/progress-puzzle.js +1 -219
  154. package/dist/knowledge/progress-risk.js +1 -461
  155. package/dist/knowledge/progress-templates.js +1 -228
  156. package/dist/knowledge/progress-translation.js +1 -405
  157. package/dist/knowledge/proof-confirm.js +1 -187
  158. package/dist/knowledge/proof-risk.js +1 -207
  159. package/dist/knowledge/proof-translation.js +1 -283
  160. package/dist/knowledge/registrar-risk.js +1 -217
  161. package/dist/knowledge/repository-confirm.js +1 -286
  162. package/dist/knowledge/repository-risk.js +1 -373
  163. package/dist/knowledge/repository-translation.js +1 -445
  164. package/dist/knowledge/reputation-rules.js +1 -99
  165. package/dist/knowledge/resource-risk.js +1 -157
  166. package/dist/knowledge/reward-confirm.js +1 -526
  167. package/dist/knowledge/reward-context.js +1 -504
  168. package/dist/knowledge/reward-ledger.js +1 -502
  169. package/dist/knowledge/reward-puzzle.js +1 -300
  170. package/dist/knowledge/reward-risk.js +1 -627
  171. package/dist/knowledge/reward-templates.js +1 -197
  172. package/dist/knowledge/reward-translation.js +1 -501
  173. package/dist/knowledge/safety-rules.js +1 -404
  174. package/dist/knowledge/scenario-modes.js +1 -321
  175. package/dist/knowledge/service-confirm.js +1 -807
  176. package/dist/knowledge/service-context.js +1 -403
  177. package/dist/knowledge/service-ledger.js +1 -609
  178. package/dist/knowledge/service-puzzle.js +1 -236
  179. package/dist/knowledge/service-risk.js +1 -651
  180. package/dist/knowledge/service-templates.js +1 -456
  181. package/dist/knowledge/service-translation.js +1 -622
  182. package/dist/knowledge/template-registry.js +1 -353
  183. package/dist/knowledge/tool-constraints.js +1 -195
  184. package/dist/knowledge/tools-reference.js +1 -178
  185. package/dist/knowledge/treasury-confirm.js +1 -512
  186. package/dist/knowledge/treasury-context.js +1 -363
  187. package/dist/knowledge/treasury-ledger.js +1 -300
  188. package/dist/knowledge/treasury-puzzle.js +1 -216
  189. package/dist/knowledge/treasury-risk.js +1 -440
  190. package/dist/knowledge/treasury-templates.js +1 -358
  191. package/dist/knowledge/treasury-translation.js +1 -498
  192. package/dist/knowledge/trust-metrics.js +1 -198
  193. package/dist/knowledge/util-risk.js +1 -135
  194. package/dist/loop-engineering/aggregate.js +1 -132
  195. package/dist/loop-engineering/context-collect.js +1 -83
  196. package/dist/loop-engineering/diagnose.js +1 -273
  197. package/dist/loop-engineering/improve.js +1 -405
  198. package/dist/loop-engineering/index.js +1 -4
  199. package/dist/loop-engineering/pipeline.js +1 -56
  200. package/dist/mode-market/index.js +1 -3
  201. package/dist/mode-market/registry.js +1 -124
  202. package/dist/mode-market/review.js +1 -214
  203. package/dist/mode-market/submission.js +1 -85
  204. package/dist/participation/collaborator-interest.d.ts +23 -0
  205. package/dist/participation/collaborator-interest.js +1 -0
  206. package/dist/participation/customer-interest.d.ts +25 -0
  207. package/dist/participation/customer-interest.js +1 -0
  208. package/dist/participation/merchant-interest.js +1 -100
  209. package/dist/participation/radar-core.d.ts +13 -3
  210. package/dist/participation/radar-core.js +1 -269
  211. package/dist/participation/supplier-interest.d.ts +25 -0
  212. package/dist/participation/supplier-interest.js +1 -0
  213. package/dist/persona/analyzer.js +1 -66
  214. package/dist/persona/bridge.js +1 -86
  215. package/dist/persona/defaults.js +1 -195
  216. package/dist/persona/experience-bridge.js +1 -23
  217. package/dist/persona/index.js +1 -71
  218. package/dist/persona/model.js +1 -111
  219. package/dist/persona/store.js +1 -62
  220. package/dist/persona/types.d.ts +3 -1
  221. package/dist/persona/types.js +1 -5
  222. package/dist/project/business-puzzle.js +1 -383
  223. package/dist/project/context-assembly.js +1 -254
  224. package/dist/project/deployment-bridge.js +1 -120
  225. package/dist/project/deployment-doc.js +1 -1126
  226. package/dist/project/edit-planner.js +1 -1342
  227. package/dist/project/evaluation.js +1 -2011
  228. package/dist/project/game-theory.js +1 -177
  229. package/dist/project/graph-builder.js +1 -656
  230. package/dist/project/graph.js +1 -340
  231. package/dist/project/handlers.js +1 -1784
  232. package/dist/project/index.d.ts +1 -0
  233. package/dist/project/index.js +1 -301
  234. package/dist/project/intent-analyzer.js +1 -149
  235. package/dist/project/machine-nodes.js +1 -36
  236. package/dist/project/merchant-guide.js +1 -264
  237. package/dist/project/migration.js +1 -125
  238. package/dist/project/mode-actions.js +1 -309
  239. package/dist/project/namespace.js +1 -206
  240. package/dist/project/participation-radar.js +1 -428
  241. package/dist/project/pipeline-actions.js +1 -109
  242. package/dist/project/project-store.js +1 -422
  243. package/dist/project/query.js +1 -153
  244. package/dist/project/reverse-mapping.d.ts +34 -0
  245. package/dist/project/reverse-mapping.js +1 -0
  246. package/dist/project/risk-aggregator.js +1 -295
  247. package/dist/project/rollback-policy.js +1 -290
  248. package/dist/project/semantic-assembler.js +1 -345
  249. package/dist/project/semantic-graph.js +1 -292
  250. package/dist/project/stage-gate.js +1 -369
  251. package/dist/project/substep-trace.js +1 -332
  252. package/dist/project/task-tracker.js +1 -78
  253. package/dist/role/derivation.d.ts +18 -0
  254. package/dist/role/derivation.js +1 -0
  255. package/dist/role/index.d.ts +5 -0
  256. package/dist/role/index.js +1 -0
  257. package/dist/role/model.d.ts +8 -0
  258. package/dist/role/model.js +1 -0
  259. package/dist/role/resolution.d.ts +11 -0
  260. package/dist/role/resolution.js +1 -0
  261. package/dist/role/types.d.ts +11 -0
  262. package/dist/role/types.js +1 -0
  263. package/dist/rules.js +1 -52
  264. package/dist/safety/confirm-gate.js +1 -88
  265. package/dist/safety/index.js +1 -3
  266. package/dist/safety/preview.js +1 -52
  267. package/dist/schema/call/allocation.js +1 -34
  268. package/dist/schema/call/arbitration.js +1 -113
  269. package/dist/schema/call/base.d.ts +15 -15
  270. package/dist/schema/call/base.js +1 -370
  271. package/dist/schema/call/bridge-handler.js +1 -265
  272. package/dist/schema/call/bridge.d.ts +7 -7
  273. package/dist/schema/call/bridge.js +1 -458
  274. package/dist/schema/call/contact.js +1 -37
  275. package/dist/schema/call/demand.js +1 -47
  276. package/dist/schema/call/guard.js +1 -161
  277. package/dist/schema/call/handler.js +1 -322
  278. package/dist/schema/call/index.js +1 -20
  279. package/dist/schema/call/machine.js +1 -193
  280. package/dist/schema/call/order.js +1 -35
  281. package/dist/schema/call/payment.js +1 -37
  282. package/dist/schema/call/permission-handler.js +1 -54
  283. package/dist/schema/call/permission.js +1 -105
  284. package/dist/schema/call/personal.js +1 -78
  285. package/dist/schema/call/progress.js +1 -47
  286. package/dist/schema/call/proof.js +1 -33
  287. package/dist/schema/call/repository.js +1 -77
  288. package/dist/schema/call/reward.js +1 -30
  289. package/dist/schema/call/semantic.js +1 -1679
  290. package/dist/schema/call/service.js +1 -184
  291. package/dist/schema/call/treasury.js +1 -71
  292. package/dist/schema/common/index.js +1 -407
  293. package/dist/schema/config/index.js +1 -68
  294. package/dist/schema/evaluation/index.d.ts +213 -16
  295. package/dist/schema/evaluation/index.js +1 -356
  296. package/dist/schema/index.js +1 -17
  297. package/dist/schema/intent-radar/index.d.ts +13 -13
  298. package/dist/schema/intent-radar/index.js +1 -89
  299. package/dist/schema/local/index.d.ts +21 -21
  300. package/dist/schema/local/index.js +1 -927
  301. package/dist/schema/local/wip.js +1 -187
  302. package/dist/schema/messenger/index.d.ts +7 -7
  303. package/dist/schema/messenger/index.js +1 -475
  304. package/dist/schema/operations.d.ts +7 -7
  305. package/dist/schema/operations.js +1 -520
  306. package/dist/schema/persona/index.d.ts +54 -54
  307. package/dist/schema/persona/index.js +1 -148
  308. package/dist/schema/project/index.d.ts +94 -48
  309. package/dist/schema/project/index.js +1 -2057
  310. package/dist/schema/query/index.d.ts +423 -7
  311. package/dist/schema/query/index.js +1 -1646
  312. package/dist/schema/schema-query/index.js +1 -104
  313. package/dist/schema/schema-version.js +1 -76
  314. package/dist/schema/sync-layer4.js +1 -286
  315. package/dist/schema/task-status.js +1 -36
  316. package/dist/schema/trust/index.js +1 -314
  317. package/dist/schema/utils/guard-parser.js +1 -419
  318. package/dist/schema/utils/guard-query-utils.js +1 -46
  319. package/dist/schema/utils/node-parser.js +1 -369
  320. package/dist/schema/utils/object-type-utils.js +1 -35
  321. package/dist/schema/utils/permission-index-utils.js +1 -7
  322. package/dist/schema/utils/permission-machine-check.js +1 -121
  323. package/dist/schema/utils/skills-recommendation.js +1 -77
  324. package/dist/schema-query/index.js +1 -810
  325. package/dist/schemas/account_operation.output.json +5 -2
  326. package/dist/schemas/bridge_operation.output.json +5 -2
  327. package/dist/schemas/evaluation_operation.output.json +112 -7
  328. package/dist/schemas/evaluation_operation.schema.json +93 -6
  329. package/dist/schemas/index.json +1 -1
  330. package/dist/schemas/intent_radar.output.json +4 -1
  331. package/dist/schemas/intent_radar.schema.json +4 -1
  332. package/dist/schemas/local_info_operation.output.json +5 -2
  333. package/dist/schemas/local_mark_operation.output.json +5 -2
  334. package/dist/schemas/messenger_operation.output.json +5 -2
  335. package/dist/schemas/onchain_events.output.json +5 -2
  336. package/dist/schemas/onchain_operations.output.json +5 -2
  337. package/dist/schemas/onchain_operations.schema.json +4 -4
  338. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  339. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  340. package/dist/schemas/onchain_operations_service.schema.json +1 -1
  341. package/dist/schemas/onchain_table_data.output.json +6 -3
  342. package/dist/schemas/persona_operation.output.json +4 -1
  343. package/dist/schemas/persona_operation.schema.json +4 -1
  344. package/dist/schemas/project_operation.output.json +28 -8
  345. package/dist/schemas/query_toolkit.output.json +8 -5
  346. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  347. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  348. package/dist/telemetry/index.js +1 -112
  349. package/dist/telemetry/redact.js +1 -23
  350. package/dist/telemetry/storage.js +1 -80
  351. package/dist/tools/handlers/bridge.js +1 -1
  352. package/dist/tools/handlers/config.js +1 -74
  353. package/dist/tools/handlers/evaluation.js +1 -123
  354. package/dist/tools/handlers/file-export.js +1 -90
  355. package/dist/tools/handlers/intent-radar.js +1 -76
  356. package/dist/tools/handlers/local.js +1 -53
  357. package/dist/tools/handlers/messenger.js +1 -188
  358. package/dist/tools/handlers/onchain.js +1 -1180
  359. package/dist/tools/handlers/persona.js +1 -89
  360. package/dist/tools/handlers/project.js +1 -211
  361. package/dist/tools/handlers/query.js +1 -434
  362. package/dist/tools/handlers/schema-query.js +1 -176
  363. package/dist/tools/handlers/task-status.js +1 -26
  364. package/dist/tools/handlers/trust.js +1 -380
  365. package/dist/tools/handlers/wip.js +1 -90
  366. package/dist/tools/index.js +1 -1382
  367. package/dist/tools/retry.js +1 -85
  368. package/dist/tools/rules-hook.js +1 -23
  369. package/dist/tools/shared.js +1 -130
  370. package/dist/tools/types.js +1 -1
  371. package/dist/tools/upgrade-check.d.ts +19 -0
  372. package/dist/tools/upgrade-check.js +1 -0
  373. package/dist/tools/wip-deploy-assist.js +1 -306
  374. package/dist/tools/wrap.js +1 -500
  375. package/package.json +4 -2
@@ -1,656 +1 @@
1
- import { query_objects, queryTableItem_EntityLinker, LocalProject, } from "@wowok/wowok";
2
- const MAX_OBJECTS_PER_QUERY = 50;
3
- function shortTypeName(objectType) {
4
- if (!objectType)
5
- return "unknown";
6
- const base = objectType.replace(/<.*>/, "").trim();
7
- const segments = base.split("::");
8
- return segments[segments.length - 1] || "unknown";
9
- }
10
- export function extractAddressFields(obj) {
11
- const refs = [];
12
- const rawType = obj.type;
13
- let objType = rawType;
14
- if (rawType && rawType.includes("::")) {
15
- const parts = rawType.split("::");
16
- objType = parts[parts.length - 1];
17
- }
18
- const isAddress = (v) => typeof v === "string" && v.startsWith("0x") && v.length >= 10;
19
- const addRef = (addr, field, refType) => {
20
- if (isAddress(addr) && addr !== "0x0" && addr !== obj.object) {
21
- refs.push({ address: addr, field, type: refType });
22
- }
23
- };
24
- const addRefArray = (arr, field, refType) => {
25
- if (Array.isArray(arr)) {
26
- for (const item of arr) {
27
- addRef(item, field, refType);
28
- }
29
- }
30
- };
31
- const addRefOption = (val, field, refType) => {
32
- if (val !== null && val !== undefined) {
33
- addRef(val, field, refType);
34
- }
35
- };
36
- const data = obj;
37
- switch (objType) {
38
- case "Service": {
39
- addRefOption(data.machine, "machine", "bind");
40
- addRefOption(data.buy_guard, "buy_guard", "validate");
41
- addRefOption(data.um, "um", "bind");
42
- addRef(data.permission, "permission", "validate");
43
- addRefArray(data.repositories, "repositories", "consume");
44
- addRefArray(data.arbitrations, "arbitrations", "trigger");
45
- addRefArray(data.rewards, "rewards", "trigger");
46
- if (data.order_allocators?.allocators) {
47
- for (const alloc of data.order_allocators.allocators) {
48
- addRef(alloc.guard, "allocator_guard", "validate");
49
- }
50
- const firstGuard = data.order_allocators.allocators[0]?.guard;
51
- addRef(firstGuard, "order_allocators", "create");
52
- }
53
- break;
54
- }
55
- case "Machine": {
56
- addRef(data.permission, "permission", "validate");
57
- addRefArray(data.consensus_repositories, "consensus_repositories", "consume");
58
- break;
59
- }
60
- case "Order": {
61
- addRef(data.service, "service", "consume");
62
- addRefOption(data.machine, "machine", "consume");
63
- addRefOption(data.progress, "progress", "trigger");
64
- addRefArray(data.dispute, "dispute", "trigger");
65
- addRefOption(data.allocation, "allocation", "bind");
66
- break;
67
- }
68
- case "Progress": {
69
- addRef(data.machine, "machine", "bind");
70
- addRefArray(data.context_repositories, "context_repositories", "consume");
71
- break;
72
- }
73
- case "Treasury": {
74
- addRef(data.permission, "permission", "validate");
75
- if (Array.isArray(data.external_deposit_guard)) {
76
- for (const g of data.external_deposit_guard)
77
- addRef(g?.guard, "external_deposit_guard", "validate");
78
- }
79
- if (Array.isArray(data.external_withdraw_guard)) {
80
- for (const g of data.external_withdraw_guard)
81
- addRef(g?.guard, "external_withdraw_guard", "validate");
82
- }
83
- break;
84
- }
85
- case "Allocation": {
86
- if (Array.isArray(data.allocators)) {
87
- for (const alloc of data.allocators)
88
- addRef(alloc?.guard, "allocator_guard", "validate");
89
- }
90
- addRefOption(data.payment_info?.for_object, "for_object", "bind");
91
- addRefOption(data.payment_info?.for_guard, "for_guard", "validate");
92
- addRefArray(data.payment, "payment", "trigger");
93
- break;
94
- }
95
- case "Arbitration": {
96
- addRef(data.permission, "permission", "validate");
97
- if (Array.isArray(data.voting_guard)) {
98
- for (const vg of data.voting_guard)
99
- addRef(vg?.guard, "voting_guard", "validate");
100
- }
101
- addRefOption(data.usage_guard, "usage_guard", "validate");
102
- break;
103
- }
104
- case "Reward": {
105
- addRef(data.permission, "permission", "validate");
106
- if (Array.isArray(data.guards)) {
107
- for (const rg of data.guards)
108
- addRef(rg?.guard, "guard", "validate");
109
- }
110
- break;
111
- }
112
- case "Repository": {
113
- addRef(data.permission, "permission", "validate");
114
- addRefArray(data.rewards, "rewards", "trigger");
115
- if (Array.isArray(data.policies)) {
116
- for (const policy of data.policies) {
117
- if (Array.isArray(policy?.write_guard)) {
118
- for (const wg of policy.write_guard)
119
- addRef(wg?.guard, "write_guard", "validate");
120
- }
121
- addRefOption(policy?.quote_guard, "quote_guard", "validate");
122
- }
123
- }
124
- break;
125
- }
126
- case "Demand": {
127
- addRef(data.permission, "permission", "validate");
128
- if (Array.isArray(data.guards)) {
129
- for (const dg of data.guards)
130
- addRef(dg?.guard, "guard", "validate");
131
- }
132
- addRefArray(data.rewards, "rewards", "trigger");
133
- break;
134
- }
135
- case "Contact": {
136
- addRef(data.permission, "permission", "validate");
137
- break;
138
- }
139
- case "Permission": {
140
- break;
141
- }
142
- case "Payment": {
143
- addRefOption(data.info?.for_object, "for_object", "bind");
144
- addRefOption(data.info?.for_guard, "for_guard", "validate");
145
- if (Array.isArray(data.record)) {
146
- for (const r of data.record) {
147
- const rec = r?.recipient;
148
- if (rec && typeof rec === "object" && typeof rec.Entity === "string") {
149
- addRef(rec.Entity, "recipient_entity", "consume");
150
- }
151
- }
152
- }
153
- break;
154
- }
155
- case "Guard": {
156
- break;
157
- }
158
- default:
159
- break;
160
- }
161
- return refs;
162
- }
163
- class RateLimiter {
164
- maxConcurrency;
165
- qps;
166
- queue = [];
167
- activeCount = 0;
168
- lastRequestTime = 0;
169
- constructor(maxConcurrency, qps) {
170
- this.maxConcurrency = maxConcurrency;
171
- this.qps = qps;
172
- }
173
- async acquire() {
174
- if (this.activeCount < this.maxConcurrency) {
175
- this.activeCount++;
176
- await this.enforceRate();
177
- return;
178
- }
179
- return new Promise((resolve) => {
180
- this.queue.push(() => {
181
- this.activeCount++;
182
- this.enforceRate().then(resolve);
183
- });
184
- });
185
- }
186
- release() {
187
- this.activeCount--;
188
- if (this.queue.length > 0) {
189
- const next = this.queue.shift();
190
- next();
191
- }
192
- }
193
- async enforceRate() {
194
- const now = Date.now();
195
- const minInterval = 1000 / this.qps;
196
- const elapsed = now - this.lastRequestTime;
197
- if (elapsed < minInterval) {
198
- await sleep(minInterval - elapsed);
199
- }
200
- this.lastRequestTime = Date.now();
201
- }
202
- async run(fn) {
203
- await this.acquire();
204
- try {
205
- return await fn();
206
- }
207
- finally {
208
- this.release();
209
- }
210
- }
211
- }
212
- function sleep(ms) {
213
- return new Promise((resolve) => setTimeout(resolve, ms));
214
- }
215
- const EXPECTED_RELATIONSHIPS = new Map([
216
- ["Service", [
217
- { targetType: "Machine", fieldName: "machine", relationshipType: "bind", single: true },
218
- { targetType: "Guard", fieldName: "buy_guard", relationshipType: "validate", single: true },
219
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
220
- { targetType: "Guard", fieldName: "allocator_guard", relationshipType: "validate" },
221
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
222
- { targetType: "Arbitration", fieldName: "arbitrations", relationshipType: "trigger" },
223
- { targetType: "Reward", fieldName: "rewards", relationshipType: "trigger" },
224
- { targetType: "Repository", fieldName: "repositories", relationshipType: "consume" },
225
- ]],
226
- ["Machine", [
227
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
228
- { targetType: "Repository", fieldName: "consensus_repositories", relationshipType: "consume" },
229
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
230
- ]],
231
- ["Order", [
232
- { targetType: "Service", fieldName: "service", relationshipType: "consume", single: true },
233
- { targetType: "Machine", fieldName: "machine", relationshipType: "consume", single: true },
234
- { targetType: "Progress", fieldName: "progress", relationshipType: "trigger", single: true },
235
- { targetType: "Arb", fieldName: "dispute", relationshipType: "trigger" },
236
- { targetType: "Allocation", fieldName: "allocation", relationshipType: "bind", single: true },
237
- ]],
238
- ["Progress", [
239
- { targetType: "Machine", fieldName: "machine", relationshipType: "bind", single: true },
240
- { targetType: "Repository", fieldName: "context_repositories", relationshipType: "consume" },
241
- ]],
242
- ["Allocation", [
243
- { targetType: "Guard", fieldName: "allocator_guard", relationshipType: "validate" },
244
- { targetType: "Guard", fieldName: "for_guard", relationshipType: "validate", single: true },
245
- { targetType: "Payment", fieldName: "payment", relationshipType: "trigger" },
246
- ]],
247
- ["Reward", [
248
- { targetType: "Guard", fieldName: "guard", relationshipType: "validate" },
249
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
250
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
251
- ]],
252
- ["Repository", [
253
- { targetType: "Guard", fieldName: "write_guard", relationshipType: "validate" },
254
- { targetType: "Guard", fieldName: "quote_guard", relationshipType: "validate", single: true },
255
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
256
- { targetType: "Reward", fieldName: "rewards", relationshipType: "trigger" },
257
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
258
- ]],
259
- ["Demand", [
260
- { targetType: "Guard", fieldName: "guard", relationshipType: "validate" },
261
- { targetType: "Reward", fieldName: "rewards", relationshipType: "trigger" },
262
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
263
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
264
- ]],
265
- ["Treasury", [
266
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
267
- { targetType: "Guard", fieldName: "external_deposit_guard", relationshipType: "validate" },
268
- { targetType: "Guard", fieldName: "external_withdraw_guard", relationshipType: "validate" },
269
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
270
- ]],
271
- ["Arbitration", [
272
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
273
- { targetType: "Guard", fieldName: "voting_guard", relationshipType: "validate" },
274
- { targetType: "Guard", fieldName: "usage_guard", relationshipType: "validate", single: true },
275
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
276
- ]],
277
- ["Payment", [
278
- { targetType: "Guard", fieldName: "for_guard", relationshipType: "validate", single: true },
279
- ]],
280
- ["Contact", [
281
- { targetType: "Permission", fieldName: "permission", relationshipType: "validate", single: true },
282
- ]],
283
- ["Permission", [
284
- { targetType: "Contact", fieldName: "um", relationshipType: "bind", single: true },
285
- ]],
286
- ]);
287
- export class GraphBuilder {
288
- localProject;
289
- rateLimiter;
290
- options;
291
- constructor(options) {
292
- const batchSize = Math.min(Math.max(options?.batchSize ?? MAX_OBJECTS_PER_QUERY, 1), MAX_OBJECTS_PER_QUERY);
293
- this.options = {
294
- maxDepth: options?.maxDepth ?? 3,
295
- maxConcurrency: options?.maxConcurrency ?? 5,
296
- rateLimitQPS: options?.rateLimitQPS ?? 10,
297
- cacheTTL: options?.cacheTTL ?? 3600000,
298
- enableRegistrar: options?.enableRegistrar ?? true,
299
- enablePotential: options?.enablePotential ?? false,
300
- projectId: options?.projectId ?? null,
301
- network: options?.network ?? "testnet",
302
- batchSize,
303
- };
304
- this.rateLimiter = new RateLimiter(this.options.maxConcurrency, this.options.rateLimitQPS);
305
- this.localProject = LocalProject.Instance();
306
- }
307
- async buildRelationshipGraph(rootAddress) {
308
- const allEdges = [];
309
- const reputationMap = new Map();
310
- const visited = new Set();
311
- const objectCache = new Map();
312
- const pendingAddresses = new Set([rootAddress]);
313
- await this.buildInternalRefsBatched(pendingAddresses, visited, allEdges, objectCache);
314
- if (this.options.enableRegistrar) {
315
- const allAddresses = new Set([rootAddress]);
316
- for (const edge of allEdges) {
317
- allAddresses.add(edge.sourceObject);
318
- allAddresses.add(edge.targetObject);
319
- }
320
- const registrarPromises = Array.from(allAddresses).map((addr) => this.buildRegistrarRefs(addr).then((result) => {
321
- allEdges.push(...result.edges);
322
- if (result.reputation) {
323
- reputationMap.set(addr, result.reputation);
324
- }
325
- }));
326
- await Promise.all(registrarPromises);
327
- }
328
- if (this.options.enablePotential && this.options.projectId) {
329
- const potentialEdges = await this.buildPotentialRefs(this.options.projectId, allEdges);
330
- allEdges.push(...potentialEdges);
331
- }
332
- const resolvedEdges = this.resolveConflicts(allEdges);
333
- const nodes = this.buildNodes(resolvedEdges, objectCache, rootAddress);
334
- const savedEdges = await this.localProject.saveGraphEdges(this.options.projectId, resolvedEdges);
335
- return {
336
- graph: {
337
- nodes,
338
- edges: savedEdges,
339
- builtAt: Date.now(),
340
- },
341
- reputation: reputationMap,
342
- };
343
- }
344
- async buildInternalRefsBatched(pendingAddresses, visited, edges, objectCache) {
345
- const batchSize = this.options.batchSize;
346
- for (let depth = 0; depth < this.options.maxDepth; depth++) {
347
- const currentLevel = [];
348
- for (const addr of pendingAddresses) {
349
- if (!visited.has(addr)) {
350
- visited.add(addr);
351
- currentLevel.push(addr);
352
- }
353
- }
354
- pendingAddresses.clear();
355
- if (currentLevel.length === 0)
356
- break;
357
- const nextLevelPending = new Set();
358
- for (let i = 0; i < currentLevel.length; i += batchSize) {
359
- const batch = currentLevel.slice(i, i + batchSize);
360
- const objects = await this.fetchObjectsBatch(batch, objectCache);
361
- for (const addr of batch) {
362
- const obj = objects.get(addr);
363
- if (!obj)
364
- continue;
365
- const refs = extractAddressFields(obj);
366
- for (const ref of refs) {
367
- edges.push({
368
- sourceObject: addr,
369
- targetObject: ref.address,
370
- edgeSource: "internal",
371
- relationshipType: this.mapRefTypeToRelationship(ref.type),
372
- fieldName: ref.field,
373
- depth,
374
- verified: true,
375
- weight: 1.0,
376
- direction: "outbound",
377
- metadata: { ref_type: ref.type },
378
- });
379
- if (!visited.has(ref.address)) {
380
- nextLevelPending.add(ref.address);
381
- }
382
- }
383
- }
384
- }
385
- for (const addr of nextLevelPending) {
386
- pendingAddresses.add(addr);
387
- }
388
- }
389
- }
390
- async fetchObjectsBatch(addresses, objectCache) {
391
- const result = new Map();
392
- const toFetch = [];
393
- for (const addr of addresses) {
394
- const cached = objectCache.get(addr);
395
- if (cached) {
396
- result.set(addr, cached);
397
- }
398
- else {
399
- toFetch.push(addr);
400
- }
401
- }
402
- if (toFetch.length === 0)
403
- return result;
404
- const response = await this.rateLimiter.run(async () => {
405
- return await query_objects({
406
- objects: toFetch,
407
- network: this.options.network,
408
- });
409
- });
410
- for (const obj of response.objects ?? []) {
411
- if (!obj || !obj.object)
412
- continue;
413
- objectCache.set(obj.object, obj);
414
- result.set(obj.object, obj);
415
- void this.localProject.cacheObject(obj.object, obj.type ?? null, JSON.stringify(obj), this.options.network).catch(() => {
416
- });
417
- }
418
- return result;
419
- }
420
- mapRefTypeToRelationship(refType) {
421
- switch (refType) {
422
- case "bind":
423
- return "bind";
424
- case "validate":
425
- return "validate";
426
- case "consume":
427
- return "consume";
428
- case "trigger":
429
- return "trigger";
430
- case "reference":
431
- return "affiliation";
432
- default:
433
- return "bind";
434
- }
435
- }
436
- async buildRegistrarRefs(address) {
437
- try {
438
- const result = await this.rateLimiter.run(async () => {
439
- return await queryTableItem_EntityLinker({
440
- address,
441
- network: this.options.network,
442
- });
443
- });
444
- if (!result || !result.votes || result.votes.length === 0) {
445
- return { edges: [] };
446
- }
447
- const edges = [];
448
- const reputation = {
449
- likes: 0,
450
- dislikes: 0,
451
- affiliations: 0,
452
- voters: [],
453
- };
454
- for (const vote of result.votes) {
455
- if (vote.like)
456
- reputation.likes++;
457
- if (vote.dislike)
458
- reputation.dislikes++;
459
- if (vote.affiliation)
460
- reputation.affiliations++;
461
- reputation.voters.push({
462
- who: vote.address,
463
- like: vote.like ?? false,
464
- dislike: vote.dislike ?? false,
465
- affiliation: vote.affiliation ?? false,
466
- time: vote.time,
467
- });
468
- if (vote.affiliation) {
469
- edges.push({
470
- sourceObject: vote.address,
471
- targetObject: address,
472
- edgeSource: "registrar",
473
- relationshipType: "affiliation",
474
- fieldName: null,
475
- depth: 0,
476
- verified: true,
477
- weight: 0.9,
478
- direction: "inbound",
479
- metadata: {
480
- like: vote.like ?? false,
481
- dislike: vote.dislike ?? false,
482
- affiliation: true,
483
- time: vote.time,
484
- },
485
- });
486
- }
487
- else if (vote.like || vote.dislike) {
488
- edges.push({
489
- sourceObject: vote.address,
490
- targetObject: address,
491
- edgeSource: "registrar",
492
- relationshipType: "affiliation",
493
- fieldName: null,
494
- depth: 0,
495
- verified: true,
496
- weight: 0.3,
497
- direction: "inbound",
498
- metadata: {
499
- like: vote.like ?? false,
500
- dislike: vote.dislike ?? false,
501
- affiliation: false,
502
- disaffiliated: true,
503
- time: vote.time,
504
- },
505
- });
506
- }
507
- }
508
- return { edges, reputation };
509
- }
510
- catch {
511
- return { edges: [] };
512
- }
513
- }
514
- async buildPotentialRefs(projectId, existingEdges) {
515
- const potentialEdges = [];
516
- const projectObjects = await this.localProject.listObjects(projectId);
517
- if (projectObjects.length === 0)
518
- return potentialEdges;
519
- const existingPairs = new Set(existingEdges.map((e) => `${e.sourceObject}→${e.targetObject}`));
520
- const sourceFieldBindings = new Map();
521
- for (const e of existingEdges) {
522
- if (e.fieldName) {
523
- const key = `${e.sourceObject}#${e.fieldName}`;
524
- if (!sourceFieldBindings.has(key)) {
525
- sourceFieldBindings.set(key, new Set());
526
- }
527
- sourceFieldBindings.get(key).add(e.targetObject);
528
- }
529
- }
530
- const byType = new Map();
531
- for (const obj of projectObjects) {
532
- const type = shortTypeName(obj.objectType);
533
- if (!byType.has(type))
534
- byType.set(type, []);
535
- byType.get(type).push({
536
- address: obj.objectAddress,
537
- name: obj.objectName,
538
- });
539
- }
540
- for (const [sourceType, expectedRels] of EXPECTED_RELATIONSHIPS) {
541
- const sources = byType.get(sourceType);
542
- if (!sources || sources.length === 0)
543
- continue;
544
- for (const source of sources) {
545
- for (const expected of expectedRels) {
546
- const targets = byType.get(expected.targetType);
547
- if (!targets || targets.length === 0)
548
- continue;
549
- const fieldKey = `${source.address}#${expected.fieldName}`;
550
- const existingBindings = sourceFieldBindings.get(fieldKey);
551
- const hasOtherBinding = existingBindings !== undefined && existingBindings.size > 0;
552
- if (hasOtherBinding)
553
- continue;
554
- const representativeTarget = targets.find((t) => t.address !== source.address &&
555
- !existingPairs.has(`${source.address}→${t.address}`) &&
556
- !existingBindings?.has(t.address));
557
- if (!representativeTarget)
558
- continue;
559
- potentialEdges.push({
560
- sourceObject: source.address,
561
- targetObject: representativeTarget.address,
562
- edgeSource: "potential",
563
- relationshipType: expected.relationshipType,
564
- fieldName: expected.fieldName,
565
- depth: 0,
566
- verified: false,
567
- weight: 0.6,
568
- direction: "outbound",
569
- metadata: {
570
- reason: "expected_relationship_missing",
571
- expected_target_type: expected.targetType,
572
- source_object_name: source.name,
573
- representative: true,
574
- alternative_target_count: targets.length - 1,
575
- },
576
- });
577
- }
578
- }
579
- }
580
- return potentialEdges;
581
- }
582
- resolveConflicts(edges) {
583
- const edgeMap = new Map();
584
- for (const edge of edges) {
585
- if (!edge.sourceObject || !edge.targetObject)
586
- continue;
587
- const key = `${edge.sourceObject}→${edge.targetObject}:${edge.relationshipType}`;
588
- const list = edgeMap.get(key) ?? [];
589
- list.push(edge);
590
- edgeMap.set(key, list);
591
- }
592
- const result = [];
593
- for (const list of edgeMap.values()) {
594
- if (list.length === 1) {
595
- result.push(list[0]);
596
- continue;
597
- }
598
- const priority = (e) => {
599
- let p = 0;
600
- if (e.edgeSource === "internal")
601
- p += 100;
602
- if (e.edgeSource === "registrar")
603
- p += 50;
604
- if (e.verified)
605
- p += 10;
606
- p += (e.weight ?? 0.5) * 10;
607
- return p;
608
- };
609
- list.sort((a, b) => priority(b) - priority(a));
610
- const winner = list[0];
611
- const mergedMetadata = { ...(winner.metadata ?? {}) };
612
- for (let i = 1; i < list.length; i++) {
613
- mergedMetadata[`alt_${list[i].edgeSource}`] = list[i].metadata ?? {};
614
- }
615
- result.push({ ...winner, metadata: mergedMetadata });
616
- }
617
- return result;
618
- }
619
- buildNodes(edges, objectCache, rootAddress) {
620
- const nodeMap = new Map();
621
- const ensureNode = (addr) => {
622
- if (!nodeMap.has(addr)) {
623
- const obj = objectCache.get(addr);
624
- const queryName = obj?.query_name;
625
- const objectName = queryName && queryName !== addr ? queryName : null;
626
- const isTemplate = addr.startsWith("draft:");
627
- nodeMap.set(addr, {
628
- address: addr,
629
- objectType: obj?.type ?? null,
630
- objectName,
631
- role: null,
632
- isCore: addr === rootAddress,
633
- isTemplate,
634
- });
635
- }
636
- return nodeMap.get(addr);
637
- };
638
- for (const edge of edges) {
639
- const source = ensureNode(edge.sourceObject);
640
- const target = ensureNode(edge.targetObject);
641
- if (edge.edgeSource === "internal" && edge.relationshipType === "bind") {
642
- if (source.isCore) {
643
- target.role = "dependency";
644
- }
645
- }
646
- if (edge.edgeSource === "potential") {
647
- target.role = "reference";
648
- }
649
- }
650
- return Array.from(nodeMap.values());
651
- }
652
- }
653
- export async function buildGraph(rootAddress, options) {
654
- const builder = new GraphBuilder(options);
655
- return builder.buildRelationshipGraph(rootAddress);
656
- }
1
+ import{query_objects,queryTableItem_EntityLinker,LocalProject}from'@wowok/wowok';const MAX_OBJECTS_PER_QUERY=0x32;function shortTypeName(a){if(!a)return'unknown';const b=a['replace'](/<.*>/,'')['trim'](),c=b['split']('::');return c[c['length']-0x1]||'unknown';}export function extractAddressFields(a){const b=[],c=a['type'];let d=c;if(c&&c['includes']('::')){const k=c['split']('::');d=k[k['length']-0x1];}const e=l=>typeof l==='string'&&l['startsWith']('0x')&&l['length']>=0xa,f=(l,m,n)=>{e(l)&&l!=='0x0'&&l!==a['object']&&b['push']({'address':l,'field':m,'type':n});},h=(l,m,n)=>{if(Array['isArray'](l))for(const o of l){f(o,m,n);}},i=(l,m,n)=>{l!==null&&l!==undefined&&f(l,m,n);},j=a;switch(d){case'Service':{i(j['machine'],'machine','bind'),i(j['buy_guard'],'buy_guard','validate'),i(j['um'],'um','bind'),f(j['permission'],'permission','validate'),h(j['repositories'],'repositories','consume'),h(j['arbitrations'],'arbitrations','trigger'),h(j['rewards'],'rewards','trigger');if(j['order_allocators']?.['allocators']){for(const m of j['order_allocators']['allocators']){f(m['guard'],'allocator_guard','validate');}const l=j['order_allocators']['allocators'][0x0]?.['guard'];f(l,'order_allocators','create');}break;}case'Machine':{f(j['permission'],'permission','validate'),h(j['consensus_repositories'],'consensus_repositories','consume');break;}case'Order':{f(j['service'],'service','consume'),i(j['machine'],'machine','consume'),i(j['progress'],'progress','trigger'),h(j['dispute'],'dispute','trigger'),i(j['allocation'],'allocation','bind');break;}case'Progress':{f(j['machine'],'machine','bind'),h(j['context_repositories'],'context_repositories','consume');break;}case'Treasury':{f(j['permission'],'permission','validate');if(Array['isArray'](j['external_deposit_guard'])){for(const n of j['external_deposit_guard'])f(n?.['guard'],'external_deposit_guard','validate');}if(Array['isArray'](j['external_withdraw_guard'])){for(const o of j['external_withdraw_guard'])f(o?.['guard'],'external_withdraw_guard','validate');}break;}case'Allocation':{if(Array['isArray'](j['allocators'])){for(const p of j['allocators'])f(p?.['guard'],'allocator_guard','validate');}i(j['payment_info']?.['for_object'],'for_object','bind'),i(j['payment_info']?.['for_guard'],'for_guard','validate'),h(j['payment'],'payment','trigger');break;}case'Arbitration':{f(j['permission'],'permission','validate');if(Array['isArray'](j['voting_guard'])){for(const q of j['voting_guard'])f(q?.['guard'],'voting_guard','validate');}i(j['usage_guard'],'usage_guard','validate');break;}case'Reward':{f(j['permission'],'permission','validate');if(Array['isArray'](j['guards'])){for(const s of j['guards'])f(s?.['guard'],'guard','validate');}break;}case'Repository':{f(j['permission'],'permission','validate'),h(j['rewards'],'rewards','trigger');if(Array['isArray'](j['policies']))for(const t of j['policies']){if(Array['isArray'](t?.['write_guard'])){for(const u of t['write_guard'])f(u?.['guard'],'write_guard','validate');}i(t?.['quote_guard'],'quote_guard','validate');}break;}case'Demand':{f(j['permission'],'permission','validate');if(Array['isArray'](j['guards'])){for(const v of j['guards'])f(v?.['guard'],'guard','validate');}h(j['rewards'],'rewards','trigger');break;}case'Contact':{f(j['permission'],'permission','validate');break;}case'Permission':{break;}case'Payment':{i(j['info']?.['for_object'],'for_object','bind'),i(j['info']?.['for_guard'],'for_guard','validate');if(Array['isArray'](j['record']))for(const w of j['record']){const x=w?.['recipient'];x&&typeof x==='object'&&typeof x['Entity']==='string'&&f(x['Entity'],'recipient_entity','consume');}break;}case'Guard':{break;}default:break;}return b;}class RateLimiter{['maxConcurrency'];['qps'];['queue']=[];['activeCount']=0x0;['lastRequestTime']=0x0;constructor(a,b){this['maxConcurrency']=a,this['qps']=b;}async['acquire'](){if(this['activeCount']<this['maxConcurrency']){this['activeCount']++,await this['enforceRate']();return;}return new Promise(a=>{this['queue']['push'](()=>{this['activeCount']++,this['enforceRate']()['then'](a);});});}['release'](){this['activeCount']--;if(this['queue']['length']>0x0){const a=this['queue']['shift']();a();}}async['enforceRate'](){const a=Date['now'](),b=0x3e8/this['qps'],c=a-this['lastRequestTime'];c<b&&await sleep(b-c),this['lastRequestTime']=Date['now']();}async['run'](a){await this['acquire']();try{return await a();}finally{this['release']();}}}function sleep(a){return new Promise(b=>setTimeout(b,a));}const EXPECTED_RELATIONSHIPS=new Map([['Service',[{'targetType':'Machine','fieldName':'machine','relationshipType':'bind','single':!![]},{'targetType':'Guard','fieldName':'buy_guard','relationshipType':'validate','single':!![]},{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Guard','fieldName':'allocator_guard','relationshipType':'validate'},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]},{'targetType':'Arbitration','fieldName':'arbitrations','relationshipType':'trigger'},{'targetType':'Reward','fieldName':'rewards','relationshipType':'trigger'},{'targetType':'Repository','fieldName':'repositories','relationshipType':'consume'}]],['Machine',[{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Repository','fieldName':'consensus_repositories','relationshipType':'consume'},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Order',[{'targetType':'Service','fieldName':'service','relationshipType':'consume','single':!![]},{'targetType':'Machine','fieldName':'machine','relationshipType':'consume','single':!![]},{'targetType':'Progress','fieldName':'progress','relationshipType':'trigger','single':!![]},{'targetType':'Arb','fieldName':'dispute','relationshipType':'trigger'},{'targetType':'Allocation','fieldName':'allocation','relationshipType':'bind','single':!![]}]],['Progress',[{'targetType':'Machine','fieldName':'machine','relationshipType':'bind','single':!![]},{'targetType':'Repository','fieldName':'context_repositories','relationshipType':'consume'}]],['Allocation',[{'targetType':'Guard','fieldName':'allocator_guard','relationshipType':'validate'},{'targetType':'Guard','fieldName':'for_guard','relationshipType':'validate','single':!![]},{'targetType':'Payment','fieldName':'payment','relationshipType':'trigger'}]],['Reward',[{'targetType':'Guard','fieldName':'guard','relationshipType':'validate'},{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Repository',[{'targetType':'Guard','fieldName':'write_guard','relationshipType':'validate'},{'targetType':'Guard','fieldName':'quote_guard','relationshipType':'validate','single':!![]},{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Reward','fieldName':'rewards','relationshipType':'trigger'},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Demand',[{'targetType':'Guard','fieldName':'guard','relationshipType':'validate'},{'targetType':'Reward','fieldName':'rewards','relationshipType':'trigger'},{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Treasury',[{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Guard','fieldName':'external_deposit_guard','relationshipType':'validate'},{'targetType':'Guard','fieldName':'external_withdraw_guard','relationshipType':'validate'},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Arbitration',[{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]},{'targetType':'Guard','fieldName':'voting_guard','relationshipType':'validate'},{'targetType':'Guard','fieldName':'usage_guard','relationshipType':'validate','single':!![]},{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]],['Payment',[{'targetType':'Guard','fieldName':'for_guard','relationshipType':'validate','single':!![]}]],['Contact',[{'targetType':'Permission','fieldName':'permission','relationshipType':'validate','single':!![]}]],['Permission',[{'targetType':'Contact','fieldName':'um','relationshipType':'bind','single':!![]}]]]);export class GraphBuilder{['localProject'];['rateLimiter'];['options'];constructor(a){const b=Math['min'](Math['max'](a?.['batchSize']??MAX_OBJECTS_PER_QUERY,0x1),MAX_OBJECTS_PER_QUERY);this['options']={'maxDepth':a?.['maxDepth']??0x3,'maxConcurrency':a?.['maxConcurrency']??0x5,'rateLimitQPS':a?.['rateLimitQPS']??0xa,'cacheTTL':a?.['cacheTTL']??0x36ee80,'enableRegistrar':a?.['enableRegistrar']??!![],'enablePotential':a?.['enablePotential']??![],'projectId':a?.['projectId']??null,'network':a?.['network']??'testnet','batchSize':b},this['rateLimiter']=new RateLimiter(this['options']['maxConcurrency'],this['options']['rateLimitQPS']),this['localProject']=LocalProject['Instance']();}async['buildRelationshipGraph'](a){const b=[],c=new Map(),d=new Set(),e=new Map(),f=new Set([a]);await this['buildInternalRefsBatched'](f,d,b,e);if(this['options']['enableRegistrar']){const j=new Set([a]);for(const l of b){j['add'](l['sourceObject']),j['add'](l['targetObject']);}const k=Array['from'](j)['map'](m=>this['buildRegistrarRefs'](m)['then'](n=>{b['push'](...n['edges']),n['reputation']&&c['set'](m,n['reputation']);}));await Promise['all'](k);}if(this['options']['enablePotential']&&this['options']['projectId']){const m=await this['buildPotentialRefs'](this['options']['projectId'],b);b['push'](...m);}const g=this['resolveConflicts'](b),h=this['buildNodes'](g,e,a),i=await this['localProject']['saveGraphEdges'](this['options']['projectId'],g);return{'graph':{'nodes':h,'edges':i,'builtAt':Date['now']()},'reputation':c};}async['buildInternalRefsBatched'](a,b,c,d){const e=this['options']['batchSize'];for(let f=0x0;f<this['options']['maxDepth'];f++){const g=[];for(const j of a){!b['has'](j)&&(b['add'](j),g['push'](j));}a['clear']();if(g['length']===0x0)break;const h=new Set();for(let k=0x0;k<g['length'];k+=e){const l=g['slice'](k,k+e),m=await this['fetchObjectsBatch'](l,d);for(const n of l){const o=m['get'](n);if(!o)continue;const p=extractAddressFields(o);for(const q of p){c['push']({'sourceObject':n,'targetObject':q['address'],'edgeSource':'internal','relationshipType':this['mapRefTypeToRelationship'](q['type']),'fieldName':q['field'],'depth':f,'verified':!![],'weight':0x1,'direction':'outbound','metadata':{'ref_type':q['type']}}),!b['has'](q['address'])&&h['add'](q['address']);}}}for(const r of h){a['add'](r);}}}async['fetchObjectsBatch'](a,b){const c=new Map(),d=[];for(const f of a){const g=b['get'](f);g?c['set'](f,g):d['push'](f);}if(d['length']===0x0)return c;const e=await this['rateLimiter']['run'](async()=>{return await query_objects({'objects':d,'network':this['options']['network']});});for(const h of e['objects']??[]){if(!h||!h['object'])continue;b['set'](h['object'],h),c['set'](h['object'],h),void this['localProject']['cacheObject'](h['object'],h['type']??null,JSON['stringify'](h),this['options']['network'])['catch'](()=>{});}return c;}['mapRefTypeToRelationship'](a){switch(a){case'bind':return'bind';case'validate':return'validate';case'consume':return'consume';case'trigger':return'trigger';case'reference':return'affiliation';default:return'bind';}}async['buildRegistrarRefs'](a){try{const b=await this['rateLimiter']['run'](async()=>{return await queryTableItem_EntityLinker({'address':a,'network':this['options']['network']});});if(!b||!b['votes']||b['votes']['length']===0x0)return{'edges':[]};const c=[],d={'likes':0x0,'dislikes':0x0,'affiliations':0x0,'voters':[]};for(const e of b['votes']){if(e['like'])d['likes']++;if(e['dislike'])d['dislikes']++;if(e['affiliation'])d['affiliations']++;d['voters']['push']({'who':e['address'],'like':e['like']??![],'dislike':e['dislike']??![],'affiliation':e['affiliation']??![],'time':e['time']});if(e['affiliation'])c['push']({'sourceObject':e['address'],'targetObject':a,'edgeSource':'registrar','relationshipType':'affiliation','fieldName':null,'depth':0x0,'verified':!![],'weight':0.9,'direction':'inbound','metadata':{'like':e['like']??![],'dislike':e['dislike']??![],'affiliation':!![],'time':e['time']}});else(e['like']||e['dislike'])&&c['push']({'sourceObject':e['address'],'targetObject':a,'edgeSource':'registrar','relationshipType':'affiliation','fieldName':null,'depth':0x0,'verified':!![],'weight':0.3,'direction':'inbound','metadata':{'like':e['like']??![],'dislike':e['dislike']??![],'affiliation':![],'disaffiliated':!![],'time':e['time']}});}return{'edges':c,'reputation':d};}catch{return{'edges':[]};}}async['buildPotentialRefs'](a,b){const c=[],d=await this['localProject']['listObjects'](a);if(d['length']===0x0)return c;const f=new Set(b['map'](i=>i['sourceObject']+'→'+i['targetObject'])),g=new Map();for(const i of b){if(i['fieldName']){const j=i['sourceObject']+'#'+i['fieldName'];!g['has'](j)&&g['set'](j,new Set()),g['get'](j)['add'](i['targetObject']);}}const h=new Map();for(const k of d){const l=shortTypeName(k['objectType']);if(!h['has'](l))h['set'](l,[]);h['get'](l)['push']({'address':k['objectAddress'],'name':k['objectName']});}for(const [m,n]of EXPECTED_RELATIONSHIPS){const o=h['get'](m);if(!o||o['length']===0x0)continue;for(const p of o){for(const q of n){const r=h['get'](q['targetType']);if(!r||r['length']===0x0)continue;const s=p['address']+'#'+q['fieldName'],t=g['get'](s),u=t!==undefined&&t['size']>0x0;if(u)continue;const v=r['find'](w=>w['address']!==p['address']&&!f['has'](p['address']+'→'+w['address'])&&!t?.['has'](w['address']));if(!v)continue;c['push']({'sourceObject':p['address'],'targetObject':v['address'],'edgeSource':'potential','relationshipType':q['relationshipType'],'fieldName':q['fieldName'],'depth':0x0,'verified':![],'weight':0.6,'direction':'outbound','metadata':{'reason':'expected_relationship_missing','expected_target_type':q['targetType'],'source_object_name':p['name'],'representative':!![],'alternative_target_count':r['length']-0x1}});}}}return c;}['resolveConflicts'](a){const b=new Map();for(const d of a){if(!d['sourceObject']||!d['targetObject'])continue;const e=d['sourceObject']+'→'+d['targetObject']+':'+d['relationshipType'],f=b['get'](e)??[];f['push'](d),b['set'](e,f);}const c=[];for(const g of b['values']()){if(g['length']===0x1){c['push'](g[0x0]);continue;}const h=l=>{let m=0x0;if(l['edgeSource']==='internal')m+=0x64;if(l['edgeSource']==='registrar')m+=0x32;if(l['verified'])m+=0xa;return m+=(l['weight']??0.5)*0xa,m;};g['sort']((l,m)=>h(m)-h(l));const j=g[0x0],k={...j['metadata']??{}};for(let l=0x1;l<g['length'];l++){k['alt_'+g[l]['edgeSource']]=g[l]['metadata']??{};}c['push']({...j,'metadata':k});}return c;}['buildNodes'](a,b,c){const d=new Map(),e=f=>{if(!d['has'](f)){const g=b['get'](f),h=g?.['query_name'],i=h&&h!==f?h:null,j=f['startsWith']('draft:');d['set'](f,{'address':f,'objectType':g?.['type']??null,'objectName':i,'role':null,'isCore':f===c,'isTemplate':j});}return d['get'](f);};for(const f of a){const g=e(f['sourceObject']),h=e(f['targetObject']);f['edgeSource']==='internal'&&f['relationshipType']==='bind'&&(g['isCore']&&(h['role']='dependency')),f['edgeSource']==='potential'&&(h['role']='reference');}return Array['from'](d['values']());}}export async function buildGraph(a,b){const c=new GraphBuilder(b);return c['buildRelationshipGraph'](a);}