@wowok/agent-mcp 2.7.7 → 2.7.8

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 (239) hide show
  1. package/dist/customer/index.d.ts +3 -4
  2. package/dist/customer/index.js +1 -1
  3. package/dist/customer/info-puzzle.js +1 -1
  4. package/dist/customer/order-monitor.d.ts +0 -9
  5. package/dist/customer/order-monitor.js +1 -1
  6. package/dist/customer/order-strategy.d.ts +0 -19
  7. package/dist/customer/order-strategy.js +1 -1
  8. package/dist/customer/reminder-system.d.ts +0 -5
  9. package/dist/customer/reminder-system.js +1 -1
  10. package/dist/evaluation/game-strategy.js +1 -1
  11. package/dist/evaluation/injection.d.ts +6 -0
  12. package/dist/evaluation/injection.js +1 -0
  13. package/dist/evaluation/node-game.js +1 -1
  14. package/dist/examples/machine-multisig-threshold.json +1 -0
  15. package/dist/harness/recover.js +1 -1
  16. package/dist/harness/types.d.ts +1 -1
  17. package/dist/harness/verify.js +1 -1
  18. package/dist/intent/enrich.js +1 -1
  19. package/dist/intent/matcher.js +1 -1
  20. package/dist/intent/types.d.ts +1 -1
  21. package/dist/intent/types.js +1 -1
  22. package/dist/knowledge/arbitration-ledger.js +1 -1
  23. package/dist/knowledge/contract-invariants.d.ts +53 -0
  24. package/dist/knowledge/contract-invariants.js +1 -0
  25. package/dist/knowledge/deployment-scanner.js +1 -1
  26. package/dist/knowledge/dynamic-pricing.d.ts +0 -2
  27. package/dist/knowledge/dynamic-pricing.js +1 -1
  28. package/dist/knowledge/event-semantics.d.ts +20 -0
  29. package/dist/knowledge/event-semantics.js +1 -0
  30. package/dist/knowledge/examples-scanner-cli.js +1 -1
  31. package/dist/knowledge/examples-scanner.js +1 -1
  32. package/dist/knowledge/glossary.js +1 -1
  33. package/dist/knowledge/guard-submission-prompt.js +1 -1
  34. package/dist/knowledge/immutability.d.ts +11 -0
  35. package/dist/knowledge/immutability.js +1 -0
  36. package/dist/knowledge/index.d.ts +12 -6
  37. package/dist/knowledge/index.js +1 -1
  38. package/dist/knowledge/industry-registry.js +1 -1
  39. package/dist/knowledge/intent-metrics.d.ts +1 -1
  40. package/dist/knowledge/jsonrpc-enum.d.ts +37 -0
  41. package/dist/knowledge/jsonrpc-enum.js +1 -0
  42. package/dist/knowledge/machine-confirm.js +1 -1
  43. package/dist/knowledge/machine-risk.js +1 -1
  44. package/dist/knowledge/machine-topology.d.ts +11 -0
  45. package/dist/knowledge/machine-topology.js +1 -1
  46. package/dist/knowledge/machine-translation.js +1 -1
  47. package/dist/knowledge/market-metrics.d.ts +11 -0
  48. package/dist/knowledge/market-metrics.js +1 -1
  49. package/dist/knowledge/mcp-schema-audit-cli.js +1 -1
  50. package/dist/knowledge/mcp-schema-audit.d.ts +1 -0
  51. package/dist/knowledge/mcp-schema-audit.js +1 -1
  52. package/dist/knowledge/messenger-guard-guidance.d.ts +17 -0
  53. package/dist/knowledge/messenger-guard-guidance.js +1 -0
  54. package/dist/knowledge/operation-dictionary.d.ts +18 -0
  55. package/dist/knowledge/operation-dictionary.js +1 -0
  56. package/dist/knowledge/service-ledger.js +1 -1
  57. package/dist/knowledge/service-risk.js +1 -1
  58. package/dist/knowledge/service-translation.js +1 -1
  59. package/dist/knowledge/supply-chain.d.ts +24 -0
  60. package/dist/knowledge/supply-chain.js +1 -0
  61. package/dist/knowledge/template-registry.js +1 -1
  62. package/dist/knowledge/tools-reference.js +1 -1
  63. package/dist/knowledge/trust-metrics.d.ts +27 -2
  64. package/dist/knowledge/trust-metrics.js +1 -1
  65. package/dist/knowledge/workflow-guidance.d.ts +22 -1
  66. package/dist/knowledge/workflow-guidance.js +1 -1
  67. package/dist/monitor/EventStore.d.ts +78 -0
  68. package/dist/monitor/EventStore.js +1 -0
  69. package/dist/participation/radar-core.d.ts +0 -1
  70. package/dist/participation/radar-core.js +1 -1
  71. package/dist/persona/address-format.d.ts +6 -0
  72. package/dist/persona/address-format.js +1 -0
  73. package/dist/persona/analyzer.js +1 -1
  74. package/dist/persona/index.d.ts +3 -0
  75. package/dist/persona/index.js +1 -1
  76. package/dist/persona/types.d.ts +1 -1
  77. package/dist/persona/types.js +1 -1
  78. package/dist/project/business-puzzle.js +1 -1
  79. package/dist/project/edit-planner.js +1 -1
  80. package/dist/project/evaluation.js +1 -1
  81. package/dist/project/graph-builder.js +1 -1
  82. package/dist/project/handlers.d.ts +2 -18
  83. package/dist/project/handlers.js +1 -1
  84. package/dist/project/index.js +1 -1
  85. package/dist/project/machine-nodes.d.ts +23 -0
  86. package/dist/project/machine-nodes.js +1 -1
  87. package/dist/project/machine-panorama.d.ts +41 -0
  88. package/dist/project/machine-panorama.js +1 -0
  89. package/dist/project/object-panorama.d.ts +179 -0
  90. package/dist/project/object-panorama.js +1 -0
  91. package/dist/project/object-type.d.ts +1 -0
  92. package/dist/project/object-type.js +1 -0
  93. package/dist/project/participation-radar.js +1 -1
  94. package/dist/project/semantic-assembler.js +1 -1
  95. package/dist/project/service-panorama.d.ts +180 -0
  96. package/dist/project/service-panorama.js +1 -0
  97. package/dist/project/stage-gate.d.ts +0 -1
  98. package/dist/project/stage-gate.js +1 -1
  99. package/dist/project/task-tracker.d.ts +4 -0
  100. package/dist/project/task-tracker.js +1 -1
  101. package/dist/role/derivation.d.ts +19 -2
  102. package/dist/role/derivation.js +1 -1
  103. package/dist/role/index.d.ts +2 -2
  104. package/dist/role/index.js +1 -1
  105. package/dist/role/model.js +1 -1
  106. package/dist/role/resolution.d.ts +16 -0
  107. package/dist/role/resolution.js +1 -1
  108. package/dist/role/types.d.ts +1 -1
  109. package/dist/role/types.js +1 -1
  110. package/dist/safety/confirm-gate.js +1 -1
  111. package/dist/schema/call/allocation.d.ts +1 -0
  112. package/dist/schema/call/arbitration.d.ts +4 -3
  113. package/dist/schema/call/arbitration.js +1 -1
  114. package/dist/schema/call/base.d.ts +16 -0
  115. package/dist/schema/call/base.js +1 -1
  116. package/dist/schema/call/bridge.d.ts +7 -0
  117. package/dist/schema/call/contact.d.ts +1 -0
  118. package/dist/schema/call/demand.d.ts +1 -0
  119. package/dist/schema/call/guard.d.ts +3 -0
  120. package/dist/schema/call/handler.js +1 -1
  121. package/dist/schema/call/machine.d.ts +2 -0
  122. package/dist/schema/call/machine.js +1 -1
  123. package/dist/schema/call/order.d.ts +1 -0
  124. package/dist/schema/call/payment.d.ts +1 -0
  125. package/dist/schema/call/permission.d.ts +1 -0
  126. package/dist/schema/call/personal.d.ts +38 -0
  127. package/dist/schema/call/personal.js +1 -1
  128. package/dist/schema/call/progress.d.ts +1 -0
  129. package/dist/schema/call/proof.d.ts +2 -0
  130. package/dist/schema/call/repository.d.ts +5 -4
  131. package/dist/schema/call/reward.d.ts +1 -12
  132. package/dist/schema/call/reward.js +1 -1
  133. package/dist/schema/call/semantic.d.ts +3 -2
  134. package/dist/schema/call/semantic.js +1 -1
  135. package/dist/schema/call/service.d.ts +1 -0
  136. package/dist/schema/call/service.js +1 -1
  137. package/dist/schema/call/treasury.d.ts +1 -0
  138. package/dist/schema/common/index.js +1 -1
  139. package/dist/schema/evaluation/index.d.ts +146 -0
  140. package/dist/schema/evaluation/index.js +1 -1
  141. package/dist/schema/index.d.ts +1 -0
  142. package/dist/schema/index.js +1 -1
  143. package/dist/schema/intent-radar/index.d.ts +30 -3
  144. package/dist/schema/intent-radar/index.js +1 -1
  145. package/dist/schema/local/index.d.ts +9 -0
  146. package/dist/schema/local/index.js +1 -1
  147. package/dist/schema/messenger/index.d.ts +54 -0
  148. package/dist/schema/messenger/index.js +1 -1
  149. package/dist/schema/operations.d.ts +864 -8
  150. package/dist/schema/operations.js +1 -1
  151. package/dist/schema/permission/index.d.ts +17 -0
  152. package/dist/schema/permission/index.js +1 -1
  153. package/dist/schema/project/index.d.ts +6 -0
  154. package/dist/schema/project/index.js +1 -1
  155. package/dist/schema/query/index.d.ts +658 -56
  156. package/dist/schema/query/index.js +1 -1
  157. package/dist/schema/schema-version.js +1 -1
  158. package/dist/schema/trust/index.d.ts +17 -0
  159. package/dist/schema/trust/index.js +1 -1
  160. package/dist/schema/watch/index.d.ts +204 -0
  161. package/dist/schema/watch/index.js +1 -0
  162. package/dist/schema/workflow/index.d.ts +301 -0
  163. package/dist/schema/workflow/index.js +1 -1
  164. package/dist/schema-query-impl/index.js +1 -1
  165. package/dist/schemas/account_operation.output.json +5 -2
  166. package/dist/schemas/bridge_operation.output.json +5 -2
  167. package/dist/schemas/bridge_operation.schema.json +25 -9
  168. package/dist/schemas/evaluation_operation.output.json +276 -1
  169. package/dist/schemas/evaluation_operation.schema.json +307 -0
  170. package/dist/schemas/guard2file.schema.json +6 -2
  171. package/dist/schemas/index.json +13 -1
  172. package/dist/schemas/intent_radar.output.json +20 -2
  173. package/dist/schemas/intent_radar.schema.json +10 -1
  174. package/dist/schemas/local_info_operation.output.json +5 -2
  175. package/dist/schemas/local_mark_operation.output.json +5 -2
  176. package/dist/schemas/machineNode2file.schema.json +6 -2
  177. package/dist/schemas/messenger_operation.output.json +105 -2
  178. package/dist/schemas/messenger_operation.schema.json +98 -0
  179. package/dist/schemas/monitor_events.output.json +1360 -0
  180. package/dist/schemas/monitor_events.schema.json +62 -0
  181. package/dist/schemas/onchain_events.output.json +237 -14
  182. package/dist/schemas/onchain_events.schema.json +20 -0
  183. package/dist/schemas/onchain_operations.output.json +10 -5
  184. package/dist/schemas/onchain_operations.schema.json +511 -419
  185. package/dist/schemas/onchain_operations_allocation.schema.json +11 -7
  186. package/dist/schemas/onchain_operations_arbitration.schema.json +14 -9
  187. package/dist/schemas/onchain_operations_contact.schema.json +9 -5
  188. package/dist/schemas/onchain_operations_demand.schema.json +9 -5
  189. package/dist/schemas/onchain_operations_gen_passport.schema.json +6 -2
  190. package/dist/schemas/onchain_operations_gen_proof.schema.json +6 -2
  191. package/dist/schemas/onchain_operations_guard.schema.json +6 -2
  192. package/dist/schemas/onchain_operations_machine.schema.json +14 -10
  193. package/dist/schemas/onchain_operations_order.schema.json +9 -5
  194. package/dist/schemas/onchain_operations_payment.schema.json +7 -3
  195. package/dist/schemas/onchain_operations_permission.schema.json +9 -5
  196. package/dist/schemas/onchain_operations_personal.schema.json +44 -2
  197. package/dist/schemas/onchain_operations_progress.schema.json +9 -5
  198. package/dist/schemas/onchain_operations_proof.schema.json +6 -2
  199. package/dist/schemas/onchain_operations_repository.schema.json +290 -305
  200. package/dist/schemas/onchain_operations_reward.schema.json +14 -10
  201. package/dist/schemas/onchain_operations_service.schema.json +17 -13
  202. package/dist/schemas/onchain_operations_treasury.schema.json +14 -10
  203. package/dist/schemas/onchain_table_data.output.json +3750 -208
  204. package/dist/schemas/onchain_table_data.schema.json +311 -0
  205. package/dist/schemas/permission_operation.output.json +32 -0
  206. package/dist/schemas/project_operation.schema.json +14 -8
  207. package/dist/schemas/query_toolkit.output.json +405 -320
  208. package/dist/schemas/query_toolkit.schema.json +139 -1
  209. package/dist/schemas/trust_score.output.json +38 -0
  210. package/dist/schemas/trust_score.schema.json +32 -0
  211. package/dist/schemas/watch_operation.output.json +827 -0
  212. package/dist/schemas/watch_operation.schema.json +145 -0
  213. package/dist/schemas/workflow_operation.output.json +263 -5
  214. package/dist/schemas/workflow_operation.schema.json +597 -2
  215. package/dist/tools/handlers/config.js +1 -1
  216. package/dist/tools/handlers/evaluation.js +1 -1
  217. package/dist/tools/handlers/intent-radar.js +1 -1
  218. package/dist/tools/handlers/messenger.js +1 -1
  219. package/dist/tools/handlers/monitor.d.ts +2 -0
  220. package/dist/tools/handlers/monitor.js +1 -0
  221. package/dist/tools/handlers/onchain.js +1 -1
  222. package/dist/tools/handlers/permission.js +1 -1
  223. package/dist/tools/handlers/project.js +1 -1
  224. package/dist/tools/handlers/query.js +1 -1
  225. package/dist/tools/handlers/trust.d.ts +14 -0
  226. package/dist/tools/handlers/trust.js +1 -1
  227. package/dist/tools/handlers/watch.d.ts +2 -0
  228. package/dist/tools/handlers/watch.js +1 -0
  229. package/dist/tools/handlers/workflow.js +1 -1
  230. package/dist/tools/index.d.ts +2 -0
  231. package/dist/tools/index.js +1 -1
  232. package/dist/tools/shared.js +1 -1
  233. package/package.json +2 -2
  234. package/dist/customer/post-purchase.d.ts +0 -44
  235. package/dist/customer/post-purchase.js +0 -1
  236. package/dist/project/migration.d.ts +0 -22
  237. package/dist/project/migration.js +0 -1
  238. package/dist/project/rollback-policy.d.ts +0 -45
  239. package/dist/project/rollback-policy.js +0 -1
@@ -3,9 +3,8 @@ export { assembleServiceBasics, assembleWorkflowAnalysis, assembleFundSafety, as
3
3
  export { riskLevelFromScore, riskLevelLabel, riskLevelEmoji, assessRisk, passesRiskThreshold, } from "./risk-assessment.js";
4
4
  export { getIndustryRiskChecks, getIndustryNeeds, checkIndustryNeeds, assessIndustryRisks, inferIndustry, type IndustryNeedTier, type IndustryNeed, type IndustryRiskCheck, type IndustryRiskResult, } from "./industry-risks.js";
5
5
  export { getDefaultPreferences, getIndustryTemplate, inferPreferences, matchServiceToPreferences, mergePreferences, validatePreferences, SUPPORTED_INDUSTRIES, type Industry, type IndustryTemplate, type OrderHistoryEntry, type PreferenceInference, type ServiceForMatching, type PreferenceMatchResult, } from "./user-preferences.js";
6
- export { monitorOrder, sortAlerts, getCriticalAlerts, getActionableAlerts, summarizeAlerts, isBlockingAlert, alertsToReminders, type AlertSeverity, type AlertCategory, type MonitorAlert, type OrderSnapshot, type OrderHistorySnapshot, type OrderMonitorContext, type MonitorThresholds, } from "./order-monitor.js";
7
- export { recommendStrategy, detectScenarios, flowMigrationStrategy, repeatGameStrategy, rightsProtectionStrategy, type StrategyContext, type StrategyRecommendation, } from "./order-strategy.js";
8
- export { generatePostPurchaseAdvice, trackRefund, handleQualityIssue, handleMerchantUnreachable, arbitrationSupport, generateArbitrationTemplate, type PostPurchasePhase, type PostPurchaseContext, type PostPurchaseAction, } from "./post-purchase.js";
9
- export { generateReminders, sortAndCapReminders, generateMultiStageReminders, isBlocking, getBlockingReminders, summarizeReminders, topReminders, type ReminderStage, type ReminderContext, } from "./reminder-system.js";
6
+ export { monitorOrder, sortAlerts, type AlertSeverity, type AlertCategory, type MonitorAlert, type OrderSnapshot, type OrderHistorySnapshot, type OrderMonitorContext, type MonitorThresholds, } from "./order-monitor.js";
7
+ export { recommendStrategy, detectScenarios, type StrategyContext, type StrategyRecommendation, } from "./order-strategy.js";
8
+ export { generateReminders, sortAndCapReminders, isBlocking, getBlockingReminders, type ReminderStage, type ReminderContext, } from "./reminder-system.js";
10
9
  export { assemblePreorderAdvice, type PreorderAdviceInput, type PreorderAdvice, type ConfidenceScore, } from "./customer-advice.js";
11
10
  export { buildPreorderComparison, type PreorderCompareRow, type PreorderComparison, } from "./preorder-compare.js";
@@ -1 +1 @@
1
- export{CUSTOMER_INTELLIGENCE_VERSION,RISK_LEVELS,RISK_DIMENSION_MAX}from'./types.js';export{assembleServiceBasics,assembleWorkflowAnalysis,assembleFundSafety,assembleTrustSignals,assembleMerchantBehavior,assembleMarketContext,assembleInfoPuzzle,assembleUserMetrics,evaluateServiceNesting}from'./info-puzzle.js';export{riskLevelFromScore,riskLevelLabel,riskLevelEmoji,assessRisk,passesRiskThreshold}from'./risk-assessment.js';export{getIndustryRiskChecks,getIndustryNeeds,checkIndustryNeeds,assessIndustryRisks,inferIndustry}from'./industry-risks.js';export{getDefaultPreferences,getIndustryTemplate,inferPreferences,matchServiceToPreferences,mergePreferences,validatePreferences,SUPPORTED_INDUSTRIES}from'./user-preferences.js';export{monitorOrder,sortAlerts,getCriticalAlerts,getActionableAlerts,summarizeAlerts,isBlockingAlert,alertsToReminders}from'./order-monitor.js';export{recommendStrategy,detectScenarios,flowMigrationStrategy,repeatGameStrategy,rightsProtectionStrategy}from'./order-strategy.js';export{generatePostPurchaseAdvice,trackRefund,handleQualityIssue,handleMerchantUnreachable,arbitrationSupport,generateArbitrationTemplate}from'./post-purchase.js';export{generateReminders,sortAndCapReminders,generateMultiStageReminders,isBlocking,getBlockingReminders,summarizeReminders,topReminders}from'./reminder-system.js';export{assemblePreorderAdvice}from'./customer-advice.js';export{buildPreorderComparison}from'./preorder-compare.js';
1
+ export{CUSTOMER_INTELLIGENCE_VERSION,RISK_LEVELS,RISK_DIMENSION_MAX}from'./types.js';export{assembleServiceBasics,assembleWorkflowAnalysis,assembleFundSafety,assembleTrustSignals,assembleMerchantBehavior,assembleMarketContext,assembleInfoPuzzle,assembleUserMetrics,evaluateServiceNesting}from'./info-puzzle.js';export{riskLevelFromScore,riskLevelLabel,riskLevelEmoji,assessRisk,passesRiskThreshold}from'./risk-assessment.js';export{getIndustryRiskChecks,getIndustryNeeds,checkIndustryNeeds,assessIndustryRisks,inferIndustry}from'./industry-risks.js';export{getDefaultPreferences,getIndustryTemplate,inferPreferences,matchServiceToPreferences,mergePreferences,validatePreferences,SUPPORTED_INDUSTRIES}from'./user-preferences.js';export{monitorOrder,sortAlerts}from'./order-monitor.js';export{recommendStrategy,detectScenarios}from'./order-strategy.js';export{generateReminders,sortAndCapReminders,isBlocking,getBlockingReminders}from'./reminder-system.js';export{assemblePreorderAdvice}from'./customer-advice.js';export{buildPreorderComparison}from'./preorder-compare.js';
@@ -1 +1 @@
1
- import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';export function assembleServiceBasics(a,b,c=![]){const d=(b['sales']??[])['filter'](f=>!f['suspension']),e=d['some'](f=>f['wip_hash']&&f['wip_hash']['length']>0x0);return{'service_id':a,'name':b['name']??a,'bPublished':b['bPublished']??![],'bPaused':b['bPaused']??![],'price':b['price']??'0','price_raw':b['priceRaw']??0x0n,'token_type':b['token_type']??'0x2::wow::WOW','sales_count':d['length'],'machine_id':b['machine'],'buy_guard_id':b['buy_guard'],'customer_required_count':b['customer_required']?.['length']??0x0,'customer_required':(b['customer_required']??[])['filter'](f=>typeof f==='string'),'arbitrations_count':b['arbitrations']?.['length']??0x0,'compensation_fund_balance':b['compensation_fund']?.['balance']??0x0n,'compensation_lock_duration':b['compensation_lock_duration']??0x0,'um_id':b['um'],'has_wip':e,'wip_verified':c};}export function assembleWorkflowAnalysis(a,b,c,d){const e=[],f=[],g=[];let h=0x0,i=0x0,j=0x0,k=![],l=![],m=![];const n=/(^|_)(disputed?|refund(?:ed)?|arbitration|arb)(_|$)/i,o=/^(wonder|no_wonder|praise|complain|thumbs_up|thumbs_down|positive_review|negative_review)$/i,p=a['reduce']((w,x)=>w+(x['forwards']?.['length']??0x0),0x0);for(const w of a){n['test'](w['name']['trim']())&&(m=!![]);}for(const x of a){const y=x['forwards']??[];y['length']===0x0&&f['push'](x['name']);for(const z of y){const A=z['namedOperator'],B=z['guard'];if(A==='')B?j++:h++;else A===null||A===undefined?i++:i++;const C=(z['to']??'')['trim']()['toLowerCase']();o['test'](C)&&(l=!![]),C['includes']('milestone')&&(k=!![]);}}for(const D of a){const E=D['forwards']??[];if(E['length']>0x0&&!f['includes'](D['name'])){const F=E['every'](G=>G['namedOperator']!==''&&G['namedOperator']!==null);F&&h===0x0&&g['push'](D['name']);}}const q=(d?.['arbitrations']?.['length']??0x0)>0x0,r=d?.['compensation_fund']?.['balance']??0x0n,s=q&&r>0x0n,t=d?.['order_allocators']?.[0x0]?.['allocators']??[],u=t['some'](G=>G['surplus_to']==='order'||G['surplus_to']==='Order'),v=s||u;if(!v)e['push']('no_refund_path');if(!q)e['push']('no_arbitration_binding');if(m)e['push']('dispute_anti_pattern');if(h===0x0)e['push']('no_user_operable_path');if(g['length']>0x0)e['push']('potential_dead_ends');return{'machine_published':b,'machine_paused':c,'total_nodes':a['length'],'total_forwards':p,'user_operable_forwards':h,'provider_only_forwards':i,'guard_gated_forwards':j,'has_refund_path':v,'has_arb_refund_path':s,'has_refund_allocator':u,'has_arbitration_path':q,'has_arbitration_binding':q,'has_wonder_node':l,'has_dispute_anti_pattern':m,'has_milestone_nodes':k,'dead_end_nodes':g,'terminal_nodes':f,'risk_signals':e};}export function assembleFundSafety(a,b){const c=a['order_allocators']?.[0x0]?.['allocators']??[],d=a['compensation_fund']?.['balance']??0x0n,e=a['compensation_lock_duration']??0x0,f=c['find'](j=>{const k=j['amount'];return k?.['type']==='FixedValue'&&k['value']===b;}),g=c['some'](j=>j['surplus_to']==='order'||j['surplus_to']==='Order');let h='none';b>0x0n&&(d>0x0n&&b>d*0x3n&&(h='low'));const i=e===0x0||e>0x7;return{'has_order_allocator':c['length']>0x0,'has_refund_allocator':!!f||g,'allocator_count':c['length'],'refund_allocator_exists':g,'surplus_to_provider':c['some'](j=>j['surplus_to']!=='order'&&j['surplus_to']!=='Order'),'user_path_has_allocator':c['length']>0x0,'compensation_covers_order':d>=b,'compensation_ratio':b>0x0n?Math['min'](0x1,Number(d*0x64n/b)/0x64):0x0,'lock_duration_safe':i,'price_anomaly':h};}export function assembleTrustSignals(a,b,c,d,e,f,g){const h=b['filter'](n=>n['rating']==='like')['length'],i=b['filter'](n=>n['rating']==='dislike')['length'],j=b['filter'](n=>n['verified']||n['has_evidence'])['length'],k=b['length'],l=k>0x0?h/k:0x0,m=d!==undefined&&e!==undefined?d!==e:!![];return{'arbitration_independent':m,'arbitration_count':a['arbitrations']?.['length']??0x0,'arbitration_paused':![],'review_likes':h,'review_dislikes':i,'review_verified_count':j,'review_total':k,'like_rate':l,'trust_score':c['score'],'trust_level':c['level'],'has_contact':!!a['um'],'has_messenger':!!a['um'],'arbitration_permission_shared':f,'arbitration_permission_overlap':g};}const REPUTATION_MIN_VOTES=0x3;function toReputation(a){const b=a['likes']+a['dislikes'];return{'likes':a['likes'],'dislikes':a['dislikes'],'like_ratio':b>0x0?a['likes']/b:0x1};}function reputationRedFlags(a){if(!a)return[];const b=a['likes']+a['dislikes'];if(b>=REPUTATION_MIN_VOTES&&a['like_ratio']<0.5)return['reputation_negative'];return[];}export function assembleMerchantBehavior(a,b,c){const d=c?toReputation(c):undefined,e=reputationRedFlags(d);if(b&&b['length']>0x0){const l=b['length'],m=b['filter'](v=>v['status']==='completed')['length'],n=b['filter'](v=>v['has_dispute'])['length'],o=b['filter'](v=>v['is_repeat'])['length'],p=l>0x0?m/l:0x0,q=l>0x0?n/l:0x0,r=l>0x0?o/l:0x0,s=Math['floor'](l/0x2);let t='stable';if(l>=0x4&&s>0x0){const v=b['slice'](0x0,s)['filter'](z=>z['has_dispute'])['length'],w=b['slice'](s)['filter'](z=>z['has_dispute'])['length'],x=v/s,y=w/(l-s);if(y<x*0.85)t='improving';else{if(y>x*1.15)t='declining';}}const u=[...e];if(q>0.1)u['push']('dispute_rate_high');if(t==='declining')u['push']('declining_trend');return{'total_orders':l,'completed_rate':p,'dispute_rate':q,'refund_rate':0x0,'arb_loss_rate':0x0,'repeat_buyer_rate':r,'recent_trend':t,'red_flags':u,'reputation':d};}const f=a['filter'](z=>z['type']['includes']('Order')||z['type']['includes']('order')),g=a['filter'](z=>z['type']['includes']('Dispute')||z['type']['includes']('Arb')),h=f['length'],i=g['length'],j=h>0x0?i/h:0x0,k=[...e];if(j>0.1)k['push']('dispute_rate_high');return{'total_orders':h,'completed_rate':h>0x0?Math['max'](0x0,0x1-j):0x0,'dispute_rate':j,'refund_rate':0x0,'arb_loss_rate':0x0,'repeat_buyer_rate':0x0,'recent_trend':'stable','red_flags':k,'reputation':d};}export function assembleMarketContext(a,b){if(a['length']===0x0)return{'similar_services_count':0x0,'avg_price':0x0n,'min_price':0x0n,'max_price':0x0n,'price_percentile':0x0,'supply_demand_ratio':0x0};const c=a['map'](j=>j['price'])['sort']((j,k)=>j<k?-0x1:j>k?0x1:0x0),d=c['reduce']((j,k)=>j+k,0x0n),e=d/BigInt(c['length']),f=c[0x0],g=c[c['length']-0x1];let h=0x0;for(const j of c){if(j<b)h++;}const i=c['length']>0x0?h/c['length']:0x0;return{'similar_services_count':a['length'],'avg_price':e,'min_price':f,'max_price':g,'price_percentile':i,'supply_demand_ratio':a['length']};}export function assembleInfoPuzzle(a,b,c='evaluate'){const d=[],e=assembleServiceBasics(a,b['service'],b['wip_verified']??![]);let f,g,h;if(c==='evaluate'||c==='preorder'||c==='monitor'){b['machine_nodes']?f=assembleWorkflowAnalysis(b['machine_nodes'],b['machine_published']??![],b['machine_paused']??![],b['service']):d['push']('machine_workflow');const m=b['order_amount']??e['price_raw'];g=assembleFundSafety(b['service'],m),b['reviews']&&b['trust_score']?h=assembleTrustSignals(b['service'],b['reviews'],b['trust_score'],b['arbitration_owner'],b['service_owner']):d['push']('reviews_or_trust_score');}let i;if(c==='preorder'||c==='monitor'){if(b['events']||b['order_history'])i=assembleMerchantBehavior(b['events']??[],b['order_history'],b['merchant_reputation']);else b['merchant_reputation']?i=assembleMerchantBehavior([],undefined,b['merchant_reputation']):d['push']('merchant_behavior');}let j;(c==='evaluate'||c==='preorder')&&(b['similar_services']?j=assembleMarketContext(b['similar_services'],e['price_raw']):d['push']('market_context'));let k;b['user_metrics_config']&&b['user_metrics_config']['metrics']['length']>0x0&&(k=assembleUserMetrics(b['user_metrics_config'],b['user_metrics_context']??{}));let l=b['service_nesting'];return!l&&b['service_nesting_raw']&&(l=evaluateServiceNesting(b['service_nesting_raw'])),{'service_id':a,'service_basics':e,'workflow_analysis':f,'fund_safety':g,'trust_signals':h,'merchant_behavior':i,'market_context':j,'user_metrics':k,'service_nesting':l,'completeness':computeCompleteness(c,[e,f,g,h,i,j,k,l]),'gaps':d,'assembled_at':Date['now']()};}export function assembleUserMetrics(a,b){const c=a['adjustment_cap']??0xa,d=[],e=a['metrics']['reduce']((i,j)=>i+Math['max'](0x0,j['weight']),0x0);for(const i of a['metrics']){const j=e>0x0?Math['max'](0x0,i['weight'])/e:0x0,k=resolvePath(b,i['params']['path']??i['name']),{passed:l,score:m,observed_value:n}=evaluateMetric(i,k);d['push']({'name':i['name'],'label':i['label'],'passed':l,'score':m,'observed_value':formatObservedValue(k),'weight':j,'advice':l?i['advice_on_pass']:i['advice_on_fail']});}const f=d['reduce']((o,p)=>o+p['score']*p['weight'],0x0),g=Math['round'](f*0x64),h=Math['round']((g-0x32)/0x32*c);return{'metrics':d,'score':g,'adjustment':h,'source_file':a['source_file'],'evaluated_at':Date['now']()};}function resolvePath(a,b){if(!b)return undefined;const c=b['split']('.');let d=a;for(const e of c){if(d===null||d===undefined)return undefined;if(typeof d!=='object')return undefined;d=d[e];}return d;}function evaluateMetric(a,b){const c=a['params'];switch(a['evaluator']){case'threshold':{const d=typeof b==='number'?b:typeof b==='string'?Number(b):typeof b==='bigint'?Number(b):NaN,e=typeof c['threshold']==='number'?c['threshold']:typeof c['threshold']==='string'?Number(c['threshold']):NaN;if(isNaN(d)||isNaN(e))return{'passed':![],'score':0x0,'observed_value':b};const f=c['invert']?d<=e:d>=e,g=Math['abs'](e)*0.5||0x1,h=c['invert']?(e-d)/g+0x1:(d-e)/g+0x1,i=Math['max'](0x0,Math['min'](0x1,h));return{'passed':f,'score':i,'observed_value':b};}case'ratio':{const j=typeof b==='number'?b:typeof b==='string'?Number(b):NaN,k=c['min']??0x0,l=c['max']??0x1;if(isNaN(j))return{'passed':![],'score':0x0,'observed_value':b};const m=j>=k&&j<=l,n=l-k,o=(k+l)/0x2,q=n>0x0?Math['max'](0x0,0x1-Math['abs'](j-o)/(n/0x2)):0x1;return{'passed':m,'score':q,'observed_value':b};}case'boolean':{const r=!!b;return{'passed':r,'score':r?0x1:0x0,'observed_value':b};}case'presence':{const s=b!==undefined&&b!==null&&b!=='';return{'passed':s,'score':s?0x1:0x0,'observed_value':b};}case'regex_match':{if(typeof b!=='string'||!c['pattern'])return{'passed':![],'score':0x0,'observed_value':b};try{const t=new RegExp(c['pattern']),u=t['test'](b);return{'passed':u,'score':u?0x1:0x0,'observed_value':b};}catch{return{'passed':![],'score':0x0,'observed_value':b};}}case'custom_query':{return{'passed':![],'score':0.5,'observed_value':b};}default:return{'passed':![],'score':0x0,'observed_value':b};}}function formatObservedValue(a){if(typeof a==='string'||typeof a==='number'||typeof a==='boolean')return a;if(typeof a==='bigint')return a['toString']();if(a===undefined||a===null)return undefined;try{return JSON['stringify'](a);}catch{return String(a);}}function computeCompleteness(a,b){const c=a==='browse'?0x1:a==='evaluate'?0x4:a==='preorder'?0x6:0x5,d=b['slice'](0x0,c),e=d['filter'](f=>f!==undefined&&f!==null)['length'];return Math['min'](0x1,e/c);}export function evaluateServiceNesting(b){const c=b['depth']??0x0,d=b['maxDepth']??0x3,e=c>=d,f={'arbitrations':[],'rewards':[],'repositories':[]};let g=0x0;if(b['machine']){const v=b['machine'],w=[];let x=0x0;if(v['published'])x+=0xa;else w['push']('Machine\x20not\x20published');v['paused']&&(x+=0x28,w['push']('Machine\x20paused'));v['has_no_entry']&&(x+=0x32,w['push']('No\x20entry\x20point\x20(R-M1-01)'));v['has_no_terminal']&&(x+=0x32,w['push']('No\x20terminal\x20node\x20(R-M1-02)'));v['has_dispute_anti_pattern']&&(x+=0x3c,w['push']('Dispute\x20anti-pattern\x20(R-M1-11):\x20machine\x20illegally\x20models\x20dispute\x20flow'));const y=v['structural_issue_count']??0x0;y>0x0&&(x+=y*0xf,w['push'](y+'\x20structural\x20issue(s)\x20detected\x20(cycles/dead-ends/orphans)')),x=Math['min'](0x64,x),f['machine']={'object_id':v['object_id'],'published':v['published'],'risk_level':scoreToNestingLevel(x),'issues':w},g++;}for(const z of b['arbitrations']??[]){const A=[];let B=0x0;if(z['voting_guard_count']===0x0)B+=0x32,A['push']('No\x20voting_guard\x20configured\x20—\x20no\x20arbitrators\x20can\x20vote');else z['voting_guard_count']<=0x2?(B+=0x1e,A['push']('Few\x20arbitrators\x20(<=2)\x20—\x20limited\x20dispute\x20resolution\x20capacity')):B+=0xa;z['paused']&&(B+=0x28,A['push']('Arbitration\x20paused\x20—\x20disputes\x20cannot\x20be\x20filed')),z['fee_balance']===0x0n&&(B+=0x1e,A['push']('No\x20compensation\x20fund\x20balance\x20—\x20rulings\x20cannot\x20pay\x20out')),B=Math['min'](0x64,B),f['arbitrations']['push']({'object_id':z['object_id'],'voting_guard_count':z['voting_guard_count'],'fee_balance':z['fee_balance']['toString'](),'paused':z['paused'],'risk_level':scoreToNestingLevel(B),'issues':A}),g++;}for(const C of b['rewards']??[]){const D=[];let E=0x0;C['balance']===0x0n&&(E+=0x3c,D['push']('Reward\x20fund\x20empty\x20—\x20claims\x20will\x20fail')),C['guard_count']===0x0&&(E+=0x32,D['push']('No\x20claim_guard\x20—\x20anyone\x20could\x20claim\x20(or\x20no\x20one\x20can,\x20depending\x20on\x20default)')),C['expiration_time']&&C['expiration_time']>0x0&&C['expiration_time']<Date['now']()&&(E+=0x28,D['push']('Reward\x20expired\x20—\x20claims\x20no\x20longer\x20possible')),E=Math['min'](0x64,E),f['rewards']['push']({'object_id':C['object_id'],'balance':C['balance']['toString'](),'guard_count':C['guard_count'],'risk_level':scoreToNestingLevel(E),'issues':D}),g++;}for(const F of b['repositories']??[]){const G=[];let H=0x0;!F['has_write_guard']&&(H+=0x28,G['push']('No\x20write_guard\x20—\x20Repository\x20is\x20open\x20to\x20arbitrary\x20writes')),F['is_empty']&&(H+=0x14,G['push']('Repository\x20empty\x20—\x20no\x20historical\x20data\x20for\x20evaluation')),H=Math['min'](0x64,H),f['repositories']['push']({'object_id':F['object_id'],'risk_level':scoreToNestingLevel(H),'issues':G}),g++;}if(g===0x0)return undefined;const h=f['machine']?nestingLevelToScore(f['machine']['risk_level']):0x0,i=f['machine']?0x23:0x0,j=f['arbitrations']['length']>0x0?Math['max'](...f['arbitrations']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,k=f['arbitrations']['length']>0x0?0x1e:0x0,l=f['rewards']['length']>0x0?Math['max'](...f['rewards']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,n=f['rewards']['length']>0x0?0x14:0x0,o=f['repositories']['length']>0x0?Math['max'](...f['repositories']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,p=f['repositories']['length']>0x0?0xf:0x0,q=i+k+n+p,s=q>0x0?Math['round']((h*i+j*k+l*n+o*p)/q):0x0,t=[];if(f['machine'])t['push'](f['machine']['risk_level']);for(const I of f['arbitrations'])t['push'](I['risk_level']);for(const J of f['rewards'])t['push'](J['risk_level']);for(const K of f['repositories'])t['push'](K['risk_level']);const u=t['reduce'](highestLevel,'low');return{'depth_reached':c,'truncated':e,'bindings':f,'overall_risk_level':u,'overall_risk_score':s,'total_bindings_evaluated':g,'evaluated_at':Date['now']()};}function scoreToNestingLevel(a){if(a>=0x4b)return'critical';if(a>=0x32)return'high';if(a>=0x19)return'medium';return'low';}function nestingLevelToScore(a){switch(a){case'critical':return 0x5a;case'high':return 0x41;case'medium':return 0x28;case'low':return 0xa;}}function highestLevel(c,d){const e={'low':0x0,'medium':0x1,'high':0x2,'critical':0x3};return e[c]>=e[d]?c:d;}export{CUSTOMER_INTELLIGENCE_VERSION};
1
+ import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';export function assembleServiceBasics(a,b,c=![]){const d=(b['sales']??[])['filter'](f=>!f['suspension']),e=d['some'](f=>f['wip_hash']&&f['wip_hash']['length']>0x0);return{'service_id':a,'name':b['name']??a,'bPublished':b['bPublished']??![],'bPaused':b['bPaused']??![],'price':b['price']??'0','price_raw':b['priceRaw']??0x0n,'token_type':b['token_type']??'0x2::wow::WOW','sales_count':d['length'],'machine_id':b['machine'],'buy_guard_id':b['buy_guard'],'customer_required_count':b['customer_required']?.['length']??0x0,'customer_required':(b['customer_required']??[])['filter'](f=>typeof f==='string'),'arbitrations_count':b['arbitrations']?.['length']??0x0,'compensation_fund_balance':b['compensation_fund']?.['balance']??0x0n,'compensation_lock_duration':b['compensation_lock_duration']??0x0,'um_id':b['um'],'has_wip':e,'wip_verified':c};}export function assembleWorkflowAnalysis(a,b,c,d){const e=[],f=[],g=[];let h=0x0,i=0x0,j=0x0,k=![],l=![],m=![];const n=/(^|_)(disputed?|refund(?:ed)?|arbitration|arb)(_|$)/i,o=/^(wonder|no_wonder|praise|complain|thumbs_up|thumbs_down|positive_review|negative_review)$/i,p=a['reduce']((w,x)=>w+(x['forwards']?.['length']??0x0),0x0);for(const w of a){n['test'](w['name']['trim']())&&(m=!![]);}for(const x of a){const y=x['forwards']??[];y['length']===0x0&&f['push'](x['name']);for(const z of y){const A=z['namedOperator'],B=z['guard'];if(A==='')B?j++:h++;else A===null||A===undefined?i++:i++;const C=(z['to']??'')['trim']()['toLowerCase']();o['test'](C)&&(l=!![]),C['includes']('milestone')&&(k=!![]);}}for(const D of a){const E=D['forwards']??[];if(E['length']>0x0&&!f['includes'](D['name'])){const F=E['every'](G=>G['namedOperator']!==''&&G['namedOperator']!==null);F&&h===0x0&&g['push'](D['name']);}}const q=(d?.['arbitrations']?.['length']??0x0)>0x0,r=d?.['compensation_fund']?.['balance']??0x0n,s=q&&r>0x0n,t=d?.['order_allocators']?.[0x0]?.['allocators']??[],u=t['some'](G=>G['surplus_to']==='order'||G['surplus_to']==='Order'),v=s||u;if(!v)e['push']('no_refund_path');if(!q)e['push']('no_arbitration_binding');if(m)e['push']('dispute_anti_pattern');if(h===0x0)e['push']('no_user_operable_path');if(g['length']>0x0)e['push']('potential_dead_ends');return{'machine_published':b,'machine_paused':c,'total_nodes':a['length'],'total_forwards':p,'user_operable_forwards':h,'provider_only_forwards':i,'guard_gated_forwards':j,'has_refund_path':v,'has_arb_refund_path':s,'has_refund_allocator':u,'has_arbitration_path':q,'has_arbitration_binding':q,'has_wonder_node':l,'has_dispute_anti_pattern':m,'has_milestone_nodes':k,'dead_end_nodes':g,'terminal_nodes':f,'risk_signals':e};}export function assembleFundSafety(a,b){const c=a['order_allocators']?.[0x0]?.['allocators']??[],d=a['compensation_fund']?.['balance']??0x0n,e=a['compensation_lock_duration']??0x0,f=c['find'](j=>{const k=j['amount'];return k?.['type']==='FixedValue'&&k['value']===b;}),g=c['some'](j=>j['surplus_to']==='order'||j['surplus_to']==='Order');let h='none';b>0x0n&&(d>0x0n&&b>d*0x3n&&(h='low'));const i=e===0x0||e>0x7;return{'has_order_allocator':c['length']>0x0,'has_refund_allocator':!!f||g,'allocator_count':c['length'],'refund_allocator_exists':g,'surplus_to_provider':c['some'](j=>j['surplus_to']!=='order'&&j['surplus_to']!=='Order'),'user_path_has_allocator':c['length']>0x0,'compensation_covers_order':d>=b,'compensation_ratio':b>0x0n?Math['min'](0x1,Number(d*0x64n/b)/0x64):0x0,'lock_duration_safe':i,'price_anomaly':h};}export function assembleTrustSignals(a,b,c,d,e,f,g){const h=b['filter'](n=>n['rating']==='like')['length'],i=b['filter'](n=>n['rating']==='dislike')['length'],j=b['filter'](n=>n['verified']||n['has_evidence'])['length'],k=b['length'],l=k>0x0?h/k:0x0,m=d!==undefined&&e!==undefined?d!==e:!![];return{'arbitration_independent':m,'arbitration_count':a['arbitrations']?.['length']??0x0,'arbitration_paused':![],'review_likes':h,'review_dislikes':i,'review_verified_count':j,'review_total':k,'like_rate':l,'trust_score':c['score'],'trust_level':c['level'],'has_contact':!!a['um'],'has_messenger':!!a['um'],'arbitration_permission_shared':f,'arbitration_permission_overlap':g};}const REPUTATION_MIN_VOTES=0x3;function toReputation(a){const b=a['likes']+a['dislikes'];return{'likes':a['likes'],'dislikes':a['dislikes'],'like_ratio':b>0x0?a['likes']/b:0x1};}function reputationRedFlags(a){if(!a)return[];const b=a['likes']+a['dislikes'];if(b>=REPUTATION_MIN_VOTES&&a['like_ratio']<0.5)return['reputation_negative'];return[];}export function assembleMerchantBehavior(a,b,c){const d=c?toReputation(c):undefined,e=reputationRedFlags(d);if(b&&b['length']>0x0){const l=b['length'],m=b['filter'](v=>v['status']==='completed')['length'],n=b['filter'](v=>v['has_dispute'])['length'],o=b['filter'](v=>v['is_repeat'])['length'],p=l>0x0?m/l:0x0,q=l>0x0?n/l:0x0,r=l>0x0?o/l:0x0,s=Math['floor'](l/0x2);let t='stable';if(l>=0x4&&s>0x0){const v=b['slice'](0x0,s)['filter'](z=>z['has_dispute'])['length'],w=b['slice'](s)['filter'](z=>z['has_dispute'])['length'],x=v/s,y=w/(l-s);if(y<x*0.85)t='improving';else{if(y>x*1.15)t='declining';}}const u=[...e];if(q>0.1)u['push']('dispute_rate_high');if(t==='declining')u['push']('declining_trend');return{'total_orders':l,'completed_rate':p,'dispute_rate':q,'refund_rate':0x0,'arb_loss_rate':0x0,'repeat_buyer_rate':r,'recent_trend':t,'red_flags':u,'reputation':d};}const f=a['filter'](z=>z['type']['includes']('Order')||z['type']['includes']('order')),g=a['filter'](z=>z['type']['includes']('Dispute')||z['type']['includes']('Arb')),h=f['length'],i=g['length'],j=h>0x0?i/h:0x0,k=[...e];if(j>0.1)k['push']('dispute_rate_high');return{'total_orders':h,'completed_rate':h>0x0?Math['max'](0x0,0x1-j):0x0,'dispute_rate':j,'refund_rate':0x0,'arb_loss_rate':0x0,'repeat_buyer_rate':0x0,'recent_trend':'stable','red_flags':k,'reputation':d};}export function assembleMarketContext(a,b){if(a['length']===0x0)return{'similar_services_count':0x0,'avg_price':0x0n,'min_price':0x0n,'max_price':0x0n,'price_percentile':0x0,'supply_demand_ratio':0x0};const c=a['map'](j=>j['price'])['sort']((j,k)=>j<k?-0x1:j>k?0x1:0x0),d=c['reduce']((j,k)=>j+k,0x0n),e=d/BigInt(c['length']),f=c[0x0],g=c[c['length']-0x1];let h=0x0;for(const j of c){if(j<b)h++;}const i=c['length']>0x0?h/c['length']:0x0;return{'similar_services_count':a['length'],'avg_price':e,'min_price':f,'max_price':g,'price_percentile':i,'supply_demand_ratio':0x0};}export function assembleInfoPuzzle(a,b,c='evaluate'){const d=[],e=assembleServiceBasics(a,b['service'],b['wip_verified']??![]);let f,g,h;if(c==='evaluate'||c==='preorder'||c==='monitor'){b['machine_nodes']?f=assembleWorkflowAnalysis(b['machine_nodes'],b['machine_published']??![],b['machine_paused']??![],b['service']):d['push']('machine_workflow');const m=b['order_amount']??e['price_raw'];g=assembleFundSafety(b['service'],m),b['reviews']&&b['trust_score']?h=assembleTrustSignals(b['service'],b['reviews'],b['trust_score'],b['arbitration_owner'],b['service_owner']):d['push']('reviews_or_trust_score');}let i;if(c==='preorder'||c==='monitor'){if(b['events']||b['order_history'])i=assembleMerchantBehavior(b['events']??[],b['order_history'],b['merchant_reputation']);else b['merchant_reputation']?i=assembleMerchantBehavior([],undefined,b['merchant_reputation']):d['push']('merchant_behavior');}let j;(c==='evaluate'||c==='preorder')&&(b['similar_services']?j=assembleMarketContext(b['similar_services'],e['price_raw']):d['push']('market_context'));let k;b['user_metrics_config']&&b['user_metrics_config']['metrics']['length']>0x0&&(k=assembleUserMetrics(b['user_metrics_config'],b['user_metrics_context']??{}));let l=b['service_nesting'];return!l&&b['service_nesting_raw']&&(l=evaluateServiceNesting(b['service_nesting_raw'])),{'service_id':a,'service_basics':e,'workflow_analysis':f,'fund_safety':g,'trust_signals':h,'merchant_behavior':i,'market_context':j,'user_metrics':k,'service_nesting':l,'completeness':computeCompleteness(c,[e,f,g,h,i,j,k,l]),'gaps':d,'assembled_at':Date['now']()};}export function assembleUserMetrics(a,b){const c=a['adjustment_cap']??0xa,d=[],e=a['metrics']['reduce']((i,j)=>i+Math['max'](0x0,j['weight']),0x0);for(const i of a['metrics']){const j=e>0x0?Math['max'](0x0,i['weight'])/e:0x0,k=resolvePath(b,i['params']['path']??i['name']),{passed:l,score:m,observed_value:n}=evaluateMetric(i,k);d['push']({'name':i['name'],'label':i['label'],'passed':l,'score':m,'observed_value':formatObservedValue(k),'weight':j,'advice':l?i['advice_on_pass']:i['advice_on_fail']});}const f=d['reduce']((o,p)=>o+p['score']*p['weight'],0x0),g=Math['round'](f*0x64),h=Math['round']((g-0x32)/0x32*c);return{'metrics':d,'score':g,'adjustment':h,'source_file':a['source_file'],'evaluated_at':Date['now']()};}function resolvePath(a,b){if(!b)return undefined;const c=b['split']('.');let d=a;for(const e of c){if(d===null||d===undefined)return undefined;if(typeof d!=='object')return undefined;d=d[e];}return d;}function evaluateMetric(a,b){const c=a['params'];switch(a['evaluator']){case'threshold':{const d=typeof b==='number'?b:typeof b==='string'?Number(b):typeof b==='bigint'?Number(b):NaN,e=typeof c['threshold']==='number'?c['threshold']:typeof c['threshold']==='string'?Number(c['threshold']):NaN;if(isNaN(d)||isNaN(e))return{'passed':![],'score':0x0,'observed_value':b};const f=c['invert']?d<=e:d>=e,g=Math['abs'](e)*0.5||0x1,h=c['invert']?(e-d)/g+0x1:(d-e)/g+0x1,i=Math['max'](0x0,Math['min'](0x1,h));return{'passed':f,'score':i,'observed_value':b};}case'ratio':{const j=typeof b==='number'?b:typeof b==='string'?Number(b):NaN,k=c['min']??0x0,l=c['max']??0x1;if(isNaN(j))return{'passed':![],'score':0x0,'observed_value':b};const m=j>=k&&j<=l,n=l-k,o=(k+l)/0x2,q=n>0x0?Math['max'](0x0,0x1-Math['abs'](j-o)/(n/0x2)):0x1;return{'passed':m,'score':q,'observed_value':b};}case'boolean':{const r=!!b;return{'passed':r,'score':r?0x1:0x0,'observed_value':b};}case'presence':{const s=b!==undefined&&b!==null&&b!=='';return{'passed':s,'score':s?0x1:0x0,'observed_value':b};}case'regex_match':{if(typeof b!=='string'||!c['pattern'])return{'passed':![],'score':0x0,'observed_value':b};try{const t=new RegExp(c['pattern']),u=t['test'](b);return{'passed':u,'score':u?0x1:0x0,'observed_value':b};}catch{return{'passed':![],'score':0x0,'observed_value':b};}}case'custom_query':{return{'passed':![],'score':0.5,'observed_value':b};}default:return{'passed':![],'score':0x0,'observed_value':b};}}function formatObservedValue(a){if(typeof a==='string'||typeof a==='number'||typeof a==='boolean')return a;if(typeof a==='bigint')return a['toString']();if(a===undefined||a===null)return undefined;try{return JSON['stringify'](a);}catch{return String(a);}}function computeCompleteness(a,b){const c=a==='browse'?0x1:a==='evaluate'?0x4:a==='preorder'?0x6:0x5,d=b['slice'](0x0,c),e=d['filter'](f=>f!==undefined&&f!==null)['length'];return Math['min'](0x1,e/c);}export function evaluateServiceNesting(b){const c=b['depth']??0x0,d=b['maxDepth']??0x3,e=c>=d,f={'arbitrations':[],'rewards':[],'repositories':[]};let g=0x0;if(b['machine']){const v=b['machine'],w=[];let x=0x0;if(v['published'])x+=0xa;else w['push']('Machine\x20not\x20published');v['paused']&&(x+=0x28,w['push']('Machine\x20paused'));v['has_no_entry']&&(x+=0x32,w['push']('No\x20entry\x20point\x20(R-M1-01)'));v['has_no_terminal']&&(x+=0x32,w['push']('No\x20terminal\x20node\x20(R-M1-02)'));v['has_dispute_anti_pattern']&&(x+=0x3c,w['push']('Dispute\x20anti-pattern\x20(R-M1-11):\x20machine\x20illegally\x20models\x20dispute\x20flow'));const y=v['structural_issue_count']??0x0;y>0x0&&(x+=y*0xf,w['push'](y+'\x20structural\x20issue(s)\x20detected\x20(cycles/dead-ends/orphans)')),x=Math['min'](0x64,x),f['machine']={'object_id':v['object_id'],'published':v['published'],'risk_level':scoreToNestingLevel(x),'issues':w},g++;}for(const z of b['arbitrations']??[]){const A=[];let B=0x0;if(z['voting_guard_count']===0x0)B+=0x32,A['push']('No\x20voting_guard\x20configured\x20—\x20no\x20arbitrators\x20can\x20vote');else z['voting_guard_count']<=0x2?(B+=0x1e,A['push']('Few\x20arbitrators\x20(<=2)\x20—\x20limited\x20dispute\x20resolution\x20capacity')):B+=0xa;z['paused']&&(B+=0x28,A['push']('Arbitration\x20paused\x20—\x20disputes\x20cannot\x20be\x20filed')),z['fee_balance']===0x0n&&(B+=0x1e,A['push']('No\x20compensation\x20fund\x20balance\x20—\x20rulings\x20cannot\x20pay\x20out')),B=Math['min'](0x64,B),f['arbitrations']['push']({'object_id':z['object_id'],'voting_guard_count':z['voting_guard_count'],'fee_balance':z['fee_balance']['toString'](),'paused':z['paused'],'risk_level':scoreToNestingLevel(B),'issues':A}),g++;}for(const C of b['rewards']??[]){const D=[];let E=0x0;C['balance']===0x0n&&(E+=0x3c,D['push']('Reward\x20fund\x20empty\x20—\x20claims\x20will\x20fail')),C['guard_count']===0x0&&(E+=0x32,D['push']('No\x20claim_guard\x20—\x20anyone\x20could\x20claim\x20(or\x20no\x20one\x20can,\x20depending\x20on\x20default)')),C['expiration_time']&&C['expiration_time']>0x0&&C['expiration_time']<Date['now']()&&(E+=0x28,D['push']('Reward\x20expired\x20—\x20claims\x20no\x20longer\x20possible')),E=Math['min'](0x64,E),f['rewards']['push']({'object_id':C['object_id'],'balance':C['balance']['toString'](),'guard_count':C['guard_count'],'risk_level':scoreToNestingLevel(E),'issues':D}),g++;}for(const F of b['repositories']??[]){const G=[];let H=0x0;!F['has_write_guard']&&(H+=0x28,G['push']('No\x20write_guard\x20—\x20Repository\x20is\x20open\x20to\x20arbitrary\x20writes')),F['is_empty']&&(H+=0x14,G['push']('Repository\x20empty\x20—\x20no\x20historical\x20data\x20for\x20evaluation')),H=Math['min'](0x64,H),f['repositories']['push']({'object_id':F['object_id'],'risk_level':scoreToNestingLevel(H),'issues':G}),g++;}if(g===0x0)return undefined;const h=f['machine']?nestingLevelToScore(f['machine']['risk_level']):0x0,i=f['machine']?0x23:0x0,j=f['arbitrations']['length']>0x0?Math['max'](...f['arbitrations']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,k=f['arbitrations']['length']>0x0?0x1e:0x0,l=f['rewards']['length']>0x0?Math['max'](...f['rewards']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,n=f['rewards']['length']>0x0?0x14:0x0,o=f['repositories']['length']>0x0?Math['max'](...f['repositories']['map'](I=>nestingLevelToScore(I['risk_level']))):0x0,p=f['repositories']['length']>0x0?0xf:0x0,q=i+k+n+p,s=q>0x0?Math['round']((h*i+j*k+l*n+o*p)/q):0x0,t=[];if(f['machine'])t['push'](f['machine']['risk_level']);for(const I of f['arbitrations'])t['push'](I['risk_level']);for(const J of f['rewards'])t['push'](J['risk_level']);for(const K of f['repositories'])t['push'](K['risk_level']);const u=t['reduce'](highestLevel,'low');return{'depth_reached':c,'truncated':e,'bindings':f,'overall_risk_level':u,'overall_risk_score':s,'total_bindings_evaluated':g,'evaluated_at':Date['now']()};}function scoreToNestingLevel(a){if(a>=0x4b)return'critical';if(a>=0x32)return'high';if(a>=0x19)return'medium';return'low';}function nestingLevelToScore(a){switch(a){case'critical':return 0x5a;case'high':return 0x41;case'medium':return 0x28;case'low':return 0xa;}}function highestLevel(c,d){const e={'low':0x0,'medium':0x1,'high':0x2,'critical':0x3};return e[c]>=e[d]?c:d;}export{CUSTOMER_INTELLIGENCE_VERSION};
@@ -65,13 +65,4 @@ export interface MonitorThresholds {
65
65
  }
66
66
  export declare function monitorOrder(ctx: OrderMonitorContext): MonitorAlert[];
67
67
  export declare function sortAlerts(alerts: MonitorAlert[]): MonitorAlert[];
68
- export declare function getCriticalAlerts(alerts: MonitorAlert[]): MonitorAlert[];
69
- export declare function getActionableAlerts(alerts: MonitorAlert[]): MonitorAlert[];
70
- export declare function summarizeAlerts(alerts: MonitorAlert[]): string;
71
- export declare function isBlockingAlert(alert: MonitorAlert): boolean;
72
- export declare function alertsToReminders(alerts: MonitorAlert[]): Array<{
73
- id: string;
74
- priority: "required" | "recommended" | "info" | "reminder";
75
- message: string;
76
- }>;
77
68
  export { CUSTOMER_INTELLIGENCE_VERSION };
@@ -1 +1 @@
1
- import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';import{formatAmountText}from'../knowledge/fund-layer.js';const DEFAULT_THRESHOLDS={'progress_stall_hours':0x0,'compensation_drop_ratio':0.3,'compensation_coverage_min':0x1,'messenger_timeout_hours':0x18,'review_window_closing_days':0x3,'arb_window_closing_days':0x3};export function monitorOrder(a){const b=[],c={...DEFAULT_THRESHOLDS,...a['thresholds']??{}},d=a['current'];if(d['completed'])return b['push'](...detectPostCompletionAlerts(d,c)),sortAlerts(b);if(d['refunded'])return b['push']({'id':'refund_received','category':'refund_received','severity':'info','title':'Refund\x20received','message':'Order\x20'+d['order_id']+'\x20refund\x20has\x20been\x20received','timestamp':d['now'],'order_id':d['order_id'],'service_id':d['service_id']}),sortAlerts(b);return b['push'](...detectProgressStall(d,a['previous'],c)),b['push'](...detectCompensationChange(d,a['previous'],c)),b['push'](...detectMessengerTimeout(d,c)),d['pending_user_action']&&b['push']({'id':'user_action_required','category':'user_action_required','severity':'info','title':'Waiting\x20for\x20user\x20action','message':'Order\x20'+d['order_id']+'\x20advanced\x20to\x20node\x20'+(d['current_node']??'unknown')+';\x20your\x20action\x20is\x20required\x20to\x20continue','action':'View\x20the\x20Machine\x20node\x20requirements\x20and\x20submit\x20the\x20corresponding\x20Guard\x20submission','timestamp':d['now'],'order_id':d['order_id'],'service_id':d['service_id'],'node':d['current_node']}),sortAlerts(b);}function detectProgressStall(a,b,c){const d=[];if(!a['current_node'])return d;const e=a['last_progress_at']??a['created_at'],f=a['now']-e,g=f/0x36ee80,h=a['expected_progress_hours']??0x18,i=c['progress_stall_hours']>0x0?c['progress_stall_hours']:h*0x2;if(g>i){const j=g>i*0x2?'critical':'warning';d['push']({'id':'progress_stall','category':'progress_stall','severity':j,'title':j==='critical'?'Order\x20severely\x20stalled':'Order\x20progress\x20stalled','message':'Order\x20has\x20been\x20stuck\x20at\x20node\x20'+a['current_node']+'\x20for\x20over\x20'+Math['round'](g)+'\x20hours\x20(expected\x20'+h+'\x20hours)','action':j==='critical'?'Recommend\x20contacting\x20the\x20merchant\x20immediately\x20via\x20Messenger;\x20if\x20the\x20merchant\x20remains\x20unresponsive,\x20consider\x20initiating\x20arbitration':'Recommend\x20contacting\x20the\x20merchant\x20via\x20Messenger\x20to\x20ask\x20about\x20progress','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'node':a['current_node'],'metric':{'label':'Stall\x20duration','value':Math['round'](g),'threshold':Math['round'](i),'unit':'hours'}});}if(b&&b['previous_node']===a['current_node']){const k=a['now']-b['snapshot_at'],l=k/0x36ee80;l>h&&d['push']({'id':'node_unchanged','category':'progress_stall','severity':'warning','title':'Node\x20unchanged','message':'Since\x20the\x20last\x20check\x20('+Math['round'](l)+'\x20hours),\x20the\x20order\x20is\x20still\x20at\x20'+a['current_node'],'action':'Confirm\x20whether\x20this\x20is\x20expected;\x20if\x20not,\x20contact\x20the\x20merchant','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'node':a['current_node'],'metric':{'label':'Node\x20stay\x20duration','value':Math['round'](l),'threshold':Math['round'](h),'unit':'hours'}});}return d;}function detectCompensationChange(a,b,c){const d=[];if(a['compensation_balance']===undefined)return d;if(a['order_amount']!==undefined&&a['order_amount']>0x0n){const e=Number(a['compensation_balance']*0x64n/a['order_amount'])/0x64;if(e<c['compensation_coverage_min']){const f=e<0.5?'critical':'warning';d['push']({'id':'compensation_insufficient','category':'compensation_insufficient','severity':f,'title':'Compensation\x20fund\x20coverage\x20insufficient','message':'Merchant\x20compensation\x20fund\x20covers\x20only\x20'+Math['round'](e*0x64)+'%\x20of\x20the\x20order\x20amount\x20(required\x20'+Math['round'](c['compensation_coverage_min']*0x64)+'%):\x20fund\x20'+formatAmountText(a['compensation_balance'],a['token']?.['decimals'],a['token']?.['symbol'])+'\x20vs\x20order\x20'+formatAmountText(a['order_amount'],a['token']?.['decimals'],a['token']?.['symbol']),'action':'Require\x20the\x20merchant\x20to\x20top\x20up\x20the\x20compensation\x20fund\x20before\x20ordering,\x20or\x20negotiate\x20higher\x20coverage\x20via\x20Messenger','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Compensation\x20coverage','value':Math['round'](e*0x64),'threshold':Math['round'](c['compensation_coverage_min']*0x64),'unit':'%'}});}}if(b&&b['previous_compensation_balance']!==undefined){const g=b['previous_compensation_balance'];if(g>0x0n&&a['compensation_balance']<g){const h=Number((g-a['compensation_balance'])*0x64n/g)/0x64;if(h>=c['compensation_drop_ratio']){const i=h>=0.5?'critical':'warning';d['push']({'id':'compensation_drop','category':'compensation_drop','severity':i,'title':'Compensation\x20fund\x20balance\x20dropped\x20significantly','message':'Merchant\x20compensation\x20fund\x20dropped\x20from\x20'+formatAmountText(g,a['token']?.['decimals'],a['token']?.['symbol'])+'\x20to\x20'+formatAmountText(a['compensation_balance'],a['token']?.['decimals'],a['token']?.['symbol'])+'\x20(down\x20'+Math['round'](h*0x64)+'%)','action':'Immediately\x20ask\x20the\x20merchant\x20for\x20the\x20reason;\x20if\x20it\x20keeps\x20dropping,\x20the\x20merchant\x20may\x20be\x20processing\x20payouts\x20for\x20other\x20orders,\x20which\x20is\x20a\x20risk','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Compensation\x20drop\x20ratio','value':Math['round'](h*0x64),'threshold':Math['round'](c['compensation_drop_ratio']*0x64),'unit':'%'}});}}}return d;}function detectMessengerTimeout(a,b){const c=[];if(a['has_messenger']===![])return c['push']({'id':'no_messenger_channel','category':'messenger_timeout','severity':'info','title':'Merchant\x20has\x20no\x20Messenger\x20channel','message':'Merchant\x20has\x20not\x20configured\x20Messenger;\x20no\x20way\x20to\x20negotiate\x20online\x20or\x20get\x20post-sale\x20support','action':'Confirm\x20other\x20contact\x20methods\x20before\x20ordering;\x20recommend\x20requiring\x20the\x20merchant\x20to\x20configure\x20Messenger','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id']}),c;if(a['last_user_message_at']&&!a['last_merchant_reply_at']){const d=a['now']-a['last_user_message_at'],e=d/0x36ee80;if(e>b['messenger_timeout_hours']){const f=e>b['messenger_timeout_hours']*0x2?'critical':'warning';c['push']({'id':'messenger_unanswered','category':'messenger_timeout','severity':f,'title':'Merchant\x20Messenger\x20no\x20reply','message':'Merchant\x20has\x20not\x20replied\x20to\x20your\x20Messenger\x20message\x20for\x20'+Math['round'](e)+'\x20hours','action':a['has_arbitration']?'Consider\x20initiating\x20an\x20arbitration\x20application\x20(arbitration\x20window\x20is\x20limited)':'Merchant\x20has\x20no\x20arbitration\x20configured;\x20recommend\x20urging\x20via\x20other\x20contact\x20methods;\x20if\x20there\x20is\x20no\x20response,\x20funds\x20may\x20be\x20frozen','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'No-reply\x20duration','value':Math['round'](e),'threshold':Math['round'](b['messenger_timeout_hours']),'unit':'hours'}});}}if(a['last_merchant_reply_at']&&a['last_user_message_at']&&a['last_user_message_at']>a['last_merchant_reply_at']){const g=a['now']-a['last_user_message_at'],h=g/0x36ee80;h>b['messenger_timeout_hours']&&c['push']({'id':'messenger_re_unanswered','category':'messenger_timeout','severity':'warning','title':'Merchant\x20did\x20not\x20reply\x20again','message':'The\x20merchant\x20has\x20not\x20replied\x20to\x20your\x20message\x20from\x20'+Math['round'](h)+'\x20hours\x20ago','action':'Send\x20a\x20follow-up\x20message;\x20if\x20the\x20merchant\x20remains\x20unresponsive,\x20consider\x20arbitration','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Re-no-reply\x20duration','value':Math['round'](h),'threshold':Math['round'](b['messenger_timeout_hours']),'unit':'hours'}});}return c;}function detectPostCompletionAlerts(a,b){const c=[];return a['review_window_days']!==undefined&&a['review_window_days']>0x0&&(a['review_window_days']<=b['review_window_closing_days']?c['push']({'id':'review_window_closing','category':'review_window','severity':'info','title':'Review\x20window\x20about\x20to\x20close','message':'The\x20review\x20window\x20will\x20close\x20in\x20'+a['review_window_days']+'\x20day(s)','action':'Submit\x20a\x20review\x20as\x20soon\x20as\x20possible\x20(evidence\x20can\x20be\x20submitted\x20together\x20if\x20available)','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Remaining\x20days','value':a['review_window_days'],'threshold':b['review_window_closing_days'],'unit':'days'}}):c['push']({'id':'review_reminder','category':'review_window','severity':'info','title':'Order\x20completed','message':'Order\x20completed;\x20review\x20window\x20has\x20'+a['review_window_days']+'\x20day(s)\x20remaining','action':'Submit\x20a\x20review\x20to\x20help\x20other\x20users\x20decide','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id']})),a['arb_window_days']!==undefined&&a['arb_window_days']>0x0&&(a['arb_window_days']<=b['arb_window_closing_days']&&c['push']({'id':'arb_window_closing','category':'arb_window','severity':'warning','title':'Arbitration\x20application\x20window\x20about\x20to\x20close','message':'The\x20arbitration\x20application\x20window\x20will\x20close\x20in\x20'+a['arb_window_days']+'\x20day(s)','action':'If\x20there\x20are\x20unresolved\x20disputes,\x20initiate\x20an\x20arbitration\x20application\x20immediately','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Remaining\x20days','value':a['arb_window_days'],'threshold':b['arb_window_closing_days'],'unit':'days'}})),c;}export function sortAlerts(a){const b={'critical':0x3,'warning':0x2,'info':0x1};return[...a]['sort']((c,d)=>b[d['severity']]-b[c['severity']]);}export function getCriticalAlerts(a){return a['filter'](b=>b['severity']==='critical');}export function getActionableAlerts(a){return a['filter'](b=>b['severity']==='critical'||b['severity']==='warning');}export function summarizeAlerts(a){if(a['length']===0x0)return'✅\x20No\x20alerts;\x20order\x20status\x20is\x20normal';const b=a['filter'](f=>f['severity']==='critical'),c=a['filter'](f=>f['severity']==='warning'),d=a['filter'](f=>f['severity']==='info'),e=[];if(b['length']>0x0)e['push']('🔴\x20'+b['length']+'\x20critical\x20alert(s)');if(c['length']>0x0)e['push']('🟠\x20'+c['length']+'\x20warning(s)');if(d['length']>0x0)e['push']('ℹ️\x20'+d['length']+'\x20info');return e['join'](',\x20');}export function isBlockingAlert(a){return a['severity']==='critical';}export function alertsToReminders(a){return a['map'](b=>({'id':b['id'],'priority':b['severity']==='critical'?'required':b['severity']==='warning'?'recommended':'info','message':b['title']+':\x20'+b['message']}));}export{CUSTOMER_INTELLIGENCE_VERSION};
1
+ import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';import{formatAmountText}from'../knowledge/fund-layer.js';const DEFAULT_THRESHOLDS={'progress_stall_hours':0x0,'compensation_drop_ratio':0.3,'compensation_coverage_min':0x1,'messenger_timeout_hours':0x18,'review_window_closing_days':0x3,'arb_window_closing_days':0x3};export function monitorOrder(a){const b=[],c={...DEFAULT_THRESHOLDS,...a['thresholds']??{}},d=a['current'];if(d['completed'])return b['push'](...detectPostCompletionAlerts(d,c)),sortAlerts(b);if(d['refunded'])return b['push']({'id':'refund_received','category':'refund_received','severity':'info','title':'Refund\x20received','message':'Order\x20'+d['order_id']+'\x20refund\x20has\x20been\x20received','timestamp':d['now'],'order_id':d['order_id'],'service_id':d['service_id']}),sortAlerts(b);return b['push'](...detectProgressStall(d,a['previous'],c)),b['push'](...detectCompensationChange(d,a['previous'],c)),b['push'](...detectMessengerTimeout(d,c)),d['pending_user_action']&&b['push']({'id':'user_action_required','category':'user_action_required','severity':'info','title':'Waiting\x20for\x20user\x20action','message':'Order\x20'+d['order_id']+'\x20advanced\x20to\x20node\x20'+(d['current_node']??'unknown')+';\x20your\x20action\x20is\x20required\x20to\x20continue','action':'View\x20the\x20Machine\x20node\x20requirements\x20and\x20submit\x20the\x20corresponding\x20Guard\x20submission','timestamp':d['now'],'order_id':d['order_id'],'service_id':d['service_id'],'node':d['current_node']}),sortAlerts(b);}function detectProgressStall(a,b,c){const d=[];if(!a['current_node'])return d;const e=a['last_progress_at']??a['created_at'],f=a['now']-e,g=f/0x36ee80,h=a['expected_progress_hours']??0x18,i=c['progress_stall_hours']>0x0?c['progress_stall_hours']:h*0x2;if(g>i){const j=g>i*0x2?'critical':'warning';d['push']({'id':'progress_stall','category':'progress_stall','severity':j,'title':j==='critical'?'Order\x20severely\x20stalled':'Order\x20progress\x20stalled','message':'Order\x20has\x20been\x20stuck\x20at\x20node\x20'+a['current_node']+'\x20for\x20over\x20'+Math['round'](g)+'\x20hours\x20(expected\x20'+h+'\x20hours)','action':j==='critical'?'Recommend\x20contacting\x20the\x20merchant\x20immediately\x20via\x20Messenger;\x20if\x20the\x20merchant\x20remains\x20unresponsive,\x20consider\x20initiating\x20arbitration':'Recommend\x20contacting\x20the\x20merchant\x20via\x20Messenger\x20to\x20ask\x20about\x20progress','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'node':a['current_node'],'metric':{'label':'Stall\x20duration','value':Math['round'](g),'threshold':Math['round'](i),'unit':'hours'}});}if(b&&b['previous_node']===a['current_node']){const k=a['now']-b['snapshot_at'],l=k/0x36ee80;l>h&&d['push']({'id':'node_unchanged','category':'progress_stall','severity':'warning','title':'Node\x20unchanged','message':'Since\x20the\x20last\x20check\x20('+Math['round'](l)+'\x20hours),\x20the\x20order\x20is\x20still\x20at\x20'+a['current_node'],'action':'Confirm\x20whether\x20this\x20is\x20expected;\x20if\x20not,\x20contact\x20the\x20merchant','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'node':a['current_node'],'metric':{'label':'Node\x20stay\x20duration','value':Math['round'](l),'threshold':Math['round'](h),'unit':'hours'}});}return d;}function detectCompensationChange(a,b,c){const d=[];if(a['compensation_balance']===undefined)return d;if(a['order_amount']!==undefined&&a['order_amount']>0x0n){const e=Number(a['compensation_balance']*0x64n/a['order_amount'])/0x64;if(e<c['compensation_coverage_min']){const f=e<0.5?'critical':'warning';d['push']({'id':'compensation_insufficient','category':'compensation_insufficient','severity':f,'title':'Compensation\x20fund\x20coverage\x20insufficient','message':'Merchant\x20compensation\x20fund\x20covers\x20only\x20'+Math['round'](e*0x64)+'%\x20of\x20the\x20order\x20amount\x20(required\x20'+Math['round'](c['compensation_coverage_min']*0x64)+'%):\x20fund\x20'+formatAmountText(a['compensation_balance'],a['token']?.['decimals'],a['token']?.['symbol'])+'\x20vs\x20order\x20'+formatAmountText(a['order_amount'],a['token']?.['decimals'],a['token']?.['symbol']),'action':'Require\x20the\x20merchant\x20to\x20top\x20up\x20the\x20compensation\x20fund\x20before\x20ordering,\x20or\x20negotiate\x20higher\x20coverage\x20via\x20Messenger','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Compensation\x20coverage','value':Math['round'](e*0x64),'threshold':Math['round'](c['compensation_coverage_min']*0x64),'unit':'%'}});}}if(b&&b['previous_compensation_balance']!==undefined){const g=b['previous_compensation_balance'];if(g>0x0n&&a['compensation_balance']<g){const h=Number((g-a['compensation_balance'])*0x64n/g)/0x64;if(h>=c['compensation_drop_ratio']){const i=h>=0.5?'critical':'warning';d['push']({'id':'compensation_drop','category':'compensation_drop','severity':i,'title':'Compensation\x20fund\x20balance\x20dropped\x20significantly','message':'Merchant\x20compensation\x20fund\x20dropped\x20from\x20'+formatAmountText(g,a['token']?.['decimals'],a['token']?.['symbol'])+'\x20to\x20'+formatAmountText(a['compensation_balance'],a['token']?.['decimals'],a['token']?.['symbol'])+'\x20(down\x20'+Math['round'](h*0x64)+'%)','action':'Immediately\x20ask\x20the\x20merchant\x20for\x20the\x20reason;\x20if\x20it\x20keeps\x20dropping,\x20the\x20merchant\x20may\x20be\x20processing\x20payouts\x20for\x20other\x20orders,\x20which\x20is\x20a\x20risk','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Compensation\x20drop\x20ratio','value':Math['round'](h*0x64),'threshold':Math['round'](c['compensation_drop_ratio']*0x64),'unit':'%'}});}}}return d;}function detectMessengerTimeout(a,b){const c=[];if(a['has_messenger']===![])return c['push']({'id':'no_messenger_channel','category':'messenger_timeout','severity':'info','title':'Merchant\x20has\x20no\x20Messenger\x20channel','message':'Merchant\x20has\x20not\x20configured\x20Messenger;\x20no\x20way\x20to\x20negotiate\x20online\x20or\x20get\x20post-sale\x20support','action':'Confirm\x20other\x20contact\x20methods\x20before\x20ordering;\x20recommend\x20requiring\x20the\x20merchant\x20to\x20configure\x20Messenger','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id']}),c;if(a['last_user_message_at']&&!a['last_merchant_reply_at']){const d=a['now']-a['last_user_message_at'],e=d/0x36ee80;if(e>b['messenger_timeout_hours']){const f=e>b['messenger_timeout_hours']*0x2?'critical':'warning';c['push']({'id':'messenger_unanswered','category':'messenger_timeout','severity':f,'title':'Merchant\x20Messenger\x20no\x20reply','message':'Merchant\x20has\x20not\x20replied\x20to\x20your\x20Messenger\x20message\x20for\x20'+Math['round'](e)+'\x20hours','action':a['has_arbitration']?'Consider\x20initiating\x20an\x20arbitration\x20application\x20(arbitration\x20window\x20is\x20limited)':'Merchant\x20has\x20no\x20arbitration\x20configured;\x20recommend\x20urging\x20via\x20other\x20contact\x20methods;\x20if\x20there\x20is\x20no\x20response,\x20funds\x20may\x20be\x20frozen','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'No-reply\x20duration','value':Math['round'](e),'threshold':Math['round'](b['messenger_timeout_hours']),'unit':'hours'}});}}if(a['last_merchant_reply_at']&&a['last_user_message_at']&&a['last_user_message_at']>a['last_merchant_reply_at']){const g=a['now']-a['last_user_message_at'],h=g/0x36ee80;h>b['messenger_timeout_hours']&&c['push']({'id':'messenger_re_unanswered','category':'messenger_timeout','severity':'warning','title':'Merchant\x20did\x20not\x20reply\x20again','message':'The\x20merchant\x20has\x20not\x20replied\x20to\x20your\x20message\x20from\x20'+Math['round'](h)+'\x20hours\x20ago','action':'Send\x20a\x20follow-up\x20message;\x20if\x20the\x20merchant\x20remains\x20unresponsive,\x20consider\x20arbitration','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Re-no-reply\x20duration','value':Math['round'](h),'threshold':Math['round'](b['messenger_timeout_hours']),'unit':'hours'}});}return c;}function detectPostCompletionAlerts(a,b){const c=[];return a['review_window_days']!==undefined&&a['review_window_days']>0x0&&(a['review_window_days']<=b['review_window_closing_days']?c['push']({'id':'review_window_closing','category':'review_window','severity':'info','title':'Review\x20window\x20about\x20to\x20close','message':'The\x20review\x20window\x20will\x20close\x20in\x20'+a['review_window_days']+'\x20day(s)','action':'Submit\x20a\x20review\x20as\x20soon\x20as\x20possible\x20(evidence\x20can\x20be\x20submitted\x20together\x20if\x20available)','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Remaining\x20days','value':a['review_window_days'],'threshold':b['review_window_closing_days'],'unit':'days'}}):c['push']({'id':'review_reminder','category':'review_window','severity':'info','title':'Order\x20completed','message':'Order\x20completed;\x20review\x20window\x20has\x20'+a['review_window_days']+'\x20day(s)\x20remaining','action':'Submit\x20a\x20review\x20to\x20help\x20other\x20users\x20decide','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id']})),a['arb_window_days']!==undefined&&a['arb_window_days']>0x0&&(a['arb_window_days']<=b['arb_window_closing_days']&&c['push']({'id':'arb_window_closing','category':'arb_window','severity':'warning','title':'Arbitration\x20application\x20window\x20about\x20to\x20close','message':'The\x20arbitration\x20application\x20window\x20will\x20close\x20in\x20'+a['arb_window_days']+'\x20day(s)','action':'If\x20there\x20are\x20unresolved\x20disputes,\x20initiate\x20an\x20arbitration\x20application\x20immediately','timestamp':a['now'],'order_id':a['order_id'],'service_id':a['service_id'],'metric':{'label':'Remaining\x20days','value':a['arb_window_days'],'threshold':b['arb_window_closing_days'],'unit':'days'}})),c;}export function sortAlerts(a){const b={'critical':0x3,'warning':0x2,'info':0x1};return[...a]['sort']((c,d)=>b[d['severity']]-b[c['severity']]);}export{CUSTOMER_INTELLIGENCE_VERSION};
@@ -14,23 +14,4 @@ export interface StrategyRecommendation {
14
14
  }
15
15
  export declare function recommendStrategy(scenario: GameScenario, ctx: StrategyContext): StrategyRecommendation;
16
16
  export declare function detectScenarios(puzzle: InfoPuzzle): GameScenario[];
17
- export declare function flowMigrationStrategy(puzzle: InfoPuzzle): {
18
- strategy: string;
19
- risk: "low" | "medium" | "high";
20
- advice: string;
21
- };
22
- export declare function repeatGameStrategy(_puzzle: InfoPuzzle, history: {
23
- completed: number;
24
- disputes: number;
25
- refunds: number;
26
- }): {
27
- strategy: string;
28
- is_long_term_partner: boolean;
29
- advice: string;
30
- };
31
- export declare function rightsProtectionStrategy(puzzle: InfoPuzzle, prefs?: UserPreferences): {
32
- required_rights: string[];
33
- negotiable_rights: string[];
34
- red_lines: string[];
35
- };
36
17
  export { CUSTOMER_INTELLIGENCE_VERSION };
@@ -1 +1 @@
1
- import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';const SCENARIO_SPECS={'info_asymmetry':{'scenario':'info_asymmetry','merchant_tactic':'Hides\x20key\x20workflow\x20information;\x20Machine\x20is\x20not\x20public','user_strategy':'Request\x20machineNode2file\x20export\x20+\x20Guard\x20configuration;\x20ask\x20about\x20key\x20nodes\x20via\x20Messenger','nash_equilibrium':'Merchant\x20becomes\x20transparent\x20(provides\x20full\x20Machine\x20docs)\x20↔\x20User\x20purchases','fallback':'Abandon\x20purchase','confidence':a=>{if(a['workflow_analysis']===undefined)return 0.9;if(a['completeness']<0.5)return 0.9;return 0.5;},'rationale':a=>{if(a['workflow_analysis']===undefined)return'Workflow\x20structure\x20analysis\x20missing;\x20severe\x20information\x20asymmetry';if(a['completeness']<0.5)return'Information\x20completeness\x20is\x20only\x20'+Math['round'](a['completeness']*0x64)+'%;\x20key\x20puzzle\x20pieces\x20missing';return'Information\x20completeness\x20is\x20acceptable,\x20but\x20still\x20recommend\x20requesting\x20Machine\x20docs';}},'fund_safety':{'scenario':'fund_safety','merchant_tactic':'No\x20compensation\x20fund\x20or\x20insufficient\x20compensation\x20fund','user_strategy':'Require\x20merchant\x20to\x20top\x20up\x20compensation_fund\x20to\x20100%\x20of\x20order\x20amount;\x20write\x20into\x20WTS\x20agreement','nash_equilibrium':'Merchant\x20tops\x20up\x20compensation\x20fund\x20↔\x20User\x20purchases','fallback':'Choose\x20another\x20merchant\x20or\x20require\x20arbitration\x20upfront','confidence':a=>{const b=a['fund_safety'];if(!b)return 0.6;if(b['compensation_covers_order']===![])return 0.95;return 0.4;},'rationale':a=>{const b=a['fund_safety'];if(!b)return'Fund\x20safety\x20analysis\x20missing';if(b['compensation_covers_order']===![])return'Compensation\x20fund\x20covers\x20only\x20'+Math['round'](b['compensation_ratio']*0x64)+'%\x20of\x20order\x20amount';return'Compensation\x20fund\x20covers\x20the\x20order\x20amount';}},'refund_dispute':{'scenario':'refund_dispute','merchant_tactic':'No\x20refund\x20path\x20or\x20unfair\x20refund\x20Allocator\x20configuration','user_strategy':'Negotiate\x20refund\x20terms\x20via\x20Messenger\x20+\x20require\x20100%→Order\x20Allocator','nash_equilibrium':'Merchant\x20configures\x20refund\x20Allocator\x20↔\x20User\x20purchases','fallback':'Arbitration','confidence':a=>{const b=a['workflow_analysis'];if(!b)return 0.5;if(b['has_refund_path']===![])return 0.85;return 0.4;},'rationale':a=>{const b=a['workflow_analysis'];if(!b)return'Workflow\x20structure\x20missing;\x20cannot\x20confirm\x20refund\x20path';if(b['has_refund_path']===![])return'No\x20refund\x20path\x20detected\x20in\x20the\x20workflow';return'Refund\x20path\x20exists';}},'arbitration_fairness':{'scenario':'arbitration_fairness','merchant_tactic':'Self-built\x20arbitration\x20(owner=service\x20owner)','user_strategy':'Require\x20third-party\x20arbitration;\x20verify\x20arb\x20owner\x20via\x20query_toolkit','nash_equilibrium':'Third-party\x20arbitration\x20↔\x20User\x20purchases','fallback':'Do\x20not\x20purchase','confidence':a=>{const b=a['trust_signals'];if(!b)return 0.6;if(b['arbitration_independent']===![])return 0.9;return 0.3;},'rationale':a=>{const b=a['trust_signals'];if(!b)return'Trust\x20signals\x20missing;\x20cannot\x20judge\x20arbitration\x20independence';if(b['arbitration_independent']===![])return'Arbitrator\x20and\x20merchant\x20are\x20the\x20same\x20address;\x20fairness\x20is\x20questionable';return'Arbitration\x20is\x20independent;\x20fairness\x20is\x20assured';}},'pricing':{'scenario':'pricing','merchant_tactic':'Price\x20is\x2020%+\x20above\x20market\x20average','user_strategy':'Cite\x20puzzle.market_context.avg_price\x20in\x20negotiation;\x20request\x20discount\x20or\x20Reward','nash_equilibrium':'Merchant\x20lowers\x20price\x20or\x20provides\x20Reward\x20↔\x20User\x20purchases','fallback':'Accept\x20current\x20price\x20but\x20request\x20additional\x20benefits','confidence':a=>{const b=a['market_context'];if(!b)return 0.4;if(b['price_percentile']>0.8)return 0.7;return 0.3;},'rationale':a=>{const b=a['market_context'];if(!b)return'Market\x20context\x20data\x20missing';return'Price\x20is\x20at\x20the\x20'+Math['round'](b['price_percentile']*0x64)+'th\x20market\x20percentile';}},'delivery_sla':{'scenario':'delivery_sla','merchant_tactic':'No\x20milestone\x20nodes\x20/\x20no\x20delivery\x20time\x20commitment','user_strategy':'Require\x20milestone\x20nodes\x20+\x20write\x20time\x20commitment\x20into\x20WTS','nash_equilibrium':'Merchant\x20configures\x20SLA\x20↔\x20User\x20purchases','fallback':'Accept\x20but\x20agree\x20on\x20timeline\x20in\x20writing\x20via\x20Messenger','confidence':a=>{const b=a['workflow_analysis'];if(!b)return 0.5;if(b['has_milestone_nodes']===![])return 0.8;return 0.3;},'rationale':a=>{const b=a['workflow_analysis'];if(!b)return'Workflow\x20structure\x20missing;\x20cannot\x20assess\x20milestones';if(b['has_milestone_nodes']===![])return'No\x20milestone\x20nodes\x20detected';return'Milestone\x20nodes\x20are\x20configured';}},'quality_verification':{'scenario':'quality_verification','merchant_tactic':'WIP\x20hash\x20not\x20verified','user_strategy':'Require\x20WIP\x20hash\x20verification;\x20request\x20samples\x20or\x20phased\x20delivery\x20evidence','nash_equilibrium':'Merchant\x20provides\x20WIP\x20verification\x20↔\x20User\x20purchases','fallback':'Request\x20samples\x20via\x20Messenger','confidence':a=>{const b=a['service_basics'];if(b['wip_verified']===![])return 0.85;return 0.3;},'rationale':a=>{const b=a['service_basics'];if(b['wip_verified']===![])return'WIP\x20hash\x20is\x20unverified;\x20deliverables\x20may\x20have\x20been\x20tampered\x20with';return'WIP\x20hash\x20is\x20verified';}},'after_sales':{'scenario':'after_sales','merchant_tactic':'No\x20Messenger\x20or\x20post-sale\x20support','user_strategy':'Require\x20Messenger\x20to\x20be\x20configured;\x20require\x20post-sale\x20terms\x20to\x20be\x20written\x20down','nash_equilibrium':'Merchant\x20provides\x20post-sale\x20channel\x20↔\x20User\x20purchases','fallback':'Use\x20Contact\x20channel\x20as\x20a\x20substitute','confidence':a=>{const b=a['trust_signals'];if(!b)return 0.5;if(b['has_messenger']===![])return 0.75;return 0.3;},'rationale':a=>{const b=a['trust_signals'];if(!b)return'Trust\x20signals\x20missing;\x20cannot\x20confirm\x20Messenger';if(b['has_messenger']===![])return'Messenger\x20is\x20not\x20configured;\x20no\x20post-sale\x20channel';return'Messenger\x20is\x20configured';}}};export function recommendStrategy(a,b){const c=SCENARIO_SPECS[a],{puzzle:d,prefs:e}=b,f={'scenario':c['scenario'],'merchant_tactic':c['merchant_tactic'],'user_strategy':c['user_strategy'],'nash_equilibrium':c['nash_equilibrium']},g=clampConfidence(c['confidence'](d)),h=applyPrefsToFallback(a,c['fallback'],e),i=c['rationale'](d);return{'scenario':c['scenario'],'strategy':f,'confidence':g,'fallback':h,'rationale':i};}export function detectScenarios(a){const b=[];return(a['workflow_analysis']===undefined||a['completeness']<0.5)&&b['push']('info_asymmetry'),a['fund_safety']?.['compensation_covers_order']===![]&&b['push']('fund_safety'),a['workflow_analysis']?.['has_refund_path']===![]&&b['push']('refund_dispute'),a['trust_signals']?.['arbitration_independent']===![]&&b['push']('arbitration_fairness'),a['market_context']&&a['market_context']['price_percentile']>0.8&&b['push']('pricing'),a['workflow_analysis']?.['has_milestone_nodes']===![]&&b['push']('delivery_sla'),a['service_basics']['wip_verified']===![]&&b['push']('quality_verification'),a['trust_signals']?.['has_messenger']===![]&&b['push']('after_sales'),b['slice'](0x0,0x3);}export function flowMigrationStrategy(a){const b=a['workflow_analysis'];if(!b||b['machine_published']===![])return{'strategy':'Machine\x20is\x20not\x20published;\x20strongly\x20recommend\x20requiring\x20the\x20merchant\x20to\x20publish\x20before\x20ordering','risk':'high','advice':'An\x20unpublished\x20Machine\x20means\x20the\x20workflow\x20is\x20not\x20yet\x20in\x20effect;\x20after\x20ordering,\x20the\x20order\x20may\x20not\x20advance\x20along\x20the\x20expected\x20path.\x20Suggest\x20asking\x20the\x20merchant\x20via\x20Messenger\x20to\x20publish\x20the\x20Machine\x20before\x20placing\x20the\x20order.'};if(b['machine_paused']===!![])return{'strategy':'Machine\x20is\x20paused;\x20confirm\x20the\x20reason\x20before\x20ordering','risk':'medium','advice':'The\x20Machine\x20has\x20been\x20paused\x20by\x20the\x20merchant;\x20it\x20may\x20be\x20temporary\x20maintenance\x20or\x20an\x20active\x20delisting.\x20Suggest\x20asking\x20the\x20merchant\x20via\x20Messenger\x20about\x20the\x20reason\x20and\x20confirming\x20the\x20resumption\x20time\x20before\x20ordering.'};return{'strategy':'Safe\x20to\x20order;\x20workflow\x20is\x20stable','risk':'low','advice':'The\x20Machine\x20is\x20published\x20and\x20not\x20paused;\x20the\x20workflow\x20is\x20active\x20and\x20it\x20is\x20safe\x20to\x20order.\x20Still\x20recommend\x20monitoring\x20progress\x20via\x20Progress\x20nodes\x20after\x20ordering.'};}export function repeatGameStrategy(a,b){const c=b['completed']>=0x5&&(b['completed']===0x0||b['disputes']/b['completed']<0.2);if(c){const e=b['completed']>0x0?Math['round'](b['disputes']/b['completed']*0x64):0x0;return{'strategy':'Long-term\x20trust\x20established;\x20consider\x20bulk\x20ordering\x20/\x20discount\x20negotiation','is_long_term_partner':!![],'advice':'Historical\x20completed\x20orders:\x20'+b['completed']+',\x20dispute\x20rate:\x20'+e+'%,\x20trust\x20level\x20is\x20high.\x20'+'Consider\x20bulk\x20ordering\x20to\x20negotiate\x20discounts,\x20or\x20negotiate\x20a\x20long-term\x20cooperation\x20agreement.\x20Still\x20recommend\x20keeping\x20WTS\x20evidence\x20for\x20future\x20rights\x20protection.'};}if(b['completed']<0x5)return{'strategy':'First-time\x20cooperation;\x20recommend\x20a\x20small\x20test\x20order\x20before\x20scaling\x20up\x20once\x20trust\x20is\x20established','is_long_term_partner':![],'advice':'Only\x20'+b['completed']+'\x20historical\x20order(s);\x20sample\x20is\x20insufficient\x20to\x20judge\x20long-term\x20trust.\x20'+'Recommend\x20testing\x20the\x20merchant\x27s\x20fulfillment\x20and\x20communication\x20efficiency\x20with\x20a\x20small\x20order\x20first,\x20'+'and\x20scaling\x20up\x20once\x20trust\x20is\x20accumulated.\x20Focus\x20on\x20refund\x20path\x20and\x20arbitration\x20configuration.'};const d=Math['round'](b['disputes']/b['completed']*0x64);return{'strategy':'Historical\x20dispute\x20rate\x20is\x20high;\x20recommend\x20ordering\x20with\x20caution\x20and\x20strengthening\x20risk\x20safeguards','is_long_term_partner':![],'advice':'Among\x20'+b['completed']+'\x20historical\x20orders,\x20the\x20dispute\x20rate\x20of\x20'+d+'%\x20is\x20high.\x20Recommend\x20requiring\x20the\x20merchant\x20to\x20top\x20up\x20the\x20compensation\x20fund,\x20write\x20terms\x20into\x20the\x20WTS\x20agreement,\x20and\x20strengthen\x20upfront\x20arbitration\x20clauses\x20for\x20this\x20order.'};}export function rightsProtectionStrategy(a,b){const c=[],d=[],e=[],f=a['workflow_analysis']?.['has_refund_path']??![],g=a['workflow_analysis']?.['has_arbitration_path']??![],h=a['trust_signals']?.['arbitration_independent']??!![],i=a['fund_safety']?.['compensation_ratio']??0x0;!f?c['push']('Require\x20the\x20merchant\x20to\x20configure\x20a\x20refund\x20Allocator\x20(100%→Order)'):c['push']('Confirm\x20the\x20refund\x20path\x20is\x20available');if(!g)c['push']('Require\x20the\x20merchant\x20to\x20bind\x20a\x20third-party\x20arbitration\x20service');else!h?c['push']('Require\x20the\x20merchant\x20to\x20switch\x20to\x20third-party\x20arbitration\x20(currently\x20self-built\x20arbitration)'):c['push']('Confirm\x20the\x20arbitration\x20path\x20is\x20available');i<0x1?c['push']('Require\x20the\x20merchant\x20to\x20top\x20up\x20the\x20compensation\x20fund\x20to\x20100%\x20of\x20the\x20order\x20amount\x20(currently\x20covers\x20'+Math['round'](i*0x64)+'%)'):c['push']('Confirm\x20the\x20compensation\x20fund\x20is\x20sufficient');b?.['require_arbitration']&&!g&&c['push']('User\x20preference\x20requires\x20mandatory\x20arbitration');b?.['require_compensation_fund']&&i<0x1&&c['push']('User\x20preference\x20requires\x20a\x20mandatory\x20compensation\x20fund');d['push']('Price\x20(negotiate\x20based\x20on\x20market\x20average)'),d['push']('Delivery\x20time\x20(agree\x20in\x20writing\x20via\x20Messenger)'),d['push']('Reward\x20or\x20discount\x20(based\x20on\x20puzzle.market_context)');b&&(b['bargain_hunting']>0.5&&d['push']('Additional\x20discount\x20(user\x20has\x20a\x20strong\x20bargain-hunting\x20tendency)'),b['reward_seeking']&&d['push']('Reward\x20incentive\x20terms'),b['delivery_speed_priority']==='urgent'&&d['push']('Expedited\x20delivery\x20commitment'));!g&&!f&&e['push']('No\x20arbitration\x20and\x20no\x20refund\x20path:\x20the\x20merchant\x20can\x20breach\x20at\x20will,\x20funds\x20are\x20unprotected;\x20recommend\x20not\x20purchasing');i<0.5&&e['push']('Compensation\x20fund\x20coverage\x20is\x20only\x20'+Math['round'](i*0x64)+'%\x20(<50%):\x20payout\x20is\x20severely\x20insufficient\x20if\x20the\x20order\x20fails;\x20recommend\x20not\x20purchasing');if(b){const j=a['trust_signals']?.['trust_score']??0x64;j<b['min_trust_score']&&e['push']('Composite\x20trust\x20score\x20'+j+'\x20is\x20below\x20the\x20user\x27s\x20minimum\x20requirement\x20of\x20'+b['min_trust_score']);}return{'required_rights':c,'negotiable_rights':d,'red_lines':e};}function clampConfidence(a){if(a<0x0)return 0x0;if(a>0x1)return 0x1;return a;}function applyPrefsToFallback(a,b,c){if(!c)return b;if(c['risk_appetite']==='conservative'){if(a==='arbitration_fairness'||a==='fund_safety')return'Abandon\x20purchase\x20(conservative\x20user)';}if(c['risk_appetite']==='aggressive'){if(a==='pricing')return'Accept\x20current\x20price\x20but\x20request\x20additional\x20Reward\x20or\x20discount';}return b;}export{CUSTOMER_INTELLIGENCE_VERSION};
1
+ import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';const SCENARIO_SPECS={'info_asymmetry':{'scenario':'info_asymmetry','merchant_tactic':'Hides\x20key\x20workflow\x20information;\x20Machine\x20is\x20not\x20public','user_strategy':'Request\x20machineNode2file\x20export\x20+\x20Guard\x20configuration;\x20ask\x20about\x20key\x20nodes\x20via\x20Messenger','nash_equilibrium':'Merchant\x20becomes\x20transparent\x20(provides\x20full\x20Machine\x20docs)\x20↔\x20User\x20purchases','fallback':'Abandon\x20purchase','confidence':a=>{if(a['workflow_analysis']===undefined)return 0.9;if(a['completeness']<0.5)return 0.9;return 0.5;},'rationale':a=>{if(a['workflow_analysis']===undefined)return'Workflow\x20structure\x20analysis\x20missing;\x20severe\x20information\x20asymmetry';if(a['completeness']<0.5)return'Information\x20completeness\x20is\x20only\x20'+Math['round'](a['completeness']*0x64)+'%;\x20key\x20puzzle\x20pieces\x20missing';return'Information\x20completeness\x20is\x20acceptable,\x20but\x20still\x20recommend\x20requesting\x20Machine\x20docs';}},'fund_safety':{'scenario':'fund_safety','merchant_tactic':'No\x20compensation\x20fund\x20or\x20insufficient\x20compensation\x20fund','user_strategy':'Require\x20merchant\x20to\x20top\x20up\x20compensation_fund\x20to\x20100%\x20of\x20order\x20amount;\x20write\x20into\x20WTS\x20agreement','nash_equilibrium':'Merchant\x20tops\x20up\x20compensation\x20fund\x20↔\x20User\x20purchases','fallback':'Choose\x20another\x20merchant\x20or\x20require\x20arbitration\x20upfront','confidence':a=>{const b=a['fund_safety'];if(!b)return 0.6;if(b['compensation_covers_order']===![])return 0.95;return 0.4;},'rationale':a=>{const b=a['fund_safety'];if(!b)return'Fund\x20safety\x20analysis\x20missing';if(b['compensation_covers_order']===![])return'Compensation\x20fund\x20covers\x20only\x20'+Math['round'](b['compensation_ratio']*0x64)+'%\x20of\x20order\x20amount';return'Compensation\x20fund\x20covers\x20the\x20order\x20amount';}},'refund_dispute':{'scenario':'refund_dispute','merchant_tactic':'No\x20refund\x20path\x20or\x20unfair\x20refund\x20Allocator\x20configuration','user_strategy':'Negotiate\x20refund\x20terms\x20via\x20Messenger\x20+\x20require\x20100%→Order\x20Allocator','nash_equilibrium':'Merchant\x20configures\x20refund\x20Allocator\x20↔\x20User\x20purchases','fallback':'Arbitration','confidence':a=>{const b=a['workflow_analysis'];if(!b)return 0.5;if(b['has_refund_path']===![])return 0.85;return 0.4;},'rationale':a=>{const b=a['workflow_analysis'];if(!b)return'Workflow\x20structure\x20missing;\x20cannot\x20confirm\x20refund\x20path';if(b['has_refund_path']===![])return'No\x20refund\x20path\x20detected\x20in\x20the\x20workflow';return'Refund\x20path\x20exists';}},'arbitration_fairness':{'scenario':'arbitration_fairness','merchant_tactic':'Self-built\x20arbitration\x20(owner=service\x20owner)','user_strategy':'Require\x20third-party\x20arbitration;\x20verify\x20arb\x20owner\x20via\x20query_toolkit','nash_equilibrium':'Third-party\x20arbitration\x20↔\x20User\x20purchases','fallback':'Do\x20not\x20purchase','confidence':a=>{const b=a['trust_signals'];if(!b)return 0.6;if(b['arbitration_independent']===![])return 0.9;return 0.3;},'rationale':a=>{const b=a['trust_signals'];if(!b)return'Trust\x20signals\x20missing;\x20cannot\x20judge\x20arbitration\x20independence';if(b['arbitration_independent']===![])return'Arbitrator\x20and\x20merchant\x20are\x20the\x20same\x20address;\x20fairness\x20is\x20questionable';return'Arbitration\x20is\x20independent;\x20fairness\x20is\x20assured';}},'pricing':{'scenario':'pricing','merchant_tactic':'Price\x20is\x2020%+\x20above\x20market\x20average','user_strategy':'Cite\x20puzzle.market_context.avg_price\x20in\x20negotiation;\x20request\x20discount\x20or\x20Reward','nash_equilibrium':'Merchant\x20lowers\x20price\x20or\x20provides\x20Reward\x20↔\x20User\x20purchases','fallback':'Accept\x20current\x20price\x20but\x20request\x20additional\x20benefits','confidence':a=>{const b=a['market_context'];if(!b)return 0.4;if(b['price_percentile']>0.8)return 0.7;return 0.3;},'rationale':a=>{const b=a['market_context'];if(!b)return'Market\x20context\x20data\x20missing';return'Price\x20is\x20at\x20the\x20'+Math['round'](b['price_percentile']*0x64)+'th\x20market\x20percentile';}},'delivery_sla':{'scenario':'delivery_sla','merchant_tactic':'No\x20milestone\x20nodes\x20/\x20no\x20delivery\x20time\x20commitment','user_strategy':'Require\x20milestone\x20nodes\x20+\x20write\x20time\x20commitment\x20into\x20WTS','nash_equilibrium':'Merchant\x20configures\x20SLA\x20↔\x20User\x20purchases','fallback':'Accept\x20but\x20agree\x20on\x20timeline\x20in\x20writing\x20via\x20Messenger','confidence':a=>{const b=a['workflow_analysis'];if(!b)return 0.5;if(b['has_milestone_nodes']===![])return 0.8;return 0.3;},'rationale':a=>{const b=a['workflow_analysis'];if(!b)return'Workflow\x20structure\x20missing;\x20cannot\x20assess\x20milestones';if(b['has_milestone_nodes']===![])return'No\x20milestone\x20nodes\x20detected';return'Milestone\x20nodes\x20are\x20configured';}},'quality_verification':{'scenario':'quality_verification','merchant_tactic':'WIP\x20hash\x20not\x20verified','user_strategy':'Require\x20WIP\x20hash\x20verification;\x20request\x20samples\x20or\x20phased\x20delivery\x20evidence','nash_equilibrium':'Merchant\x20provides\x20WIP\x20verification\x20↔\x20User\x20purchases','fallback':'Request\x20samples\x20via\x20Messenger','confidence':a=>{const b=a['service_basics'];if(b['wip_verified']===![])return 0.85;return 0.3;},'rationale':a=>{const b=a['service_basics'];if(b['wip_verified']===![])return'WIP\x20hash\x20is\x20unverified;\x20deliverables\x20may\x20have\x20been\x20tampered\x20with';return'WIP\x20hash\x20is\x20verified';}},'after_sales':{'scenario':'after_sales','merchant_tactic':'No\x20Messenger\x20or\x20post-sale\x20support','user_strategy':'Require\x20Messenger\x20to\x20be\x20configured;\x20require\x20post-sale\x20terms\x20to\x20be\x20written\x20down','nash_equilibrium':'Merchant\x20provides\x20post-sale\x20channel\x20↔\x20User\x20purchases','fallback':'Use\x20Contact\x20channel\x20as\x20a\x20substitute','confidence':a=>{const b=a['trust_signals'];if(!b)return 0.5;if(b['has_messenger']===![])return 0.75;return 0.3;},'rationale':a=>{const b=a['trust_signals'];if(!b)return'Trust\x20signals\x20missing;\x20cannot\x20confirm\x20Messenger';if(b['has_messenger']===![])return'Messenger\x20is\x20not\x20configured;\x20no\x20post-sale\x20channel';return'Messenger\x20is\x20configured';}}};export function recommendStrategy(a,b){const c=SCENARIO_SPECS[a],{puzzle:d,prefs:e}=b,f={'scenario':c['scenario'],'merchant_tactic':c['merchant_tactic'],'user_strategy':c['user_strategy'],'nash_equilibrium':c['nash_equilibrium']},g=clampConfidence(c['confidence'](d)),h=applyPrefsToFallback(a,c['fallback'],e),i=c['rationale'](d);return{'scenario':c['scenario'],'strategy':f,'confidence':g,'fallback':h,'rationale':i};}export function detectScenarios(a){const b=[];return(a['workflow_analysis']===undefined||a['completeness']<0.5)&&b['push']('info_asymmetry'),a['fund_safety']?.['compensation_covers_order']===![]&&b['push']('fund_safety'),a['workflow_analysis']?.['has_refund_path']===![]&&b['push']('refund_dispute'),a['trust_signals']?.['arbitration_independent']===![]&&b['push']('arbitration_fairness'),a['market_context']&&a['market_context']['price_percentile']>0.8&&b['push']('pricing'),a['workflow_analysis']?.['has_milestone_nodes']===![]&&b['push']('delivery_sla'),a['service_basics']['wip_verified']===![]&&b['push']('quality_verification'),a['trust_signals']?.['has_messenger']===![]&&b['push']('after_sales'),b['slice'](0x0,0x3);}function clampConfidence(a){if(a<0x0)return 0x0;if(a>0x1)return 0x1;return a;}function applyPrefsToFallback(a,b,c){if(!c)return b;if(c['risk_appetite']==='conservative'){if(a==='arbitration_fairness'||a==='fund_safety')return'Abandon\x20purchase\x20(conservative\x20user)';}if(c['risk_appetite']==='aggressive'){if(a==='pricing')return'Accept\x20current\x20price\x20but\x20request\x20additional\x20Reward\x20or\x20discount';}return b;}export{CUSTOMER_INTELLIGENCE_VERSION};
@@ -37,11 +37,6 @@ export interface ReminderContext {
37
37
  }
38
38
  export declare function generateReminders(ctx: ReminderContext): Reminder[];
39
39
  export declare function sortAndCapReminders(reminders: Reminder[]): Reminder[];
40
- export declare function generateMultiStageReminders(ctx: Partial<ReminderContext> & {
41
- stage: ReminderStage;
42
- }, additionalStages?: ReminderStage[]): Reminder[];
43
40
  export declare function isBlocking(reminder: Reminder): boolean;
44
41
  export declare function getBlockingReminders(reminders: Reminder[]): Reminder[];
45
- export declare function summarizeReminders(reminders: Reminder[]): string;
46
- export declare function topReminders(reminders: Reminder[], n?: number): Reminder[];
47
42
  export { CUSTOMER_INTELLIGENCE_VERSION };
@@ -1 +1 @@
1
- import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';import{formatAmountText}from'../knowledge/fund-layer.js';const REMINDER_RULES=[{'id':'browse_reviews_summary','stage':'browse','priority':'info','message':a=>'This\x20Service\x20has\x20'+a['review_count']+'\x20reviews,\x20like\x20rate\x20'+Math['round']((a['like_rate']??0x0)*0x64)+'%','applies':a=>(a['review_count']??0x0)>0x0,'dedup_key':'reviews_summary'},{'id':'browse_price_anomaly_low','stage':'browse','priority':'recommended','message':a=>{if(!a['avg_market_price']||!a['service_price']||a['avg_market_price']===0x0n)return'⚠️\x20Price\x20is\x20abnormally\x20low,\x20beware\x20of\x20quality\x20risk';const b=Number(a['service_price']*0x64n/a['avg_market_price'])/0x64,c=Math['round']((0x1-b)*0x64);return'⚠️\x20Price\x20is\x20'+c+'%\x20below\x20the\x20average\x20for\x20similar\x20services,\x20beware\x20of\x20quality\x20risk';},'applies':a=>{if(!a['avg_market_price']||!a['service_price'])return![];if(a['avg_market_price']===0x0n)return![];const b=Number(a['service_price']*0x64n/a['avg_market_price'])/0x64;return b<0.6;},'dedup_key':'price_anomaly'},{'id':'browse_no_arbitration','stage':'browse','priority':'recommended','message':'⚠️\x20This\x20Service\x20has\x20no\x20arbitration\x20configured;\x20disputes\x20have\x20no\x20resolution\x20channel','applies':a=>a['has_arbitration']===![],'dedup_key':'no_arbitration'},{'id':'browse_no_compensation','stage':'browse','priority':'recommended','message':'⚠️\x20This\x20Service\x20has\x20no\x20compensation\x20fund;\x20no\x20automatic\x20payout\x20source\x20if\x20the\x20order\x20fails','applies':a=>a['has_compensation']===![],'dedup_key':'no_compensation'},{'id':'evaluate_checklist','stage':'evaluate','priority':'info','message':'📋\x20Running\x204-dimension\x20risk\x20check\x20(workflow/fund/trust/behavior)...','applies':()=>!![],'dedup_key':'checklist_start'},{'id':'evaluate_high_risk','stage':'evaluate','priority':'required','message':a=>'🔴\x20Composite\x20risk\x20score\x20'+a['risk_score']+'/100,\x20strongly\x20recommend\x20not\x20purchasing','applies':a=>(a['risk_level']??'low')==='high','dedup_key':'high_risk_score'},{'id':'evaluate_medium_high_risk','stage':'evaluate','priority':'recommended','message':a=>'🟠\x20Composite\x20risk\x20score\x20'+a['risk_score']+'/100,\x20purchase\x20with\x20caution\x20and\x20focus\x20on\x202-3\x20key\x20risks','applies':a=>(a['risk_level']??'low')==='medium_high','dedup_key':'medium_high_risk'},{'id':'evaluate_ambiguous_guard','stage':'evaluate','priority':'required','message':a=>'🔴\x20Detected\x20'+(a['ambiguous_guards']?.['length']??0x0)+'\x20ambiguous\x20Guard(s);\x20manual\x20review\x20is\x20required\x20before\x20proceeding:\x20'+(a['ambiguous_guards']?.['join'](',\x20')??''),'applies':a=>(a['ambiguous_guards']?.['length']??0x0)>0x0,'dedup_key':'ambiguous_guard'},{'id':'evaluate_no_refund_path','stage':'evaluate','priority':'recommended','message':'⚠️\x20No\x20refund\x20path:\x20if\x20delivery\x20fails,\x20funds\x20may\x20be\x20unrecoverable.\x20Recommend\x20negotiating\x20refund\x20terms\x20via\x20Messenger','applies':a=>a['has_refund_path']===![],'dedup_key':'no_refund_path'},{'id':'evaluate_refund_conditions','stage':'evaluate','priority':'info','message':a=>{const b=[];a['has_arb_refund_path']&&b['push']('Arbitration-backed\x20(dispute\x20→\x20ruling\x20→\x20compensation\x20payout)');a['has_refund_allocator']&&b['push']('refund-to-order\x20Allocator\x20(cancel/refund\x20returns\x20funds)');if(b['length']===0x0)return'';return'Refund\x20conditions:\x20'+b['join'](';\x20')+'.';},'applies':a=>a['has_refund_path']===!![]&&(a['has_arb_refund_path']===!![]||a['has_refund_allocator']===!![]),'dedup_key':'refund_conditions'},{'id':'evaluate_no_user_operable','stage':'evaluate','priority':'required','message':'🔴\x20No\x20user-operable\x20steps\x20in\x20the\x20workflow:\x20order\x20progress\x20depends\x20entirely\x20on\x20the\x20merchant','applies':a=>a['has_user_operable']===![],'dedup_key':'no_user_operable'},{'id':'evaluate_below_min_trust','stage':'evaluate','priority':'required','message':a=>'🔴\x20Risk\x20score\x20'+a['risk_score']+'\x20is\x20below\x20your\x20minimum\x20requirement\x20of\x20'+a['user_min_trust_score'],'applies':a=>a['user_min_trust_score']!==undefined&&a['risk_score']!==undefined&&a['risk_score']<a['user_min_trust_score'],'dedup_key':'below_min_trust'},{'id':'preorder_payment_confirm','stage':'preorder','priority':'required','message':a=>'🔔\x20About\x20to\x20pay\x20'+formatAmountText(a['service_price']??0x0n,a['token']?.['decimals'],a['token']?.['symbol'])+'\x20to\x20the\x20escrow\x20account,\x20please\x20confirm','applies':a=>a['service_price']!==undefined,'dedup_key':'payment_confirm'},{'id':'preorder_compensation_insufficient','stage':'preorder','priority':'recommended','message':a=>'⚠️\x20Compensation\x20balance\x20only\x20covers\x20'+Math['round']((a['compensation_ratio']??0x0)*0x64)+'%\x20of\x20the\x20order\x20amount','applies':a=>(a['compensation_ratio']??0x1)<0x1,'dedup_key':'compensation_insufficient'},{'id':'preorder_user_require_arb_missing','stage':'preorder','priority':'required','message':'🔴\x20Your\x20preferences\x20require\x20arbitration,\x20but\x20this\x20Service\x20does\x20not\x20have\x20it\x20configured','applies':a=>a['user_require_arbitration']===!![]&&a['has_arbitration']===![],'dedup_key':'user_require_arb_missing'},{'id':'preorder_user_require_comp_missing','stage':'preorder','priority':'required','message':'🔴\x20Your\x20preferences\x20require\x20a\x20compensation\x20fund,\x20but\x20this\x20Service\x20has\x20none','applies':a=>a['user_require_compensation']===!![]&&a['has_compensation']===![],'dedup_key':'user_require_comp_missing'},{'id':'preorder_no_messenger','stage':'preorder','priority':'recommended','message':'⚠️\x20Merchant\x20has\x20no\x20Messenger\x20channel;\x20no\x20way\x20to\x20negotiate\x20or\x20get\x20post-sale\x20support\x20after\x20ordering','applies':a=>a['has_messenger']===![],'dedup_key':'no_messenger'},{'id':'preorder_customer_required_no_contact','stage':'preorder','priority':'required','message':a=>'🔴\x20This\x20Service\x20requires\x20private\x20information\x20('+(a['customer_required']??[])['join'](',\x20')+'),\x20'+'but\x20it\x20has\x20NO\x20Contact/Messenger\x20channel\x20configured.\x20Your\x20private\x20information\x20cannot\x20be\x20delivered\x20securely\x20'+'—\x20do\x20NOT\x20order\x20until\x20the\x20merchant\x20binds\x20a\x20Contact\x20(um)\x20so\x20the\x20info\x20can\x20be\x20sent\x20end-to-end\x20encrypted.','applies':a=>(a['customer_required']?.['length']??0x0)>0x0&&a['has_messenger']===![],'dedup_key':'customer_required_no_contact'},{'id':'preorder_customer_required_send_info','stage':'preorder','priority':'recommended','message':a=>'🔐\x20After\x20ordering\x20you\x20MUST\x20send\x20your\x20private\x20information\x20('+(a['customer_required']??[])['join'](',\x20')+')\x20'+'to\x20the\x20merchant\x27s\x20Contact\x20via\x20end-to-end\x20encrypted\x20Messenger,\x20and\x20obtain\x20a\x20confirmation\x20reply.\x20'+'Your\x20private\x20information\x20is\x20encrypted\x20end-to-end\x20and\x20never\x20stored\x20in\x20plaintext\x20by\x20the\x20service.','applies':a=>(a['customer_required']?.['length']??0x0)>0x0&&a['has_messenger']===!![],'dedup_key':'customer_required_send_info'},{'id':'in_progress_progress_stalled','stage':'in_progress','priority':'recommended','message':a=>'⚠️\x20Order\x20has\x20been\x20stuck\x20at\x20node\x20'+a['current_node']+'\x20for\x20over\x20'+a['hours_since_last_progress']+'\x20hours,\x20suggest\x20contacting\x20the\x20merchant','applies':a=>{const b=a['hours_since_last_progress']??0x0,c=a['expected_progress_hours']??0x18;return b>c*0x2;},'dedup_key':'progress_stalled'},{'id':'in_progress_compensation_drop','stage':'in_progress','priority':'recommended','message':'⚠️\x20Merchant\x20compensation\x20fund\x20balance\x20dropped\x2030%,\x20please\x20note','applies':()=>![],'dedup_key':'compensation_drop'},{'id':'in_progress_user_action_required','stage':'in_progress','priority':'reminder','message':a=>'🔔\x20Order\x20advanced\x20to\x20node\x20'+a['current_node']+',\x20your\x20action\x20is\x20required','applies':a=>a['current_node']!==undefined&&a['current_node']!=='','dedup_key':'user_action_required'},{'id':'in_progress_messenger_unanswered','stage':'in_progress','priority':'recommended','message':a=>'⚠️\x20Merchant\x20has\x20not\x20replied\x20on\x20Messenger\x20for\x20'+a['hours_since_messenger_reply']+'\x20hours;\x20consider\x20initiating\x20arbitration','applies':a=>(a['hours_since_messenger_reply']??0x0)>0x18,'dedup_key':'messenger_unanswered'},{'id':'complete_review_reminder','stage':'complete','priority':'info','message':'💡\x20Order\x20completed,\x20would\x20you\x20like\x20to\x20submit\x20a\x20review?','applies':()=>!![],'dedup_key':'review_reminder'},{'id':'complete_review_window','stage':'complete','priority':'reminder','message':a=>'⏰\x20The\x20review\x20window\x20will\x20close\x20in\x20'+a['review_window_days']+'\x20days','applies':a=>(a['review_window_days']??0x0)>0x0,'dedup_key':'review_window'},{'id':'after_sale_arb_window','stage':'after_sale','priority':'reminder','message':a=>'⏰\x20The\x20arbitration\x20application\x20window\x20will\x20close\x20in\x20'+a['arb_window_days']+'\x20day(s)','applies':a=>(a['arb_window_days']??0x0)>0x0,'dedup_key':'arb_window'},{'id':'after_sale_refund_received','stage':'after_sale','priority':'info','message':'✅\x20Refund\x20received','applies':()=>![],'dedup_key':'refund_received'}];export function generateReminders(a){const b=REMINDER_RULES['filter'](e=>e['stage']===a['stage']),c=new Map();for(const e of b){if(!e['applies'](a))continue;const f=c['get'](e['dedup_key']);(!f||priorityRank(e['priority'])>priorityRank(f['priority']))&&c['set'](e['dedup_key'],e);}const d=Array['from'](c['values']())['map'](g=>({'id':g['id'],'stage':g['stage'],'priority':g['priority'],'message':typeof g['message']==='function'?g['message'](a):g['message'],'action':g['action']}));return sortAndCapReminders(d);}export function sortAndCapReminders(a){const b=[...a]['sort']((f,g)=>priorityRank(g['priority'])-priorityRank(f['priority'])),c=b['filter'](f=>f['priority']==='required'||f['priority']==='recommended'),d=b['filter'](f=>f['priority']==='info'||f['priority']==='reminder'),e=c['slice'](0x0,0x3);return[...e,...d];}function priorityRank(a){switch(a){case'required':return 0x4;case'recommended':return 0x3;case'info':return 0x2;case'reminder':return 0x1;}}export function generateMultiStageReminders(a,b=[]){const c=[a['stage'],...b],d=[],e=new Set();for(const f of c){const g={...a,'stage':f},h=generateReminders(g);for(const i of h){const j=f+':'+i['id'];!e['has'](j)&&(e['add'](j),d['push'](i));}}return d;}export function isBlocking(a){return a['priority']==='required';}export function getBlockingReminders(a){return a['filter'](isBlocking);}export function summarizeReminders(a){if(a['length']===0x0)return'No\x20reminders';const b=a['filter'](g=>g['priority']==='required'),c=a['filter'](g=>g['priority']==='recommended'),d=a['filter'](g=>g['priority']==='info'),e=a['filter'](g=>g['priority']==='reminder'),f=[];if(b['length'])f['push']('🔴\x20Must-read:\x20'+b['length']);if(c['length'])f['push']('⚠️\x20Recommended:\x20'+c['length']);if(d['length'])f['push']('💡\x20Info:\x20'+d['length']);if(e['length'])f['push']('🔔\x20Reminder:\x20'+e['length']);return f['join'](',\x20');}export function topReminders(a,b=0x5){return sortAndCapReminders(a)['slice'](0x0,b);}export{CUSTOMER_INTELLIGENCE_VERSION};
1
+ import{CUSTOMER_INTELLIGENCE_VERSION}from'./types.js';import{formatAmountText}from'../knowledge/fund-layer.js';const REMINDER_RULES=[{'id':'browse_reviews_summary','stage':'browse','priority':'info','message':a=>'This\x20Service\x20has\x20'+a['review_count']+'\x20reviews,\x20like\x20rate\x20'+Math['round']((a['like_rate']??0x0)*0x64)+'%','applies':a=>(a['review_count']??0x0)>0x0,'dedup_key':'reviews_summary'},{'id':'browse_price_anomaly_low','stage':'browse','priority':'recommended','message':a=>{if(!a['avg_market_price']||!a['service_price']||a['avg_market_price']===0x0n)return'⚠️\x20Price\x20is\x20abnormally\x20low,\x20beware\x20of\x20quality\x20risk';const b=Number(a['service_price']*0x64n/a['avg_market_price'])/0x64,c=Math['round']((0x1-b)*0x64);return'⚠️\x20Price\x20is\x20'+c+'%\x20below\x20the\x20average\x20for\x20similar\x20services,\x20beware\x20of\x20quality\x20risk';},'applies':a=>{if(!a['avg_market_price']||!a['service_price'])return![];if(a['avg_market_price']===0x0n)return![];const b=Number(a['service_price']*0x64n/a['avg_market_price'])/0x64;return b<0.6;},'dedup_key':'price_anomaly'},{'id':'browse_no_arbitration','stage':'browse','priority':'recommended','message':'⚠️\x20This\x20Service\x20has\x20no\x20arbitration\x20configured;\x20disputes\x20have\x20no\x20resolution\x20channel','applies':a=>a['has_arbitration']===![],'dedup_key':'no_arbitration'},{'id':'browse_no_compensation','stage':'browse','priority':'recommended','message':'⚠️\x20This\x20Service\x20has\x20no\x20compensation\x20fund;\x20no\x20automatic\x20payout\x20source\x20if\x20the\x20order\x20fails','applies':a=>a['has_compensation']===![],'dedup_key':'no_compensation'},{'id':'evaluate_checklist','stage':'evaluate','priority':'info','message':'📋\x20Running\x204-dimension\x20risk\x20check\x20(workflow/fund/trust/behavior)...','applies':()=>!![],'dedup_key':'checklist_start'},{'id':'evaluate_high_risk','stage':'evaluate','priority':'required','message':a=>'🔴\x20Composite\x20risk\x20score\x20'+a['risk_score']+'/100,\x20strongly\x20recommend\x20not\x20purchasing','applies':a=>(a['risk_level']??'low')==='high','dedup_key':'high_risk_score'},{'id':'evaluate_medium_high_risk','stage':'evaluate','priority':'recommended','message':a=>'🟠\x20Composite\x20risk\x20score\x20'+a['risk_score']+'/100,\x20purchase\x20with\x20caution\x20and\x20focus\x20on\x202-3\x20key\x20risks','applies':a=>(a['risk_level']??'low')==='medium_high','dedup_key':'medium_high_risk'},{'id':'evaluate_ambiguous_guard','stage':'evaluate','priority':'required','message':a=>'🔴\x20Detected\x20'+(a['ambiguous_guards']?.['length']??0x0)+'\x20ambiguous\x20Guard(s);\x20manual\x20review\x20is\x20required\x20before\x20proceeding:\x20'+(a['ambiguous_guards']?.['join'](',\x20')??''),'applies':a=>(a['ambiguous_guards']?.['length']??0x0)>0x0,'dedup_key':'ambiguous_guard'},{'id':'evaluate_no_refund_path','stage':'evaluate','priority':'recommended','message':'⚠️\x20No\x20refund\x20path:\x20if\x20delivery\x20fails,\x20funds\x20may\x20be\x20unrecoverable.\x20Recommend\x20negotiating\x20refund\x20terms\x20via\x20Messenger','applies':a=>a['has_refund_path']===![],'dedup_key':'no_refund_path'},{'id':'evaluate_refund_conditions','stage':'evaluate','priority':'info','message':a=>{const b=[];a['has_arb_refund_path']&&b['push']('Arbitration-backed\x20(dispute\x20→\x20ruling\x20→\x20compensation\x20payout)');a['has_refund_allocator']&&b['push']('refund-to-order\x20Allocator\x20(cancel/refund\x20returns\x20funds)');if(b['length']===0x0)return'';return'Refund\x20conditions:\x20'+b['join'](';\x20')+'.';},'applies':a=>a['has_refund_path']===!![]&&(a['has_arb_refund_path']===!![]||a['has_refund_allocator']===!![]),'dedup_key':'refund_conditions'},{'id':'evaluate_no_user_operable','stage':'evaluate','priority':'required','message':'🔴\x20No\x20user-operable\x20steps\x20in\x20the\x20workflow:\x20order\x20progress\x20depends\x20entirely\x20on\x20the\x20merchant','applies':a=>a['has_user_operable']===![],'dedup_key':'no_user_operable'},{'id':'evaluate_below_min_trust','stage':'evaluate','priority':'required','message':a=>'🔴\x20Risk\x20score\x20'+a['risk_score']+'\x20is\x20below\x20your\x20minimum\x20requirement\x20of\x20'+a['user_min_trust_score'],'applies':a=>a['user_min_trust_score']!==undefined&&a['risk_score']!==undefined&&a['risk_score']<a['user_min_trust_score'],'dedup_key':'below_min_trust'},{'id':'preorder_payment_confirm','stage':'preorder','priority':'required','message':a=>'🔔\x20About\x20to\x20pay\x20'+formatAmountText(a['service_price']??0x0n,a['token']?.['decimals'],a['token']?.['symbol'])+'\x20to\x20the\x20escrow\x20account,\x20please\x20confirm','applies':a=>a['service_price']!==undefined,'dedup_key':'payment_confirm'},{'id':'preorder_compensation_insufficient','stage':'preorder','priority':'recommended','message':a=>'⚠️\x20Compensation\x20balance\x20only\x20covers\x20'+Math['round']((a['compensation_ratio']??0x0)*0x64)+'%\x20of\x20the\x20order\x20amount','applies':a=>(a['compensation_ratio']??0x1)<0x1,'dedup_key':'compensation_insufficient'},{'id':'preorder_user_require_arb_missing','stage':'preorder','priority':'required','message':'🔴\x20Your\x20preferences\x20require\x20arbitration,\x20but\x20this\x20Service\x20does\x20not\x20have\x20it\x20configured','applies':a=>a['user_require_arbitration']===!![]&&a['has_arbitration']===![],'dedup_key':'user_require_arb_missing'},{'id':'preorder_user_require_comp_missing','stage':'preorder','priority':'required','message':'🔴\x20Your\x20preferences\x20require\x20a\x20compensation\x20fund,\x20but\x20this\x20Service\x20has\x20none','applies':a=>a['user_require_compensation']===!![]&&a['has_compensation']===![],'dedup_key':'user_require_comp_missing'},{'id':'preorder_no_messenger','stage':'preorder','priority':'recommended','message':'⚠️\x20Merchant\x20has\x20no\x20Messenger\x20channel;\x20no\x20way\x20to\x20negotiate\x20or\x20get\x20post-sale\x20support\x20after\x20ordering','applies':a=>a['has_messenger']===![],'dedup_key':'no_messenger'},{'id':'preorder_customer_required_no_contact','stage':'preorder','priority':'required','message':a=>'🔴\x20This\x20Service\x20requires\x20private\x20information\x20('+(a['customer_required']??[])['join'](',\x20')+'),\x20'+'but\x20it\x20has\x20NO\x20Contact/Messenger\x20channel\x20configured.\x20Your\x20private\x20information\x20cannot\x20be\x20delivered\x20securely\x20'+'—\x20do\x20NOT\x20order\x20until\x20the\x20merchant\x20binds\x20a\x20Contact\x20(um)\x20so\x20the\x20info\x20can\x20be\x20sent\x20end-to-end\x20encrypted.','action':'BLOCK\x20ordering\x20until\x20the\x20merchant\x20binds\x20a\x20Contact\x20(Service.um)\x20and\x20adds\x20a\x20customer-service\x20IM\x20(Contact.ims).\x20'+'Then\x20use\x20assembleRequiredInfoDeliveryPlan\x20to\x20deliver\x20the\x20info.','applies':a=>(a['customer_required']?.['length']??0x0)>0x0&&a['has_messenger']===![],'dedup_key':'customer_required_no_contact'},{'id':'preorder_customer_required_send_info','stage':'preorder','priority':'recommended','message':a=>'🔐\x20After\x20ordering\x20you\x20MUST\x20send\x20your\x20private\x20information\x20('+(a['customer_required']??[])['join'](',\x20')+')\x20'+'to\x20the\x20merchant\x27s\x20Contact\x20via\x20end-to-end\x20encrypted\x20Messenger,\x20and\x20obtain\x20a\x20confirmation\x20reply.\x20'+'Your\x20private\x20information\x20is\x20encrypted\x20end-to-end\x20and\x20never\x20stored\x20in\x20plaintext\x20by\x20the\x20service.','action':'assembleRequiredInfoDeliveryPlan:\x20(1)\x20query\x20Contact.ims;\x20(2)\x20collect\x20fields\x20via\x20local_info_operation;\x20'+'(3)\x20messenger_operation\x20send_message\x20to\x20the\x20Contact\x20IM;\x20(4)\x20wait\x20for\x20ARK/reply;\x20'+'(5)\x20write\x20Order.required_info\x20back\x20via\x20onchain_operations.','applies':a=>(a['customer_required']?.['length']??0x0)>0x0&&a['has_messenger']===!![],'dedup_key':'customer_required_send_info'},{'id':'in_progress_progress_stalled','stage':'in_progress','priority':'recommended','message':a=>'⚠️\x20Order\x20has\x20been\x20stuck\x20at\x20node\x20'+a['current_node']+'\x20for\x20over\x20'+a['hours_since_last_progress']+'\x20hours,\x20suggest\x20contacting\x20the\x20merchant','applies':a=>{const b=a['hours_since_last_progress']??0x0,c=a['expected_progress_hours']??0x18;return b>c*0x2;},'dedup_key':'progress_stalled'},{'id':'in_progress_compensation_drop','stage':'in_progress','priority':'recommended','message':'⚠️\x20Merchant\x20compensation\x20fund\x20balance\x20dropped\x2030%,\x20please\x20note','applies':()=>![],'dedup_key':'compensation_drop'},{'id':'in_progress_user_action_required','stage':'in_progress','priority':'reminder','message':a=>'🔔\x20Order\x20advanced\x20to\x20node\x20'+a['current_node']+',\x20your\x20action\x20is\x20required','applies':a=>a['current_node']!==undefined&&a['current_node']!=='','dedup_key':'user_action_required'},{'id':'in_progress_messenger_unanswered','stage':'in_progress','priority':'recommended','message':a=>'⚠️\x20Merchant\x20has\x20not\x20replied\x20on\x20Messenger\x20for\x20'+a['hours_since_messenger_reply']+'\x20hours;\x20consider\x20initiating\x20arbitration','applies':a=>(a['hours_since_messenger_reply']??0x0)>0x18,'dedup_key':'messenger_unanswered'},{'id':'complete_review_reminder','stage':'complete','priority':'info','message':'💡\x20Order\x20completed,\x20would\x20you\x20like\x20to\x20submit\x20a\x20review?','applies':()=>!![],'dedup_key':'review_reminder'},{'id':'complete_review_window','stage':'complete','priority':'reminder','message':a=>'⏰\x20The\x20review\x20window\x20will\x20close\x20in\x20'+a['review_window_days']+'\x20days','applies':a=>(a['review_window_days']??0x0)>0x0,'dedup_key':'review_window'},{'id':'after_sale_arb_window','stage':'after_sale','priority':'reminder','message':a=>'⏰\x20The\x20arbitration\x20application\x20window\x20will\x20close\x20in\x20'+a['arb_window_days']+'\x20day(s)','applies':a=>(a['arb_window_days']??0x0)>0x0,'dedup_key':'arb_window'},{'id':'after_sale_refund_received','stage':'after_sale','priority':'info','message':'✅\x20Refund\x20received','applies':()=>![],'dedup_key':'refund_received'}];export function generateReminders(a){const b=REMINDER_RULES['filter'](e=>e['stage']===a['stage']),c=new Map();for(const e of b){if(!e['applies'](a))continue;const f=c['get'](e['dedup_key']);(!f||priorityRank(e['priority'])>priorityRank(f['priority']))&&c['set'](e['dedup_key'],e);}const d=Array['from'](c['values']())['map'](g=>({'id':g['id'],'stage':g['stage'],'priority':g['priority'],'message':typeof g['message']==='function'?g['message'](a):g['message'],'action':g['action']}));return sortAndCapReminders(d);}export function sortAndCapReminders(a){const b=[...a]['sort']((f,g)=>priorityRank(g['priority'])-priorityRank(f['priority'])),c=b['filter'](f=>f['priority']==='required'||f['priority']==='recommended'),d=b['filter'](f=>f['priority']==='info'||f['priority']==='reminder'),e=c['slice'](0x0,0x3);return[...e,...d];}function priorityRank(a){switch(a){case'required':return 0x4;case'recommended':return 0x3;case'info':return 0x2;case'reminder':return 0x1;}}export function isBlocking(a){return a['priority']==='required';}export function getBlockingReminders(a){return a['filter'](isBlocking);}export{CUSTOMER_INTELLIGENCE_VERSION};
@@ -1 +1 @@
1
- export const OUTCOME_SEMANTICS={'completion':['fund_released_to_merchant','refund_leverage_given_up'],'refund':['fund_returned_to_buyer','arbitration_review_triggered'],'advance':['node_advanced']};export const ROLE_INTERESTS={'customer':{'prefer':['fund_returned_to_buyer'],'avoid':['fund_released_to_merchant','refund_leverage_given_up'],'sensitivity':0x1},'merchant':{'prefer':['fund_released_to_merchant'],'avoid':['fund_returned_to_buyer','arbitration_review_triggered'],'sensitivity':0x1},'collaborator':{'prefer':['node_advanced'],'avoid':[],'sensitivity':0x1},'supplier':{'prefer':['fund_released_to_merchant','node_advanced'],'avoid':['fund_returned_to_buyer'],'sensitivity':0x1},'prospect':{'prefer':['fund_returned_to_buyer'],'avoid':['fund_released_to_merchant','arbitration_review_triggered','refund_leverage_given_up'],'sensitivity':0x1},'arbitrator':{'prefer':[],'avoid':['arbitration_review_triggered'],'sensitivity':0x1},'system':{'prefer':[],'avoid':[],'sensitivity':0x1}};export function classifyOutcome(a){if(a?.['startsWith']('Completion'))return'completion';if(a?.['startsWith']('Refund'))return'refund';return'advance';}export function appetiteMultiplier(a){switch(a){case'conservative':return 1.5;case'aggressive':return 0.6;default:return 0x1;}}export function interestsOf(a){return ROLE_INTERESTS[a]??{'prefer':[],'avoid':[],'sensitivity':0x1};}function dedupe(a){return Array['from'](new Set(a));}export function resolveInterests(a,b){const c=interestsOf(a),d=c['sensitivity']*appetiteMultiplier(b?.['risk_appetite']),e=[...c['prefer']],f=[...c['avoid']];for(const g of b?.['requirements']??[]){const h=g['toLowerCase'](),i=/forbid|never|\bno\b/['test'](h);if(h['includes']('arbitration')&&i)f['push']('arbitration_review_triggered');if(h['includes']('refund')&&!i)e['push']('fund_returned_to_buyer');if((h['includes']('upfront')||h['includes']('before\x20delivery'))&&i)f['push']('fund_released_to_merchant');if(h['includes']('milestone')&&!i)e['push']('node_advanced');}return{'prefer':dedupe(e),'avoid':dedupe(f),'sensitivity':d};}export function evaluateOutcome(a,b,c){const d=OUTCOME_SEMANTICS[a]??[],e=resolveInterests(b,c),f=e['sensitivity'],g=[],h=[];for(const l of d){if(e['prefer']['includes'](l))g['push'](l);if(e['avoid']['includes'](l))h['push'](l);}const i=g['length']*0x14,j=Math['round'](h['length']*0x19*f),k=Math['max'](0x0,Math['min'](0x64,0x3c+i-j));return{'gain_score':i,'risk_score':j,'net_score':k,'gains':g,'risks':h};}export function consistencyScore(a,b){return evaluateOutcome(a,b)['net_score'];}
1
+ export const OUTCOME_SEMANTICS={'completion':['fund_released_to_merchant','refund_leverage_given_up'],'refund':['fund_returned_to_buyer','arbitration_review_triggered'],'advance':['node_advanced']};export const ROLE_INTERESTS={'customer':{'prefer':['fund_returned_to_buyer'],'avoid':['fund_released_to_merchant','refund_leverage_given_up'],'sensitivity':0x1},'merchant':{'prefer':['fund_released_to_merchant'],'avoid':['fund_returned_to_buyer','arbitration_review_triggered'],'sensitivity':0x1},'demander':{'prefer':['node_advanced'],'avoid':[],'sensitivity':0x1},'collaborator':{'prefer':['node_advanced'],'avoid':[],'sensitivity':0x1},'supplier':{'prefer':['fund_released_to_merchant','node_advanced'],'avoid':['fund_returned_to_buyer'],'sensitivity':0x1},'prospect':{'prefer':['fund_returned_to_buyer'],'avoid':['fund_released_to_merchant','arbitration_review_triggered','refund_leverage_given_up'],'sensitivity':0x1},'arbitrator':{'prefer':[],'avoid':['arbitration_review_triggered'],'sensitivity':0x1},'neutral':{'prefer':[],'avoid':[],'sensitivity':0x1},'system':{'prefer':[],'avoid':[],'sensitivity':0x1}};export function classifyOutcome(a){if(a?.['startsWith']('Completion'))return'completion';if(a?.['startsWith']('Refund'))return'refund';return'advance';}export function appetiteMultiplier(a){switch(a){case'conservative':return 1.5;case'aggressive':return 0.6;default:return 0x1;}}export function interestsOf(a){return ROLE_INTERESTS[a]??{'prefer':[],'avoid':[],'sensitivity':0x1};}function dedupe(a){return Array['from'](new Set(a));}export function resolveInterests(a,b){const c=interestsOf(a),d=c['sensitivity']*appetiteMultiplier(b?.['risk_appetite']),e=[...c['prefer']],f=[...c['avoid']];for(const g of b?.['requirements']??[]){const h=g['toLowerCase'](),i=/forbid|never|\bno\b/['test'](h);if(h['includes']('arbitration')&&i)f['push']('arbitration_review_triggered');if(h['includes']('refund')&&!i)e['push']('fund_returned_to_buyer');if((h['includes']('upfront')||h['includes']('before\x20delivery'))&&i)f['push']('fund_released_to_merchant');if(h['includes']('milestone')&&!i)e['push']('node_advanced');}return{'prefer':dedupe(e),'avoid':dedupe(f),'sensitivity':d};}export function evaluateOutcome(a,b,c){const d=OUTCOME_SEMANTICS[a]??[],e=resolveInterests(b,c),f=e['sensitivity'],g=[],h=[];for(const l of d){if(e['prefer']['includes'](l))g['push'](l);if(e['avoid']['includes'](l))h['push'](l);}const i=g['length']*0x14,j=Math['round'](h['length']*0x19*f),k=Math['max'](0x0,Math['min'](0x64,0x3c+i-j));return{'gain_score':i,'risk_score':j,'net_score':k,'gains':g,'risks':h};}export function consistencyScore(a,b){return evaluateOutcome(a,b)['net_score'];}
@@ -0,0 +1,6 @@
1
+ import { type UserProfile } from "../experience/index.js";
2
+ import { type IntentRecord } from "../intent/index.js";
3
+ import type { UserInjection } from "./types.js";
4
+ export declare function experienceToInjection(profile: UserProfile | null | undefined): UserInjection | undefined;
5
+ export declare function intentToInjection(intents: IntentRecord[] | null | undefined): UserInjection | undefined;
6
+ export declare function buildUserInjection(account?: string): Promise<UserInjection | undefined>;
@@ -0,0 +1 @@
1
+ import{getEffectivePersona,mergeInjections,personaToInjection}from'../persona/index.js';import{getProfile}from'../experience/index.js';import{listIntents}from'../intent/index.js';export function experienceToInjection(a){if(!a)return undefined;const b={'risk_appetite':a['risk_appetite'],'expertise_tier':a['expertise_tier'],'preferred_confirmation':a['preferred_confirmation']};a['preferred_industries']?.['length']&&(b['preferred_industries']=a['preferred_industries']);const c=(a['frequent_pitfalls']??[])['filter'](d=>!!d)['map'](d=>({'rule_id':'r_trust','condition':'forbid','note':'pitfall:\x20'+d}));return{'intent':'expertise='+a['expertise_tier']+';\x20success_rate='+Math['round']((a['success_rate']??0x0)*0x64)+'%','preferences':b,'requirements':c['length']?c:undefined};}export function intentToInjection(a){if(!a||a['length']===0x0)return undefined;const b=Array['from'](new Set(a['flatMap'](e=>e['industries']??[]))),c=Array['from'](new Set(a['flatMap'](e=>e['keywords']??[]))),d={};if(b['length'])d['intent_industries']=b;if(c['length'])d['intent_keywords']=c;return{'intent':a['map'](e=>e['intent'])['filter'](Boolean)['join'](';\x20'),'preferences':d};}export async function buildUserInjection(a){let b,c;try{b=a?personaToInjection(await getEffectivePersona(a)):undefined;}catch{b=undefined;}const d=experienceToInjection(getProfile());try{c=a?intentToInjection(await listIntents(a)):undefined;}catch{c=undefined;}return mergeInjections(mergeInjections(b,d),c);}
@@ -1 +1 @@
1
- import{classifyOutcome,evaluateOutcome}from'./game-strategy.js';export function evaluateNodeGame(a){const b=a['operable']['map'](c=>{const d=scoreForward(c,a['perspective'],{'risk_appetite':a['appetite'],'requirements':a['requirements']},a['order_amount']);return{'forward':c['name'],'to_node':c['to_node'],'execution_path':c['execution_path'],'guard':c['guard'],'favorability':d['favorability'],'gain_score':d['gain_score'],'risk_score':d['risk_score'],'is_optimal':![],'payoff_note':d['payoff'],'risk':d['risk']};});return b['sort']((c,d)=>d['favorability']-c['favorability']),b['length']>0x0&&(b[0x0]['is_optimal']=!![]),{'current_node':a['current_node'],'perspective':a['perspective'],'actions':b,'cooperation':evaluateCooperation(a),'value_at_stake':a['order_amount'],'risk_exposure':a['compensation_fund'],'summary':buildSummary(a,b)};}function evaluateCooperation(a){if(!a['threshold']||a['threshold']<=0x1)return undefined;const b=a['operable']['reduce']((g,h)=>g+(h['weight']??0x1),0x0),c=a['threshold']-b,d=c>0x0?a['waiting_on']['map'](f=>f['role']):[],e=a['allocation'];return{'threshold':a['threshold'],'my_weight':b,'needed_from_others':Math['max'](0x0,c),'collaborators':d,'allocation':e,'allocation_note':e?describeAllocation(e):undefined};}function describeAllocation(b){const c=['settlement\x20splits\x20across\x20'+b['recipient_slots']+'\x20recipient\x20slot(s)'];if(b['direct_to_me_slots']>0x0)c['push'](b['direct_to_me_slots']+'\x20pay\x20directly\x20to\x20you');if(b['guard_gated_slots']>0x0)c['push'](b['guard_gated_slots']+'\x20are\x20guard-resolved\x20(may\x20pay\x20a\x20cooperating\x20party)');if(b['to_payer_slots']>0x0)c['push'](b['to_payer_slots']+'\x20route\x20back\x20to\x20the\x20payer\x20(refund-oriented)');return c['join'](';\x20')+'.';}function scoreForward(a,b,c,d){const e=classifyOutcome(a['consequence']),g=evaluateOutcome(e,b,c);return{'favorability':g['net_score'],'gain_score':g['gain_score'],'risk_score':g['risk_score'],'payoff':payoffNote(e,b,d),'risk':riskOf(e,b)};}function amountSuffix(a){return a!=null?'\x20('+a+'\x20raw\x20units)':'';}function payoffNote(a,b,c){if(b==='customer'||b==='prospect')switch(a){case'refund':return'funds\x20return\x20to\x20you'+amountSuffix(c)+'\x20(refund/cancel\x20path)';case'completion':return'releases\x20escrowed\x20funds'+amountSuffix(c)+'\x20to\x20the\x20merchant\x20—\x20only\x20confirm\x20if\x20the\x20deliverable\x20matches\x20the\x20agreement';case'advance':return'advances\x20the\x20order\x20to\x20the\x20next\x20node\x20(funds'+amountSuffix(c)+'\x20stay\x20escrowed)';}if(b==='merchant'||b==='collaborator'||b==='supplier')switch(a){case'completion':return'settlement'+amountSuffix(c)+'\x20released\x20to\x20you\x20+\x20shorter\x20fund-settlement\x20cycle';case'refund':return'refund'+amountSuffix(c)+'\x20—\x20downside,\x20recorded\x20on-chain\x20(arb-loss/stall\x20stats)';case'advance':return'advance\x20the\x20workflow\x20to\x20shorten\x20settlement'+amountSuffix(c);}return'neutral\x20for\x20'+b;}function riskOf(a,b){if(b==='customer'||b==='prospect'){if(a==='completion')return'high';if(a==='refund')return'low';return'medium';}if(b==='merchant'||b==='collaborator'||b==='supplier'){if(a==='refund')return'high';return'low';}return'medium';}function buildSummary(a,b){if(b['length']===0x0)return a['waiting_on']['length']>0x0?'Waiting\x20on\x20'+a['waiting_on']['map'](e=>e['role'])['join'](',\x20'):'No\x20operable\x20actions\x20at\x20node\x20\x27'+(a['current_node']||'(entry)')+'\x27';const c=b[0x0];let d='Optimal\x20for\x20'+a['perspective']+':\x20\x27'+c['forward']+'\x27\x20→\x20\x27'+c['to_node']+'\x27\x20('+c['payoff_note']+')';return b['length']>0x1&&(d+='\x20—\x20choosing\x20this\x20closes\x20the\x20other\x20'+(b['length']-0x1)+'\x20option(s)\x20(opportunity\x20competition:\x20your\x20gain\x20may\x20be\x20another\x20role\x27s\x20lost\x20chance).'),d;}
1
+ import{classifyOutcome,evaluateOutcome}from'./game-strategy.js';export function evaluateNodeGame(a){const b=a['operable']['map'](c=>{const d=scoreForward(c,a['perspective'],{'risk_appetite':a['appetite'],'requirements':a['requirements']},a['order_amount']);return{'forward':c['name'],'to_node':c['to_node'],'execution_path':c['execution_path'],'guard':c['guard'],'favorability':d['favorability'],'gain_score':d['gain_score'],'risk_score':d['risk_score'],'is_optimal':![],'payoff_note':d['payoff'],'risk':d['risk']};});return b['sort']((c,d)=>d['favorability']-c['favorability']),b['length']>0x0&&(b[0x0]['is_optimal']=!![]),{'current_node':a['current_node'],'perspective':a['perspective'],'actions':b,'cooperation':evaluateCooperation(a),'value_at_stake':a['order_amount'],'risk_exposure':a['compensation_fund'],'summary':buildSummary(a,b)};}function evaluateCooperation(a){if(!a['threshold']||a['threshold']<=0x1)return undefined;const b=a['operable']['reduce']((g,h)=>g+(h['weight']??0x1),0x0),c=a['threshold']-b,d=c>0x0?a['waiting_on']['map'](f=>f['role']):[],e=a['allocation'];return{'threshold':a['threshold'],'my_weight':b,'needed_from_others':Math['max'](0x0,c),'collaborators':d,'allocation':e,'allocation_note':e?describeAllocation(e):undefined};}function describeAllocation(b){const c=['settlement\x20splits\x20across\x20'+b['recipient_slots']+'\x20recipient\x20slot(s)'];if(b['direct_to_me_slots']>0x0)c['push'](b['direct_to_me_slots']+'\x20pay\x20directly\x20to\x20you');if(b['guard_gated_slots']>0x0)c['push'](b['guard_gated_slots']+'\x20are\x20guard-resolved\x20(may\x20pay\x20a\x20cooperating\x20party)');if(b['to_payer_slots']>0x0)c['push'](b['to_payer_slots']+'\x20route\x20back\x20to\x20the\x20payer\x20(refund-oriented)');return c['join'](';\x20')+'.';}function scoreForward(a,b,c,d){const e=classifyOutcome(a['consequence']),g=evaluateOutcome(e,b,c);return{'favorability':g['net_score'],'gain_score':g['gain_score'],'risk_score':g['risk_score'],'payoff':payoffNote(e,b,d),'risk':riskLabel(g['risk_score'])};}function amountSuffix(a){return a!=null?'\x20('+a+'\x20raw\x20units)':'';}function riskLabel(a){if(a<=0x0)return'low';if(a>=0x32)return'high';return'medium';}function payoffNote(a,b,c){if(b==='customer'||b==='prospect'||b==='demander')switch(a){case'refund':return'funds\x20return\x20to\x20you'+amountSuffix(c)+'\x20(refund/cancel\x20path)';case'completion':return'releases\x20escrowed\x20funds'+amountSuffix(c)+'\x20to\x20the\x20merchant\x20—\x20only\x20confirm\x20if\x20the\x20deliverable\x20matches\x20the\x20agreement';case'advance':return'advances\x20the\x20order\x20to\x20the\x20next\x20node\x20(funds'+amountSuffix(c)+'\x20stay\x20escrowed)';}if(b==='merchant'||b==='collaborator'||b==='supplier')switch(a){case'completion':return'settlement'+amountSuffix(c)+'\x20released\x20to\x20you\x20+\x20shorter\x20fund-settlement\x20cycle';case'refund':return'refund'+amountSuffix(c)+'\x20—\x20downside,\x20recorded\x20on-chain\x20(arb-loss/stall\x20stats)';case'advance':return'advance\x20the\x20workflow\x20to\x20shorten\x20settlement'+amountSuffix(c);}return'neutral\x20for\x20'+b;}function buildSummary(a,b){if(b['length']===0x0)return a['waiting_on']['length']>0x0?'Waiting\x20on\x20'+a['waiting_on']['map'](e=>e['role'])['join'](',\x20'):'No\x20operable\x20actions\x20at\x20node\x20\x27'+(a['current_node']||'(entry)')+'\x27';const c=b[0x0];let d='Optimal\x20for\x20'+a['perspective']+':\x20\x27'+c['forward']+'\x27\x20→\x20\x27'+c['to_node']+'\x27\x20('+c['payoff_note']+')';return b['length']>0x1&&(d+='\x20—\x20choosing\x20this\x20closes\x20the\x20other\x20'+(b['length']-0x1)+'\x20option(s)\x20(opportunity\x20competition:\x20your\x20gain\x20may\x20be\x20another\x20role\x27s\x20lost\x20chance).'),d;}
@@ -78,6 +78,7 @@
78
78
  "notes": [
79
79
  "MULTI-SIG MECHANICS: pair threshold=2 means Progress advances from 'under_review' to 'approved' only when the CUMULATIVE weight of completed DISTINCT forwards on that pair reaches 2. Each of the three approver forwards contributes weight 1, so any 2 of the 3 approvers must act — a 2-of-3 signature scheme.",
80
80
  "Each approver calls progress operate with their OWN forward name (e.g. 'Approve Alice'). The same forward cannot be double-counted; distinct forwards by the same operator would still count separately, so map each forward to a distinct permissionIndex (1001/1002/1003 = three approver roles in the Permission table).",
81
+ "⚠️ SINGLE-OPERATOR LOCK (E_NOT_THE_HOLDER): each forward is locked by the FIRST operator that accomplishes it — a second operator re-executing the same accomplished forward aborts E_NOT_THE_HOLDER, and the weight is counted only ONCE. This is exactly why a threshold-N transition needs N DISTINCT forwards (here 2-of-3): each of the three approver forwards can be executed by exactly one person. Do NOT try to have several people 'all execute Approve Alice' — it will abort for everyone after the first.",
81
82
  "threshold semantics (MachineNodePairSchema): 'If total Forward weight is greater than or equal to threshold, node advancement is triggered.' Weighted variants are possible — e.g. give a senior approver weight 2 so they can approve alone (threshold 2 met by one forward).",
82
83
  "Entry-node rule: 'submitted' has prev_node='' with at least one forward (schema-enforced FIX-002). namedOperator='' = order owner; permissionIndex references Permission table entries.",
83
84
  "Compare with machine-template-7node-rental.json where every pair uses threshold 1 (single-signature sequential flow).",
@@ -1 +1 @@
1
- export const RECOVERY_RULES={'insufficient_balance':{'error_code':'insufficient_balance','strategy':'claim_faucet','max_attempts':0x3,'automation':'semi','detail':'1.\x20Testnet:\x20claim\x20WOW\x20from\x20the\x20faucet\x202.\x20Mainnet:\x20transfer\x20ETH/USDT/USDC/WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge\x20(query\x20active\x20EVM\x20account\x20→\x20top\x20up\x20from\x20external\x20wallet\x20→\x20confirm\x20→\x20cross-chain)\x203.\x20Mention\x20the\x20WOW\x20airdrop\x20(under\x20construction)\x204.\x20Retry\x20original\x20operation','user_prompt':'Insufficient\x20balance\x20for\x20gas\x20or\x20operation.\x20How\x20to\x20obtain\x20WOW\x20tokens:\x20(1)\x20Testnet\x20—\x20claim\x20WOW\x20from\x20the\x20faucet\x20(https://faucet.testnet.wowok.net);\x20all\x20merchant\x20and\x20order\x20testing\x20can\x20use\x20WOW\x20as\x20the\x20payment\x20token.\x20(2)\x20Mainnet\x20—\x20transfer\x20ETH\x20/\x20USDT\x20/\x20USDC\x20/\x20WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge:\x20first\x20query\x20the\x20active\x20EVM\x20account\x20(bridge_operation\x20query_active_evm_account,\x20auto-generated\x20on\x20first\x20use),\x20then\x20transfer\x20from\x20an\x20external\x20wallet\x20(e.g.\x20MetaMask)\x20to\x20that\x20address,\x20confirm\x20the\x20balance\x20arrived,\x20and\x20cross-chain\x20to\x20WOW\x20mainnet\x20(bridge_operation\x20cross_chain_evm_to_wow).\x20(3)\x20WOW\x20mainnet\x20airdrop:\x20https://airdrop.wowok.net\x20(under\x20construction).'},'network_error':{'error_code':'network_error','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Exponential\x20backoff\x20retry:\x201s\x20/\x202s\x20/\x204s\x20/\x208s\x20/\x2016s.\x20Switch\x20RPC\x20node\x20if\x20available.'},'guard_rejected':{'error_code':'guard_rejected','strategy':'fill_submission','max_attempts':0x2,'automation':'semi','detail':'1.\x20Parse\x20Guard\x20table\x20structure\x202.\x20Prompt\x20user\x20to\x20fill\x20submission\x20fields\x203.\x20Resubmit\x20with\x20call_with_submission','user_prompt':'Guard\x20verification\x20rejected.\x20Please\x20fill\x20in\x20the\x20required\x20submission\x20data\x20and\x20resubmit.'},'immutable_violation':{'error_code':'immutable_violation','strategy':'recreate','max_attempts':0x1,'automation':'semi','detail':'1.\x20Stop\x20modification\x20attempt\x202.\x20Evaluate\x20creating\x20a\x20new\x20object\x20as\x20replacement\x203.\x20Re-plan\x20affected\x20phases','user_prompt':'Cannot\x20modify\x20an\x20immutable\x20object.\x20A\x20new\x20object\x20must\x20be\x20created\x20as\x20a\x20replacement.\x20Confirm\x20to\x20proceed\x20with\x20recreation.'},'permission_denied':{'error_code':'permission_denied','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20object\x27s\x20permission_guard\x202.\x20List\x20accounts\x20with\x20permission\x203.\x20Switch\x20account\x20or\x20prompt\x20user\x20to\x20add\x20permission','user_prompt':'Current\x20account\x20lacks\x20permission\x20for\x20this\x20operation.\x20Switch\x20to\x20an\x20authorized\x20account\x20or\x20update\x20the\x20Permission\x20object.'},'object_not_found':{'error_code':'object_not_found','strategy':'query_and_retry','max_attempts':0x3,'automation':'semi','detail':'1.\x20Re-query\x20the\x20object\x20(may\x20be\x20sync\x20delay)\x202.\x20If\x20truly\x20absent,\x20search\x20for\x20similar\x20objects\x203.\x20Prompt\x20user\x20to\x20reselect','user_prompt':'Referenced\x20object\x20not\x20found.\x20It\x20may\x20be\x20a\x20synchronization\x20delay.\x20Retrying...\x20If\x20the\x20issue\x20persists,\x20please\x20select\x20a\x20valid\x20object.'},'state_conflict':{'error_code':'state_conflict','strategy':'adjust_params','max_attempts':0x2,'automation':'full','detail':'1.\x20Query\x20object\x27s\x20current\x20true\x20state\x202.\x20Update\x20ODG\x20status\x20annotations\x203.\x20Adjust\x20subsequent\x20operations\x20(e.g.,\x20skip\x20completed\x20steps)'},'invalid_parameter':{'error_code':'invalid_parameter','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20the\x20relevant\x20schema\x202.\x20Auto-fix\x20obvious\x20errors\x20(e.g.,\x20BigInt\x20vs\x20string)\x203.\x20If\x20unfixable,\x20prompt\x20user','user_prompt':'Parameter\x20validation\x20failed.\x20Please\x20check\x20the\x20parameter\x20types\x20and\x20values\x20against\x20the\x20schema\x20and\x20retry.'},'unknown':{'error_code':'unknown','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'1.\x20Report\x20full\x20error\x20context\x20to\x20telemetry\x202.\x20Escalate\x20to\x20human\x20intervention\x203.\x20Flag\x20for\x20Loop\x20Engineering\x20rule\x20addition','user_prompt':'An\x20unclassified\x20error\x20occurred.\x20Please\x20review\x20the\x20error\x20details\x20and\x20contact\x20support\x20if\x20needed.\x20This\x20error\x20has\x20been\x20logged\x20for\x20tool\x20improvement.'}};const operationAttempts=new Map();function getAttemptCount(a,b){const c=operationAttempts['get'](a);if(!c)return 0x0;return c['get'](b)??0x0;}function incrementAttempt(a,b){!operationAttempts['has'](a)&&operationAttempts['set'](a,new Map());const c=operationAttempts['get'](a),d=(c['get'](b)??0x0)+0x1;return c['set'](b,d),d;}function getTotalAttempts(a){const b=operationAttempts['get'](a);if(!b)return 0x0;let c=0x0;for(const d of b['values']())c+=d;return c;}export function resetAttempts(a){operationAttempts['delete'](a);}export function recover(a,b,c){const d=RECOVERY_RULES[a]??RECOVERY_RULES['unknown'],e=0x5,f=getTotalAttempts(b),g=getAttemptCount(b,a);if(f>=e)return{'strategy':'stop','should_retry':![],'max_attempts':e,'current_attempt':f,'detail':'Total\x20retry\x20limit\x20('+e+')\x20reached\x20for\x20operation\x20'+b+'.\x20Escalating\x20to\x20human\x20intervention.','user_prompt':'Maximum\x20retry\x20attempts\x20reached.\x20Manual\x20intervention\x20required.'};if(g>=d['max_attempts'])return{'strategy':'escalate_human','should_retry':![],'max_attempts':d['max_attempts'],'current_attempt':g,'detail':'Per-error-code\x20retry\x20limit\x20('+d['max_attempts']+')\x20reached\x20for\x20'+a+'.\x20Escalating\x20to\x20human.','user_prompt':'Recovery\x20attempts\x20for\x20'+a+'\x20exhausted.\x20Manual\x20intervention\x20required.'};const h=incrementAttempt(b,a);return{'strategy':d['strategy'],'should_retry':d['automation']==='full'||h<d['max_attempts'],'max_attempts':d['max_attempts'],'current_attempt':h,'adjusted_params':d['adjusted_params'],'user_prompt':d['user_prompt'],'detail':d['detail']};}export function getBackoffDelay(a){return Math['pow'](0x2,a-0x1)*0x3e8;}
1
+ export const RECOVERY_RULES={'insufficient_balance':{'error_code':'insufficient_balance','strategy':'claim_faucet','max_attempts':0x3,'automation':'semi','detail':'1.\x20Testnet:\x20claim\x20WOW\x20from\x20the\x20faucet\x202.\x20Mainnet:\x20transfer\x20ETH/USDT/USDC/WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge\x20(query\x20active\x20EVM\x20account\x20→\x20top\x20up\x20from\x20external\x20wallet\x20→\x20confirm\x20→\x20cross-chain)\x203.\x20Mention\x20the\x20WOW\x20airdrop\x20(under\x20construction)\x204.\x20Retry\x20original\x20operation','user_prompt':'Insufficient\x20balance\x20for\x20gas\x20or\x20operation.\x20How\x20to\x20obtain\x20WOW\x20tokens:\x20(1)\x20Testnet\x20—\x20claim\x20WOW\x20from\x20the\x20faucet\x20(https://faucet.testnet.wowok.net);\x20all\x20merchant\x20and\x20order\x20testing\x20can\x20use\x20WOW\x20as\x20the\x20payment\x20token.\x20(2)\x20Mainnet\x20—\x20transfer\x20ETH\x20/\x20USDT\x20/\x20USDC\x20/\x20WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge:\x20first\x20query\x20the\x20active\x20EVM\x20account\x20(bridge_operation\x20query_active_evm_account,\x20auto-generated\x20on\x20first\x20use),\x20then\x20transfer\x20from\x20an\x20external\x20wallet\x20(e.g.\x20MetaMask)\x20to\x20that\x20address,\x20confirm\x20the\x20balance\x20arrived,\x20and\x20cross-chain\x20to\x20WOW\x20mainnet\x20(bridge_operation\x20cross_chain_evm_to_wow).\x20(3)\x20WOW\x20mainnet\x20airdrop:\x20https://airdrop.wowok.net\x20(under\x20construction).'},'network_error':{'error_code':'network_error','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Exponential\x20backoff\x20retry:\x201s\x20/\x202s\x20/\x204s\x20/\x208s\x20/\x2016s.\x20Switch\x20RPC\x20node\x20if\x20available.'},'guard_rejected':{'error_code':'guard_rejected','strategy':'fill_submission','max_attempts':0x2,'automation':'semi','detail':'1.\x20Parse\x20Guard\x20table\x20structure\x202.\x20Prompt\x20user\x20to\x20fill\x20submission\x20fields\x203.\x20Resubmit\x20with\x20call_with_submission','user_prompt':'Guard\x20verification\x20rejected.\x20Please\x20fill\x20in\x20the\x20required\x20submission\x20data\x20and\x20resubmit.'},'time_lock_not_elapsed':{'error_code':'time_lock_not_elapsed','strategy':'wait_and_retry','max_attempts':0x1,'automation':'semi','detail':'1.\x20Verify\x20Service\x20is\x20paused\x20(bPaused=true).\x20If\x20not,\x20submit\x20pause=true\x20first.\x202.\x20Wait\x20until\x20paused_time\x20+\x20setting_lock_duration\x20<=\x20current\x20clock.\x203.\x20Retry\x20the\x20original\x20operation.\x20Do\x20NOT\x20recreate\x20the\x20object.','user_prompt':'Service\x20setting_lock_duration\x20has\x20not\x20elapsed\x20since\x20the\x20Service\x20was\x20paused.\x20Please\x20pause\x20the\x20Service\x20if\x20it\x20is\x20not\x20already\x20paused,\x20wait\x20for\x20the\x20lock\x20duration\x20to\x20elapse,\x20then\x20retry.'},'immutable_violation':{'error_code':'immutable_violation','strategy':'recreate','max_attempts':0x1,'automation':'semi','detail':'1.\x20Stop\x20modification\x20attempt\x202.\x20Evaluate\x20creating\x20a\x20new\x20object\x20as\x20replacement\x203.\x20Re-plan\x20affected\x20phases','user_prompt':'Cannot\x20modify\x20an\x20immutable\x20object.\x20A\x20new\x20object\x20must\x20be\x20created\x20as\x20a\x20replacement.\x20Confirm\x20to\x20proceed\x20with\x20recreation.'},'permission_denied':{'error_code':'permission_denied','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20object\x27s\x20permission_guard\x202.\x20List\x20accounts\x20with\x20permission\x203.\x20Switch\x20account\x20or\x20prompt\x20user\x20to\x20add\x20permission','user_prompt':'Current\x20account\x20lacks\x20permission\x20for\x20this\x20operation.\x20Switch\x20to\x20an\x20authorized\x20account\x20or\x20update\x20the\x20Permission\x20object.'},'object_not_found':{'error_code':'object_not_found','strategy':'query_and_retry','max_attempts':0x3,'automation':'semi','detail':'1.\x20Re-query\x20the\x20object\x20(may\x20be\x20sync\x20delay)\x202.\x20If\x20truly\x20absent,\x20search\x20for\x20similar\x20objects\x203.\x20Prompt\x20user\x20to\x20reselect','user_prompt':'Referenced\x20object\x20not\x20found.\x20It\x20may\x20be\x20a\x20synchronization\x20delay.\x20Retrying...\x20If\x20the\x20issue\x20persists,\x20please\x20select\x20a\x20valid\x20object.'},'state_conflict':{'error_code':'state_conflict','strategy':'adjust_params','max_attempts':0x2,'automation':'full','detail':'1.\x20Query\x20object\x27s\x20current\x20true\x20state\x202.\x20Update\x20ODG\x20status\x20annotations\x203.\x20Adjust\x20subsequent\x20operations\x20(e.g.,\x20skip\x20completed\x20steps)'},'invalid_parameter':{'error_code':'invalid_parameter','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20the\x20relevant\x20schema\x202.\x20Auto-fix\x20obvious\x20errors\x20(e.g.,\x20BigInt\x20vs\x20string)\x203.\x20If\x20unfixable,\x20prompt\x20user','user_prompt':'Parameter\x20validation\x20failed.\x20Please\x20check\x20the\x20parameter\x20types\x20and\x20values\x20against\x20the\x20schema\x20and\x20retry.'},'unknown':{'error_code':'unknown','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'1.\x20Report\x20full\x20error\x20context\x20to\x20telemetry\x202.\x20Escalate\x20to\x20human\x20intervention\x203.\x20Flag\x20for\x20Loop\x20Engineering\x20rule\x20addition','user_prompt':'An\x20unclassified\x20error\x20occurred.\x20Please\x20review\x20the\x20error\x20details\x20and\x20contact\x20support\x20if\x20needed.\x20This\x20error\x20has\x20been\x20logged\x20for\x20tool\x20improvement.'}};const operationAttempts=new Map();function getAttemptCount(a,b){const c=operationAttempts['get'](a);if(!c)return 0x0;return c['get'](b)??0x0;}function incrementAttempt(a,b){!operationAttempts['has'](a)&&operationAttempts['set'](a,new Map());const c=operationAttempts['get'](a),d=(c['get'](b)??0x0)+0x1;return c['set'](b,d),d;}function getTotalAttempts(a){const b=operationAttempts['get'](a);if(!b)return 0x0;let c=0x0;for(const d of b['values']())c+=d;return c;}export function resetAttempts(a){operationAttempts['delete'](a);}export function recover(a,b,c){const d=RECOVERY_RULES[a]??RECOVERY_RULES['unknown'],e=0x5,f=getTotalAttempts(b),g=getAttemptCount(b,a);if(f>=e)return{'strategy':'stop','should_retry':![],'max_attempts':e,'current_attempt':f,'detail':'Total\x20retry\x20limit\x20('+e+')\x20reached\x20for\x20operation\x20'+b+'.\x20Escalating\x20to\x20human\x20intervention.','user_prompt':'Maximum\x20retry\x20attempts\x20reached.\x20Manual\x20intervention\x20required.'};if(g>=d['max_attempts'])return{'strategy':'escalate_human','should_retry':![],'max_attempts':d['max_attempts'],'current_attempt':g,'detail':'Per-error-code\x20retry\x20limit\x20('+d['max_attempts']+')\x20reached\x20for\x20'+a+'.\x20Escalating\x20to\x20human.','user_prompt':'Recovery\x20attempts\x20for\x20'+a+'\x20exhausted.\x20Manual\x20intervention\x20required.'};const h=incrementAttempt(b,a);return{'strategy':d['strategy'],'should_retry':d['automation']==='full'||h<d['max_attempts'],'max_attempts':d['max_attempts'],'current_attempt':h,'adjusted_params':d['adjusted_params'],'user_prompt':d['user_prompt'],'detail':d['detail']};}export function getBackoffDelay(a){return Math['pow'](0x2,a-0x1)*0x3e8;}
@@ -74,7 +74,7 @@ export interface VerifyReport {
74
74
  summary: string;
75
75
  timestamp: string;
76
76
  }
77
- export type RecoveryStrategy = "retry" | "claim_faucet" | "fill_submission" | "recreate" | "switch_account" | "query_and_retry" | "adjust_params" | "escalate_human" | "stop";
77
+ export type RecoveryStrategy = "retry" | "claim_faucet" | "fill_submission" | "recreate" | "switch_account" | "query_and_retry" | "adjust_params" | "escalate_human" | "stop" | "wait_and_retry";
78
78
  export interface RecoveryAction {
79
79
  strategy: RecoveryStrategy;
80
80
  should_retry: boolean;
@@ -1 +1 @@
1
- function verifyCreated(a,b){const c=[],d=a['expected']['semantic_created']??[],e=b['semantic']?.['created']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g&&c['push']({'dimension':'created','expected':'role='+f['role'],'actual':'not\x20found','severity':'fail','detail':'Expected\x20to\x20create\x20object\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20none\x20was\x20created'});}for(const h of e){const i=d['find'](j=>j['role']===h['role']);!i&&c['push']({'dimension':'created','expected':'no\x20object\x20with\x20role='+h['role'],'actual':'role='+h['role'],'severity':'warn','detail':'Unexpected\x20object\x20created\x20with\x20role\x20\x27'+h['role']+'\x27\x20—\x20may\x20indicate\x20rule\x20table\x20gap'});}return c;}function verifyModified(a,b){const c=[],d=a['expected']['semantic_modified']??[],e=b['semantic']?.['modified']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g&&c['push']({'dimension':'modified','expected':'role='+f['role']+'\x20fields='+JSON['stringify'](f['expect_fields']??{}),'actual':'not\x20modified','severity':'fail','detail':'Expected\x20to\x20modify\x20object\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20it\x20was\x20not\x20modified'});}return c;}function verifyReleased(a,b){const c=[],d=a['expected']['semantic_released']??[],e=b['semantic']?.['released']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g?c['push']({'dimension':'released','expected':'role='+f['role']+'\x20amount='+(f['amount']??'?')+'\x20from='+(f['from']??'?')+'\x20to='+(f['to']??'?'),'actual':'no\x20fund\x20movement','severity':'fail','detail':'Expected\x20fund\x20movement\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20none\x20occurred\x20—\x20fund\x20flow\x20risk'}):(f['amount']&&f['amount']!==g['amount']&&c['push']({'dimension':'released','expected':'amount='+f['amount'],'actual':'amount='+g['amount'],'severity':'fail','detail':'Fund\x20amount\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20risk'}),f['from']&&g['from']&&f['from']!==g['from']&&c['push']({'dimension':'released','expected':'from='+f['from'],'actual':'from='+g['from'],'severity':'fail','detail':'Fund\x20source\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20direction\x20risk'}),f['to']&&g['to']&&f['to']!==g['to']&&c['push']({'dimension':'released','expected':'to='+f['to'],'actual':'to='+g['to'],'severity':'fail','detail':'Fund\x20destination\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20direction\x20risk'}));}return c;}function verifyEvents(a,b){const c=[],d=a['expected']['events']??[],e=b['semantic']?.['events']??[];for(const f of d){const g=e['find'](h=>h['event_type']['includes'](f['type'])||h['business_meaning']['toLowerCase']()['includes'](f['type']['toLowerCase']()));!g&&c['push']({'dimension':'event','expected':'event_type\x20contains\x20\x27'+f['type']+'\x27','actual':'event\x20not\x20found','severity':'warn','detail':'Expected\x20event\x20\x27'+f['type']+'\x27\x20was\x20not\x20found\x20—\x20may\x20indicate\x20semantic\x20layer\x20gap\x20or\x20operation\x20didn\x27t\x20trigger\x20it'});}return c;}function verifyStateTransition(a,b){const c=[],d=a['expected']['state_transition'];if(!d)return c;if(b['semantic']?.['status']==='success')return c;return b['semantic']?.['status']==='failed'&&c['push']({'dimension':'state','expected':d['from']+'\x20→\x20'+d['to'],'actual':'operation\x20failed','severity':'fail','detail':'Expected\x20state\x20transition\x20\x27'+d['from']+'\x20→\x20'+d['to']+'\x27\x20failed\x20—\x20operation\x20did\x20not\x20succeed'}),c;}export function verify(a){const b=[...verifyCreated(a['expected'],a['actual']),...verifyModified(a['expected'],a['actual']),...verifyReleased(a['expected'],a['actual']),...verifyEvents(a['expected'],a['actual']),...verifyStateTransition(a['expected'],a['actual'])],c=b['some'](i=>i['severity']==='fail'),d=b['some'](i=>i['severity']==='warn'),e=c?'fail':d?'warn':'pass',f=b['filter'](i=>i['severity']==='fail')['length'],g=b['filter'](i=>i['severity']==='warn')['length'];let h;if(e==='pass')h='All\x20verifications\x20passed\x20—\x20expected\x20results\x20match\x20actual\x20results';else e==='warn'?h=g+'\x20warning(s)\x20—\x20operation\x20succeeded\x20with\x20minor\x20discrepancies':h=f+'\x20failure(s),\x20'+g+'\x20warning(s)\x20—\x20expected\x20results\x20do\x20not\x20match\x20actual\x20results';return{'status':e,'mismatches':b,'summary':h,'timestamp':new Date()['toISOString']()};}export function generateExpected(a,b,c,d){const e={'result_type':'transaction'};switch(c){case'service':d?.['publish']===!![]||d?.['bPublished']===!![]?(e['semantic_modified']=[{'role':'Service','expect_fields':{'bPublished':!![]}}],e['state_transition']={'from':'unpublished','to':'published'}):e['semantic_created']=[{'role':'Service'}];break;case'machine':e['semantic_created']=[{'role':'Machine'}];break;case'guard':e['semantic_created']=[{'role':'Guard'}],e['events']=[{'type':'GuardCreated','expect_count':'>=1'}];break;case'permission':e['semantic_created']=[{'role':'Permission'}];break;case'order':d?.['arb']!==undefined?e['state_transition']={'from':'ordered','to':'arbitration'}:(e['semantic_created']=[{'role':'Order'}],e['semantic_released']=[{'role':'payment'}],e['events']=[{'type':'OrderPaid','expect_count':'>=1'}]);break;case'payment':e['semantic_released']=[{'role':'payment'}];break;case'treasury':d?.['deposit']!==undefined?e['semantic_released']=[{'role':'deposit'}]:e['semantic_released']=[{'role':'release'}];break;case'reward':d?.['claim']!==undefined||d?.['withdraw']!==undefined?e['semantic_released']=[{'role':'reward'}]:e['semantic_created']=[{'role':'Reward'}];break;case'allocation':e['semantic_released']=[{'role':'release'}],e['events']=[{'type':'Allocation','expect_count':'>=1'}];break;case'demand':d?.['submit']!==undefined?e['semantic_modified']=[{'role':'Demand'}]:e['semantic_created']=[{'role':'Demand'}];break;default:break;}return{'operation':a,'intent':b,'pre_conditions':[],'expected':e};}
1
+ function verifyCreated(a,b){const c=[],d=a['expected']['semantic_created']??[],e=b['semantic']?.['created']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g&&c['push']({'dimension':'created','expected':'role='+f['role'],'actual':'not\x20found','severity':'fail','detail':'Expected\x20to\x20create\x20object\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20none\x20was\x20created'});}for(const h of e){const i=d['find'](j=>j['role']===h['role']);!i&&c['push']({'dimension':'created','expected':'no\x20object\x20with\x20role='+h['role'],'actual':'role='+h['role'],'severity':'warn','detail':'Unexpected\x20object\x20created\x20with\x20role\x20\x27'+h['role']+'\x27\x20—\x20may\x20indicate\x20rule\x20table\x20gap'});}return c;}function verifyModified(a,b){const c=[],d=a['expected']['semantic_modified']??[],e=b['semantic']?.['modified']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g&&c['push']({'dimension':'modified','expected':'role='+f['role']+'\x20fields='+JSON['stringify'](f['expect_fields']??{}),'actual':'not\x20modified','severity':'fail','detail':'Expected\x20to\x20modify\x20object\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20it\x20was\x20not\x20modified'});}return c;}function verifyReleased(a,b){const c=[],d=a['expected']['semantic_released']??[],e=b['semantic']?.['released']??[];for(const f of d){const g=e['find'](h=>h['role']===f['role']);!g?c['push']({'dimension':'released','expected':'role='+f['role']+'\x20amount='+(f['amount']??'?')+'\x20from='+(f['from']??'?')+'\x20to='+(f['to']??'?'),'actual':'no\x20fund\x20movement','severity':'fail','detail':'Expected\x20fund\x20movement\x20with\x20role\x20\x27'+f['role']+'\x27,\x20but\x20none\x20occurred\x20—\x20fund\x20flow\x20risk'}):(f['amount']&&f['amount']!==g['amount']&&c['push']({'dimension':'released','expected':'amount='+f['amount'],'actual':'amount='+g['amount'],'severity':'fail','detail':'Fund\x20amount\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20risk'}),f['from']&&g['from']&&f['from']!==g['from']&&c['push']({'dimension':'released','expected':'from='+f['from'],'actual':'from='+g['from'],'severity':'fail','detail':'Fund\x20source\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20direction\x20risk'}),f['to']&&g['to']&&f['to']!==g['to']&&c['push']({'dimension':'released','expected':'to='+f['to'],'actual':'to='+g['to'],'severity':'fail','detail':'Fund\x20destination\x20mismatch\x20for\x20role\x20\x27'+f['role']+'\x27\x20—\x20fund\x20flow\x20direction\x20risk'}));}return c;}function verifyEvents(a,b){const c=[],d=a['expected']['events']??[],e=b['semantic']?.['events']??[];for(const f of d){const g=e['find'](h=>h['event_type']['includes'](f['type'])||h['business_meaning']['toLowerCase']()['includes'](f['type']['toLowerCase']()));!g&&c['push']({'dimension':'event','expected':'event_type\x20contains\x20\x27'+f['type']+'\x27','actual':'event\x20not\x20found','severity':'warn','detail':'Expected\x20event\x20\x27'+f['type']+'\x27\x20was\x20not\x20found\x20—\x20may\x20indicate\x20semantic\x20layer\x20gap\x20or\x20operation\x20didn\x27t\x20trigger\x20it'});}return c;}function verifyStateTransition(a,b){const c=[],d=a['expected']['state_transition'];if(!d)return c;if(b['semantic']?.['status']==='success')return c;return b['semantic']?.['status']==='failed'&&c['push']({'dimension':'state','expected':d['from']+'\x20→\x20'+d['to'],'actual':'operation\x20failed','severity':'fail','detail':'Expected\x20state\x20transition\x20\x27'+d['from']+'\x20→\x20'+d['to']+'\x27\x20failed\x20—\x20operation\x20did\x20not\x20succeed'}),c;}export function verify(a){const b=[...verifyCreated(a['expected'],a['actual']),...verifyModified(a['expected'],a['actual']),...verifyReleased(a['expected'],a['actual']),...verifyEvents(a['expected'],a['actual']),...verifyStateTransition(a['expected'],a['actual'])],c=b['some'](i=>i['severity']==='fail'),d=b['some'](i=>i['severity']==='warn'),e=c?'fail':d?'warn':'pass',f=b['filter'](i=>i['severity']==='fail')['length'],g=b['filter'](i=>i['severity']==='warn')['length'];let h;if(e==='pass')h='All\x20verifications\x20passed\x20—\x20expected\x20results\x20match\x20actual\x20results';else e==='warn'?h=g+'\x20warning(s)\x20—\x20operation\x20succeeded\x20with\x20minor\x20discrepancies':h=f+'\x20failure(s),\x20'+g+'\x20warning(s)\x20—\x20expected\x20results\x20do\x20not\x20match\x20actual\x20results';return{'status':e,'mismatches':b,'summary':h,'timestamp':new Date()['toISOString']()};}export function generateExpected(a,b,c,d){const e={'result_type':'transaction'};switch(c){case'service':d?.['publish']===!![]||d?.['bPublished']===!![]?(e['semantic_modified']=[{'role':'Service','expect_fields':{'bPublished':!![]}}],e['state_transition']={'from':'unpublished','to':'published'},e['events']=[{'type':'ServiceEvent','expect_count':'>=1'}]):e['semantic_created']=[{'role':'Service'}];break;case'machine':e['semantic_created']=[{'role':'Machine'}];break;case'guard':e['semantic_created']=[{'role':'Guard'}];break;case'permission':e['semantic_created']=[{'role':'Permission'}];break;case'order':d?.['arb']!==undefined?(e['state_transition']={'from':'ordered','to':'arbitration'},e['events']=[{'type':'ArbEvent','expect_count':'>=1'}]):(e['semantic_created']=[{'role':'Order'}],e['semantic_released']=[{'role':'payment'}],e['events']=[{'type':'NewOrderEvent','expect_count':'>=1'}]);break;case'payment':e['semantic_released']=[{'role':'payment'}],e['events']=[{'type':'NewPaymentEvent','expect_count':'>=1'}];break;case'treasury':d?.['deposit']!==undefined?e['semantic_released']=[{'role':'deposit'}]:e['semantic_released']=[{'role':'release'}];e['events']=[{'type':'TreasuryEvent','expect_count':'>=1'},{'type':'NewPaymentEvent','expect_count':'>=1'}];break;case'reward':if(d?.['claim']!==undefined||d?.['withdraw']!==undefined)e['semantic_released']=[{'role':'reward'}],e['events']=[{'type':'RewardClaimEvent','expect_count':'>=1'}];else d?.['coin']!==undefined||d?.['add']!==undefined?e['events']=[{'type':'RewardFundEvent','expect_count':'>=1'}]:e['semantic_created']=[{'role':'Reward'}];break;case'allocation':e['semantic_released']=[{'role':'release'}],e['events']=[{'type':'AllocationEvent','expect_count':'>=1'},{'type':'NewPaymentEvent','expect_count':'>=1'}];break;case'demand':if(d?.['submit']!==undefined||d?.['present']!==undefined)e['semantic_modified']=[{'role':'Demand'}],e['events']=[{'type':'DemandPresentEvent','expect_count':'>=1'}];else d?.['reward']!==undefined||d?.['rewards']!==undefined?e['events']=[{'type':'DemandChangedEvent','expect_count':'>=1'}]:e['semantic_created']=[{'role':'Demand'}];break;case'progress':e['events']=[{'type':'ProgressEvent','expect_count':'>=1'}];break;default:break;}return{'operation':a,'intent':b,'pre_conditions':[],'expected':e};}