@wowok/agent-mcp 2.6.1 → 2.6.4

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 (246) hide show
  1. package/dist/customer/customer-advice.d.ts +31 -0
  2. package/dist/customer/customer-advice.js +129 -0
  3. package/dist/customer/index.d.ts +2 -0
  4. package/dist/customer/index.js +2 -0
  5. package/dist/customer/info-puzzle.d.ts +9 -2
  6. package/dist/customer/info-puzzle.js +34 -7
  7. package/dist/customer/order-monitor.d.ts +2 -0
  8. package/dist/customer/order-monitor.js +3 -2
  9. package/dist/customer/post-purchase.d.ts +2 -0
  10. package/dist/customer/post-purchase.js +6 -5
  11. package/dist/customer/preorder-compare.d.ts +24 -0
  12. package/dist/customer/preorder-compare.js +34 -0
  13. package/dist/customer/reminder-system.d.ts +2 -0
  14. package/dist/customer/reminder-system.js +2 -1
  15. package/dist/customer/risk-assessment.js +30 -7
  16. package/dist/customer/types.d.ts +7 -0
  17. package/dist/examples/arbitration-dispute-create.json +41 -0
  18. package/dist/examples/arbitration-vote-weighted.json +35 -0
  19. package/dist/examples/arbitration-voting-guard-add.json +38 -0
  20. package/dist/examples/demand-present-service.json +33 -0
  21. package/dist/examples/gen-passport-verify-guard.json +48 -0
  22. package/dist/examples/guard-template-balance-check.json +59 -0
  23. package/dist/examples/guard-template-time-lock.json +60 -0
  24. package/dist/examples/insurance-guard-claim-timelock.json +75 -0
  25. package/dist/examples/insurance-guard-withdraw-allocation.json +96 -0
  26. package/dist/examples/insurance-machine-create-publish.json +75 -0
  27. package/dist/examples/insurance-service-allocators-publish.json +56 -0
  28. package/dist/examples/machine-multisig-threshold.json +86 -0
  29. package/dist/examples/machine-template-7node-rental.json +119 -0
  30. package/dist/examples/payment-scenario-bound.json +45 -0
  31. package/dist/examples/rental-ziroom-machine-create.json +149 -0
  32. package/dist/examples/rental-ziroom-permission-create.json +42 -0
  33. package/dist/examples/rental-ziroom-service-create.json +89 -0
  34. package/dist/examples/retail-adv-guard-customer-win-create.json +80 -0
  35. package/dist/examples/retail-adv-guard-messenger-proof-create.json +65 -0
  36. package/dist/examples/retail-adv-guard-reward-timeout-create.json +92 -0
  37. package/dist/examples/retail-adv-reward-guard-add.json +51 -0
  38. package/dist/examples/retail-myshop-allocation-activate.json +55 -0
  39. package/dist/examples/retail-myshop-arbitration-create.json +40 -0
  40. package/dist/examples/retail-myshop-contact-create.json +43 -0
  41. package/dist/examples/retail-myshop-order-create.json +56 -0
  42. package/dist/examples/retail-myshop-progress-operate.json +38 -0
  43. package/dist/examples/retail-myshop-reward-create.json +35 -0
  44. package/dist/examples/retail-myshop-service-create.json +88 -0
  45. package/dist/examples/service-discount-issue.json +46 -0
  46. package/dist/examples/threebody-guard-create.json +56 -0
  47. package/dist/examples/threebody-machine-create.json +72 -0
  48. package/dist/examples/threebody-permission-create.json +38 -0
  49. package/dist/examples/threebody-service-allocators.json +49 -0
  50. package/dist/examples/travel-guard-time-lock.json +69 -0
  51. package/dist/examples/travel-guard-weather-oracle.json +70 -0
  52. package/dist/examples/travel-machine-create.json +136 -0
  53. package/dist/examples/travel-repository-create.json +47 -0
  54. package/dist/examples/travel-service-create.json +102 -0
  55. package/dist/examples/travel-treasury-create.json +34 -0
  56. package/dist/examples/treasury-deposit.json +37 -0
  57. package/dist/examples/treasury-withdraw.json +38 -0
  58. package/dist/extensions/business-modules.d.ts +49 -0
  59. package/dist/extensions/business-modules.js +287 -0
  60. package/dist/extensions/capability-manifest.js +216 -29
  61. package/dist/extensions/constraint-registry.js +21 -19
  62. package/dist/extensions/metric-registry.js +14 -14
  63. package/dist/extensions/mode-evaluator.js +16 -16
  64. package/dist/extensions/modes.js +141 -49
  65. package/dist/extensions/registry.d.ts +16 -9
  66. package/dist/extensions/registry.js +132 -44
  67. package/dist/extensions/types.d.ts +2 -0
  68. package/dist/index.js +50 -0
  69. package/dist/knowledge/deployment-scanner.js +1 -1
  70. package/dist/knowledge/fund-layer.d.ts +138 -0
  71. package/dist/knowledge/fund-layer.js +969 -0
  72. package/dist/knowledge/guard-render.d.ts +57 -0
  73. package/dist/knowledge/guard-render.js +700 -0
  74. package/dist/knowledge/guard-submission-prompt.d.ts +31 -0
  75. package/dist/knowledge/guard-submission-prompt.js +171 -0
  76. package/dist/knowledge/guard-templates.d.ts +10 -0
  77. package/dist/knowledge/guard-templates.js +50 -0
  78. package/dist/knowledge/index.d.ts +2 -2
  79. package/dist/knowledge/index.js +2 -2
  80. package/dist/knowledge/machine-ledger.js +1 -1
  81. package/dist/knowledge/machine-render.d.ts +41 -0
  82. package/dist/knowledge/machine-render.js +565 -0
  83. package/dist/knowledge/machine-risk.js +4 -1
  84. package/dist/knowledge/machine-templates.js +4 -4
  85. package/dist/knowledge/progress-context.js +1 -1
  86. package/dist/knowledge/progress-ledger.js +3 -3
  87. package/dist/knowledge/progress-templates.js +1 -1
  88. package/dist/knowledge/progress-translation.js +1 -1
  89. package/dist/knowledge/reward-confirm.js +2 -2
  90. package/dist/knowledge/reward-puzzle.js +1 -1
  91. package/dist/knowledge/reward-risk.js +9 -9
  92. package/dist/knowledge/reward-templates.js +2 -2
  93. package/dist/knowledge/safety-rules.d.ts +83 -1
  94. package/dist/knowledge/safety-rules.js +166 -2
  95. package/dist/knowledge/scenario-modes.d.ts +1 -1
  96. package/dist/knowledge/scenario-modes.js +13 -11
  97. package/dist/knowledge/service-confirm.d.ts +1 -1
  98. package/dist/knowledge/service-confirm.js +3 -3
  99. package/dist/knowledge/service-context.js +1 -1
  100. package/dist/knowledge/service-ledger.js +1 -1
  101. package/dist/knowledge/service-risk.d.ts +1 -1
  102. package/dist/knowledge/service-risk.js +3 -3
  103. package/dist/knowledge/service-templates.js +2 -2
  104. package/dist/knowledge/service-translation.d.ts +1 -1
  105. package/dist/knowledge/service-translation.js +7 -7
  106. package/dist/knowledge/template-registry.d.ts +48 -0
  107. package/dist/knowledge/template-registry.js +341 -0
  108. package/dist/knowledge/tool-constraints.js +6 -6
  109. package/dist/knowledge/tools-reference.js +11 -8
  110. package/dist/participation/merchant-interest.d.ts +32 -0
  111. package/dist/participation/merchant-interest.js +100 -0
  112. package/dist/participation/radar-core.d.ts +104 -0
  113. package/dist/participation/radar-core.js +269 -0
  114. package/dist/project/context-assembly.js +8 -0
  115. package/dist/project/deployment-bridge.js +6 -5
  116. package/dist/project/deployment-doc.js +5 -5
  117. package/dist/project/edit-planner.d.ts +123 -0
  118. package/dist/project/edit-planner.js +1342 -0
  119. package/dist/project/evaluation.d.ts +36 -0
  120. package/dist/project/evaluation.js +734 -68
  121. package/dist/project/game-theory.d.ts +43 -0
  122. package/dist/project/game-theory.js +177 -0
  123. package/dist/project/graph-builder.js +7 -1
  124. package/dist/project/handlers.d.ts +137 -2
  125. package/dist/project/handlers.js +423 -51
  126. package/dist/project/intent-analyzer.d.ts +71 -0
  127. package/dist/project/intent-analyzer.js +149 -0
  128. package/dist/project/machine-nodes.d.ts +2 -0
  129. package/dist/project/machine-nodes.js +36 -0
  130. package/dist/project/merchant-guide.d.ts +165 -0
  131. package/dist/project/merchant-guide.js +264 -0
  132. package/dist/project/mode-actions.d.ts +199 -0
  133. package/dist/project/mode-actions.js +309 -0
  134. package/dist/project/participation-radar.d.ts +18 -0
  135. package/dist/project/participation-radar.js +428 -0
  136. package/dist/project/pipeline-actions.d.ts +101 -0
  137. package/dist/project/pipeline-actions.js +109 -0
  138. package/dist/project/semantic-graph.d.ts +95 -0
  139. package/dist/project/semantic-graph.js +245 -0
  140. package/dist/project/stage-gate.js +4 -4
  141. package/dist/schema/call/allocation.d.ts +11 -11
  142. package/dist/schema/call/allocation.js +13 -3
  143. package/dist/schema/call/arbitration.d.ts +21 -21
  144. package/dist/schema/call/arbitration.js +30 -9
  145. package/dist/schema/call/base.d.ts +2 -2
  146. package/dist/schema/call/base.js +1 -1
  147. package/dist/schema/call/bridge.d.ts +127 -127
  148. package/dist/schema/call/bridge.js +12 -12
  149. package/dist/schema/call/contact.d.ts +3 -3
  150. package/dist/schema/call/contact.js +2 -2
  151. package/dist/schema/call/demand.d.ts +3 -3
  152. package/dist/schema/call/demand.js +2 -2
  153. package/dist/schema/call/guard.d.ts +11 -11
  154. package/dist/schema/call/guard.js +2 -2
  155. package/dist/schema/call/machine.d.ts +2072 -679
  156. package/dist/schema/call/machine.js +51 -5
  157. package/dist/schema/call/order.d.ts +7 -7
  158. package/dist/schema/call/order.js +3 -6
  159. package/dist/schema/call/payment.d.ts +3 -3
  160. package/dist/schema/call/permission.d.ts +3 -3
  161. package/dist/schema/call/permission.js +2 -2
  162. package/dist/schema/call/personal.d.ts +337 -3
  163. package/dist/schema/call/personal.js +10 -0
  164. package/dist/schema/call/progress.d.ts +177 -9
  165. package/dist/schema/call/progress.js +7 -3
  166. package/dist/schema/call/proof.d.ts +6 -6
  167. package/dist/schema/call/repository.d.ts +3 -3
  168. package/dist/schema/call/repository.js +2 -2
  169. package/dist/schema/call/reward.d.ts +57 -57
  170. package/dist/schema/call/reward.js +3 -3
  171. package/dist/schema/call/semantic.js +48 -2
  172. package/dist/schema/call/service.d.ts +285 -113
  173. package/dist/schema/call/service.js +92 -28
  174. package/dist/schema/call/treasury.d.ts +57 -57
  175. package/dist/schema/call/treasury.js +3 -3
  176. package/dist/schema/common/index.d.ts +2 -0
  177. package/dist/schema/common/index.js +46 -10
  178. package/dist/schema/local/index.js +5 -1
  179. package/dist/schema/messenger/index.js +4 -1
  180. package/dist/schema/operations.d.ts +1318 -317
  181. package/dist/schema/operations.js +76 -7
  182. package/dist/schema/project/index.d.ts +5662 -164
  183. package/dist/schema/project/index.js +1136 -5
  184. package/dist/schema/query/index.d.ts +580 -19
  185. package/dist/schema/query/index.js +88 -36
  186. package/dist/schema/schema-query/index.d.ts +59 -3
  187. package/dist/schema/schema-query/index.js +45 -6
  188. package/dist/schema/trust/index.d.ts +1012 -6
  189. package/dist/schema/trust/index.js +212 -11
  190. package/dist/schema/utils/node-parser.js +13 -0
  191. package/dist/schema/utils/object-type-utils.d.ts +12 -0
  192. package/dist/schema/utils/object-type-utils.js +35 -0
  193. package/dist/schema/utils/permission-machine-check.d.ts +49 -0
  194. package/dist/schema/utils/permission-machine-check.js +121 -0
  195. package/dist/schema/utils/skills-recommendation.d.ts +2 -0
  196. package/dist/schema/utils/skills-recommendation.js +77 -0
  197. package/dist/schema-query/index.d.ts +17 -1
  198. package/dist/schema-query/index.js +359 -3
  199. package/dist/schemas/account_operation.schema.json +1 -1
  200. package/dist/schemas/bridge_operation.schema.json +14 -7
  201. package/dist/schemas/guard2file.schema.json +2 -0
  202. package/dist/schemas/index.json +1 -1
  203. package/dist/schemas/machineNode2file.schema.json +2 -0
  204. package/dist/schemas/messenger_operation.schema.json +1 -1
  205. package/dist/schemas/onchain_events.output.json +1 -1
  206. package/dist/schemas/onchain_operations.output.json +2820 -0
  207. package/dist/schemas/onchain_operations.schema.json +255 -65
  208. package/dist/schemas/onchain_operations_allocation.schema.json +7 -6
  209. package/dist/schemas/onchain_operations_arbitration.schema.json +14 -10
  210. package/dist/schemas/onchain_operations_contact.schema.json +4 -3
  211. package/dist/schemas/onchain_operations_demand.schema.json +4 -3
  212. package/dist/schemas/onchain_operations_gen_passport.schema.json +4 -2
  213. package/dist/schemas/onchain_operations_gen_proof.schema.json +2 -0
  214. package/dist/schemas/onchain_operations_guard.schema.json +579 -1
  215. package/dist/schemas/onchain_operations_machine.schema.json +5 -4
  216. package/dist/schemas/onchain_operations_order.schema.json +7 -6
  217. package/dist/schemas/onchain_operations_payment.schema.json +2 -1
  218. package/dist/schemas/onchain_operations_permission.schema.json +3 -2
  219. package/dist/schemas/onchain_operations_personal.schema.json +37 -0
  220. package/dist/schemas/onchain_operations_progress.schema.json +91 -4
  221. package/dist/schemas/onchain_operations_proof.schema.json +2 -1
  222. package/dist/schemas/onchain_operations_repository.schema.json +4 -3
  223. package/dist/schemas/onchain_operations_reward.schema.json +7 -6
  224. package/dist/schemas/onchain_operations_service.schema.json +80 -19
  225. package/dist/schemas/onchain_operations_treasury.schema.json +5 -4
  226. package/dist/schemas/onchain_table_data.output.json +1 -1
  227. package/dist/schemas/onchain_table_data.schema.json +10 -9
  228. package/dist/schemas/project_operation.output.json +3318 -57
  229. package/dist/schemas/project_operation.schema.json +728 -4
  230. package/dist/schemas/query_toolkit.output.json +16 -16
  231. package/dist/schemas/query_toolkit.schema.json +40 -3
  232. package/dist/schemas/schema_query.output.json +65 -2
  233. package/dist/schemas/schema_query.schema.json +31 -5
  234. package/dist/schemas/trust_score.output.json +392 -1
  235. package/dist/schemas/trust_score.schema.json +275 -1
  236. package/dist/schemas/wowok_buildin_info.output.json +81 -8
  237. package/dist/schemas/wowok_buildin_info.schema.json +46 -2
  238. package/dist/tools/handlers/onchain.js +636 -6
  239. package/dist/tools/handlers/project.js +71 -2
  240. package/dist/tools/handlers/query.js +117 -2
  241. package/dist/tools/handlers/schema-query.js +65 -1
  242. package/dist/tools/handlers/trust.js +192 -6
  243. package/dist/tools/index.d.ts +8 -0
  244. package/dist/tools/index.js +229 -15
  245. package/dist/tools/wrap.js +194 -15
  246. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { IndustryModeRegistry } from "../extensions/registry.js";
2
+ import { collectPermissionIndexes, checkPermissionAuthorization, } from "../schema/utils/permission-machine-check.js";
2
3
  const CRITICAL_BINDINGS = [
3
4
  { sourceType: "Service", targetType: "Machine", fieldName: "machine", critical: true },
4
5
  { sourceType: "Service", targetType: "Permission", fieldName: "permission", critical: true },
@@ -21,7 +22,7 @@ const MERCHANT_REQUIRED_ITEMS = [
21
22
  { id: "R11", objectType: "Repository", fieldName: "repositories", required: false, description: "Documentation — published data" },
22
23
  { id: "R12", objectType: "Demand", fieldName: "", required: false, description: "Market discovery — demand signals" },
23
24
  ];
24
- function resolveRequiredItems(industry, compensationFundBalance = 0) {
25
+ function resolveRequiredItems(industry, compensationFundBalance = 0, hasAllocationEscrow = false) {
25
26
  let result = MERCHANT_REQUIRED_ITEMS;
26
27
  if (industry && industry !== "general") {
27
28
  let mode;
@@ -42,6 +43,14 @@ function resolveRequiredItems(industry, compensationFundBalance = 0) {
42
43
  }
43
44
  }
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
+ }
45
54
  if (compensationFundBalance > 0) {
46
55
  result = result.map(item => item.id === "R7" ? { ...item, required: true } : item);
47
56
  }
@@ -75,6 +84,16 @@ function shortTypeName(objectType) {
75
84
  }
76
85
  return shortName;
77
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
+ }
78
97
  function parseCacheData(cached) {
79
98
  if (!cached)
80
99
  return null;
@@ -130,6 +149,26 @@ export function getMachineNodeCount(data) {
130
149
  }
131
150
  return 0;
132
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
+ }
133
172
  function getBalanceValue(data, field) {
134
173
  if (!data)
135
174
  return 0;
@@ -192,7 +231,7 @@ function getMaxSalePrice(data) {
192
231
  }
193
232
  return max;
194
233
  }
195
- function detectCircularRefs(edges) {
234
+ function detectCircularRefs(edges, objectTypeMap) {
196
235
  const adj = new Map();
197
236
  for (const e of edges) {
198
237
  if (e.edgeSource === "potential")
@@ -239,12 +278,45 @@ function detectCircularRefs(edges) {
239
278
  else if (recursionStack.has(neighbor)) {
240
279
  const cycleStart = path.indexOf(neighbor);
241
280
  const cycle = path.slice(cycleStart).concat(neighbor);
242
- cycles.push(cycle.join("→"));
281
+ if (!isWoWokNormalFundCycle(cycle, objectTypeMap)) {
282
+ cycles.push(cycle.join("→"));
283
+ }
243
284
  }
244
285
  }
245
286
  }
246
287
  return cycles;
247
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
+ }
248
320
  function adjustWeightsForPerspective(criterionScores, perspective) {
249
321
  if (perspective === "consumer") {
250
322
  return criterionScores.map(c => {
@@ -276,6 +348,43 @@ function normalizeWeights(criterionScores) {
276
348
  return criterionScores;
277
349
  return criterionScores.map(c => ({ ...c, weight: c.weight / total }));
278
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
+ }
279
388
  function buildBindingIndex(edges) {
280
389
  const idx = new Map();
281
390
  for (const e of edges) {
@@ -317,13 +426,7 @@ function evaluateIndustryPattern(project, objects, objectCache, edges) {
317
426
  }
318
427
  if (!mode)
319
428
  return result;
320
- const byType = new Map();
321
- for (const obj of objects) {
322
- const t = shortTypeName(obj.objectType);
323
- if (!byType.has(t))
324
- byType.set(t, []);
325
- byType.get(t).push(obj);
326
- }
429
+ const byType = groupByType(objects);
327
430
  const bindingIndex = buildBindingIndex(edges);
328
431
  let matchCount = 0;
329
432
  let totalChecks = 0;
@@ -334,7 +437,7 @@ function evaluateIndustryPattern(project, objects, objectCache, edges) {
334
437
  if (machines.length > 0) {
335
438
  const machineObj = machines[0];
336
439
  const cached = parseCacheData(objectCache.get(machineObj.objectAddress));
337
- const nodeCount = getNumberField(cached, "node_count") || countArrayField(cached ?? {}, "nodes");
440
+ const nodeCount = getMachineNodeCount(cached);
338
441
  if (nodeCount > 0 && nodeCount >= expectedNodes.length) {
339
442
  matchCount++;
340
443
  result.strengths.push(`Industry pattern match: Machine has ${nodeCount} nodes, covering "${industryName}" mode's ${expectedNodes.length} expected node(s)`);
@@ -444,19 +547,35 @@ function evaluateIndustryPattern(project, objects, objectCache, edges) {
444
547
  deduction: 0,
445
548
  });
446
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
+ }
447
572
  return result;
448
573
  }
449
574
  function evaluateRisk(input) {
450
575
  const findings = [];
451
576
  const strengths = [];
452
577
  const { objects, edges, objectCache, project } = input;
453
- const byType = new Map();
454
- for (const obj of objects) {
455
- const t = shortTypeName(obj.objectType);
456
- if (!byType.has(t))
457
- byType.set(t, []);
458
- byType.get(t).push(obj);
459
- }
578
+ const byType = groupByType(objects);
460
579
  const services = byType.get("Service") ?? [];
461
580
  const bindingIndex = buildBindingIndex(edges);
462
581
  let structuralScore = 100;
@@ -499,8 +618,13 @@ function evaluateRisk(input) {
499
618
  structuralScore = clampScore(structuralScore);
500
619
  let fundScore = 100;
501
620
  const treasuries = byType.get("Treasury") ?? [];
621
+ const allocations = byType.get("Allocation") ?? [];
502
622
  const serviceData = serviceObj ? parseCacheData(objectCache.get(serviceObj.objectAddress)) : null;
503
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;
504
628
  let industryRequiresFund = true;
505
629
  if (project.industry && project.industry !== "general") {
506
630
  try {
@@ -512,7 +636,17 @@ function evaluateRisk(input) {
512
636
  catch { }
513
637
  }
514
638
  if (treasuries.length === 0 && compensationBalance === 0) {
515
- if (industryRequiresFund) {
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) {
516
650
  fundScore -= 30;
517
651
  findings.push({
518
652
  criterion: "fund_safety",
@@ -539,13 +673,23 @@ function evaluateRisk(input) {
539
673
  strengths.push(`Service.compensation_fund has ${compensationBalance} units — inline refund fund active`);
540
674
  const maxSalePrice = getMaxSalePrice(serviceData);
541
675
  if (maxSalePrice > 0) {
542
- const requiredThreshold = 5 * maxSalePrice;
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;
543
687
  if (compensationBalance < requiredThreshold) {
544
688
  fundScore -= 10;
545
689
  findings.push({
546
690
  criterion: "fund_safety",
547
691
  severity: "warning",
548
- message: `Service.compensation_fund balance (${compensationBalance}) is less than 5× 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.`,
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}×)`,
549
693
  deduction: -10,
550
694
  });
551
695
  }
@@ -553,7 +697,7 @@ function evaluateRisk(input) {
553
697
  findings.push({
554
698
  criterion: "fund_safety",
555
699
  severity: "info",
556
- message: `Service.compensation_fund balance (${compensationBalance}) covers 5× the max order amount (${maxSalePrice}). Fund is sufficient for refund protection.`,
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}×)`,
557
701
  deduction: 0,
558
702
  });
559
703
  }
@@ -632,6 +776,160 @@ function evaluateRisk(input) {
632
776
  });
633
777
  }
634
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
+ }
635
933
  governanceScore = clampScore(governanceScore);
636
934
  let coherenceScore = 100;
637
935
  const objectAddresses = new Set();
@@ -661,7 +959,13 @@ function evaluateRisk(input) {
661
959
  deduction,
662
960
  });
663
961
  }
664
- const cycles = detectCircularRefs(edges);
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);
665
969
  if (cycles.length > 0) {
666
970
  coherenceScore -= 15;
667
971
  findings.push({
@@ -675,15 +979,91 @@ function evaluateRisk(input) {
675
979
  strengths.push("Graph is coherent — no dangling refs or cycles");
676
980
  }
677
981
  coherenceScore = clampScore(coherenceScore);
678
- let criterionScores = [
679
- { name: "structural_risk", score: structuralScore, weight: 0.25, rationale: `${CRITICAL_BINDINGS.filter(b => b.sourceType === "Service").length} expected Service bindings checked` },
680
- { name: "fund_safety", score: fundScore, weight: 0.2, rationale: `Treasury + compensation_fund coverage` },
681
- { name: "operational_risk", score: operationalScore, weight: 0.2, rationale: `Service state + arbitration coverage` },
682
- { name: "governance_risk", score: governanceScore, weight: 0.15, rationale: `Permission + UM presence` },
683
- { name: "graph_coherence", score: coherenceScore, weight: 0.2, rationale: `${danglingCount} dangling + ${cycles.length} circular refs` },
684
- ];
685
- criterionScores = normalizeWeights(adjustWeightsForPerspective(criterionScores, project.perspective));
686
- const overall = clampScore(criterionScores.reduce((sum, c) => sum + c.score * c.weight, 0));
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);
687
1067
  const criticalCount = findings.filter(f => f.severity === "critical").length;
688
1068
  const summary = criticalCount > 0
689
1069
  ? `HIGH RISK: ${criticalCount} critical issue(s). ${findings.length} total findings.`
@@ -703,13 +1083,7 @@ function evaluateTrust(input) {
703
1083
  const findings = [];
704
1084
  const strengths = [];
705
1085
  const { objects, edges, objectCache, reputation, project } = input;
706
- const byType = new Map();
707
- for (const obj of objects) {
708
- const t = shortTypeName(obj.objectType);
709
- if (!byType.has(t))
710
- byType.set(t, []);
711
- byType.get(t).push(obj);
712
- }
1086
+ const byType = groupByType(objects);
713
1087
  const services = byType.get("Service") ?? [];
714
1088
  let reputationScore = 50;
715
1089
  if (reputation && reputation.size > 0 && services[0]) {
@@ -923,15 +1297,13 @@ function evaluateTrust(input) {
923
1297
  });
924
1298
  }
925
1299
  diligenceScore = clampScore(diligenceScore);
926
- let criterionScores = [
927
- { name: "reputation", score: reputationScore, weight: 0.25, rationale: `Registrar likes/dislikes + affiliations` },
928
- { name: "arbitration_coverage", score: arbitrationScore, weight: 0.2, rationale: `Dispute resolution availability` },
929
- { name: "guard_quality", score: guardScore, weight: 0.2, rationale: `Validation rules + buy_guard binding` },
930
- { name: "transparency", score: transparencyScore, weight: 0.15, rationale: `Description + Repository + Contact presence` },
931
- { name: "consumer_diligence", score: diligenceScore, weight: 0.2, rationale: `${diligencePassed.length}/${CONSUMER_DUE_DILIGENCE.length} E-checks passed` },
932
- ];
933
- criterionScores = normalizeWeights(adjustWeightsForPerspective(criterionScores, project.perspective));
934
- const overall = clampScore(criterionScores.reduce((sum, c) => sum + c.score * c.weight, 0));
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);
935
1307
  const summary = overall >= 70
936
1308
  ? `Trusted project (score ${overall}/100). ${strengths.length} strength(s).`
937
1309
  : `Limited trust signals (score ${overall}/100). ${findings.length} finding(s).`;
@@ -950,13 +1322,7 @@ function evaluateCompleteness(input) {
950
1322
  const findings = [];
951
1323
  const strengths = [];
952
1324
  const { objects, edges, objectCache, project } = input;
953
- const byType = new Map();
954
- for (const obj of objects) {
955
- const t = shortTypeName(obj.objectType);
956
- if (!byType.has(t))
957
- byType.set(t, []);
958
- byType.get(t).push(obj);
959
- }
1325
+ const byType = groupByType(objects);
960
1326
  const services = byType.get("Service") ?? [];
961
1327
  const bindingIndex = buildBindingIndex(edges);
962
1328
  const svcObjForRequiredItems = services[0];
@@ -964,7 +1330,12 @@ function evaluateCompleteness(input) {
964
1330
  ? parseCacheData(objectCache.get(svcObjForRequiredItems.objectAddress))
965
1331
  : null;
966
1332
  const compensationBalanceForItems = getBalanceValue(svcDataForRequiredItems, "compensation_fund");
967
- const requiredItems = resolveRequiredItems(project.industry ?? undefined, compensationBalanceForItems);
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);
968
1339
  const requiredCount = requiredItems.filter(r => r.required).length;
969
1340
  const optionalItems = requiredItems.filter(r => !r.required);
970
1341
  let requiredMet = 0;
@@ -1077,7 +1448,7 @@ function evaluateCompleteness(input) {
1077
1448
  for (const m of machines) {
1078
1449
  const data = parseCacheData(objectCache.get(m.objectAddress));
1079
1450
  if (data) {
1080
- const nodeCount = getNumberField(data, "node_count") || countArrayField(data, "nodes");
1451
+ const nodeCount = getMachineNodeCount(data);
1081
1452
  if (nodeCount > 0) {
1082
1453
  strengths.push(`Machine has ${nodeCount} node(s)`);
1083
1454
  }
@@ -1199,14 +1570,12 @@ function evaluateCompleteness(input) {
1199
1570
  readinessScore = 0;
1200
1571
  }
1201
1572
  readinessScore = clampScore(readinessScore);
1202
- let criterionScores = [
1203
- { name: "object_coverage", score: coverageScore, weight: 0.3, rationale: `R1-R8: ${requiredMet}/${requiredCount} required, R9-R12: ${optionalMet}/${optionalItems.length} optional` },
1204
- { name: "binding_completeness", score: bindingScore, weight: 0.25, rationale: `Service critical bindings checked` },
1205
- { name: "workflow_rationality", score: workflowScore, weight: 0.2, rationale: `Machine nodes + dangling edges` },
1206
- { name: "deployment_readiness", score: readinessScore, weight: 0.25, rationale: `Service publishable state` },
1207
- ];
1208
- criterionScores = normalizeWeights(adjustWeightsForPerspective(criterionScores, project.perspective));
1209
- const overall = clampScore(criterionScores.reduce((sum, c) => sum + c.score * c.weight, 0));
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);
1210
1579
  const criticalCount = findings.filter(f => f.severity === "critical").length;
1211
1580
  const summary = criticalCount > 0
1212
1581
  ? `Incomplete: ${criticalCount} critical gap(s). Not ready for deployment.`
@@ -1227,16 +1596,313 @@ function evaluateCompleteness(input) {
1227
1596
  evaluatedAt: Date.now(),
1228
1597
  };
1229
1598
  }
1230
- function evaluateWorthBuyingStub(_input, llmPrompt) {
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.";
1231
1895
  return {
1232
1896
  evaluationType: "worth_buying",
1233
1897
  score: 0,
1234
- summary: "Requires LLM evaluation — semantic prompt assembled. Call save_evaluation with the LLM result.",
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.",
1235
1901
  criterionScores: [],
1236
1902
  findings: [],
1237
1903
  strengths: [],
1238
1904
  needsLlm: true,
1239
- llmPrompt,
1905
+ llmPrompt: enrichedPrompt,
1240
1906
  evaluatedAt: Date.now(),
1241
1907
  };
1242
1908
  }