@wowok/agent-mcp 3.3.6 → 3.3.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 (220) hide show
  1. package/dist/chain-semantics/eval-order.js +1 -1
  2. package/dist/chain-semantics/field-capability.js +1 -1
  3. package/dist/chain-semantics/fund-flow.js +1 -1
  4. package/dist/chain-semantics/guard-verbs.js +1 -1
  5. package/dist/chain-semantics/object-graph.js +1 -1
  6. package/dist/communication/message-cursors.d.ts +35 -0
  7. package/dist/communication/message-cursors.js +1 -0
  8. package/dist/communication/wts-attestation.d.ts +5 -0
  9. package/dist/communication/wts-attestation.js +1 -1
  10. package/dist/composition/audit.js +1 -1
  11. package/dist/composition/compile.d.ts +3 -2
  12. package/dist/composition/compile.js +1 -1
  13. package/dist/composition/inflight.d.ts +7 -0
  14. package/dist/composition/inflight.js +1 -1
  15. package/dist/composition/materialize.d.ts +4 -1
  16. package/dist/composition/materialize.js +1 -1
  17. package/dist/config/index.d.ts +1 -0
  18. package/dist/config/index.js +1 -1
  19. package/dist/config/store-policy.d.ts +14 -0
  20. package/dist/config/store-policy.js +1 -0
  21. package/dist/config/store-policy.spec.d.ts +1 -0
  22. package/dist/config/store-policy.spec.js +1 -0
  23. package/dist/customer/industry-risks.js +1 -1
  24. package/dist/customer/user-preferences.js +1 -1
  25. package/dist/data/projection/facets.spec.js +1 -1
  26. package/dist/evaluation/builtins/graph-service.spec.js +1 -1
  27. package/dist/evaluation/engine.js +1 -1
  28. package/dist/evaluation/match-policy.d.ts +30 -6
  29. package/dist/evaluation/match-policy.js +1 -1
  30. package/dist/evaluation/match-policy.spec.js +1 -1
  31. package/dist/experience/realtime-feedback.js +1 -1
  32. package/dist/extensions/business-modules.d.ts +1 -1
  33. package/dist/extensions/business-modules.js +1 -1
  34. package/dist/extensions/industry-pack.js +1 -1
  35. package/dist/extensions/modes.js +1 -1
  36. package/dist/graph/onchain/analyze.js +1 -1
  37. package/dist/graph/onchain/expand.js +1 -1
  38. package/dist/graph/onchain/exposure.js +1 -1
  39. package/dist/graph/onchain/facts.d.ts +1 -0
  40. package/dist/graph/onchain/facts.js +1 -1
  41. package/dist/graph/onchain/facts.spec.js +1 -1
  42. package/dist/harness/recover.js +1 -1
  43. package/dist/intent/types.d.ts +1 -1
  44. package/dist/intent/types.js +1 -1
  45. package/dist/keeper/detectors.d.ts +3 -0
  46. package/dist/keeper/detectors.js +1 -1
  47. package/dist/keeper/keeper.spec.js +1 -1
  48. package/dist/knowledge/acquisition-flywheel.js +1 -1
  49. package/dist/knowledge/allocation-ledger.d.ts +1 -0
  50. package/dist/knowledge/allocation-ledger.js +1 -1
  51. package/dist/knowledge/allocator-rail-verifier.d.ts +6 -2
  52. package/dist/knowledge/allocator-rail-verifier.js +1 -1
  53. package/dist/knowledge/arbitration-ledger.js +1 -1
  54. package/dist/knowledge/audit-rules.d.ts +37 -0
  55. package/dist/knowledge/audit-rules.js +1 -1
  56. package/dist/knowledge/baselines/rules/plan.json +128 -3
  57. package/dist/knowledge/builtin-templates.d.ts +18 -1
  58. package/dist/knowledge/builtin-templates.js +1 -1
  59. package/dist/knowledge/commission-landing.d.ts +26 -0
  60. package/dist/knowledge/commission-landing.js +1 -0
  61. package/dist/knowledge/discount-threshold.js +1 -1
  62. package/dist/knowledge/event-semantics.js +1 -1
  63. package/dist/knowledge/fund-layer.d.ts +7 -0
  64. package/dist/knowledge/fund-layer.js +1 -1
  65. package/dist/knowledge/getting-started.js +1 -1
  66. package/dist/knowledge/guard-design-patterns.d.ts +1 -1
  67. package/dist/knowledge/guard-design-patterns.js +1 -1
  68. package/dist/knowledge/guard-puzzle.js +1 -1
  69. package/dist/knowledge/guard-render.d.ts +7 -0
  70. package/dist/knowledge/guard-render.js +1 -1
  71. package/dist/knowledge/guard-risk.js +1 -1
  72. package/dist/knowledge/guard-templates.d.ts +1 -1
  73. package/dist/knowledge/guard-templates.js +1 -1
  74. package/dist/knowledge/guard-translation.js +1 -1
  75. package/dist/knowledge/index.js +1 -1
  76. package/dist/knowledge/industry-generalizer.d.ts +4 -0
  77. package/dist/knowledge/industry-generalizer.js +1 -1
  78. package/dist/knowledge/industry-registry.d.ts +1 -1
  79. package/dist/knowledge/industry-registry.js +1 -1
  80. package/dist/knowledge/industry-strategy.js +1 -1
  81. package/dist/knowledge/jsonrpc-enum.js +1 -1
  82. package/dist/knowledge/machine-fork-watch.d.ts +9 -0
  83. package/dist/knowledge/machine-fork-watch.js +1 -0
  84. package/dist/knowledge/migration-preflight.js +1 -1
  85. package/dist/knowledge/projection.spec.js +1 -1
  86. package/dist/knowledge/scenario-modes.d.ts +8 -2
  87. package/dist/knowledge/scenario-modes.js +1 -1
  88. package/dist/knowledge/semantic-ir.d.ts +132 -0
  89. package/dist/knowledge/semantic-ir.js +1 -0
  90. package/dist/knowledge/service-ledger.js +1 -1
  91. package/dist/knowledge/strategy-manuals.js +1 -1
  92. package/dist/knowledge/template-index.js +1 -1
  93. package/dist/knowledge/template-loader.d.ts +45 -0
  94. package/dist/knowledge/template-loader.js +1 -1
  95. package/dist/knowledge/template-prose.d.ts +50 -0
  96. package/dist/knowledge/template-prose.js +1 -0
  97. package/dist/knowledge/template-registry.js +1 -1
  98. package/dist/knowledge/template-scanner.d.ts +5 -3
  99. package/dist/knowledge/template-scanner.js +1 -1
  100. package/dist/knowledge/template-validation.js +1 -1
  101. package/dist/knowledge/tools-reference.js +1 -1
  102. package/dist/monitor/MonitorLoop.js +1 -1
  103. package/dist/monitor/normalize.d.ts +1 -1
  104. package/dist/monitor/normalize.js +1 -1
  105. package/dist/monitor/types.js +1 -1
  106. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  107. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  108. package/dist/playbooks/service-build/merchant-guide.d.ts +16 -6
  109. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  110. package/dist/playbooks/service-build/migration-planner.d.ts +11 -2
  111. package/dist/playbooks/service-build/migration-planner.js +1 -1
  112. package/dist/playbooks/service-build/mode-actions.d.ts +8 -0
  113. package/dist/playbooks/service-build/mode-actions.js +1 -1
  114. package/dist/playbooks/service-build/object-panorama.d.ts +22 -1
  115. package/dist/playbooks/service-build/object-panorama.js +1 -1
  116. package/dist/playbooks/service-build/participation-radar.js +1 -1
  117. package/dist/playbooks/service-build/relationship-profile.js +1 -1
  118. package/dist/playbooks/service-build/reverse-mapping-nk4.spec.js +1 -1
  119. package/dist/playbooks/service-build/reverse-mapping.d.ts +1 -0
  120. package/dist/playbooks/service-build/reverse-mapping.js +1 -1
  121. package/dist/playbooks/service-build/service-panorama.js +1 -1
  122. package/dist/playbooks/service-build/service-quote.js +1 -1
  123. package/dist/playbooks/service-build/service-quote.spec.js +1 -1
  124. package/dist/review/index.js +1 -1
  125. package/dist/safety/confirm-gate.js +1 -1
  126. package/dist/schema/benchmark-migration/index.d.ts +135 -10
  127. package/dist/schema/benchmark-migration/index.js +1 -1
  128. package/dist/schema/call/allocation.d.ts +3 -0
  129. package/dist/schema/call/allocation.js +1 -1
  130. package/dist/schema/call/arbitration.js +1 -1
  131. package/dist/schema/call/base.d.ts +32 -0
  132. package/dist/schema/call/bridge.d.ts +8 -0
  133. package/dist/schema/call/error-codes.d.ts +1 -1
  134. package/dist/schema/call/error-codes.js +1 -1
  135. package/dist/schema/call/order.js +1 -1
  136. package/dist/schema/call/reward.d.ts +10 -0
  137. package/dist/schema/call/reward.js +1 -1
  138. package/dist/schema/call/semantic.js +1 -1
  139. package/dist/schema/call/service.js +1 -1
  140. package/dist/schema/common/index.js +1 -1
  141. package/dist/schema/config/index.d.ts +24 -0
  142. package/dist/schema/config/index.js +1 -1
  143. package/dist/schema/evaluation/index.d.ts +152 -0
  144. package/dist/schema/evaluation/index.js +1 -1
  145. package/dist/schema/goal/index.d.ts +16 -0
  146. package/dist/schema/goal/planning.d.ts +29 -0
  147. package/dist/schema/goal/planning.js +1 -1
  148. package/dist/schema/industry-pack/index.d.ts +70 -0
  149. package/dist/schema/industry-pack/modes.d.ts +70 -0
  150. package/dist/schema/industry-pack/modes.js +1 -1
  151. package/dist/schema/intent-radar/index.d.ts +3 -0
  152. package/dist/schema/intent-radar/index.js +1 -1
  153. package/dist/schema/local/index.d.ts +80 -0
  154. package/dist/schema/local/index.js +1 -1
  155. package/dist/schema/messenger/index.d.ts +278 -1
  156. package/dist/schema/messenger/index.js +1 -1
  157. package/dist/schema/operations.d.ts +6 -0
  158. package/dist/schema/query/bi.d.ts +38 -0
  159. package/dist/schema/query/bi.js +1 -1
  160. package/dist/schema/query/index.d.ts +148 -47
  161. package/dist/schema/query/index.js +1 -1
  162. package/dist/schema/schema-version.js +1 -1
  163. package/dist/schema/service-clone/index.d.ts +17 -0
  164. package/dist/schema/service-clone/index.js +1 -1
  165. package/dist/schema-query-impl/index.js +1 -1
  166. package/dist/schemas/account_operation.output.json +8 -0
  167. package/dist/schemas/benchmark_migration_operation.output.json +296 -2
  168. package/dist/schemas/benchmark_migration_operation.schema.json +292 -7
  169. package/dist/schemas/bridge_operation.output.json +8 -0
  170. package/dist/schemas/config_operation.output.json +95 -0
  171. package/dist/schemas/config_operation.schema.json +16 -1
  172. package/dist/schemas/evaluation_operation.output.json +240 -0
  173. package/dist/schemas/evaluation_operation.schema.json +397 -1
  174. package/dist/schemas/goal_operation.schema.json +40 -10
  175. package/dist/schemas/index.json +1 -1
  176. package/dist/schemas/industry_pack_operation.output.json +90 -2
  177. package/dist/schemas/industry_pack_operation.schema.json +236 -0
  178. package/dist/schemas/intent_radar.output.json +2 -0
  179. package/dist/schemas/intent_radar.schema.json +1 -0
  180. package/dist/schemas/local_cache_operation.output.json +8 -0
  181. package/dist/schemas/local_history_operation.output.json +8 -0
  182. package/dist/schemas/local_info_operation.output.json +8 -0
  183. package/dist/schemas/local_mark_operation.output.json +8 -0
  184. package/dist/schemas/messenger_operation.output.json +609 -1
  185. package/dist/schemas/messenger_operation.schema.json +96 -1
  186. package/dist/schemas/onchain_events.output.json +281 -11
  187. package/dist/schemas/onchain_events.schema.json +5 -1
  188. package/dist/schemas/onchain_operations.output.json +8 -0
  189. package/dist/schemas/onchain_operations.schema.json +371 -10
  190. package/dist/schemas/onchain_operations_allocation.schema.json +10 -1
  191. package/dist/schemas/onchain_operations_arbitration.schema.json +1 -1
  192. package/dist/schemas/onchain_operations_guard.schema.json +318 -0
  193. package/dist/schemas/onchain_operations_order.schema.json +1 -1
  194. package/dist/schemas/onchain_operations_reward.schema.json +35 -1
  195. package/dist/schemas/onchain_operations_service.schema.json +6 -6
  196. package/dist/schemas/query_toolkit.output.json +305 -8
  197. package/dist/schemas/service_clone_operation.output.json +79 -0
  198. package/dist/tools/handlers/benchmark-migration.d.ts +15 -0
  199. package/dist/tools/handlers/benchmark-migration.js +1 -1
  200. package/dist/tools/handlers/config.js +1 -1
  201. package/dist/tools/handlers/evaluation.js +1 -1
  202. package/dist/tools/handlers/evaluation.spec.js +1 -1
  203. package/dist/tools/handlers/intent-radar.js +1 -1
  204. package/dist/tools/handlers/messenger.d.ts +1 -0
  205. package/dist/tools/handlers/messenger.js +1 -1
  206. package/dist/tools/handlers/onchain.d.ts +20 -1
  207. package/dist/tools/handlers/onchain.js +1 -1
  208. package/dist/tools/handlers/query.d.ts +1 -0
  209. package/dist/tools/handlers/query.js +1 -1
  210. package/dist/tools/handlers/service-clone.d.ts +18 -0
  211. package/dist/tools/handlers/service-clone.js +1 -1
  212. package/dist/tools/handlers/wip.js +1 -1
  213. package/dist/tools/registry/agent.js +1 -1
  214. package/dist/tools/registry/business.js +1 -1
  215. package/dist/tools/registry/query.js +1 -1
  216. package/dist/tools/wip-verify-ledger.d.ts +14 -0
  217. package/dist/tools/wip-verify-ledger.js +1 -0
  218. package/dist/tools/wrap.d.ts +4 -0
  219. package/dist/tools/wrap.js +1 -1
  220. package/package.json +2 -2
@@ -1 +1 @@
1
- import{query_received,query_objects}from'@wowok/wowok';import{batchQueryObjectsByIds,fetchMachineNodes,fetchOrderContext,fetchPermissionContext}from'../graph/onchain/sdk-batch.js';import{extractCoinType}from'../graph/onchain/extract.js';import{enumerateActionableForwards}from'../knowledge/index.js';import{formatChainValue}from'../knowledge/fund-layer.js';import{formatShortAddress}from'../persona/address-format.js';export async function detectPaymentUnclaimed(a,b,c){const d=[];for(const e of a){const f=e['toLowerCase']();let g=null;try{g=await c['queryUnclaimed'](f,b);}catch{g=null;}if(!g||g['balance']<=0x0n||g['count']<=0x0)continue;let h;try{h=await c['formatAmount']?.(g['balance'],g['token_type'],b);}catch{h=undefined;}const i=h??g['balance']['toString']()+'\x20(smallest\x20unit)';d['push']({'dedupe_key':'payment_unclaimed:'+f,'detector':'payment_unclaimed','beneficiary':f,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+i+'\x20waiting\x20to\x20be\x20received','detail':g['count']+'\x20CoinWrapper\x20object(s)\x20hold\x20'+i+'\x20for\x20this\x20account.\x20'+'They\x20are\x20owned\x20but\x20NOT\x20spendable\x20until\x20unwrapped.\x20Execute\x20payment\x20{receive:true}\x20'+'as\x20this\x20account\x20to\x20unwrap\x20all\x20of\x20them\x20into\x20the\x20wallet\x20in\x20one\x20transaction\x20(keeper\x20can\x20'+'auto-execute\x20this\x20when\x20a\x20payment_unclaimed\x20auto-exec\x20rule\x20covers\x20the\x20account).','benefit':'Receive\x20'+i+'\x20into\x20your\x20wallet','state_fingerprint':g['count']+':'+g['balance']['toString']()});}return d;}export async function detectProgressActionable(a,b,c,d){const e=(a['order_children']??[])['filter'](n=>n['type']==='progress'&&typeof n['object']==='string')['map'](n=>n['object'])['filter'](n=>n['startsWith']('0x')),f=(a['focus']??[])['map'](n=>n['object'])['filter'](n=>typeof n==='string'&&n['startsWith']('0x')),g=[...new Set([...e,...f])]['slice'](0x0,Math['max'](0x1,d));if(g['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let h;try{h=await c['fetchProgressFields'](g,b);}catch{return[];}const i=new Map(),j=new Map(),k=new Map(),l=a['accounts'],m=[];for(const [n,o]of h){const p=typeof o?.['machine']==='string'?o['machine']:undefined;if(!p)continue;const q=p['toLowerCase']();let r=i['get'](q);if(!r){try{r=await c['fetchMachineNodes'](p,b);}catch{r=[];}i['set'](q,r);}if(r['length']===0x0)continue;let s;if(!j['has'](q)){let z;try{z=await c['fetchMachinePermissionAddr'](p,b);}catch{z=undefined;}let A;if(z)try{A=await c['fetchPermissionContext'](z,b);}catch{A=undefined;}j['set'](q,A);}s=j['get'](q);const t=typeof o?.['task']==='string'?o['task']:undefined;let u;if(t){const B=t['toLowerCase']();if(!k['has'](B))try{k['set'](B,await c['fetchOrderContext'](t,b));}catch{k['set'](B,undefined);}u=k['get'](B);}const v=(Array['isArray'](o?.['namedOperator'])?o['namedOperator']:[])['map'](C=>({'name':String(C?.['name']??''),'operators':(Array['isArray'](C?.['operators'])?C['operators']:[])['map'](D=>String(D))})),w=enumerateActionableForwards(o,r,l,v,u,s),x=typeof o?.['current']==='string'?o['current']:'',y=t?'order\x20'+formatShortAddress(t):'no\x20bound\x20order';for(const C of w){for(const D of C['executable_accounts']){const E=C['threshold']>0x1?'\x20—\x20cooperation\x20threshold\x20'+C['threshold']+'\x20(weight\x20'+C['weight']+');\x20other\x20distinct\x20forwards\x20may\x20still\x20be\x20needed':'',F=C['guard']?'\x20—\x20guard\x20'+formatShortAddress(C['guard'])+'\x20must\x20be\x20satisfied\x20(submissions\x20may\x20be\x20required)':'',G=u&&D===u['builder']['toLowerCase']()?'You\x20are\x20the\x20order\x20owner':C['operator_kind']==='named_operator'?'You\x20hold\x20the\x20named-operator\x20role\x20\x27'+C['named_operator']+'\x27':'You\x20hold\x20the\x20required\x20permission\x20index';m['push']({'dedupe_key':'progress_actionable:'+n+':'+D+':'+C['next_node']+'|'+C['forward'],'detector':'progress_actionable','beneficiary':D,'object':n,'title':'Workflow\x20action\x20available:\x20\x27'+C['forward']+'\x27\x20→\x20'+C['next_node'],'detail':'Progress\x20'+formatShortAddress(n)+'\x20('+y+')\x20sits\x20at\x20node\x20\x27'+x+'\x27.\x20'+(G+'\x20—\x20you\x20can\x20execute\x20forward\x20\x27'+C['forward']+'\x27\x20into\x20\x27'+C['next_node']+'\x27')+(''+E+F+'.\x20Advance\x20it\x20via\x20workflow_operation\x20')+'(action=\x27list\x27\x20to\x20review,\x20action=\x27operate\x27\x20to\x20execute).\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20does\x20not\x20move\x20the\x20order\x20—\x20the\x20party\x20that\x20'+'gains\x20from\x20the\x20next\x20step\x20sends\x20the\x20transaction.','benefit':benefitOfNode(C['next_node']),'state_fingerprint':C['weight']+':'+C['threshold']+':'+(C['guard']??'')+':'+C['operator_kind']});}}}return m;}function benefitOfNode(a){if(/(^|_)(completed?|done|finished|received|delivered|accepted|confirmed|finalized|success|approved)(_|$)/i['test'](a))return'Completing\x20this\x20step\x20settles\x20the\x20order\x20—\x20funds\x20are\x20released\x20to\x20the\x20provider';if(/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?)(_|$)/i['test'](a))return'This\x20step\x20routes\x20to\x20cancellation/refund\x20—\x20funds\x20return\x20to\x20the\x20buyer';if(/(^|_)(interrupt(ed)?|exception|dispute(d)?|fail(ed)?|abort(ed)?|reject(ed)?)(_|$)/i['test'](a))return'This\x20step\x20opens\x20the\x20exception\x20path\x20—\x20review\x20before\x20advancing';return'Advancing\x20keeps\x20the\x20order\x20moving\x20toward\x20settlement';}const REFUND_FLAVOR_RE=/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?|expired)(_|$)/i;export async function detectSettlementPending(a,b,c,e){const f=(a['accounts']??[])['map'](s=>s['toLowerCase']());if(f['length']===0x0)return[];const g=(a['orders']??[])['slice'](0x0,Math['max'](0x1,e));if(g['length']===0x0)return[];const h=g['map'](s=>s['order'])['filter'](s=>typeof s==='string'&&s['startsWith']('0x'));let i;try{i=await c['fetchOrderFields'](h,b);}catch{return[];}const j=[],k=[];for(const s of i['values']()){const t=s?.['data']??s;if(typeof t?.['allocation']==='string'&&t['allocation']['startsWith']('0x'))j['push'](t['allocation']);if(typeof t?.['progress']==='string'&&t['progress']['startsWith']('0x'))k['push'](t['progress']);}let l=new Map(),m=new Map();try{l=await c['fetchAllocationFields']([...new Set(j)],b);}catch{return[];}try{m=await c['fetchProgressFields']([...new Set(k)],b);}catch{m=new Map();}const o=new Set((a['services']??[])['map'](u=>u['toLowerCase']())),q=new Map(),r=[];for(const [u,v]of i){const w=v?.['data']??v,x=typeof w?.['allocation']==='string'?w['allocation']:undefined;if(!x)continue;const y=l['get'](x['toLowerCase']());if(!y)continue;const z=y?.['data']??y,A=typeof z['balance']==='bigint'?z['balance']:BigInt(z['balance']??0x0);if(A<=0x0n)continue;const B=Array['isArray'](z['payment'])?z['payment']:[];if(B['length']>0x0)continue;const C=typeof w?.['progress']==='string'?w['progress']:undefined,D=C?m['get'](C['toLowerCase']()):undefined,E=typeof D?.['current']==='string'?D['current']:'',F=typeof D?.['machine']==='string'?D['machine']:typeof w?.['machine']==='string'?w['machine']:undefined;if(!E||!F)continue;let G=q['get'](F['toLowerCase']());if(!G){try{G=await c['fetchMachineNodes'](F,b);}catch{G=[];}q['set'](F['toLowerCase'](),G);}if(G['length']===0x0)continue;const H=new Set();for(const P of G){for(const Q of P['pairs']){if((Q['forwards']??[])['length']>0x0)H['add'](P['name']);}}if(H['has'](E))continue;const I=REFUND_FLAVOR_RE['test'](E),J=[];if(I){const R=typeof w?.['builder']==='string'?w['builder']['toLowerCase']():'';if(R&&f['includes'](R))J['push'](R);}else{const S=typeof w?.['service']==='string'?w['service']['toLowerCase']():'';if(S&&o['has'](S))J['push'](...f);}if(J['length']===0x0)continue;const K=(Array['isArray'](z['allocators']?.['allocators'])?z['allocators']['allocators']:[])['map'](T=>String(T?.['guard']??''))['filter'](T=>T),L=K['length']>0x0?'Candidate\x20settle\x20guards\x20on\x20this\x20pool:\x20'+K['map'](T=>formatShortAddress(T))['join'](',\x20')+'.':'This\x20pool\x20exposes\x20no\x20readable\x20allocator\x20guards\x20—\x20inspect\x20it\x20before\x20acting.';let M;try{M=await c['formatAmount']?.(A,extractCoinType(y?.['type_raw']),b);}catch{M=undefined;}const N=M??A['toString']()+'\x20(smallest\x20unit)',O=I?'refund/cancel':'completion';for(const T of J){r['push']({'dedupe_key':'settlement_pending:'+u+':'+x,'detector':'settlement_pending','beneficiary':T,'object':x,'title':'Unsettled\x20escrow\x20—\x20'+N+'\x20on\x20a\x20'+O+'\x20terminal','detail':'Order\x20'+formatShortAddress(u)+'\x20sits\x20on\x20terminal\x20node\x20\x27'+E+'\x27\x20but\x20its\x20Allocation\x20'+(formatShortAddress(x)+'\x20still\x20holds\x20'+N+'\x20and\x20has\x20emitted\x20no\x20Payment.\x20The\x20chain\x20never\x20')+('auto-settles:\x20someone\x20must\x20trigger\x20the\x20matching\x20guard.\x20'+L+'\x20Execute\x20via\x20allocation_operation\x20')+'(operation_type=\x27allocation\x27,\x20alloc_by_guard=<guard>)\x20as\x20an\x20account\x20that\x20can\x20satisfy\x20the\x20guard,\x20then\x20'+'recipients\x20claim\x20their\x20CoinWrappers\x20(payment\x20receive).\x20Trigger\x20ONCE\x20and\x20verify\x20the\x20pool\x20drained\x20—\x20a\x20'+'fully-drained\x20pool\x20aborts\x20on\x20re-trigger,\x20but\x20a\x20max-capped\x20pool\x20re-splits\x20the\x20remainder.\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20keeps\x20the\x20funds\x20frozen\x20and\x20leaves\x20the\x20dispute\x20window\x20open.','benefit':'Release\x20'+N+'\x20from\x20escrow\x20to\x20its\x20rightful\x20recipients','state_fingerprint':A['toString']()+':'+B['length']+':'+E});}}return r;}export async function detectTimeoutIntermediate(a,b,c,d,e){const f=(a['order_children']??[])['filter'](m=>m['type']==='progress'&&typeof m['object']==='string')['map'](m=>m['object'])['filter'](m=>m['startsWith']('0x')),g=(a['focus']??[])['map'](m=>m['object'])['filter'](m=>typeof m==='string'&&m['startsWith']('0x')),h=[...new Set([...f,...g])]['slice'](0x0,Math['max'](0x1,d));if(h['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let i;try{i=await c['fetchProgressFields'](h,b);}catch{return[];}const j=c['nowMs'](),k=new Map(),l=[];for(const [m,n]of i){const o=typeof n?.['current']==='string'?n['current']:'',p=typeof n?.['current_time']==='number'?n['current_time']:0x0;if(!o||p<=0x0)continue;const q=typeof n?.['machine']==='string'?n['machine']:undefined;if(!q)continue;const r=q['toLowerCase']();let s=k['get'](r);if(!s){try{s=await c['fetchMachineNodes'](q,b);}catch{s=[];}k['set'](r,s);}const t=s['find'](A=>A['name']===o);if(!t)continue;const u=t['pairs']['some'](A=>(A['forwards']??[])['length']>0x0);if(!u)continue;const v=j-p;if(v<e)continue;const w=typeof n?.['task']==='string'?n['task']:undefined,x=(a['accounts']??[])['map'](A=>A['toLowerCase']()),y=x[0x0];if(!y)continue;const z=Math['floor'](v/(0x3e8*0x3c*0x3c));l['push']({'dedupe_key':'timeout_intermediate:'+m+':'+o,'detector':'timeout_intermediate','beneficiary':y,'object':m,'title':'Possible\x20stuck\x20intermediate\x20state\x20—\x20\x27'+o+'\x27\x20for\x20'+z+'h','detail':'Progress\x20'+formatShortAddress(m)+'\x20has\x20been\x20on\x20node\x20\x27'+o+'\x27\x20for\x20'+z+'\x20hours\x20'+('(since\x20'+new Date(p)['toISOString']()+').\x20This\x20node\x20has\x20outgoing\x20forwards\x20but\x20none\x20have\x20fired.\x20')+'If\x20this\x20node\x20has\x20a\x20time-lock\x20guard\x20(confirm\x20timeout,\x20acceptance\x20timeout,\x20inspection\x20timeout,\x20etc.),\x20'+'the\x20keeper\x20may\x20need\x20to\x20advance\x20it.\x20Check\x20the\x20template\x27s\x20keeper_dependencies\x20and\x20the\x20guard\x27s\x20time\x20window\x20'+'before\x20acting.\x20Who\x20benefits,\x20who\x20pushes:\x20a\x20stuck\x20intermediate\x20state\x20blocks\x20the\x20order\x27s\x20funds\x20and\x20'+'business\x20flow\x20—\x20the\x20party\x20that\x20gains\x20from\x20unblocking\x20it\x20sends\x20the\x20transaction.','benefit':'Unblock\x20the\x20order\x20stuck\x20at\x20\x27'+o+'\x27','state_fingerprint':o+':'+p+':'+v});}return l;}export function realPaymentDetectorDeps(){return{'queryUnclaimed':async(a,b)=>{const c=await query_received({'name_or_address':{'name_or_address':a},'type':'CoinWrapper','network':b});if(!c||typeof c!=='object'||!Array['isArray'](c['received']))return null;const d=typeof c['balance']==='bigint'?c['balance']:BigInt(c['balance']??0x0);return{'balance':d,'count':c['received']['length'],'token_type':typeof c['token_type']==='string'&&c['token_type']?c['token_type']:undefined};},'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realProgressDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of c??[]){const g=f?.['data']??f;if(f?.['type']!=='Progress')continue;const h=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(h)e['set'](h,g);}return e;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'fetchMachinePermissionAddr':async(a,b)=>{const c=await query_objects({'objects':[a],'network':b}),d=c?.['objects']?.[0x0],e=(d?.['data']??d)?.['permission'];return typeof e==='string'&&e?e:undefined;},'fetchPermissionContext':(a,b)=>fetchPermissionContext(a,b,![]),'fetchOrderContext':(a,b)=>fetchOrderContext(a,b,![])};}async function fieldsByType(a,b,c){const d=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of d??[]){if(f?.['type']!==c)continue;const g=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(g)e['set'](g,f);}return e;}export function realSettlementDetectorDeps(){return{'fetchOrderFields':(a,b)=>fieldsByType(a,b,'Order'),'fetchAllocationFields':(a,b)=>fieldsByType(a,b,'Allocation'),'fetchProgressFields':async(a,b)=>{const c=await fieldsByType(a,b,'Progress'),d=new Map();for(const [e,f]of c)d['set'](e,f?.['data']??f);return d;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realTimeoutDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await fieldsByType(a,b,'Progress'),d=new Map();for(const [e,f]of c)d['set'](e,f?.['data']??f);return d;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'nowMs':()=>Date['now']()};}
1
+ import{query_received,query_objects}from'@wowok/wowok';import{batchQueryObjectsByIds,fetchMachineNodes,fetchOrderContext,fetchPermissionContext}from'../graph/onchain/sdk-batch.js';import{extractCoinType}from'../graph/onchain/extract.js';import{enumerateActionableForwards}from'../knowledge/index.js';import{formatChainValue}from'../knowledge/fund-layer.js';import{loadGuardJsonFromChain}from'../knowledge/guard-submission-brief.js';import{formatShortAddress}from'../persona/address-format.js';export async function detectPaymentUnclaimed(a,b,c){const d=[];for(const e of a){const f=e['toLowerCase']();let g=null;try{g=await c['queryUnclaimed'](f,b);}catch{g=null;}if(!g||g['balance']<=0x0n||g['count']<=0x0)continue;let h;try{h=await c['formatAmount']?.(g['balance'],g['token_type'],b);}catch{h=undefined;}const i=h??g['balance']['toString']()+'\x20(smallest\x20unit)';d['push']({'dedupe_key':'payment_unclaimed:'+f,'detector':'payment_unclaimed','beneficiary':f,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+i+'\x20waiting\x20to\x20be\x20received','detail':g['count']+'\x20CoinWrapper\x20object(s)\x20hold\x20'+i+'\x20for\x20this\x20account.\x20'+'They\x20are\x20owned\x20but\x20NOT\x20spendable\x20until\x20unwrapped.\x20Execute\x20payment\x20{receive:true}\x20'+'as\x20this\x20account\x20to\x20unwrap\x20all\x20of\x20them\x20into\x20the\x20wallet\x20in\x20one\x20transaction\x20(keeper\x20can\x20'+'auto-execute\x20this\x20when\x20a\x20payment_unclaimed\x20auto-exec\x20rule\x20covers\x20the\x20account).','benefit':'Receive\x20'+i+'\x20into\x20your\x20wallet','state_fingerprint':g['count']+':'+g['balance']['toString']()});}return d;}export function extractGuardSignerPins(a){const b=Array['isArray'](a['table'])?a['table']:[],c=[],d=(e,f)=>{if(!e||typeof e!=='object')return;const g=f||e['type']==='logic_or'||e['type']==='logic_not';if(e['type']==='logic_equal'){const h=Array['isArray'](e['nodes'])?e['nodes']:e['left']&&e['right']?[e['left'],e['right']]:[],i=h['findIndex'](k=>k?.['type']==='context'&&k?.['context']==='Signer'),j=i>=0x0?h[0x1-i]:undefined;if(j?.['type']==='identifier'&&!g){const k=b['find'](l=>Number(l?.['identifier'])===Number(j['identifier']));k&&k['b_submission']!==!![]&&k['value_type']==='Address'&&typeof k['value']==='string'&&k['value']['startsWith']('0x')&&k['value']['length']>0x2&&c['push'](String(k['value']));}}for(const l of[e['nodes'],e['left'],e['right']]['flat']()){if(l&&typeof l==='object')d(l,g);}};return d(a['root'],![]),c;}export async function detectProgressActionable(a,b,c,d){const e=(a['order_children']??[])['filter'](p=>p['type']==='progress'&&typeof p['object']==='string')['map'](p=>p['object'])['filter'](p=>p['startsWith']('0x')),f=(a['focus']??[])['map'](p=>p['object'])['filter'](p=>typeof p==='string'&&p['startsWith']('0x')),g=[...new Set([...e,...f])]['slice'](0x0,Math['max'](0x1,d));if(g['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let h;try{h=await c['fetchProgressFields'](g,b);}catch{return[];}const i=new Map(),j=new Map(),k=new Map(),l=new Map(),m=c['fetchGuardJson']??(async(p,q)=>(await loadGuardJsonFromChain(p,q))?.['json']),n=a['accounts'],o=[];for(const [p,q]of h){const r=typeof q?.['machine']==='string'?q['machine']:undefined;if(!r)continue;const s=r['toLowerCase']();let t=i['get'](s);if(!t){try{t=await c['fetchMachineNodes'](r,b);}catch{t=[];}i['set'](s,t);}if(t['length']===0x0)continue;let u;if(!j['has'](s)){let B;try{B=await c['fetchMachinePermissionAddr'](r,b);}catch{B=undefined;}let C;if(B)try{C=await c['fetchPermissionContext'](B,b);}catch{C=undefined;}j['set'](s,C);}u=j['get'](s);const v=typeof q?.['task']==='string'?q['task']:undefined;let w;if(v){const D=v['toLowerCase']();if(!k['has'](D))try{k['set'](D,await c['fetchOrderContext'](v,b));}catch{k['set'](D,undefined);}w=k['get'](D);}const x=(Array['isArray'](q?.['namedOperator'])?q['namedOperator']:[])['map'](E=>({'name':String(E?.['name']??''),'operators':(Array['isArray'](E?.['operators'])?E['operators']:[])['map'](F=>String(F))})),y=enumerateActionableForwards(q,t,n,x,w,u),z=typeof q?.['current']==='string'?q['current']:'',A=v?'order\x20'+formatShortAddress(v):'no\x20bound\x20order';for(const E of y){let F=[];const G=typeof E['guard']==='string'?E['guard']['toLowerCase']():'';if(G){const H=l['get'](G);if(H!==undefined)F=H;else{let I;try{I=await m(E['guard'],b);}catch{I=undefined;}F=I?extractGuardSignerPins(I):[],l['set'](G,F);}}for(const J of E['executable_accounts']){if(F['length']>0x0){const N=F[0x0]['toLowerCase'](),O=F['every'](P=>P['toLowerCase']()===N);if(O&&N!==J['toLowerCase']())continue;}const K=E['threshold']>0x1?'\x20—\x20cooperation\x20threshold\x20'+E['threshold']+'\x20(weight\x20'+E['weight']+');\x20other\x20distinct\x20forwards\x20may\x20still\x20be\x20needed':'',L=E['guard']?'\x20—\x20guard\x20'+formatShortAddress(E['guard'])+'\x20must\x20be\x20satisfied\x20(submissions\x20may\x20be\x20required)':'',M=w&&J===w['builder']['toLowerCase']()?'You\x20are\x20the\x20order\x20owner':E['operator_kind']==='named_operator'?'You\x20hold\x20the\x20named-operator\x20role\x20\x27'+E['named_operator']+'\x27':'You\x20hold\x20the\x20required\x20permission\x20index';o['push']({'dedupe_key':'progress_actionable:'+p+':'+J+':'+E['next_node']+'|'+E['forward'],'detector':'progress_actionable','beneficiary':J,'object':p,'title':'Workflow\x20action\x20available:\x20\x27'+E['forward']+'\x27\x20→\x20'+E['next_node'],'detail':'Progress\x20'+formatShortAddress(p)+'\x20('+A+')\x20sits\x20at\x20node\x20\x27'+z+'\x27.\x20'+(M+'\x20—\x20you\x20can\x20execute\x20forward\x20\x27'+E['forward']+'\x27\x20into\x20\x27'+E['next_node']+'\x27')+(''+K+L+'.\x20Advance\x20it\x20via\x20workflow_operation\x20')+'(action=\x27list\x27\x20to\x20review,\x20action=\x27operate\x27\x20to\x20execute).\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20does\x20not\x20move\x20the\x20order\x20—\x20the\x20party\x20that\x20'+'gains\x20from\x20the\x20next\x20step\x20sends\x20the\x20transaction.','benefit':benefitOfNode(E['next_node']),'state_fingerprint':E['weight']+':'+E['threshold']+':'+(E['guard']??'')+':'+E['operator_kind']});}}}return o;}function benefitOfNode(a){if(/(^|_)(completed?|done|finished|received|delivered|accepted|confirmed|finalized|success|approved)(_|$)/i['test'](a))return'Completing\x20this\x20step\x20settles\x20the\x20order\x20—\x20funds\x20are\x20released\x20to\x20the\x20provider';if(/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?)(_|$)/i['test'](a))return'This\x20step\x20routes\x20to\x20cancellation/refund\x20—\x20funds\x20return\x20to\x20the\x20buyer';if(/(^|_)(interrupt(ed)?|exception|dispute(d)?|fail(ed)?|abort(ed)?|reject(ed)?)(_|$)/i['test'](a))return'This\x20step\x20opens\x20the\x20exception\x20path\x20—\x20review\x20before\x20advancing';return'Advancing\x20keeps\x20the\x20order\x20moving\x20toward\x20settlement';}const REFUND_FLAVOR_RE=/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?|expired)(_|$)/i;export async function detectSettlementPending(a,b,c,e){const f=(a['accounts']??[])['map'](s=>s['toLowerCase']());if(f['length']===0x0)return[];const g=(a['orders']??[])['slice'](0x0,Math['max'](0x1,e));if(g['length']===0x0)return[];const h=g['map'](s=>s['order'])['filter'](s=>typeof s==='string'&&s['startsWith']('0x'));let i;try{i=await c['fetchOrderFields'](h,b);}catch{return[];}const j=[],k=[];for(const s of i['values']()){const t=s?.['data']??s;if(typeof t?.['allocation']==='string'&&t['allocation']['startsWith']('0x'))j['push'](t['allocation']);if(typeof t?.['progress']==='string'&&t['progress']['startsWith']('0x'))k['push'](t['progress']);}let l=new Map(),m=new Map();try{l=await c['fetchAllocationFields']([...new Set(j)],b);}catch{return[];}try{m=await c['fetchProgressFields']([...new Set(k)],b);}catch{m=new Map();}const o=new Set((a['services']??[])['map'](u=>u['toLowerCase']())),q=new Map(),r=[];for(const [u,v]of i){const w=v?.['data']??v,x=typeof w?.['allocation']==='string'?w['allocation']:undefined;if(!x)continue;const y=l['get'](x['toLowerCase']());if(!y)continue;const z=y?.['data']??y,A=typeof z['balance']==='bigint'?z['balance']:BigInt(z['balance']??0x0);if(A<=0x0n)continue;const B=Array['isArray'](z['payment'])?z['payment']:[];if(B['length']>0x0)continue;const C=typeof w?.['progress']==='string'?w['progress']:undefined,D=C?m['get'](C['toLowerCase']()):undefined,E=typeof D?.['current']==='string'?D['current']:'',F=typeof D?.['machine']==='string'?D['machine']:typeof w?.['machine']==='string'?w['machine']:undefined;if(!E||!F)continue;let G=q['get'](F['toLowerCase']());if(!G){try{G=await c['fetchMachineNodes'](F,b);}catch{G=[];}q['set'](F['toLowerCase'](),G);}if(G['length']===0x0)continue;const H=new Set();for(const P of G){for(const Q of P['pairs']){if((Q['forwards']??[])['length']>0x0)H['add'](P['name']);}}if(H['has'](E))continue;const I=REFUND_FLAVOR_RE['test'](E),J=[];if(I){const R=typeof w?.['builder']==='string'?w['builder']['toLowerCase']():'';if(R&&f['includes'](R))J['push'](R);}else{const S=typeof w?.['service']==='string'?w['service']['toLowerCase']():'';if(S&&o['has'](S))J['push'](...f);}if(J['length']===0x0)continue;const K=(Array['isArray'](z['allocators']?.['allocators'])?z['allocators']['allocators']:[])['map'](T=>String(T?.['guard']??''))['filter'](T=>T),L=K['length']>0x0?'Candidate\x20settle\x20guards\x20on\x20this\x20pool:\x20'+K['map'](T=>formatShortAddress(T))['join'](',\x20')+'.':'This\x20pool\x20exposes\x20no\x20readable\x20allocator\x20guards\x20—\x20inspect\x20it\x20before\x20acting.';let M;try{M=await c['formatAmount']?.(A,extractCoinType(y?.['type_raw']),b);}catch{M=undefined;}const N=M??A['toString']()+'\x20(smallest\x20unit)',O=I?'refund/cancel':'completion';for(const T of J){r['push']({'dedupe_key':'settlement_pending:'+u+':'+x,'detector':'settlement_pending','beneficiary':T,'object':x,'title':'Unsettled\x20escrow\x20—\x20'+N+'\x20on\x20a\x20'+O+'\x20terminal','detail':'Order\x20'+formatShortAddress(u)+'\x20sits\x20on\x20terminal\x20node\x20\x27'+E+'\x27\x20but\x20its\x20Allocation\x20'+(formatShortAddress(x)+'\x20still\x20holds\x20'+N+'\x20and\x20has\x20emitted\x20no\x20Payment.\x20The\x20chain\x20never\x20')+('auto-settles:\x20someone\x20must\x20trigger\x20the\x20matching\x20guard.\x20'+L+'\x20Execute\x20via\x20allocation_operation\x20')+'(operation_type=\x27allocation\x27,\x20alloc_by_guard=<guard>)\x20as\x20an\x20account\x20that\x20can\x20satisfy\x20the\x20guard,\x20then\x20'+'recipients\x20claim\x20their\x20CoinWrappers\x20(payment\x20receive).\x20Trigger\x20ONCE\x20and\x20verify\x20the\x20pool\x20drained\x20—\x20a\x20'+'fully-drained\x20pool\x20aborts\x20on\x20re-trigger,\x20but\x20a\x20max-capped\x20pool\x20re-splits\x20the\x20remainder.\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20keeps\x20the\x20funds\x20frozen\x20and\x20leaves\x20the\x20dispute\x20window\x20open.','benefit':'Release\x20'+N+'\x20from\x20escrow\x20to\x20its\x20rightful\x20recipients','state_fingerprint':A['toString']()+':'+B['length']+':'+E});}}return r;}export async function detectTimeoutIntermediate(a,b,c,d,e){const f=(a['order_children']??[])['filter'](m=>m['type']==='progress'&&typeof m['object']==='string')['map'](m=>m['object'])['filter'](m=>m['startsWith']('0x')),g=(a['focus']??[])['map'](m=>m['object'])['filter'](m=>typeof m==='string'&&m['startsWith']('0x')),h=[...new Set([...f,...g])]['slice'](0x0,Math['max'](0x1,d));if(h['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let i;try{i=await c['fetchProgressFields'](h,b);}catch{return[];}const j=c['nowMs'](),k=new Map(),l=[];for(const [m,n]of i){const o=typeof n?.['current']==='string'?n['current']:'',p=typeof n?.['current_time']==='number'?n['current_time']:0x0;if(!o||p<=0x0)continue;const q=typeof n?.['machine']==='string'?n['machine']:undefined;if(!q)continue;const r=q['toLowerCase']();let s=k['get'](r);if(!s){try{s=await c['fetchMachineNodes'](q,b);}catch{s=[];}k['set'](r,s);}const t=s['find'](A=>A['name']===o);if(!t)continue;const u=t['pairs']['some'](A=>(A['forwards']??[])['length']>0x0);if(!u)continue;const v=j-p;if(v<e)continue;const w=typeof n?.['task']==='string'?n['task']:undefined,x=(a['accounts']??[])['map'](A=>A['toLowerCase']()),y=x[0x0];if(!y)continue;const z=Math['floor'](v/(0x3e8*0x3c*0x3c));l['push']({'dedupe_key':'timeout_intermediate:'+m+':'+o,'detector':'timeout_intermediate','beneficiary':y,'object':m,'title':'Possible\x20stuck\x20intermediate\x20state\x20—\x20\x27'+o+'\x27\x20for\x20'+z+'h','detail':'Progress\x20'+formatShortAddress(m)+'\x20has\x20been\x20on\x20node\x20\x27'+o+'\x27\x20for\x20'+z+'\x20hours\x20'+('(since\x20'+new Date(p)['toISOString']()+').\x20This\x20node\x20has\x20outgoing\x20forwards\x20but\x20none\x20have\x20fired.\x20')+'If\x20this\x20node\x20has\x20a\x20time-lock\x20guard\x20(confirm\x20timeout,\x20acceptance\x20timeout,\x20inspection\x20timeout,\x20etc.),\x20'+'the\x20keeper\x20may\x20need\x20to\x20advance\x20it.\x20Check\x20the\x20template\x27s\x20keeper_dependencies\x20and\x20the\x20guard\x27s\x20time\x20window\x20'+'before\x20acting.\x20Who\x20benefits,\x20who\x20pushes:\x20a\x20stuck\x20intermediate\x20state\x20blocks\x20the\x20order\x27s\x20funds\x20and\x20'+'business\x20flow\x20—\x20the\x20party\x20that\x20gains\x20from\x20unblocking\x20it\x20sends\x20the\x20transaction.','benefit':'Unblock\x20the\x20order\x20stuck\x20at\x20\x27'+o+'\x27','state_fingerprint':o+':'+p+':'+v});}return l;}export function realPaymentDetectorDeps(){return{'queryUnclaimed':async(a,b)=>{const c=await query_received({'name_or_address':{'name_or_address':a},'type':'CoinWrapper','network':b});if(!c||typeof c!=='object'||!Array['isArray'](c['received']))return null;const d=typeof c['balance']==='bigint'?c['balance']:BigInt(c['balance']??0x0);return{'balance':d,'count':c['received']['length'],'token_type':typeof c['token_type']==='string'&&c['token_type']?c['token_type']:undefined};},'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realProgressDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of c??[]){const g=f?.['data']??f;if(f?.['type']!=='Progress')continue;const h=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(h)e['set'](h,g);}return e;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'fetchMachinePermissionAddr':async(a,b)=>{const c=await query_objects({'objects':[a],'network':b}),d=c?.['objects']?.[0x0],e=(d?.['data']??d)?.['permission'];return typeof e==='string'&&e?e:undefined;},'fetchPermissionContext':(a,b)=>fetchPermissionContext(a,b,![]),'fetchOrderContext':(a,b)=>fetchOrderContext(a,b,![])};}async function fieldsByType(a,b,c){const d=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of d??[]){if(f?.['type']!==c)continue;const g=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(g)e['set'](g,f);}return e;}export function realSettlementDetectorDeps(){return{'fetchOrderFields':(a,b)=>fieldsByType(a,b,'Order'),'fetchAllocationFields':(a,b)=>fieldsByType(a,b,'Allocation'),'fetchProgressFields':async(a,b)=>{const c=await fieldsByType(a,b,'Progress'),d=new Map();for(const [e,f]of c)d['set'](e,f?.['data']??f);return d;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realTimeoutDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await fieldsByType(a,b,'Progress'),d=new Map();for(const [e,f]of c)d['set'](e,f?.['data']??f);return d;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'nowMs':()=>Date['now']()};}
@@ -1 +1 @@
1
- import{describe,expect,it}from'vitest';import{KeeperStore}from'./KeeperStore.js';import{detectPaymentUnclaimed,detectProgressActionable,detectSettlementPending}from'./detectors.js';import{executeKeeperTask,runKeeperScan}from'./KeeperScan.js';import{clampKeeperConfig,defaultKeeperConfig,KEEPER_MIN}from'./types.js';const NET='testnet',ACCT='0xaaa111',OTHER='0xbbb222';function memStorage(){const a=new Map();return{'get':async b=>a['get'](b),'put':async(b,c)=>void a['set'](b,c)};}function makeStore(){return new KeeperStore(memStorage());}function paymentItem(a,b,c=0x1){return{'dedupe_key':'payment_unclaimed:'+a,'detector':'payment_unclaimed','beneficiary':a,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+b+'\x20waiting','state_fingerprint':c+':'+b['toString']()};}function makeScope(a){return{'version':0x1,'resolved_at':0x0,'accounts':[ACCT],'permissions':[],'managed_objects':[],'services':[],'orders':[],'order_children':[],'focus':[],'index':{},...a};}describe('keeper\x20config',()=>{it('returns\x20safe\x20defaults:\x20reminders\x20ON,\x20auto\x20rules\x20none',async()=>{const a=makeStore(),b=await a['getConfig'](NET);expect(b['enabled'])['toBe'](!![]),expect(b['detectors']['payment_unclaimed'])['toBe'](!![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]),expect(await a['listRules'](NET))['toEqual']([]);}),it('config_set\x20patch\x20merges\x20detectors\x20individually',async()=>{const a=makeStore(),b=await a['saveConfig'](NET,{'detectors':{'payment_unclaimed':![]}});expect(b['detectors']['payment_unclaimed'])['toBe'](![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]);const c=await a['getConfig'](NET);expect(c['detectors']['payment_unclaimed'])['toBe'](![]),expect(c['detectors']['progress_actionable'])['toBe'](!![]);}),it('clamps\x20numeric\x20bounds\x20(cost/gas\x20guards)',()=>{const a=clampKeeperConfig({...defaultKeeperConfig(),'scan_interval_ms':0x1,'max_scan_objects':0x0,'max_auto_execute_per_scan':0x0,'auto_retry_cooldown_ms':0x0});expect(a['scan_interval_ms'])['toBe'](KEEPER_MIN['scan_interval_ms']),expect(a['max_scan_objects'])['toBe'](KEEPER_MIN['max_scan_objects']),expect(a['max_auto_execute_per_scan'])['toBe'](KEEPER_MIN['max_auto_execute_per_scan']),expect(a['auto_retry_cooldown_ms'])['toBe'](KEEPER_MIN['auto_retry_cooldown_ms']);});}),describe('keeper\x20rules',()=>{const a=b=>({'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0,...b});it('matchingAutoRules\x20honors\x20enabled\x20/\x20auto_execute\x20/\x20account\x20coverage',async()=>{const b=makeStore();await b['upsertRule'](NET,a()),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'progress_actionable',ACCT))['toHaveLength'](0x0),await b['upsertRule'](NET,a({'id':'krule_2','accounts':[OTHER['toUpperCase']()]})),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER))['toHaveLength'](0x2),await b['upsertRule'](NET,a({'id':'krule_3','enabled':![]})),await b['upsertRule'](NET,a({'id':'krule_4','auto_execute':![]}));const c=await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER);expect(c['map'](d=>d['id'])['sort']())['toEqual'](['krule_1','krule_2']);});}),describe('KeeperStore.upsertDesired',()=>{it('opens\x20new\x20tasks,\x20refreshes\x20on\x20fingerprint\x20change,\x20no\x20churn\x20when\x20identical',async()=>{const a=makeStore();let b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);expect(b)['toEqual']({'opened':0x1,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0),expect(b)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0xfan)],0xbb8),expect(b)['toEqual']({'opened':0x0,'refreshed':0x1,'revived':0x0,'superseded':0x0});const c=(await a['listTasks'](NET))[0x0];expect(c['title'])['toContain']('250'),expect(c['updated_at'])['toBe'](0xbb8);}),it('dismissed\x20stays\x20dismissed\x20for\x20identical\x20state,\x20revives\x20on\x20material\x20change',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'dismissed',0x5dc,'not\x20now');let c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0);expect(c['revived'])['toBe'](0x0),expect((await a['getTask'](NET,b['id']))['status'])['toBe']('dismissed'),c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x190n,0x2)],0xbb8),expect(c['revived'])['toBe'](0x1);const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('pending'),expect(d['resolution'])['toBeUndefined'](),expect(d['resolved_at'])['toBeUndefined']();}),it('executed\x20tasks\x20are\x20terminal\x20—\x20same\x20dedupe_key\x20never\x20re-opens\x20them',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'auto_executed',0x5dc,'tx\x20ABC','krule_1');const c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x1f4n)],0x7d0);expect(c)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0});const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('executed'),expect(d['rule_id'])['toBe']('krule_1');}),it('supersedes\x20pending\x20tasks\x20of\x20THIS\x20detector\x20only',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8),await a['upsertDesired'](NET,'progress_actionable',[{'dedupe_key':'progress_actionable:0xp1:0xaaa111:shipped|deliver','detector':'progress_actionable','beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator'}],0x3e8);const b=await a['upsertDesired'](NET,'payment_unclaimed',[],0x7d0);expect(b['superseded'])['toBe'](0x1);const c=await a['listTasks'](NET),d=c['find'](f=>f['detector']==='payment_unclaimed'),e=c['find'](f=>f['detector']==='progress_actionable');expect(d['status'])['toBe']('superseded'),expect(d['resolution'])['toBe']('superseded'),expect(e['status'])['toBe']('pending');}),it('execute_failed\x20keeps\x20the\x20task\x20pending\x20with\x20failure\x20bookkeeping',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'execute_failed',0x1388,'insufficient\x20gas','krule_1');const c=await a['getTask'](NET,b['id']);expect(c['status'])['toBe']('pending'),expect(c['last_auto_attempt_at'])['toBe'](0x1388),expect(c['auto_attempts'])['toBe'](0x1),expect(c['resolution_note'])['toBe']('insufficient\x20gas');});}),describe('detectPaymentUnclaimed',()=>{it('emits\x20a\x20claim-to-self\x20task\x20for\x20accounts\x20with\x20unclaimed\x20wrappers',async()=>{const a=await detectPaymentUnclaimed([ACCT['toUpperCase'](),OTHER,'0xccc333'],NET,{'queryUnclaimed':async c=>{if(c===ACCT)return{'balance':0x64n,'count':0x2,'token_type':'0x2::wow::WOW'};if(c===OTHER)return{'balance':0x0n,'count':0x0};throw new Error('rpc\x20down');},'formatAmount':async()=>'0.0000001\x20WOW'});expect(a)['toHaveLength'](0x1);const b=a[0x0];expect(b['dedupe_key'])['toBe']('payment_unclaimed:'+ACCT),expect(b['beneficiary'])['toBe'](ACCT),expect(b['operation'])['toEqual']({'operation_type':'payment','data':{'receive':!![]}}),expect(b['state_fingerprint'])['toBe']('2:100'),expect(b['title'])['toContain']('0.0000001\x20WOW');}),it('falls\x20back\x20to\x20raw\x20units\x20when\x20formatting\x20fails',async()=>{const a=await detectPaymentUnclaimed([ACCT],NET,{'queryUnclaimed':async()=>({'balance':0x2an,'count':0x1}),'formatAmount':async()=>{throw new Error('no\x20metadata');}});expect(a[0x0]['title'])['toContain']('42\x20(smallest\x20unit)');});}),describe('detectProgressActionable',()=>{const a='0xprog1',b='0xmachine1',c=[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],d=(g=[])=>({'machine':b,'current':'start','session':g,'namedOperator':[{'name':'courier','operators':[ACCT]}]}),e=g=>({'fetchProgressFields':async()=>new Map([[a,g]]),'fetchMachineNodes':async()=>c,'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}),f=makeScope({'order_children':[{'type':'progress','object':a}]});it('routes\x20an\x20actionable\x20forward\x20to\x20its\x20named\x20operator',async()=>{const g=await detectProgressActionable(f,NET,e(d()),0x14);expect(g)['toHaveLength'](0x1),expect(g[0x0]['dedupe_key'])['toBe']('progress_actionable:'+a+':'+ACCT+':shipped|deliver'),expect(g[0x0]['beneficiary'])['toBe'](ACCT),expect(g[0x0]['operation'])['toBeUndefined'](),expect(g[0x0]['detail'])['toContain']('workflow_operation');}),it('omits\x20accomplished\x20forwards\x20(single-operator\x20lock)',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':ACCT,'accomplished':!![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('restricts\x20a\x20held\x20forward\x20to\x20its\x20holder',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':OTHER,'accomplished':![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const g=await detectProgressActionable(f,NET,{...e(d()),'fetchProgressFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(g)['toEqual']([]);});}),describe('detectSettlementPending',()=>{const a='0xorder1',b='0xpool1',c='0xprog1',d='0xmachine1',e='0xsvc1',f=i=>[{'name':'paid','pairs':[{'prev_node':'','threshold':0x1,'forwards':[{'name':'settle','weight':0x1}]}]},{'name':i,'pairs':[{'prev_node':'paid','threshold':0x1,'forwards':[]}]}];function g(i,j,k,l){return{'fetchOrderFields':async()=>new Map([[a,{'type':'Order','object':a,'data':i}]]),'fetchAllocationFields':async()=>new Map([[b,{'type':'Allocation','object':b,'type_raw':'0x2::allocation::Allocation<0x2::coin::COIN>','data':j}]]),'fetchProgressFields':async()=>new Map([[c,k]]),'fetchMachineNodes':async()=>l};}const h={'allocation':b,'progress':c,'machine':d,'service':e,'builder':ACCT};it('routes\x20a\x20completion\x20terminal\x20with\x20an\x20unsettled\x20pool\x20to\x20the\x20merchant\x20account',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgsettle'}]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['detector'])['toBe']('settlement_pending'),expect(j[0x0]['title'])['toContain']('completion'),expect(j[0x0]['detail'])['toContain']('alloc_by_guard');}),it('routes\x20a\x20refund\x20terminal\x20to\x20the\x20buyer\x20(order\x20builder)\x20account',async()=>{const i=makeScope({'orders':[{'order':a,'role':'buyer'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgrefund'}]}},{'current':'refunded','machine':d},f('refunded')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['title'])['toContain']('refund/cancel');}),it('skips\x20a\x20pool\x20already\x20drained\x20(balance\x200)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'0','payment':[],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20pool\x20that\x20already\x20emitted\x20a\x20Payment',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':['0xpay1'],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20non-terminal\x20node\x20(still\x20has\x20outgoing\x20forwards)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[]}},{'current':'paid','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20order\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,{...g(h,{'balance':'5000','payment':[]},{'current':'completed','machine':d},f('completed')),'fetchOrderFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(j)['toEqual']([]);});});function scanDepsFor(a,b){let c=0x2710;const d=[],e={'store':a,'payment':{'queryUnclaimed':async()=>({'balance':0x64n,'count':0x1})},'progress':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined},'settlement':{'fetchOrderFields':async()=>new Map(),'fetchAllocationFields':async()=>new Map(),'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[]},'timeout':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'nowMs':()=>0x2710},'execute':async f=>{return d['push']({'operation_type':f['operation_type'],'account':f['account'],'via':f['via']}),{'ok':!![],'digest':'DIGEST1'};},'now':()=>c,'logger':()=>{},...b};return{'deps':e,'executed':d,'advance':f=>{c+=f;},'setClock':f=>{c=f;}};}describe('runKeeperScan',()=>{it('skips\x20when\x20disabled\x20and\x20when\x20inside\x20the\x20cadence\x20interval',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a);await a['saveConfig'](NET,{'enabled':![]});let c=await runKeeperScan(NET,makeScope(),b);expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('disabled'),await a['saveConfig'](NET,{'enabled':!![]}),await a['setLastScanAt'](NET,0x2710),c=await runKeeperScan(NET,makeScope(),b),expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('interval');}),it('auto-executes\x20a\x20payment\x20task\x20ONLY\x20with\x20a\x20covering\x20enabled\x20rule',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);let d=await runKeeperScan(NET,makeScope(),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0}),d=await runKeeperScan(NET,makeScope(),b,{'force':!![]}),expect(d['auto_executed'])['toBe'](0x1),expect(c[0x0])['toEqual']({'operation_type':'payment','account':ACCT,'via':'rule\x20krule_1'});const e=(await a['listTasks'](NET))[0x0];expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('auto_executed'),expect(e['rule_id'])['toBe']('krule_1'),expect(e['resolution_note'])['toContain']('DIGEST1');}),it('never\x20auto-executes\x20progress\x20tasks\x20(reminder-only\x20boundary)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a,{'payment':{'queryUnclaimed':async()=>null},'progress':{'fetchProgressFields':async()=>new Map([['0xprog1',{'machine':'0xm1','current':'start','session':[],'namedOperator':[{'name':'courier','operators':[ACCT]}]}]]),'fetchMachineNodes':async()=>[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}});await a['upsertRule'](NET,{'id':'krule_p','enabled':!![],'detector':'progress_actionable','accounts':[],'auto_execute':!![],'created_at':0x0});const d=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),expect((await a['listTasks'](NET))[0x0]['status'])['toBe']('pending');}),it('backs\x20off\x20after\x20a\x20failed\x20auto-exec\x20until\x20the\x20cooldown\x20passes',async()=>{const a=makeStore(),b=scanDepsFor(a,{'execute':async()=>({'ok':![],'error':'insufficient\x20gas'})});await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});let c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]});expect(c['auto_failed'])['toBe'](0x1);const d=(await a['listTasks'](NET))[0x0];expect(d['status'])['toBe']('pending'),expect(d['resolution_note'])['toBe']('insufficient\x20gas'),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x0),expect(c['auto_executed'])['toBe'](0x0),b['advance'](0x1f*0xea60),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x1);}),it('caps\x20auto-executions\x20per\x20scan\x20(gas\x20guard)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);await a['saveConfig'](NET,{'max_auto_execute_per_scan':0x1}),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});const d=makeScope({'accounts':[ACCT,OTHER]}),e=await runKeeperScan(NET,d,b,{'force':!![]});expect(e['opened'])['toBe'](0x2),expect(e['auto_executed'])['toBe'](0x1),expect(c)['toHaveLength'](0x1),expect(await a['listTasks'](NET,{'status':'pending'}))['toHaveLength'](0x1);});}),describe('executeKeeperTask\x20(manual)',()=>{it('resolves\x20a\x20payment\x20task\x20as\x20manual_executed',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0],{deps:c}=scanDepsFor(a),d=await executeKeeperTask(NET,b,c);expect(d['ok'])['toBe'](!![]);const e=await a['getTask'](NET,b['id']);expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('manual_executed');}),it('refuses\x20reminder-only\x20tasks\x20(progress)\x20with\x20guidance',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a),c={'id':'ktask_x','dedupe_key':'progress_actionable:0xp:0xaaa111:shipped|deliver','detector':'progress_actionable','network':NET,'beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator','status':'pending','created_at':0x0,'updated_at':0x0},d=await executeKeeperTask(NET,c,b);expect(d['ok'])['toBe'](![]),expect(d['error'])['toContain']('reminder-only');});}),describe('timeout_intermediate',()=>{const a=0xa*0x5265c00,b={'current':'awaiting_host_confirmation','current_time':a-0x1e*0x36ee80,'machine':'0xmach1','task':'0xorder1'};function c(e,f){return{'fetchProgressFields':async()=>new Map(e===undefined?[]:[['0xprog1',e]]),'fetchMachineNodes':async()=>f,'nowMs':()=>a};}function d(e,f){return{'name':e,'pairs':[{'prev_node':'paid','threshold':0x0,'forwards':Array['from']({'length':f},()=>({}))}]};}it('surfaces\x20a\x20progress\x20stuck\x20on\x20an\x20intermediate\x20node\x20past\x20the\x20threshold',async()=>{const {detectTimeoutIntermediate:e}=await import('./detectors.js'),f=await e(makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),NET,c(b,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80);expect(f)['toHaveLength'](0x1),expect(f[0x0]['detector'])['toBe']('timeout_intermediate'),expect(f[0x0]['beneficiary'])['toBe'](ACCT);}),it('stays\x20silent\x20below\x20the\x20threshold,\x20on\x20terminal\x20nodes,\x20and\x20on\x20missing\x20data',async()=>{const {detectTimeoutIntermediate:e}=await import('./detectors.js'),f=makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),g={...b,'current_time':a-0x1*0x36ee80};expect(await e(f,NET,c(g,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0),expect(await e(f,NET,c(b,[d('awaiting_host_confirmation',0x0)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0),expect(await e(f,NET,c(undefined,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0);}),it('the\x20scan\x20wires\x20the\x20detector:\x20a\x20stuck\x20progress\x20opens\x20a\x20reminder\x20task\x20(never\x20auto-exec)',async()=>{const e=makeStore(),f=scanDepsFor(e,{'payment':{'queryUnclaimed':async()=>null}}),{deps:g}=f;g['timeout']=c(b,[d('awaiting_host_confirmation',0x1)]),await e['upsertRule'](NET,{'id':'krule_t','enabled':!![],'detector':'timeout_intermediate','accounts':[],'auto_execute':!![],'created_at':0x0});const h=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),g,{'force':!![]});expect(h['opened'])['toBe'](0x1),expect(h['auto_executed'])['toBe'](0x0);const i=(await e['listTasks'](NET))[0x0];expect(i['detector'])['toBe']('timeout_intermediate'),expect(i['status'])['toBe']('pending');});});
1
+ import{describe,expect,it}from'vitest';import{KeeperStore}from'./KeeperStore.js';import{detectPaymentUnclaimed,detectProgressActionable,detectSettlementPending}from'./detectors.js';import{executeKeeperTask,runKeeperScan}from'./KeeperScan.js';import{clampKeeperConfig,defaultKeeperConfig,KEEPER_MIN}from'./types.js';const NET='testnet',ACCT='0xaaa111',OTHER='0xbbb222';function memStorage(){const a=new Map();return{'get':async b=>a['get'](b),'put':async(b,c)=>void a['set'](b,c)};}function makeStore(){return new KeeperStore(memStorage());}function paymentItem(a,b,c=0x1){return{'dedupe_key':'payment_unclaimed:'+a,'detector':'payment_unclaimed','beneficiary':a,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+b+'\x20waiting','state_fingerprint':c+':'+b['toString']()};}function makeScope(a){return{'version':0x1,'resolved_at':0x0,'accounts':[ACCT],'permissions':[],'managed_objects':[],'services':[],'orders':[],'order_children':[],'focus':[],'index':{},...a};}describe('keeper\x20config',()=>{it('returns\x20safe\x20defaults:\x20reminders\x20ON,\x20auto\x20rules\x20none',async()=>{const a=makeStore(),b=await a['getConfig'](NET);expect(b['enabled'])['toBe'](!![]),expect(b['detectors']['payment_unclaimed'])['toBe'](!![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]),expect(await a['listRules'](NET))['toEqual']([]);}),it('config_set\x20patch\x20merges\x20detectors\x20individually',async()=>{const a=makeStore(),b=await a['saveConfig'](NET,{'detectors':{'payment_unclaimed':![]}});expect(b['detectors']['payment_unclaimed'])['toBe'](![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]);const c=await a['getConfig'](NET);expect(c['detectors']['payment_unclaimed'])['toBe'](![]),expect(c['detectors']['progress_actionable'])['toBe'](!![]);}),it('clamps\x20numeric\x20bounds\x20(cost/gas\x20guards)',()=>{const a=clampKeeperConfig({...defaultKeeperConfig(),'scan_interval_ms':0x1,'max_scan_objects':0x0,'max_auto_execute_per_scan':0x0,'auto_retry_cooldown_ms':0x0});expect(a['scan_interval_ms'])['toBe'](KEEPER_MIN['scan_interval_ms']),expect(a['max_scan_objects'])['toBe'](KEEPER_MIN['max_scan_objects']),expect(a['max_auto_execute_per_scan'])['toBe'](KEEPER_MIN['max_auto_execute_per_scan']),expect(a['auto_retry_cooldown_ms'])['toBe'](KEEPER_MIN['auto_retry_cooldown_ms']);});}),describe('keeper\x20rules',()=>{const a=b=>({'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0,...b});it('matchingAutoRules\x20honors\x20enabled\x20/\x20auto_execute\x20/\x20account\x20coverage',async()=>{const b=makeStore();await b['upsertRule'](NET,a()),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'progress_actionable',ACCT))['toHaveLength'](0x0),await b['upsertRule'](NET,a({'id':'krule_2','accounts':[OTHER['toUpperCase']()]})),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER))['toHaveLength'](0x2),await b['upsertRule'](NET,a({'id':'krule_3','enabled':![]})),await b['upsertRule'](NET,a({'id':'krule_4','auto_execute':![]}));const c=await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER);expect(c['map'](d=>d['id'])['sort']())['toEqual'](['krule_1','krule_2']);});}),describe('KeeperStore.upsertDesired',()=>{it('opens\x20new\x20tasks,\x20refreshes\x20on\x20fingerprint\x20change,\x20no\x20churn\x20when\x20identical',async()=>{const a=makeStore();let b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);expect(b)['toEqual']({'opened':0x1,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0),expect(b)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0xfan)],0xbb8),expect(b)['toEqual']({'opened':0x0,'refreshed':0x1,'revived':0x0,'superseded':0x0});const c=(await a['listTasks'](NET))[0x0];expect(c['title'])['toContain']('250'),expect(c['updated_at'])['toBe'](0xbb8);}),it('dismissed\x20stays\x20dismissed\x20for\x20identical\x20state,\x20revives\x20on\x20material\x20change',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'dismissed',0x5dc,'not\x20now');let c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0);expect(c['revived'])['toBe'](0x0),expect((await a['getTask'](NET,b['id']))['status'])['toBe']('dismissed'),c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x190n,0x2)],0xbb8),expect(c['revived'])['toBe'](0x1);const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('pending'),expect(d['resolution'])['toBeUndefined'](),expect(d['resolved_at'])['toBeUndefined']();}),it('executed\x20tasks\x20are\x20terminal\x20—\x20same\x20dedupe_key\x20never\x20re-opens\x20them',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'auto_executed',0x5dc,'tx\x20ABC','krule_1');const c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x1f4n)],0x7d0);expect(c)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0});const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('executed'),expect(d['rule_id'])['toBe']('krule_1');}),it('supersedes\x20pending\x20tasks\x20of\x20THIS\x20detector\x20only',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8),await a['upsertDesired'](NET,'progress_actionable',[{'dedupe_key':'progress_actionable:0xp1:0xaaa111:shipped|deliver','detector':'progress_actionable','beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator'}],0x3e8);const b=await a['upsertDesired'](NET,'payment_unclaimed',[],0x7d0);expect(b['superseded'])['toBe'](0x1);const c=await a['listTasks'](NET),d=c['find'](f=>f['detector']==='payment_unclaimed'),e=c['find'](f=>f['detector']==='progress_actionable');expect(d['status'])['toBe']('superseded'),expect(d['resolution'])['toBe']('superseded'),expect(e['status'])['toBe']('pending');}),it('execute_failed\x20keeps\x20the\x20task\x20pending\x20with\x20failure\x20bookkeeping',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'execute_failed',0x1388,'insufficient\x20gas','krule_1');const c=await a['getTask'](NET,b['id']);expect(c['status'])['toBe']('pending'),expect(c['last_auto_attempt_at'])['toBe'](0x1388),expect(c['auto_attempts'])['toBe'](0x1),expect(c['resolution_note'])['toBe']('insufficient\x20gas');});}),describe('detectPaymentUnclaimed',()=>{it('emits\x20a\x20claim-to-self\x20task\x20for\x20accounts\x20with\x20unclaimed\x20wrappers',async()=>{const a=await detectPaymentUnclaimed([ACCT['toUpperCase'](),OTHER,'0xccc333'],NET,{'queryUnclaimed':async c=>{if(c===ACCT)return{'balance':0x64n,'count':0x2,'token_type':'0x2::wow::WOW'};if(c===OTHER)return{'balance':0x0n,'count':0x0};throw new Error('rpc\x20down');},'formatAmount':async()=>'0.0000001\x20WOW'});expect(a)['toHaveLength'](0x1);const b=a[0x0];expect(b['dedupe_key'])['toBe']('payment_unclaimed:'+ACCT),expect(b['beneficiary'])['toBe'](ACCT),expect(b['operation'])['toEqual']({'operation_type':'payment','data':{'receive':!![]}}),expect(b['state_fingerprint'])['toBe']('2:100'),expect(b['title'])['toContain']('0.0000001\x20WOW');}),it('falls\x20back\x20to\x20raw\x20units\x20when\x20formatting\x20fails',async()=>{const a=await detectPaymentUnclaimed([ACCT],NET,{'queryUnclaimed':async()=>({'balance':0x2an,'count':0x1}),'formatAmount':async()=>{throw new Error('no\x20metadata');}});expect(a[0x0]['title'])['toContain']('42\x20(smallest\x20unit)');});}),describe('detectProgressActionable',()=>{const a='0xprog1',b='0xmachine1',c=[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],d=(j=[])=>({'machine':b,'current':'start','session':j,'namedOperator':[{'name':'courier','operators':[ACCT]}]}),e=j=>({'fetchProgressFields':async()=>new Map([[a,j]]),'fetchMachineNodes':async()=>c,'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}),f=makeScope({'order_children':[{'type':'progress','object':a}]});it('routes\x20an\x20actionable\x20forward\x20to\x20its\x20named\x20operator',async()=>{const j=await detectProgressActionable(f,NET,e(d()),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['dedupe_key'])['toBe']('progress_actionable:'+a+':'+ACCT+':shipped|deliver'),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['operation'])['toBeUndefined'](),expect(j[0x0]['detail'])['toContain']('workflow_operation');}),it('omits\x20accomplished\x20forwards\x20(single-operator\x20lock)',async()=>{const j=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':ACCT,'accomplished':!![]}]}],k=await detectProgressActionable(f,NET,e(d(j)),0x14);expect(k)['toHaveLength'](0x0);}),it('restricts\x20a\x20held\x20forward\x20to\x20its\x20holder',async()=>{const j=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':OTHER,'accomplished':![]}]}],k=await detectProgressActionable(f,NET,e(d(j)),0x14);expect(k)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const j=await detectProgressActionable(f,NET,{...e(d()),'fetchProgressFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(j)['toEqual']([]);});const g=[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier','guard':'0xguard1'}]}]}],h=(j,k=OTHER)=>({'table':[{'identifier':0x2,'b_submission':![],'value_type':'Address','value':k}],'root':j}),i=(j,k)=>({...e(j),'fetchMachineNodes':async()=>g,'fetchGuardJson':async()=>k});it('skips\x20the\x20task\x20when\x20the\x20guard\x20pins\x20the\x20Signer\x20to\x20another\x20account',async()=>{const j=h({'type':'logic_equal','nodes':[{'type':'context','context':'Signer'},{'type':'identifier','identifier':0x2}]}),k=await detectProgressActionable(f,NET,i(d(),j),0x14);expect(k)['toEqual']([]);}),it('keeps\x20the\x20task\x20when\x20the\x20guard\x20pins\x20the\x20Signer\x20to\x20the\x20beneficiary\x20itself',async()=>{const j=h({'type':'logic_equal','nodes':[{'type':'identifier','identifier':0x2},{'type':'context','context':'Signer'}]},ACCT),k=await detectProgressActionable(f,NET,i(d(),j),0x14);expect(k)['toHaveLength'](0x1);}),it('fail-open:\x20unreadable\x20guard\x20JSON\x20still\x20emits\x20the\x20task',async()=>{const j=await detectProgressActionable(f,NET,i(d(),undefined),0x14);expect(j)['toHaveLength'](0x1);}),it('fail-open:\x20a\x20Signer\x20pin\x20inside\x20a\x20logic_or\x20branch\x20is\x20only\x20an\x20alternative,\x20not\x20a\x20pin',async()=>{const j=h({'type':'logic_or','nodes':[{'type':'logic_equal','nodes':[{'type':'context','context':'Signer'},{'type':'identifier','identifier':0x2}]},{'type':'logic_equal','nodes':[{'type':'context','context':'Signer'},{'type':'identifier','identifier':0x2}]}]}),k=await detectProgressActionable(f,NET,i(d(),j),0x14);expect(k)['toHaveLength'](0x1);}),it('fail-open:\x20a\x20dynamic\x20query\x20operand\x20(order.owner\x20==\x20Signer)\x20is\x20not\x20a\x20pin',async()=>{const j={'table':[{'identifier':0x2,'b_submission':![],'value_type':'Address','value':OTHER}],'root':{'type':'logic_equal','nodes':[{'type':'context','context':'Signer'},{'type':'query','id':0x61a}]}},k=await detectProgressActionable(f,NET,i(d(),j),0x14);expect(k)['toHaveLength'](0x1);});}),describe('detectSettlementPending',()=>{const a='0xorder1',b='0xpool1',c='0xprog1',d='0xmachine1',e='0xsvc1',f=i=>[{'name':'paid','pairs':[{'prev_node':'','threshold':0x1,'forwards':[{'name':'settle','weight':0x1}]}]},{'name':i,'pairs':[{'prev_node':'paid','threshold':0x1,'forwards':[]}]}];function g(i,j,k,l){return{'fetchOrderFields':async()=>new Map([[a,{'type':'Order','object':a,'data':i}]]),'fetchAllocationFields':async()=>new Map([[b,{'type':'Allocation','object':b,'type_raw':'0x2::allocation::Allocation<0x2::coin::COIN>','data':j}]]),'fetchProgressFields':async()=>new Map([[c,k]]),'fetchMachineNodes':async()=>l};}const h={'allocation':b,'progress':c,'machine':d,'service':e,'builder':ACCT};it('routes\x20a\x20completion\x20terminal\x20with\x20an\x20unsettled\x20pool\x20to\x20the\x20merchant\x20account',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgsettle'}]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['detector'])['toBe']('settlement_pending'),expect(j[0x0]['title'])['toContain']('completion'),expect(j[0x0]['detail'])['toContain']('alloc_by_guard');}),it('routes\x20a\x20refund\x20terminal\x20to\x20the\x20buyer\x20(order\x20builder)\x20account',async()=>{const i=makeScope({'orders':[{'order':a,'role':'buyer'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgrefund'}]}},{'current':'refunded','machine':d},f('refunded')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['title'])['toContain']('refund/cancel');}),it('skips\x20a\x20pool\x20already\x20drained\x20(balance\x200)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'0','payment':[],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20pool\x20that\x20already\x20emitted\x20a\x20Payment',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':['0xpay1'],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20non-terminal\x20node\x20(still\x20has\x20outgoing\x20forwards)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[]}},{'current':'paid','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20order\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,{...g(h,{'balance':'5000','payment':[]},{'current':'completed','machine':d},f('completed')),'fetchOrderFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(j)['toEqual']([]);});});function scanDepsFor(a,b){let c=0x2710;const d=[],e={'store':a,'payment':{'queryUnclaimed':async()=>({'balance':0x64n,'count':0x1})},'progress':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined},'settlement':{'fetchOrderFields':async()=>new Map(),'fetchAllocationFields':async()=>new Map(),'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[]},'timeout':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'nowMs':()=>0x2710},'execute':async f=>{return d['push']({'operation_type':f['operation_type'],'account':f['account'],'via':f['via']}),{'ok':!![],'digest':'DIGEST1'};},'now':()=>c,'logger':()=>{},...b};return{'deps':e,'executed':d,'advance':f=>{c+=f;},'setClock':f=>{c=f;}};}describe('runKeeperScan',()=>{it('skips\x20when\x20disabled\x20and\x20when\x20inside\x20the\x20cadence\x20interval',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a);await a['saveConfig'](NET,{'enabled':![]});let c=await runKeeperScan(NET,makeScope(),b);expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('disabled'),await a['saveConfig'](NET,{'enabled':!![]}),await a['setLastScanAt'](NET,0x2710),c=await runKeeperScan(NET,makeScope(),b),expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('interval');}),it('auto-executes\x20a\x20payment\x20task\x20ONLY\x20with\x20a\x20covering\x20enabled\x20rule',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);let d=await runKeeperScan(NET,makeScope(),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0}),d=await runKeeperScan(NET,makeScope(),b,{'force':!![]}),expect(d['auto_executed'])['toBe'](0x1),expect(c[0x0])['toEqual']({'operation_type':'payment','account':ACCT,'via':'rule\x20krule_1'});const e=(await a['listTasks'](NET))[0x0];expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('auto_executed'),expect(e['rule_id'])['toBe']('krule_1'),expect(e['resolution_note'])['toContain']('DIGEST1');}),it('never\x20auto-executes\x20progress\x20tasks\x20(reminder-only\x20boundary)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a,{'payment':{'queryUnclaimed':async()=>null},'progress':{'fetchProgressFields':async()=>new Map([['0xprog1',{'machine':'0xm1','current':'start','session':[],'namedOperator':[{'name':'courier','operators':[ACCT]}]}]]),'fetchMachineNodes':async()=>[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}});await a['upsertRule'](NET,{'id':'krule_p','enabled':!![],'detector':'progress_actionable','accounts':[],'auto_execute':!![],'created_at':0x0});const d=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),expect((await a['listTasks'](NET))[0x0]['status'])['toBe']('pending');}),it('backs\x20off\x20after\x20a\x20failed\x20auto-exec\x20until\x20the\x20cooldown\x20passes',async()=>{const a=makeStore(),b=scanDepsFor(a,{'execute':async()=>({'ok':![],'error':'insufficient\x20gas'})});await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});let c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]});expect(c['auto_failed'])['toBe'](0x1);const d=(await a['listTasks'](NET))[0x0];expect(d['status'])['toBe']('pending'),expect(d['resolution_note'])['toBe']('insufficient\x20gas'),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x0),expect(c['auto_executed'])['toBe'](0x0),b['advance'](0x1f*0xea60),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x1);}),it('caps\x20auto-executions\x20per\x20scan\x20(gas\x20guard)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);await a['saveConfig'](NET,{'max_auto_execute_per_scan':0x1}),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});const d=makeScope({'accounts':[ACCT,OTHER]}),e=await runKeeperScan(NET,d,b,{'force':!![]});expect(e['opened'])['toBe'](0x2),expect(e['auto_executed'])['toBe'](0x1),expect(c)['toHaveLength'](0x1),expect(await a['listTasks'](NET,{'status':'pending'}))['toHaveLength'](0x1);});}),describe('executeKeeperTask\x20(manual)',()=>{it('resolves\x20a\x20payment\x20task\x20as\x20manual_executed',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0],{deps:c}=scanDepsFor(a),d=await executeKeeperTask(NET,b,c);expect(d['ok'])['toBe'](!![]);const e=await a['getTask'](NET,b['id']);expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('manual_executed');}),it('refuses\x20reminder-only\x20tasks\x20(progress)\x20with\x20guidance',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a),c={'id':'ktask_x','dedupe_key':'progress_actionable:0xp:0xaaa111:shipped|deliver','detector':'progress_actionable','network':NET,'beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator','status':'pending','created_at':0x0,'updated_at':0x0},d=await executeKeeperTask(NET,c,b);expect(d['ok'])['toBe'](![]),expect(d['error'])['toContain']('reminder-only');});}),describe('timeout_intermediate',()=>{const a=0xa*0x5265c00,b={'current':'awaiting_host_confirmation','current_time':a-0x1e*0x36ee80,'machine':'0xmach1','task':'0xorder1'};function c(e,f){return{'fetchProgressFields':async()=>new Map(e===undefined?[]:[['0xprog1',e]]),'fetchMachineNodes':async()=>f,'nowMs':()=>a};}function d(e,f){return{'name':e,'pairs':[{'prev_node':'paid','threshold':0x0,'forwards':Array['from']({'length':f},()=>({}))}]};}it('surfaces\x20a\x20progress\x20stuck\x20on\x20an\x20intermediate\x20node\x20past\x20the\x20threshold',async()=>{const {detectTimeoutIntermediate:e}=await import('./detectors.js'),f=await e(makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),NET,c(b,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80);expect(f)['toHaveLength'](0x1),expect(f[0x0]['detector'])['toBe']('timeout_intermediate'),expect(f[0x0]['beneficiary'])['toBe'](ACCT);}),it('stays\x20silent\x20below\x20the\x20threshold,\x20on\x20terminal\x20nodes,\x20and\x20on\x20missing\x20data',async()=>{const {detectTimeoutIntermediate:e}=await import('./detectors.js'),f=makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),g={...b,'current_time':a-0x1*0x36ee80};expect(await e(f,NET,c(g,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0),expect(await e(f,NET,c(b,[d('awaiting_host_confirmation',0x0)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0),expect(await e(f,NET,c(undefined,[d('awaiting_host_confirmation',0x1)]),0x14,0x18*0x36ee80))['toHaveLength'](0x0);}),it('the\x20scan\x20wires\x20the\x20detector:\x20a\x20stuck\x20progress\x20opens\x20a\x20reminder\x20task\x20(never\x20auto-exec)',async()=>{const e=makeStore(),f=scanDepsFor(e,{'payment':{'queryUnclaimed':async()=>null}}),{deps:g}=f;g['timeout']=c(b,[d('awaiting_host_confirmation',0x1)]),await e['upsertRule'](NET,{'id':'krule_t','enabled':!![],'detector':'timeout_intermediate','accounts':[],'auto_execute':!![],'created_at':0x0});const h=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),g,{'force':!![]});expect(h['opened'])['toBe'](0x1),expect(h['auto_executed'])['toBe'](0x0);const i=(await e['listTasks'](NET))[0x0];expect(i['detector'])['toBe']('timeout_intermediate'),expect(i['status'])['toBe']('pending');});});
@@ -1 +1 @@
1
- export const ACQUISITION_FLYWHEEL_VERSION=0x1;export const INDUSTRY_FLYWHEELS=[{'industry':'freelance','trustSellingPoints':['Delivery\x20acceptance\x20+\x20fund\x20escrow\x20+\x20arbitration\x20guarantee','Transparent\x20process:\x20Machine\x20defines\x20clear\x20delivery\x20nodes','compensation_fund\x20secures\x20customer\x20rights'],'keyActions':[{'action':'Set\x20Reward\x20first-order\x20bonus','purpose':'Attract\x20new\x20customers\x20to\x20place\x20orders','mutableField':'rewards','metricToWatch':'New\x20customer\x20order\x20rate'},{'action':'Cumulative-spend\x20tiered\x20Reward','purpose':'Incentivize\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'},{'action':'Adjust\x20Machine\x20nodes','purpose':'Optimize\x20delivery\x20process\x20speed','mutableField':'description','metricToWatch':'Average\x20completion\x20time'},{'action':'Increase\x20compensation_fund','purpose':'Improve\x20trust\x20score','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'First-order\x20reward\x20+\x20cumulative-spend\x20tiered\x20reward\x20(e.g.\x20discount\x20after\x205\x20orders)','discountStrategy':'Monthly\x20discount\x20+\x20long-term\x20cooperation\x20discount','trustDescription':'Fund\x20escrow\x20+\x20delivery\x20acceptance\x20+\x20arbitration\x20guarantee'},{'industry':'rental','trustSellingPoints':['Deposit\x20escrow\x20+\x20damage\x20Guard\x20+\x20return\x20process','Guard\x20verifies\x20item\x20condition\x20to\x20prevent\x20disputes','compensation_fund\x20covers\x20damage\x20risk'],'keyActions':[{'action':'Set\x20Discount\x20long-term\x20rental\x20bonus','purpose':'Incentivize\x20long-term\x20rental','mutableField':'discount','metricToWatch':'Long-term\x20rental\x20ratio'},{'action':'Credit-accumulation\x20Reward','purpose':'Multi-rental\x20credit\x20accumulation','mutableField':'rewards','metricToWatch':'Re-rental\x20rate'},{'action':'Configure\x20damage\x20Guard','purpose':'Reduce\x20dispute\x20rate','mutableField':'buy_guard','metricToWatch':'Dispute\x20rate'},{'action':'Increase\x20compensation_fund','purpose':'Cover\x20damage\x20risk','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Credit\x20accumulation\x20+\x20long-term\x20rental\x20discount\x20+\x20referral\x20cashback','discountStrategy':'Monthly\x2010%\x20off\x20+\x20quarterly\x2020%\x20off\x20+\x20annual\x2030%\x20off','trustDescription':'Deposit\x20escrow\x20+\x20Guard\x20verification\x20+\x20return\x20guarantee'},{'industry':'education','trustSellingPoints':['Transparent\x20course\x20progress\x20+\x20refund\x20Guard','Machine\x20defines\x20learning\x20stages\x20and\x20acceptance\x20nodes'],'keyActions':[{'action':'Set\x20milestone\x20Reward','purpose':'Incentivize\x20course\x20completion','mutableField':'rewards','metricToWatch':'Course\x20completion\x20rate'},{'action':'Referral\x20cashback\x20Reward','purpose':'Viral\x20acquisition','mutableField':'rewards','metricToWatch':'Referral\x20rate'}],'rewardStrategy':'Milestone\x20reward\x20+\x20referral\x20cashback\x20+\x20trial-class\x20discount','discountStrategy':'Early-bird\x20price\x20+\x20group-buy\x20price\x20+\x20student-aid\x20discount','trustDescription':'Transparent\x20progress\x20+\x20refund\x20guarantee\x20+\x20acceptance\x20nodes'},{'industry':'travel','trustSellingPoints':['Itinerary\x20escrow\x20+\x20cancellation\x20Guard\x20+\x20arbitration\x20guarantee','Guard\x20verifies\x20itinerary\x20change\x20conditions'],'keyActions':[{'action':'Limited-time\x20flash-sale\x20Reward','purpose':'Clearance\x20promotion','mutableField':'rewards','metricToWatch':'Conversion\x20rate'},{'action':'Spend\x20cashback\x20Reward','purpose':'Improve\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'}],'rewardStrategy':'Limited-time\x20flash\x20sale\x20+\x20spend\x20cashback\x20+\x20referral\x20commission','discountStrategy':'Early-bird\x20price\x20+\x20group-buy\x20price\x20+\x20member\x20price','trustDescription':'Itinerary\x20escrow\x20+\x20cancellation\x20guarantee\x20+\x20arbitration'},{'industry':'subscription','trustSellingPoints':['Transparent\x20subscription\x20+\x20auto-renewal\x20Guard\x20+\x20cancel\x20anytime','Machine\x20defines\x20billing\x20cycles\x20and\x20auto-debit'],'keyActions':[{'action':'Loyalty\x20Reward','purpose':'Long-term\x20retention','mutableField':'rewards','metricToWatch':'Renewal\x20rate'},{'action':'Referral\x20cashback\x20Reward','purpose':'Viral\x20acquisition','mutableField':'rewards','metricToWatch':'Referral\x20rate'}],'rewardStrategy':'Loyalty\x20reward\x20+\x20referral\x20cashback\x20+\x20first-month\x20discount','discountStrategy':'Annual\x20discount\x20+\x20team\x20discount\x20+\x20upgrade\x20discount','trustDescription':'Transparent\x20subscription\x20+\x20renewal\x20guarantee\x20+\x20cancel\x20anytime'},{'industry':'retail','trustSellingPoints':['Transaction\x20escrow\x20+\x20logistics\x20Guard\x20+\x20refund\x20guarantee','Guard\x20verifies\x20shipping\x20and\x20receipt'],'keyActions':[{'action':'First-order\x20discount','purpose':'Attract\x20new\x20customers','mutableField':'discount','metricToWatch':'New\x20customer\x20order\x20rate'},{'action':'Spend\x20cashback\x20Reward','purpose':'Improve\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'}],'rewardStrategy':'First-order\x20discount\x20+\x20spend\x20cashback\x20+\x20spend-threshold\x20discount','discountStrategy':'Spend-threshold\x20discount\x20+\x20limited-time\x20discount\x20+\x20member\x20price','trustDescription':'Transaction\x20escrow\x20+\x20logistics\x20Guard\x20+\x20refund\x20guarantee'},{'industry':'licensing','trustSellingPoints':['License\x20terms\x20hash-anchored\x20as\x20a\x20WIP\x20object\x20—\x20the\x20grant\x20is\x20provable,\x20not\x20prose','Royalty/purchase\x20proceeds\x20split\x20on-chain\x20via\x20Allocation\x20—\x20the\x20split\x20is\x20frozen\x20at\x20publish\x20and\x20auditable\x20by\x20every\x20rights-holder','Territory\x20+\x20term\x20enforced\x20by\x20Guard\x20(allowlist\x20/\x20time-lock);\x20escrow\x20+\x20inspection\x20window\x20before\x20the\x20grant\x20is\x20final'],'keyActions':[{'action':'Anchor\x20license\x20terms\x20as\x20WIP','purpose':'Make\x20the\x20granted\x20rights\x20provable\x20in\x20a\x20dispute','mutableField':'description','metricToWatch':'Dispute\x20rate'},{'action':'Publish\x20the\x20Allocation\x20split','purpose':'Show\x20rights-holders\x20their\x20share\x20is\x20frozen\x20and\x20auditable','mutableField':'allocator','metricToWatch':'Trust\x20score'},{'action':'Configure\x20an\x20inspection-window\x20time-lock\x20Guard','purpose':'Give\x20the\x20buyer\x20a\x20verify-then-release\x20window\x20before\x20the\x20grant\x20is\x20final','mutableField':'buy_guard','metricToWatch':'Refund/dispute\x20rate'},{'action':'Increase\x20compensation_fund','purpose':'Back\x20the\x20reporting-honesty\x20promise\x20the\x20buyer\x20is\x20trusting','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Repeat-license\x20/\x20catalog-referral\x20reward;\x20early-access\x20reward\x20on\x20a\x20new\x20drop','discountStrategy':'Volume-license\x20discount\x20+\x20tiered\x20license\x20pricing\x20(basic/premium/unlimited/exclusive)','trustDescription':'Terms\x20hash-anchored\x20+\x20on-chain\x20royalty\x20split\x20+\x20territory/term\x20Guard\x20+\x20escrow\x20inspection\x20window'},{'industry':'crowdfunding','trustSellingPoints':['Each\x20contribution\x20is\x20escrowed\x20in\x20its\x20OWN\x20Allocation\x20(never\x20pooled)\x20—\x20a\x20funder\x27s\x20money\x20stays\x20attributable\x20to\x20their\x20order\x20and\x20is\x20refundable\x20to\x20them,\x20not\x20lost\x20in\x20a\x20merged\x20pot','The\x20funding\x20threshold\x20is\x20an\x20on-chain\x20aggregate\x20read\x20(a\x20shared\x20campaign\x20ledger\x20summed\x20at\x20settlement)\x20—\x20the\x20raise\x20is\x20provable,\x20and\x20the\x20deadline\x20release/refund\x20decision\x20is\x20enforced\x20by\x20Guard,\x20not\x20by\x20the\x20project\x27s\x20goodwill','Two-leg\x20escrow\x20exit:\x20on\x20deadline\x20the\x20funds\x20EITHER\x20release\x20to\x20the\x20project\x20(threshold\x20met)\x20XOR\x20refund\x20per\x20contributor\x20(threshold\x20missed)\x20—\x20never\x20both,\x20never\x20neither'],'keyActions':[{'action':'Publish\x20the\x20funding\x20threshold\x20+\x20deadline','purpose':'Make\x20the\x20all-or-nothing\x20gate\x20provable\x20so\x20funders\x20trust\x20the\x20raise\x20is\x20real','mutableField':'description','metricToWatch':'Funding\x20conversion\x20rate'},{'action':'Configure\x20the\x20two-leg\x20settlement\x20Guard\x20(release\x20XOR\x20refund)','purpose':'Guarantee\x20a\x20missed\x20campaign\x20refunds\x20every\x20contributor\x20automatically','mutableField':'allocator','metricToWatch':'Refund/dispute\x20rate'},{'action':'Set\x20an\x20early-backer\x20Reward','purpose':'Reward\x20funders\x20who\x20commit\x20before\x20the\x20deadline','mutableField':'rewards','metricToWatch':'Early-funding\x20velocity'},{'action':'Increase\x20compensation_fund','purpose':'Back\x20the\x20delivery\x20promise\x20funders\x20trust\x20after\x20a\x20successful\x20raise','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Early-backer\x20reward\x20+\x20referral\x20reward\x20(viral\x20campaign\x20sharing);\x20tiered\x20reward\x20by\x20contribution\x20level.\x20NOT\x20an\x20investment\x20return\x20—\x20never\x20promise\x20financial\x20yield\x20(L-01)','discountStrategy':'Early-bird\x20contribution\x20tier\x20+\x20group-backer\x20bundle;\x20no\x20discounting\x20that\x20implies\x20a\x20resale\x20return','trustDescription':'Per-contributor\x20escrow\x20(unpooled)\x20+\x20on-chain\x20aggregate\x20threshold\x20+\x20deadline\x20two-leg\x20release/refund\x20+\x20arbitration\x20guarantee'}];let _registryLookup=null;export function _setRegistryLookup(a){_registryLookup=a;}export function getFlywheelForIndustry(a){if(_registryLookup){const b=_registryLookup(a);if(b?.['flywheel'])return b['flywheel'];}return INDUSTRY_FLYWHEELS['find'](c=>c['industry']===a['toLowerCase']());}export function listIndustries(){return INDUSTRY_FLYWHEELS['map'](a=>a['industry']);}export function suggestAcquisitionActions(a){const b=getFlywheelForIndustry(a);return b?.['keyActions']??[];}export function generateTrustDescription(a){const b=[];if(a['industry']){const c=getFlywheelForIndustry(a['industry']);c&&b['push'](c['trustDescription']);}return a['orderCount']!==undefined&&a['orderCount']>0x0&&b['push']('Completed\x20'+a['orderCount']+'\x20orders'),a['completedRate']!==undefined&&b['push']('Completion\x20rate\x20'+Math['round'](a['completedRate']*0x64)+'%'),a['avgCompletionTime']!==undefined&&(a['avgCompletionTime']<0x1?b['push']('Average\x20completion\x20time\x20'+Math['round'](a['avgCompletionTime']*0x3c)+'\x20minutes'):b['push']('Average\x20completion\x20time\x20'+Math['round'](a['avgCompletionTime'])+'\x20hours')),a['hasCompensationFund']&&b['push']('Sufficient\x20compensation\x20fund'),a['hasArbitration']&&b['push']('Third-party\x20arbitration\x20guarantee'),a['reviewCount']!==undefined&&a['reviewCount']>0x0&&a['reviewLikeRate']!==undefined&&b['push']('Like\x20rate\x20'+Math['round'](a['reviewLikeRate']*0x64)+'%\x20('+a['reviewCount']+'\x20reviews)'),b['join'](';\x20')||'No\x20trust\x20data\x20available';}export function buildAcquisitionDashboard(a){const {orderCount:b,completedRate:c,avgCompletionTime:d,repeatCustomerRate:e,reviewLikeRate:f,reviewCount:g}=a;let h='cold_start';if(b>=0x32)h='optimization';else{if(b>=0x14)h='mature';else{if(b>=0x5)h='growing';}}const i=[];if(h==='cold_start')i['push']('Cold-start\x20stage:\x20set\x20first-order\x20Reward\x20to\x20attract\x20new\x20customers'),i['push']('Increase\x20compensation_fund\x20to\x20boost\x20initial\x20trust');else{if(h==='growing')i['push']('Growing\x20stage:\x20set\x20referral\x20cashback\x20Reward\x20for\x20viral\x20acquisition'),e!==undefined&&e<0.2&&i['push']('Repurchase\x20rate\x20is\x20low;\x20consider\x20setting\x20cumulative-spend\x20tiered\x20Reward');else h==='mature'?(f!==undefined&&f>0.8&&i['push']('High\x20like\x20rate;\x20you\x20can\x20highlight\x20trust\x20metrics\x20in\x20the\x20description'),e!==undefined&&e>0.3&&i['push']('High\x20repurchase\x20rate;\x20consider\x20setting\x20loyalty\x20Reward\x20to\x20incentivize\x20long-term\x20customers')):(i['push']('Optimization\x20stage:\x20fine-tune\x20pricing\x20and\x20Reward\x20strategies'),d!==undefined&&d>0x30&&i['push']('Completion\x20time\x20is\x20long;\x20consider\x20optimizing\x20the\x20Machine\x20process'));}return{'metrics':{'orderCount':b,'completedRate':c??0x0,'avgCompletionTime':d,'repeatCustomerRate':e,'reviewLikeRate':f,'reviewCount':g},'suggestions':i,'flywheelStage':h};}
1
+ export const ACQUISITION_FLYWHEEL_VERSION=0x1;export const INDUSTRY_FLYWHEELS=[{'industry':'freelance','trustSellingPoints':['Delivery\x20acceptance\x20+\x20fund\x20escrow\x20+\x20arbitration\x20guarantee','Transparent\x20process:\x20Machine\x20defines\x20clear\x20delivery\x20nodes','compensation_fund\x20secures\x20customer\x20rights'],'keyActions':[{'action':'Set\x20Reward\x20first-order\x20bonus','purpose':'Attract\x20new\x20customers\x20to\x20place\x20orders','mutableField':'rewards','metricToWatch':'New\x20customer\x20order\x20rate'},{'action':'Cumulative-spend\x20tiered\x20Reward','purpose':'Incentivize\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'},{'action':'Adjust\x20Machine\x20nodes','purpose':'Optimize\x20delivery\x20process\x20speed','mutableField':'description','metricToWatch':'Average\x20completion\x20time'},{'action':'Increase\x20compensation_fund','purpose':'Improve\x20trust\x20score','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'First-order\x20reward\x20+\x20cumulative-spend\x20tiered\x20reward\x20(e.g.\x20discount\x20after\x205\x20orders)','discountStrategy':'Monthly\x20discount\x20+\x20long-term\x20cooperation\x20discount','trustDescription':'Fund\x20escrow\x20+\x20delivery\x20acceptance\x20+\x20arbitration\x20guarantee'},{'industry':'rental','trustSellingPoints':['Deposit\x20escrow\x20+\x20damage\x20Guard\x20+\x20return\x20process','Guard\x20verifies\x20item\x20condition\x20to\x20prevent\x20disputes','compensation_fund\x20covers\x20damage\x20risk'],'keyActions':[{'action':'Set\x20Discount\x20long-term\x20rental\x20bonus','purpose':'Incentivize\x20long-term\x20rental','mutableField':'discount','metricToWatch':'Long-term\x20rental\x20ratio'},{'action':'Credit-accumulation\x20Reward','purpose':'Multi-rental\x20credit\x20accumulation','mutableField':'rewards','metricToWatch':'Re-rental\x20rate'},{'action':'Configure\x20damage\x20Guard','purpose':'Reduce\x20dispute\x20rate','mutableField':'buy_guard','metricToWatch':'Dispute\x20rate'},{'action':'Increase\x20compensation_fund','purpose':'Cover\x20damage\x20risk','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Credit\x20accumulation\x20+\x20long-term\x20rental\x20discount\x20+\x20referral\x20cashback','discountStrategy':'Monthly\x2010%\x20off\x20+\x20quarterly\x2020%\x20off\x20+\x20annual\x2030%\x20off','trustDescription':'Deposit\x20escrow\x20+\x20Guard\x20verification\x20+\x20return\x20guarantee'},{'industry':'education','trustSellingPoints':['Transparent\x20course\x20progress\x20+\x20refund\x20Guard','Machine\x20defines\x20learning\x20stages\x20and\x20acceptance\x20nodes'],'keyActions':[{'action':'Set\x20milestone\x20Reward','purpose':'Incentivize\x20course\x20completion','mutableField':'rewards','metricToWatch':'Course\x20completion\x20rate'},{'action':'Referral\x20cashback\x20Reward','purpose':'Viral\x20acquisition','mutableField':'rewards','metricToWatch':'Referral\x20rate'}],'rewardStrategy':'Milestone\x20reward\x20+\x20referral\x20cashback\x20+\x20trial-class\x20discount','discountStrategy':'Early-bird\x20price\x20+\x20group-buy\x20price\x20+\x20student-aid\x20discount','trustDescription':'Transparent\x20progress\x20+\x20refund\x20guarantee\x20+\x20acceptance\x20nodes'},{'industry':'travel','trustSellingPoints':['Itinerary\x20escrow\x20+\x20cancellation\x20Guard\x20+\x20arbitration\x20guarantee','Guard\x20verifies\x20itinerary\x20change\x20conditions'],'keyActions':[{'action':'Limited-time\x20flash-sale\x20Reward','purpose':'Clearance\x20promotion','mutableField':'rewards','metricToWatch':'Conversion\x20rate'},{'action':'Spend\x20cashback\x20Reward','purpose':'Improve\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'}],'rewardStrategy':'Limited-time\x20flash\x20sale\x20+\x20spend\x20cashback\x20+\x20referral\x20commission','discountStrategy':'Early-bird\x20price\x20+\x20group-buy\x20price\x20+\x20member\x20price','trustDescription':'Itinerary\x20escrow\x20+\x20cancellation\x20guarantee\x20+\x20arbitration'},{'industry':'subscription','trustSellingPoints':['Transparent\x20subscription\x20+\x20auto-renewal\x20Guard\x20+\x20cancel\x20anytime','Machine\x20defines\x20billing\x20cycles\x20and\x20auto-debit'],'keyActions':[{'action':'Loyalty\x20Reward','purpose':'Long-term\x20retention','mutableField':'rewards','metricToWatch':'Renewal\x20rate'},{'action':'Referral\x20cashback\x20Reward','purpose':'Viral\x20acquisition','mutableField':'rewards','metricToWatch':'Referral\x20rate'}],'rewardStrategy':'Loyalty\x20reward\x20+\x20referral\x20cashback\x20+\x20first-month\x20discount','discountStrategy':'Annual\x20discount\x20+\x20team\x20discount\x20+\x20upgrade\x20discount','trustDescription':'Transparent\x20subscription\x20+\x20renewal\x20guarantee\x20+\x20cancel\x20anytime'},{'industry':'retail','trustSellingPoints':['Transaction\x20escrow\x20+\x20logistics\x20Guard\x20+\x20refund\x20guarantee','Guard\x20verifies\x20shipping\x20and\x20receipt'],'keyActions':[{'action':'First-order\x20discount','purpose':'Attract\x20new\x20customers','mutableField':'discount','metricToWatch':'New\x20customer\x20order\x20rate'},{'action':'Spend\x20cashback\x20Reward','purpose':'Improve\x20repurchase','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'}],'rewardStrategy':'First-order\x20discount\x20+\x20spend\x20cashback\x20+\x20spend-threshold\x20discount','discountStrategy':'Spend-threshold\x20discount\x20+\x20limited-time\x20discount\x20+\x20member\x20price','trustDescription':'Transaction\x20escrow\x20+\x20logistics\x20Guard\x20+\x20refund\x20guarantee'},{'industry':'licensing','trustSellingPoints':['License\x20terms\x20hash-anchored\x20as\x20a\x20WIP\x20object\x20—\x20the\x20grant\x20is\x20provable,\x20not\x20prose','Royalty/purchase\x20proceeds\x20split\x20on-chain\x20via\x20Allocation\x20—\x20the\x20split\x20is\x20frozen\x20at\x20publish\x20and\x20auditable\x20by\x20every\x20rights-holder','Territory\x20+\x20term\x20enforced\x20by\x20Guard\x20(allowlist\x20/\x20time-lock);\x20escrow\x20+\x20inspection\x20window\x20before\x20the\x20grant\x20is\x20final'],'keyActions':[{'action':'Anchor\x20license\x20terms\x20as\x20WIP','purpose':'Make\x20the\x20granted\x20rights\x20provable\x20in\x20a\x20dispute','mutableField':'description','metricToWatch':'Dispute\x20rate'},{'action':'Publish\x20the\x20Allocation\x20split','purpose':'Show\x20rights-holders\x20their\x20share\x20is\x20frozen\x20and\x20auditable','mutableField':'allocator','metricToWatch':'Trust\x20score'},{'action':'Configure\x20an\x20inspection-window\x20time-lock\x20Guard','purpose':'Give\x20the\x20buyer\x20a\x20verify-then-release\x20window\x20before\x20the\x20grant\x20is\x20final','mutableField':'buy_guard','metricToWatch':'Refund/dispute\x20rate'},{'action':'Increase\x20compensation_fund','purpose':'Back\x20the\x20reporting-honesty\x20promise\x20the\x20buyer\x20is\x20trusting','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Repeat-license\x20/\x20catalog-referral\x20reward;\x20early-access\x20reward\x20on\x20a\x20new\x20drop','discountStrategy':'Volume-license\x20discount\x20+\x20tiered\x20license\x20pricing\x20(basic/premium/unlimited/exclusive)','trustDescription':'Terms\x20hash-anchored\x20+\x20on-chain\x20royalty\x20split\x20+\x20territory/term\x20Guard\x20+\x20escrow\x20inspection\x20window'},{'industry':'crowdfunding','trustSellingPoints':['Each\x20contribution\x20is\x20escrowed\x20in\x20its\x20OWN\x20Allocation\x20(never\x20pooled)\x20—\x20a\x20funder\x27s\x20money\x20stays\x20attributable\x20to\x20their\x20order\x20and\x20is\x20refundable\x20to\x20them,\x20not\x20lost\x20in\x20a\x20merged\x20pot','The\x20funding\x20threshold\x20is\x20an\x20on-chain\x20aggregate\x20read\x20(a\x20shared\x20campaign\x20ledger\x20summed\x20at\x20settlement)\x20—\x20the\x20raise\x20is\x20provable,\x20and\x20the\x20deadline\x20release/refund\x20decision\x20is\x20enforced\x20by\x20Guard,\x20not\x20by\x20the\x20project\x27s\x20goodwill','Two-leg\x20escrow\x20exit:\x20on\x20deadline\x20the\x20funds\x20EITHER\x20release\x20to\x20the\x20project\x20(threshold\x20met)\x20XOR\x20refund\x20per\x20contributor\x20(threshold\x20missed)\x20—\x20never\x20both,\x20never\x20neither'],'keyActions':[{'action':'Publish\x20the\x20funding\x20threshold\x20+\x20deadline','purpose':'Make\x20the\x20all-or-nothing\x20gate\x20provable\x20so\x20funders\x20trust\x20the\x20raise\x20is\x20real','mutableField':'description','metricToWatch':'Funding\x20conversion\x20rate'},{'action':'Configure\x20the\x20two-leg\x20settlement\x20Guard\x20(release\x20XOR\x20refund)','purpose':'Guarantee\x20a\x20missed\x20campaign\x20refunds\x20every\x20contributor\x20automatically','mutableField':'allocator','metricToWatch':'Refund/dispute\x20rate'},{'action':'Set\x20an\x20early-backer\x20Reward','purpose':'Reward\x20funders\x20who\x20commit\x20before\x20the\x20deadline','mutableField':'rewards','metricToWatch':'Early-funding\x20velocity'},{'action':'Increase\x20compensation_fund','purpose':'Back\x20the\x20delivery\x20promise\x20funders\x20trust\x20after\x20a\x20successful\x20raise','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Early-backer\x20reward\x20+\x20referral\x20reward\x20(viral\x20campaign\x20sharing);\x20tiered\x20reward\x20by\x20contribution\x20level.\x20NOT\x20an\x20investment\x20return\x20—\x20never\x20promise\x20financial\x20yield\x20(L-01)','discountStrategy':'Early-bird\x20contribution\x20tier\x20+\x20group-backer\x20bundle;\x20no\x20discounting\x20that\x20implies\x20a\x20resale\x20return','trustDescription':'Per-contributor\x20escrow\x20(unpooled)\x20+\x20on-chain\x20aggregate\x20threshold\x20+\x20deadline\x20two-leg\x20release/refund\x20+\x20arbitration\x20guarantee'},{'industry':'delivery','trustSellingPoints':['Every\x20food\x20dollar\x20is\x20escrowed\x20at\x20order\x20time\x20and\x20released\x20only\x20after\x20the\x20rider\x27s\x20delivery\x20evidence\x20passes\x20the\x20customer\x27s\x20confirmation\x20window\x20—\x20the\x20restaurant\x20cannot\x20spend\x20before\x20the\x20meal\x20arrives','Transit-loss\x20and\x20pickup\x20evidence\x20are\x20written\x20as\x20Machine\x20receipts\x20(who\x20picked\x20up,\x20when,\x20from\x20where)\x20—\x20a\x20missing\x20order\x20is\x20provable,\x20not\x20a\x20he-said-she-said','Auto-confirm\x20with\x20an\x20explicit\x20claim\x20window:\x20silence\x20after\x20delivery\x20releases\x20funds,\x20but\x20a\x20customer\x20claim\x20inside\x20the\x20window\x20still\x20reaches\x20third-party\x20arbitration'],'keyActions':[{'action':'Publish\x20the\x20commission\x20split\x20(restaurant\x20rate\x20/\x20platform\x20rate)','purpose':'Restaurants\x20trust\x20a\x20frozen\x20on-chain\x20split\x20more\x20than\x20a\x20negotiated\x20invoice','mutableField':'allocator','metricToWatch':'Restaurant\x20retention\x20rate'},{'action':'Set\x20an\x20order-frequency\x20Reward\x20(e.g.\x20every\x2010th\x20delivery\x20free\x20shipping)','purpose':'Drive\x20repurchase\x20cadence\x20—\x20the\x20core\x20economic\x20lever\x20of\x20food\x20delivery','mutableField':'rewards','metricToWatch':'Repurchase\x20rate'},{'action':'Configure\x20the\x20auto-confirm\x20+\x20claim\x20window\x20Guards','purpose':'Keep\x20settlement\x20fast\x20for\x20the\x20platform\x20while\x20preserving\x20the\x20customer\x27s\x20dispute\x20window','mutableField':'machine','metricToWatch':'Dispute\x20rate'},{'action':'Increase\x20compensation_fund','purpose':'Back\x20the\x20transit-loss\x20remedy\x20promise\x20(refund\x20or\x20re-delivery)','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Order-frequency\x20reward\x20(streak\x20/\x20every-Nth-order)\x20+\x20first-order\x20bonus;\x20rider-side\x20incentives\x20are\x20paid\x20by\x20the\x20platform\x20off-chain,\x20never\x20promised\x20from\x20the\x20escrow','discountStrategy':'First-order\x20discount\x20+\x20minimum-order\x20floor\x20+\x20peak-hour\x20surcharge;\x20coupon\x20burns\x20on\x20refund\x20(design\x20refunds\x20around\x20it)','trustDescription':'Order-time\x20escrow\x20+\x20rider\x20evidence\x20receipts\x20+\x20auto-confirm\x20with\x20claim\x20window\x20+\x20third-party\x20arbitration\x20+\x20transit-loss\x20remedy'},{'industry':'group_buy','trustSellingPoints':['The\x20group\x20threshold\x20and\x20the\x20absolute\x20cutoff\x20deadline\x20are\x20both\x20on-chain\x20Guards\x20—\x20the\x20deal\x20provably\x20happens\x20only\x20if\x20enough\x20neighbors\x20commit\x20before\x20the\x20deadline','Each\x20neighbor\x27s\x20payment\x20is\x20escrowed\x20in\x20its\x20own\x20Allocation;\x20after\x20the\x20cutoff\x20it\x20is\x20EITHER\x20released\x20to\x20the\x20group\x20leader\x20(deal\x20on)\x20XOR\x20refunded\x20per\x20buyer\x20(deal\x20off)\x20—\x20never\x20both','Unclaimed-pickup\x20expiry\x20is\x20enforced\x20by\x20a\x20time-lock\x20Guard\x20(refund\x20after\x20N\x20days\x20at\x20the\x20pickup\x20point),\x20so\x20a\x20forgotten\x20parcel\x20cannot\x20silently\x20become\x20the\x20leader\x27s\x20income'],'keyActions':[{'action':'Publish\x20the\x20group\x20threshold\x20+\x20absolute\x20cutoff\x20deadline','purpose':'Neighbors\x20trust\x20a\x20deadline\x20that\x20is\x20a\x20Guard,\x20not\x20a\x20promise','mutableField':'description','metricToWatch':'Group\x20fill\x20rate'},{'action':'Configure\x20the\x20unclaimed-expiry\x20refund\x20Guard','purpose':'Prove\x20that\x20unclaimed\x20goods\x20return\x20money\x20to\x20buyers,\x20not\x20to\x20the\x20leader','mutableField':'machine','metricToWatch':'Refund\x20rate'},{'action':'Publish\x20the\x20single-layer\x20leader\x20commission\x20as\x20an\x20on-chain\x20Allocation\x20leg','purpose':'Show\x20the\x20leader\x20earns\x20a\x20disclosed\x20rate,\x20not\x20a\x20hidden\x20markup','mutableField':'allocator','metricToWatch':'Trust\x20score'},{'action':'Pre-lock\x20a\x20delay-compensation\x20fund','purpose':'Back\x20the\x20delivery-delay\x20promise\x20that\x20community\x20groups\x20run\x20on','mutableField':'compensation_fund','metricToWatch':'Trust\x20score'}],'rewardStrategy':'Leader\x20commission\x20is\x20a\x20single\x20disclosed\x20Allocation\x20layer\x20(off-chain\x20pass-through\x20to\x20team\x20members);\x20buyer-side\x20reward\x20=\x20repeat-participation\x20streak;\x20NEVER\x20structure\x20multi-layer\x20commission\x20(headhunting/pyramid\x20exposure)','discountStrategy':'Group-size\x20tiered\x20pricing\x20(bigger\x20group\x20=\x20lower\x20unit\x20price)\x20+\x20early-bird\x20per\x20round;\x20threshold\x20math\x20must\x20stay\x20solvable\x20with\x20the\x20floor\x20price','trustDescription':'On-chain\x20group\x20threshold\x20+\x20absolute\x20deadline\x20+\x20per-buyer\x20escrow\x20(release\x20XOR\x20refund)\x20+\x20unclaimed-pickup\x20expiry\x20refund\x20+\x20single-layer\x20commission\x20disclosure'}];let _registryLookup=null;export function _setRegistryLookup(a){_registryLookup=a;}export function getFlywheelForIndustry(a){if(_registryLookup){const b=_registryLookup(a);if(b?.['flywheel'])return b['flywheel'];}return INDUSTRY_FLYWHEELS['find'](c=>c['industry']===a['toLowerCase']());}export function listIndustries(){return INDUSTRY_FLYWHEELS['map'](a=>a['industry']);}export function suggestAcquisitionActions(a){const b=getFlywheelForIndustry(a);return b?.['keyActions']??[];}export function generateTrustDescription(a){const b=[];if(a['industry']){const c=getFlywheelForIndustry(a['industry']);c&&b['push'](c['trustDescription']);}return a['orderCount']!==undefined&&a['orderCount']>0x0&&b['push']('Completed\x20'+a['orderCount']+'\x20orders'),a['completedRate']!==undefined&&b['push']('Completion\x20rate\x20'+Math['round'](a['completedRate']*0x64)+'%'),a['avgCompletionTime']!==undefined&&(a['avgCompletionTime']<0x1?b['push']('Average\x20completion\x20time\x20'+Math['round'](a['avgCompletionTime']*0x3c)+'\x20minutes'):b['push']('Average\x20completion\x20time\x20'+Math['round'](a['avgCompletionTime'])+'\x20hours')),a['hasCompensationFund']&&b['push']('Sufficient\x20compensation\x20fund'),a['hasArbitration']&&b['push']('Third-party\x20arbitration\x20guarantee'),a['reviewCount']!==undefined&&a['reviewCount']>0x0&&a['reviewLikeRate']!==undefined&&b['push']('Like\x20rate\x20'+Math['round'](a['reviewLikeRate']*0x64)+'%\x20('+a['reviewCount']+'\x20reviews)'),b['join'](';\x20')||'No\x20trust\x20data\x20available';}export function buildAcquisitionDashboard(a){const {orderCount:b,completedRate:c,avgCompletionTime:d,repeatCustomerRate:e,reviewLikeRate:f,reviewCount:g}=a;let h='cold_start';if(b>=0x32)h='optimization';else{if(b>=0x14)h='mature';else{if(b>=0x5)h='growing';}}const i=[];if(h==='cold_start')i['push']('Cold-start\x20stage:\x20set\x20first-order\x20Reward\x20to\x20attract\x20new\x20customers'),i['push']('Increase\x20compensation_fund\x20to\x20boost\x20initial\x20trust');else{if(h==='growing')i['push']('Growing\x20stage:\x20set\x20referral\x20cashback\x20Reward\x20for\x20viral\x20acquisition'),e!==undefined&&e<0.2&&i['push']('Repurchase\x20rate\x20is\x20low;\x20consider\x20setting\x20cumulative-spend\x20tiered\x20Reward');else h==='mature'?(f!==undefined&&f>0.8&&i['push']('High\x20like\x20rate;\x20you\x20can\x20highlight\x20trust\x20metrics\x20in\x20the\x20description'),e!==undefined&&e>0.3&&i['push']('High\x20repurchase\x20rate;\x20consider\x20setting\x20loyalty\x20Reward\x20to\x20incentivize\x20long-term\x20customers')):(i['push']('Optimization\x20stage:\x20fine-tune\x20pricing\x20and\x20Reward\x20strategies'),d!==undefined&&d>0x30&&i['push']('Completion\x20time\x20is\x20long;\x20consider\x20optimizing\x20the\x20Machine\x20process'));}return{'metrics':{'orderCount':b,'completedRate':c??0x0,'avgCompletionTime':d,'repeatCustomerRate':e,'reviewLikeRate':f,'reviewCount':g},'suggestions':i,'flywheelStage':h};}
@@ -46,6 +46,7 @@ export declare const ALLOCATION_ERROR_CODES: {
46
46
  readonly E_ONCE_TRIGGERED: 16;
47
47
  readonly EMIXED_RATE_BASES: 17;
48
48
  readonly EFORMULA_SPEC_INVALID: 24;
49
+ readonly EEMPTY_POOL_BATCH: 26;
49
50
  };
50
51
  export declare const ORDER_ALLOCATION_ALREADY_SPECIFIED = "E_ALLOCATION_ALREADY_SPECIFIED";
51
52
  export declare const ALLOCATION_SCENES: AllocationScene[];
@@ -1 +1 @@
1
- import{MAX_SHARING_COUNT,MAX_ALLOCATOR_COUNT}from'@wowok/wowok';export{MAX_ALLOCATOR_COUNT};export const ALLOCATION_MAX_SHARING_COUNT=MAX_SHARING_COUNT;export const ALLOCATION_MODE_AMOUNT=0x0;export const ALLOCATION_MODE_RATE=0x1;export const ALLOCATION_MODE_SURPLUS=0x2;export const ALLOCATION_MODE_RATE_GROSS=0x3;export const ALLOCATION_MODE_FORMULA=0x4;export const RATE_TOTAL_FULL=0x2710;export const ALLOCATION_ERROR_CODES={'ERECIPIENT_IDENTIFIER_NOT_ADDRESS':0x1,'EALLOCATOR_COUNT_EXCEEDED':0x2,'ENO_ALLOCATOR':0x3,'ERATE_NOT_10000':0x4,'EMULTIPLE_SURPLUS':0x5,'ERATE_EXCEEDS_10000':0x6,'EINSUFFICIENT_BALANCE':0x7,'EALLOCATORS_EMPTY':0x8,'ENO_PAYMENT_INFO':0x9,'ESHARING_COUNT_EXCEEDED':0xa,'ESHARING_MODE_INVALID':0xb,'EAMOUNT_BELOW_THRESHOLD':0xc,'EAMOUNT_EXCEEDS_MAX':0xd,'EZERO_DISTRIBUTION':0xe,'ERECIPIENT_NOT_FOR_OBJECT':0xf,'E_ONCE_TRIGGERED':0x10,'EMIXED_RATE_BASES':0x11,'EFORMULA_SPEC_INVALID':0x18};export const ORDER_ALLOCATION_ALREADY_SPECIFIED='E_ALLOCATION_ALREADY_SPECIFIED';export const ALLOCATION_SCENES=[{'id':'allocation_standard_three_way_split','name':'Standard\x20three-way\x20split\x20(merchant\x20/\x20platform\x20/\x20logistics)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'All\x20three\x20Treasury\x20objects\x20must\x20use\x20the\x20same\x20Coin<T>\x20type\x20as\x20the\x20Allocation','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20Treasury\x20address','Guard\x20verifies\x20order.service\x20binding\x20(query\x201563)\x20to\x20prevent\x20cross-project\x20bypass','Guard\x20verifies\x20progress.current_node\x20===\x20\x27Complete\x27'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','order_allocators\x20immutable\x20after\x20Service\x20publish\x20(R-A-10)'],'recommended_templates':['T-A-02']},{'id':'allocation_merchant_full_payment','name':'Merchant\x20full\x20payment\x20(single\x20recipient,\x20100%)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'Simplest\x20configuration\x20—\x20single\x20Treasury\x20or\x20personal\x20address','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'single_relaxed','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate\x20sharing\x20=\x2010000','Guard\x20only\x20verifies\x20order\x20status\x20(no\x20complex\x20conditions)','who=Entity\x20can\x20be\x20either\x20Treasury\x20or\x20personal\x20wallet'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['Simplest\x20allocation\x20configuration','No\x20multi-party\x20coordination\x20required'],'recommended_templates':['T-A-01']},{'id':'allocation_refund_first_surplus_to_merchant','name':'Refund\x20first\x20+\x20surplus\x20to\x20merchant\x20(Amount\x20+\x20Surplus\x20hybrid)','trigger_source':'service_order_allocators','distribution_strategy':'amount_plus_surplus','coin_type_note':'Refund\x20amount\x20must\x20match\x20Coin<T>\x20precision','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Surplus'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x202\x20sharing\x20items','sharing[0]:\x20Amount=refund_value,\x20who=Entity(customer_address)','sharing[1]:\x20Surplus,\x20who=Entity(merchant_treasury)','fix\x20=\x20refund_value\x20(cached\x20Amount\x20sum)','threshold\x20=\x20refund_value\x20(ensure\x20sufficient\x20balance\x20for\x20Amount)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator','F-A-07:\x20fix\x20>=\x20threshold\x20(Amount\x20sum\x20must\x20cover\x20threshold)','fix\x20must\x20precisely\x20match\x20the\x20refund\x20amount'],'recommended_templates':['T-A-03']},{'id':'allocation_treasury_personal_alternatives','name':'Treasury\x20+\x20Personal\x20alternative\x20strategies\x20(caller-specified\x20guard)','trigger_source':'service_order_allocators','distribution_strategy':'first_match_alternatives','coin_type_note':'Both\x20target\x20addresses\x20must\x20accept\x20the\x20same\x20Coin<T>','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators,\x20each\x20with\x201\x20Rate=10000\x20sharing','Allocator[0]:\x20guard=guard_treasury,\x20who=Entity(treasury_address)','Allocator[1]:\x20guard=guard_personal,\x20who=Entity(personal_address)','Two\x20Guard\x20objects\x20must\x20be\x20different\x20addresses\x20(R-A-11)','caller-specified\x20guard:\x20caller\x20selects\x20Treasury\x20or\x20Personal\x20path\x20via\x20alloc_by_guard;\x20the\x20Passport\x20hard-verifies\x20the\x20selected\x20Guard\x20(failure\x20aborts\x20with\x20E_VERIFY_FAILED;\x20caller\x20must\x20switch\x20guard\x20and\x20retry)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-14:\x20allocators[].guard\x20must\x20be\x20unique','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','Guard\x20A\x20and\x20Guard\x20B\x20may\x20share\x20root/table\x20but\x20must\x20differ\x20in\x20description'],'recommended_templates':['T-A-04']},{'id':'allocation_tiered_by_order_amount','name':'Tiered\x20split\x20by\x20order\x20amount\x20(multi-Allocator\x20amount-threshold\x20switch)','trigger_source':'service_order_allocators','distribution_strategy':'tiered_by_amount','coin_type_note':'Amount\x20threshold\x20uses\x20Coin<T>\x20smallest\x20unit\x20(e.g.\x20MIST\x20for\x20WOW)','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators\x20triggered\x20by\x20mutually\x20exclusive\x20Guard\x20conditions','Allocator[0]:\x20guard\x20verifies\x20order.amount\x20<\x20threshold,\x20Rate=10000\x20to\x20merchant','Allocator[1]:\x20guard\x20verifies\x20order.amount\x20>=\x20threshold,\x20Rate=8000/2000\x20split','caller-specified\x20guard:\x20caller\x20selects\x20the\x20matching\x20Allocator\x20based\x20on\x20order\x20amount;\x20allocator\x20order\x20is\x20irrelevant','Guard\x20queries\x20order.amount\x20(query\x201561)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20(R-A-4-02\x20design\x20clarity)','Caller\x20must\x20select\x20correct\x20guard\x20based\x20on\x20order.amount\x20(no\x20auto-fallback)'],'recommended_templates':['T-A-05']},{'id':'allocation_dynamic_recipient','name':'Multi-role\x20split\x20with\x20dynamic\x20recipient\x20(GuardIdentifier)','trigger_source':'service_order_allocators','distribution_strategy':'dynamic_recipient','coin_type_note':'Passport\x20table\x20must\x20contain\x20address-typed\x20entry\x20at\x20the\x20referenced\x20identifier','typical_allocator_count':0x1,'sharing_who_types':['Entity','GuardIdentifier'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items','sharing[0]:\x20Rate=8000,\x20who=Entity(merchant_treasury)','sharing[1]:\x20Rate=1000,\x20who=Entity(platform_treasury)','sharing[2]:\x20Rate=1000,\x20who=GuardIdentifier(0)\x20—\x20resolves\x20from\x20Passport\x20table','Customer\x20submits\x20Passport\x20with\x20referrer\x20address\x20at\x20identifier=0'],'dependencies':['Service','Treasury','Guard','Passport','Order','Payment'],'key_constraints':['F-A-13:\x20Passport\x20table[identifier]\x20must\x20be\x20address\x20type\x20(else\x20ERECIPIENT_IDENTIFIER_NOT_ADDRESS)','Guard\x20must\x20verify\x20Passport\x20completeness','Customer\x20order\x20must\x20include\x20Passport\x20with\x20referrer\x20address'],'recommended_templates':['T-A-06']},{'id':'allocation_arbitration_fees','name':'Arbitration\x20fees\x20split\x20(arbitrator\x20/\x20platform)','trigger_source':'arbitration_fees','distribution_strategy':'pure_rate','coin_type_note':'Coin<T>\x20must\x20match\x20Arbitration\x27s\x20fee\x20Coin\x20type','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Triggered\x20by\x20the\x20Arbitration\x20fee-allocation\x20operation\x20(permission\x20365),\x20direct\x20or\x20Passport\x20path','Single\x20Allocator,\x202\x20Rate\x20sharing\x20items:\x208000\x20arbitrator\x20/\x202000\x20platform','payment_info\x20reuses\x20Arbitration\x27s\x20payment_info','Caller\x20must\x20hold\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'dependencies':['Arbitration','Treasury','Guard','Payment'],'key_constraints':['Independent\x20from\x20Service-order\x20Allocation','Requires\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'recommended_templates':['T-A-08']},{'id':'allocation_refund_to_order','name':'Refund\x20Allocator\x20(100%\x20to\x20Order\x20object)','trigger_source':'service_order_allocators','distribution_strategy':'refund_to_order','coin_type_note':'who=Entity\x20must\x20be\x20the\x20Order\x20object\x20address\x20(NOT\x20a\x20personal\x20wallet)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate=10000\x20sharing','who=Entity(order_address)\x20—\x20funds\x20flow\x20back\x20to\x20Order,\x20not\x20personal\x20wallet','Guard\x20verifies\x20customer\x20refund\x20request\x20and\x20eligibility','Customer-side\x20risk\x20assessment\x20adds\x208-point\x20weight\x20(onchain_topology\x20graph\x20evaluation)'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['who=Entity\x20MUST\x20be\x20Order\x20object\x20address\x20(not\x20personal\x20address)','Customer\x20due-diligence\x20rewards\x20this\x20configuration\x20(8-point\x20weight)','Refund\x20funds\x20return\x20to\x20Order\x20for\x20downstream\x20handling'],'recommended_templates':['T-A-07']},{'id':'allocation_max_capped_retain','name':'Max-capped\x20allocation\x20(retain\x20residual\x20balance)','trigger_source':'service_order_allocators','distribution_strategy':'max_capped','coin_type_note':'max\x20field\x20uses\x20Coin<T>\x20smallest\x20unit','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['Single\x20Allocator\x20with\x20max\x20field\x20set','max\x20triple\x20role:\x20Amount\x20cap\x20+\x20NET\x20Rate\x20base\x20+\x20Surplus\x20cap','Amount\x20sharing\x20consumes\x20fix;\x20NET\x20Rate\x20sharing\x20uses\x20(max\x20-\x20fix)\x20as\x20base\x20(RateGross\x20uses\x20max\x20itself)','Residual\x20balance\x20remains\x20in\x20Allocation\x20for\x20subsequent\x20alloc()\x20calls'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','NET\x20Rate:\x20max\x20-\x20fix\x20becomes\x20the\x20base\x20(NOT\x20balance\x20-\x20fix);\x20RateGross:\x20the\x20base\x20is\x20max\x20(fix\x20not\x20removed)','Residual\x20balance\x20may\x20be\x20claimed\x20by\x20re-triggering\x20alloc()'],'recommended_templates':[]},{'id':'allocation_multi_node_trigger','name':'Multi-Machine-node\x20triggered\x20allocation\x20(Complete\x20/\x20Refund\x20/\x20Lost)','trigger_source':'service_order_allocators','distribution_strategy':'multi_node_trigger','coin_type_note':'All\x20Allocators\x20share\x20the\x20same\x20Allocation\x27s\x20Coin<T>','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['3\x20Allocators\x20mapped\x20to\x20Machine\x20terminal\x20nodes\x20(Complete/Refund/Lost)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20progress.current_node\x20==\x20<node_name>','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20terminal\x20node\x20active\x20at\x20a\x20time)','Machine.required_allocators[]\x20describes\x20each\x20trigger_node\x20mapping'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive','Sequence-sensitive:\x20business-flow\x20order','Machine.required_allocators[trigger_node]\x20must\x20map\x20to\x20Allocator\x20indices'],'recommended_templates':[]},{'id':'allocation_standalone_periodic_split','name':'Standalone\x20periodic\x20split\x20(investment\x20dividends\x20/\x20shared\x20income)','trigger_source':'standalone','distribution_strategy':'periodic_split','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20asset\x20being\x20distributed\x20(e.g.\x20profit\x20token)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x20N\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20beneficiary\x20wallet\x20(not\x20Treasury)','Guard\x20verifies\x20time-based\x20trigger\x20(e.g.\x20context(Clock).timestamp\x20>=\x20next_release)\x20or\x20signer\x20authorization','User\x20calls\x20receive()\x20to\x20deposit\x20funds,\x20then\x20alloc()\x20to\x20trigger\x20distribution','No\x20Service/Order/Progress/Machine\x20context\x20required'],'dependencies':['Treasury','Guard','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20+\x20Passport\x20MUST\x20be\x20sufficient','Caller\x20is\x20fully\x20responsible\x20for\x20receive\x20→\x20alloc\x20lifecycle\x20(no\x20auto-trigger)','Guard\x20should\x20bind\x20Signer\x20to\x20prevent\x20unauthorized\x20alloc()\x20calls'],'recommended_templates':['T-A-09']},{'id':'allocation_standalone_vesting','name':'Standalone\x20vesting\x20release\x20(time-locked\x20multi-stage\x20unlock)','trigger_source':'standalone','distribution_strategy':'time_locked_vesting','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20vested\x20asset\x20(e.g.\x20locked\x20team\x20tokens)','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate','Surplus'],'guard_requirement':'multiple_unique','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['N\x20Allocators,\x20each\x20mapped\x20to\x20a\x20vesting\x20stage\x20(e.g.\x2025%\x20at\x20month\x2012,\x2025%\x20at\x20month\x2024,\x2050%\x20surplus\x20at\x20month\x2036)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20context(Clock).timestamp\x20>=\x20stage_unlock_time','Amount\x20sharing\x20per\x20stage\x20with\x20max\x20field\x20capping\x20the\x20cumulative\x20release','Final\x20Allocator\x20uses\x20Surplus\x20to\x20drain\x20remaining\x20balance\x20after\x20last\x20vesting\x20stage','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20stage\x20active\x20at\x20a\x20time,\x20based\x20on\x20timestamp)','User\x20calls\x20receive()\x20to\x20deposit\x20locked\x20tokens,\x20then\x20alloc()\x20at\x20each\x20vesting\x20milestone'],'dependencies':['Treasury','Guard','Passport','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator\x20(final\x20stage\x20uses\x20Surplus\x20to\x20drain\x20remainder)','F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20time-lock\x20MUST\x20be\x20enforced','Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20by\x20timestamp\x20(R-A-4-02)','Caller\x20must\x20wait\x20for\x20time-lock\x20expiry\x20before\x20alloc()\x20succeeds;\x20otherwise\x20alloc()\x20silently\x20returns\x20(R-A-4-01)'],'recommended_templates':['T-A-10']}];export const ALLOCATION_LEDGER_VERSION='1.0.0';export function getScenesByTriggerSource(a){return ALLOCATION_SCENES['filter'](b=>b['trigger_source']===a);}export function getScenesByMode(a){return ALLOCATION_SCENES['filter'](b=>b['modes_used']['includes'](a));}export function getScenesByStrategy(a){return ALLOCATION_SCENES['filter'](b=>b['distribution_strategy']===a);}export function findSceneById(a){return ALLOCATION_SCENES['find'](b=>b['id']===a);}export function inferSceneFromIntent(a){const b=a['toLowerCase']();if(b['includes']('arbitration')||b['includes']('fees\x20alloc'))return findSceneById('allocation_arbitration_fees');if(b['includes']('standalone')||b['includes']('periodic\x20split')||b['includes']('investment\x20dividend')||b['includes']('shared\x20income')||b['includes']('dividend'))return findSceneById('allocation_standalone_periodic_split');if(b['includes']('vesting')||b['includes']('time-lock')||b['includes']('unlock\x20period')||b['includes']('locked\x20release')||b['includes']('token\x20unlock'))return findSceneById('allocation_standalone_vesting');if(b['includes']('refund')){if(b['includes']('order')||b['includes']('100%'))return findSceneById('allocation_refund_to_order');if(b['includes']('surplus')||b['includes']('merchant'))return findSceneById('allocation_refund_first_surplus_to_merchant');}if(b['includes']('alternative')||b['includes']('priority')||b['includes']('treasury')&&b['includes']('personal'))return findSceneById('allocation_treasury_personal_alternatives');if(b['includes']('tiered')||b['includes']('threshold\x20switch'))return findSceneById('allocation_tiered_by_order_amount');if(b['includes']('dynamic\x20recipient')||b['includes']('referrer')||b['includes']('guardidentifier'))return findSceneById('allocation_dynamic_recipient');if(b['includes']('retain')||b['includes']('max'))return findSceneById('allocation_max_capped_retain');if(b['includes']('multi-node')||b['includes']('multi\x20machine')||b['includes']('multi_node'))return findSceneById('allocation_multi_node_trigger');const c=(a['match'](/%/g)||[])['length'];if(c<=0x1)return findSceneById('allocation_merchant_full_payment');if(c>=0x2)return findSceneById('allocation_standard_three_way_split');return undefined;}export function getAllScenes(){return[...ALLOCATION_SCENES];}export function getScenesCount(){return ALLOCATION_SCENES['length'];}export function allocationModeToNumber(a){switch(a){case'Amount':return ALLOCATION_MODE_AMOUNT;case'Rate':return ALLOCATION_MODE_RATE;case'Surplus':return ALLOCATION_MODE_SURPLUS;case'RateGross':return ALLOCATION_MODE_RATE_GROSS;case'Formula':return ALLOCATION_MODE_FORMULA;}}export function allocationModeFromNumber(a){switch(a){case ALLOCATION_MODE_AMOUNT:return'Amount';case ALLOCATION_MODE_RATE:return'Rate';case ALLOCATION_MODE_SURPLUS:return'Surplus';case ALLOCATION_MODE_RATE_GROSS:return'RateGross';case ALLOCATION_MODE_FORMULA:return'Formula';default:throw new Error('Invalid\x20AllocationMode\x20number:\x20'+a);}}export function getRecipientType(a){if('GuardIdentifier'in a)return'GuardIdentifier';if('Entity'in a)return'Entity';return'Signer';}export function isSignerRecipient(a){return'Signer'in a;}export function isEntityRecipient(a){return'Entity'in a;}export function isGuardIdentifierRecipient(a){return'GuardIdentifier'in a;}export function getErrorName(a){for(const [b,d]of Object['entries'](ALLOCATION_ERROR_CODES)){if(d===a)return b;}return undefined;}export function getErrorDescription(a){const b={0x1:'GuardIdentifier\x20resolved\x20value\x20is\x20not\x20an\x20address\x20type',0x2:'Allocator\x20count\x20exceeds\x20MAX_ALLOCATOR_COUNT\x20(100)',0x3:'No\x20Allocator\x20in\x20the\x20allocators\x20vector',0x4:'Pure\x20Rate\x20mode\x20sum\x20!=\x2010000\x20(no\x20Surplus\x20to\x20absorb\x20remainder)',0x5:'Multiple\x20Surplus\x20sharing\x20in\x20a\x20single\x20Allocator',0x6:'Rate\x20+\x20Surplus\x20sum\x20>\x2010000',0x7:'balance\x20<\x20threshold\x20(insufficient\x20balance\x20to\x20trigger\x20alloc)',0x8:'allocators.allocators\x20is\x20empty',0x9:'payment_info\x20is\x20None\x20when\x20alloc()\x20is\x20called',0xa:'sharing\x20count\x20exceeds\x20MAX_SHARING_COUNT\x20(100)',0xb:'sharing\x20mode\x20is\x20not\x200\x20(Amount)\x20/\x201\x20(Rate)\x20/\x202\x20(Surplus)\x20/\x203\x20(RateGross)\x20/\x204\x20(Formula)',0xc:'Amount\x20sum\x20(fix)\x20<\x20threshold',0xd:'Amount\x20sum\x20(fix)\x20>\x20max',0xe:'distribution\x20computes\x20to\x20zero\x20while\x20the\x20pool\x20still\x20holds\x20funds\x20(or\x20balance\x20is\x200)',0xf:'GuardIdentifier\x20recipient\x20address\x20!=\x20payment_info.for_object\x20anchor\x20(abort\x20fires\x20only\x20when\x20a\x20for_object\x20binding\x20is\x20declared)',0x10:'once-trigger\x20key\x20already\x20consumed\x20—\x20the\x20guard\x20submitted\x20the\x20reserved\x20identifier\x20255\x20and\x20its\x20raw\x20submission\x20bytes\x20were\x20recorded\x20as\x20a\x20(guard,\x20allocator\x20index,\x20raw\x20bytes)\x20dynamic-field\x20key\x20on\x20this\x20Allocation',0x11:'mixed\x20rate\x20bases\x20—\x20one\x20allocator\x20carries\x20both\x20NET\x20Rate\x20and\x20RateGross\x20entries\x20while\x20a\x20fixed\x20Amount\x20total\x20is\x20present\x20(rejected\x20only\x20when\x20fix\x20>\x200;\x20with\x20fix\x20==\x200\x20the\x20two\x20bases\x20coincide\x20and\x20mixing\x20is\x20allowed)',0x12:'RateGross\x20+\x20fixed\x20Amount\x20without\x20a\x20max\x20cap\x20—\x20plan\x20payability\x20unprovable\x20at\x20declaration\x20time',0x13:'guard\x20not\x20bound\x20to\x20any\x20allocator\x20on\x20this\x20Allocation\x20(was\x20a\x20silent\x20no-op\x20success\x20before)',0x14:'allocator\x20append\x20rejected:\x20new\x20Allocators\x20is\x20not\x20a\x20pure\x20extension\x20(prefix/threshold\x20changed)',0x15:'once-for-object\x20slot\x20(identifier\x20254)\x20armed\x20but\x20payment_info\x20declares\x20no\x20for_object\x20binding',0x18:'FormulaSpec\x20rejected:\x20selector\x20is\x20not\x20COUNT(0)/SUM(1),\x20allocator/slot\x20index\x20out\x20of\x20range,\x20or\x20the\x20target\x20sharing\x20slot\x20is\x20not\x20a\x20Formula\x20(mode\x204)\x20leg'};return b[a];}
1
+ import{MAX_SHARING_COUNT,MAX_ALLOCATOR_COUNT}from'@wowok/wowok';export{MAX_ALLOCATOR_COUNT};export const ALLOCATION_MAX_SHARING_COUNT=MAX_SHARING_COUNT;export const ALLOCATION_MODE_AMOUNT=0x0;export const ALLOCATION_MODE_RATE=0x1;export const ALLOCATION_MODE_SURPLUS=0x2;export const ALLOCATION_MODE_RATE_GROSS=0x3;export const ALLOCATION_MODE_FORMULA=0x4;export const RATE_TOTAL_FULL=0x2710;export const ALLOCATION_ERROR_CODES={'ERECIPIENT_IDENTIFIER_NOT_ADDRESS':0x1,'EALLOCATOR_COUNT_EXCEEDED':0x2,'ENO_ALLOCATOR':0x3,'ERATE_NOT_10000':0x4,'EMULTIPLE_SURPLUS':0x5,'ERATE_EXCEEDS_10000':0x6,'EINSUFFICIENT_BALANCE':0x7,'EALLOCATORS_EMPTY':0x8,'ENO_PAYMENT_INFO':0x9,'ESHARING_COUNT_EXCEEDED':0xa,'ESHARING_MODE_INVALID':0xb,'EAMOUNT_BELOW_THRESHOLD':0xc,'EAMOUNT_EXCEEDS_MAX':0xd,'EZERO_DISTRIBUTION':0xe,'ERECIPIENT_NOT_FOR_OBJECT':0xf,'E_ONCE_TRIGGERED':0x10,'EMIXED_RATE_BASES':0x11,'EFORMULA_SPEC_INVALID':0x18,'EEMPTY_POOL_BATCH':0x1a};export const ORDER_ALLOCATION_ALREADY_SPECIFIED='E_ALLOCATION_ALREADY_SPECIFIED';export const ALLOCATION_SCENES=[{'id':'allocation_standard_three_way_split','name':'Standard\x20three-way\x20split\x20(merchant\x20/\x20platform\x20/\x20logistics)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'All\x20three\x20Treasury\x20objects\x20must\x20use\x20the\x20same\x20Coin<T>\x20type\x20as\x20the\x20Allocation','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20Treasury\x20address','Guard\x20verifies\x20order.service\x20binding\x20(query\x201563)\x20to\x20prevent\x20cross-project\x20bypass','Guard\x20verifies\x20progress.current_node\x20===\x20\x27Complete\x27'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','order_allocators\x20immutable\x20after\x20Service\x20publish\x20(R-A-10)'],'recommended_templates':['T-A-02']},{'id':'allocation_merchant_full_payment','name':'Merchant\x20full\x20payment\x20(single\x20recipient,\x20100%)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'Simplest\x20configuration\x20—\x20single\x20Treasury\x20or\x20personal\x20address','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'single_relaxed','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate\x20sharing\x20=\x2010000','Guard\x20only\x20verifies\x20order\x20status\x20(no\x20complex\x20conditions)','who=Entity\x20can\x20be\x20either\x20Treasury\x20or\x20personal\x20wallet'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['Simplest\x20allocation\x20configuration','No\x20multi-party\x20coordination\x20required'],'recommended_templates':['T-A-01']},{'id':'allocation_refund_first_surplus_to_merchant','name':'Refund\x20first\x20+\x20surplus\x20to\x20merchant\x20(Amount\x20+\x20Surplus\x20hybrid)','trigger_source':'service_order_allocators','distribution_strategy':'amount_plus_surplus','coin_type_note':'Refund\x20amount\x20must\x20match\x20Coin<T>\x20precision','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Surplus'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x202\x20sharing\x20items','sharing[0]:\x20Amount=refund_value,\x20who=Entity(customer_address)','sharing[1]:\x20Surplus,\x20who=Entity(merchant_treasury)','fix\x20=\x20refund_value\x20(cached\x20Amount\x20sum)','threshold\x20=\x20refund_value\x20(ensure\x20sufficient\x20balance\x20for\x20Amount)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator','F-A-07:\x20fix\x20>=\x20threshold\x20(Amount\x20sum\x20must\x20cover\x20threshold)','fix\x20must\x20precisely\x20match\x20the\x20refund\x20amount'],'recommended_templates':['T-A-03']},{'id':'allocation_treasury_personal_alternatives','name':'Treasury\x20+\x20Personal\x20alternative\x20strategies\x20(caller-specified\x20guard)','trigger_source':'service_order_allocators','distribution_strategy':'first_match_alternatives','coin_type_note':'Both\x20target\x20addresses\x20must\x20accept\x20the\x20same\x20Coin<T>','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators,\x20each\x20with\x201\x20Rate=10000\x20sharing','Allocator[0]:\x20guard=guard_treasury,\x20who=Entity(treasury_address)','Allocator[1]:\x20guard=guard_personal,\x20who=Entity(personal_address)','Two\x20Guard\x20objects\x20must\x20be\x20different\x20addresses\x20(R-A-11)','caller-specified\x20guard:\x20caller\x20selects\x20Treasury\x20or\x20Personal\x20path\x20via\x20alloc_by_guard;\x20the\x20Passport\x20hard-verifies\x20the\x20selected\x20Guard\x20(failure\x20aborts\x20with\x20E_VERIFY_FAILED;\x20caller\x20must\x20switch\x20guard\x20and\x20retry)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-14:\x20allocators[].guard\x20must\x20be\x20unique','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','Guard\x20A\x20and\x20Guard\x20B\x20may\x20share\x20root/table\x20but\x20must\x20differ\x20in\x20description'],'recommended_templates':['T-A-04']},{'id':'allocation_tiered_by_order_amount','name':'Tiered\x20split\x20by\x20order\x20amount\x20(multi-Allocator\x20amount-threshold\x20switch)','trigger_source':'service_order_allocators','distribution_strategy':'tiered_by_amount','coin_type_note':'Amount\x20threshold\x20uses\x20Coin<T>\x20smallest\x20unit\x20(e.g.\x20MIST\x20for\x20WOW)','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators\x20triggered\x20by\x20mutually\x20exclusive\x20Guard\x20conditions','Allocator[0]:\x20guard\x20verifies\x20order.amount\x20<\x20threshold,\x20Rate=10000\x20to\x20merchant','Allocator[1]:\x20guard\x20verifies\x20order.amount\x20>=\x20threshold,\x20Rate=8000/2000\x20split','caller-specified\x20guard:\x20caller\x20selects\x20the\x20matching\x20Allocator\x20based\x20on\x20order\x20amount;\x20allocator\x20order\x20is\x20irrelevant','Guard\x20queries\x20order.amount\x20(query\x201561)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20(R-A-4-02\x20design\x20clarity)','Caller\x20must\x20select\x20correct\x20guard\x20based\x20on\x20order.amount\x20(no\x20auto-fallback)'],'recommended_templates':['T-A-05']},{'id':'allocation_dynamic_recipient','name':'Multi-role\x20split\x20with\x20dynamic\x20recipient\x20(GuardIdentifier)','trigger_source':'service_order_allocators','distribution_strategy':'dynamic_recipient','coin_type_note':'Passport\x20table\x20must\x20contain\x20address-typed\x20entry\x20at\x20the\x20referenced\x20identifier','typical_allocator_count':0x1,'sharing_who_types':['Entity','GuardIdentifier'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items','sharing[0]:\x20Rate=8000,\x20who=Entity(merchant_treasury)','sharing[1]:\x20Rate=1000,\x20who=Entity(platform_treasury)','sharing[2]:\x20Rate=1000,\x20who=GuardIdentifier(0)\x20—\x20resolves\x20from\x20Passport\x20table','Customer\x20submits\x20Passport\x20with\x20referrer\x20address\x20at\x20identifier=0'],'dependencies':['Service','Treasury','Guard','Passport','Order','Payment'],'key_constraints':['F-A-13:\x20Passport\x20table[identifier]\x20must\x20be\x20address\x20type\x20(else\x20ERECIPIENT_IDENTIFIER_NOT_ADDRESS)','Guard\x20must\x20verify\x20Passport\x20completeness','Customer\x20order\x20must\x20include\x20Passport\x20with\x20referrer\x20address'],'recommended_templates':['T-A-06']},{'id':'allocation_arbitration_fees','name':'Arbitration\x20fees\x20split\x20(arbitrator\x20/\x20platform)','trigger_source':'arbitration_fees','distribution_strategy':'pure_rate','coin_type_note':'Coin<T>\x20must\x20match\x20Arbitration\x27s\x20fee\x20Coin\x20type','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Triggered\x20by\x20the\x20Arbitration\x20fee-allocation\x20operation\x20(permission\x20365),\x20direct\x20or\x20Passport\x20path','Single\x20Allocator,\x202\x20Rate\x20sharing\x20items:\x208000\x20arbitrator\x20/\x202000\x20platform','payment_info\x20reuses\x20Arbitration\x27s\x20payment_info','Caller\x20must\x20hold\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'dependencies':['Arbitration','Treasury','Guard','Payment'],'key_constraints':['Independent\x20from\x20Service-order\x20Allocation','Requires\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'recommended_templates':['T-A-08']},{'id':'allocation_refund_to_order','name':'Refund\x20Allocator\x20(100%\x20to\x20Order\x20object)','trigger_source':'service_order_allocators','distribution_strategy':'refund_to_order','coin_type_note':'who=Entity\x20must\x20be\x20the\x20Order\x20object\x20address\x20(NOT\x20a\x20personal\x20wallet)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate=10000\x20sharing','who=Entity(order_address)\x20—\x20funds\x20flow\x20back\x20to\x20Order,\x20not\x20personal\x20wallet','Guard\x20verifies\x20customer\x20refund\x20request\x20and\x20eligibility','Customer-side\x20risk\x20assessment\x20adds\x208-point\x20weight\x20(onchain_topology\x20graph\x20evaluation)'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['who=Entity\x20MUST\x20be\x20Order\x20object\x20address\x20(not\x20personal\x20address)','Customer\x20due-diligence\x20rewards\x20this\x20configuration\x20(8-point\x20weight)','Refund\x20funds\x20return\x20to\x20Order\x20for\x20downstream\x20handling'],'recommended_templates':['T-A-07']},{'id':'allocation_max_capped_retain','name':'Max-capped\x20allocation\x20(retain\x20residual\x20balance)','trigger_source':'service_order_allocators','distribution_strategy':'max_capped','coin_type_note':'max\x20field\x20uses\x20Coin<T>\x20smallest\x20unit','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['Single\x20Allocator\x20with\x20max\x20field\x20set','max\x20triple\x20role:\x20Amount\x20cap\x20+\x20NET\x20Rate\x20base\x20+\x20Surplus\x20cap','Amount\x20sharing\x20consumes\x20fix;\x20NET\x20Rate\x20sharing\x20uses\x20(max\x20-\x20fix)\x20as\x20base\x20(RateGross\x20uses\x20max\x20itself)','Residual\x20balance\x20remains\x20in\x20Allocation\x20for\x20subsequent\x20alloc()\x20calls'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','NET\x20Rate:\x20max\x20-\x20fix\x20becomes\x20the\x20base\x20(NOT\x20balance\x20-\x20fix);\x20RateGross:\x20the\x20base\x20is\x20max\x20(fix\x20not\x20removed)','Residual\x20balance\x20may\x20be\x20claimed\x20by\x20re-triggering\x20alloc()'],'recommended_templates':[]},{'id':'allocation_multi_node_trigger','name':'Multi-Machine-node\x20triggered\x20allocation\x20(Complete\x20/\x20Refund\x20/\x20Lost)','trigger_source':'service_order_allocators','distribution_strategy':'multi_node_trigger','coin_type_note':'All\x20Allocators\x20share\x20the\x20same\x20Allocation\x27s\x20Coin<T>','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['3\x20Allocators\x20mapped\x20to\x20Machine\x20terminal\x20nodes\x20(Complete/Refund/Lost)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20progress.current_node\x20==\x20<node_name>','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20terminal\x20node\x20active\x20at\x20a\x20time)','Machine.required_allocators[]\x20describes\x20each\x20trigger_node\x20mapping'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive','Sequence-sensitive:\x20business-flow\x20order','Machine.required_allocators[trigger_node]\x20must\x20map\x20to\x20Allocator\x20indices'],'recommended_templates':[]},{'id':'allocation_standalone_periodic_split','name':'Standalone\x20periodic\x20split\x20(investment\x20dividends\x20/\x20shared\x20income)','trigger_source':'standalone','distribution_strategy':'periodic_split','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20asset\x20being\x20distributed\x20(e.g.\x20profit\x20token)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x20N\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20beneficiary\x20wallet\x20(not\x20Treasury)','Guard\x20verifies\x20time-based\x20trigger\x20(e.g.\x20context(Clock).timestamp\x20>=\x20next_release)\x20or\x20signer\x20authorization','User\x20calls\x20receive()\x20to\x20deposit\x20funds,\x20then\x20alloc()\x20to\x20trigger\x20distribution','No\x20Service/Order/Progress/Machine\x20context\x20required'],'dependencies':['Treasury','Guard','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20+\x20Passport\x20MUST\x20be\x20sufficient','Caller\x20is\x20fully\x20responsible\x20for\x20receive\x20→\x20alloc\x20lifecycle\x20(no\x20auto-trigger)','Guard\x20should\x20bind\x20Signer\x20to\x20prevent\x20unauthorized\x20alloc()\x20calls'],'recommended_templates':['T-A-09']},{'id':'allocation_standalone_vesting','name':'Standalone\x20vesting\x20release\x20(time-locked\x20multi-stage\x20unlock)','trigger_source':'standalone','distribution_strategy':'time_locked_vesting','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20vested\x20asset\x20(e.g.\x20locked\x20team\x20tokens)','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate','Surplus'],'guard_requirement':'multiple_unique','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['N\x20Allocators,\x20each\x20mapped\x20to\x20a\x20vesting\x20stage\x20(e.g.\x2025%\x20at\x20month\x2012,\x2025%\x20at\x20month\x2024,\x2050%\x20surplus\x20at\x20month\x2036)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20context(Clock).timestamp\x20>=\x20stage_unlock_time','Amount\x20sharing\x20per\x20stage\x20with\x20max\x20field\x20capping\x20the\x20cumulative\x20release','Final\x20Allocator\x20uses\x20Surplus\x20to\x20drain\x20remaining\x20balance\x20after\x20last\x20vesting\x20stage','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20stage\x20active\x20at\x20a\x20time,\x20based\x20on\x20timestamp)','User\x20calls\x20receive()\x20to\x20deposit\x20locked\x20tokens,\x20then\x20alloc()\x20at\x20each\x20vesting\x20milestone'],'dependencies':['Treasury','Guard','Passport','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator\x20(final\x20stage\x20uses\x20Surplus\x20to\x20drain\x20remainder)','F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20time-lock\x20MUST\x20be\x20enforced','Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20by\x20timestamp\x20(R-A-4-02)','Caller\x20must\x20wait\x20for\x20time-lock\x20expiry\x20before\x20alloc()\x20succeeds;\x20otherwise\x20alloc()\x20silently\x20returns\x20(R-A-4-01)'],'recommended_templates':['T-A-10']}];export const ALLOCATION_LEDGER_VERSION='1.0.0';export function getScenesByTriggerSource(a){return ALLOCATION_SCENES['filter'](b=>b['trigger_source']===a);}export function getScenesByMode(a){return ALLOCATION_SCENES['filter'](b=>b['modes_used']['includes'](a));}export function getScenesByStrategy(a){return ALLOCATION_SCENES['filter'](b=>b['distribution_strategy']===a);}export function findSceneById(a){return ALLOCATION_SCENES['find'](b=>b['id']===a);}export function inferSceneFromIntent(a){const b=a['toLowerCase']();if(b['includes']('arbitration')||b['includes']('fees\x20alloc'))return findSceneById('allocation_arbitration_fees');if(b['includes']('standalone')||b['includes']('periodic\x20split')||b['includes']('investment\x20dividend')||b['includes']('shared\x20income')||b['includes']('dividend'))return findSceneById('allocation_standalone_periodic_split');if(b['includes']('vesting')||b['includes']('time-lock')||b['includes']('unlock\x20period')||b['includes']('locked\x20release')||b['includes']('token\x20unlock'))return findSceneById('allocation_standalone_vesting');if(b['includes']('refund')){if(b['includes']('order')||b['includes']('100%'))return findSceneById('allocation_refund_to_order');if(b['includes']('surplus')||b['includes']('merchant'))return findSceneById('allocation_refund_first_surplus_to_merchant');}if(b['includes']('alternative')||b['includes']('priority')||b['includes']('treasury')&&b['includes']('personal'))return findSceneById('allocation_treasury_personal_alternatives');if(b['includes']('tiered')||b['includes']('threshold\x20switch'))return findSceneById('allocation_tiered_by_order_amount');if(b['includes']('dynamic\x20recipient')||b['includes']('referrer')||b['includes']('guardidentifier'))return findSceneById('allocation_dynamic_recipient');if(b['includes']('retain')||b['includes']('max'))return findSceneById('allocation_max_capped_retain');if(b['includes']('multi-node')||b['includes']('multi\x20machine')||b['includes']('multi_node'))return findSceneById('allocation_multi_node_trigger');const c=(a['match'](/%/g)||[])['length'];if(c<=0x1)return findSceneById('allocation_merchant_full_payment');if(c>=0x2)return findSceneById('allocation_standard_three_way_split');return undefined;}export function getAllScenes(){return[...ALLOCATION_SCENES];}export function getScenesCount(){return ALLOCATION_SCENES['length'];}export function allocationModeToNumber(a){switch(a){case'Amount':return ALLOCATION_MODE_AMOUNT;case'Rate':return ALLOCATION_MODE_RATE;case'Surplus':return ALLOCATION_MODE_SURPLUS;case'RateGross':return ALLOCATION_MODE_RATE_GROSS;case'Formula':return ALLOCATION_MODE_FORMULA;}}export function allocationModeFromNumber(a){switch(a){case ALLOCATION_MODE_AMOUNT:return'Amount';case ALLOCATION_MODE_RATE:return'Rate';case ALLOCATION_MODE_SURPLUS:return'Surplus';case ALLOCATION_MODE_RATE_GROSS:return'RateGross';case ALLOCATION_MODE_FORMULA:return'Formula';default:throw new Error('Invalid\x20AllocationMode\x20number:\x20'+a);}}export function getRecipientType(a){if('GuardIdentifier'in a)return'GuardIdentifier';if('Entity'in a)return'Entity';return'Signer';}export function isSignerRecipient(a){return'Signer'in a;}export function isEntityRecipient(a){return'Entity'in a;}export function isGuardIdentifierRecipient(a){return'GuardIdentifier'in a;}export function getErrorName(a){for(const [b,d]of Object['entries'](ALLOCATION_ERROR_CODES)){if(d===a)return b;}return undefined;}export function getErrorDescription(a){const b={0x1:'GuardIdentifier\x20resolved\x20value\x20is\x20not\x20an\x20address\x20type',0x2:'Allocator\x20count\x20exceeds\x20MAX_ALLOCATOR_COUNT\x20(100)',0x3:'No\x20Allocator\x20in\x20the\x20allocators\x20vector',0x4:'Pure\x20Rate\x20mode\x20sum\x20!=\x2010000\x20(no\x20Surplus\x20to\x20absorb\x20remainder)',0x5:'Multiple\x20Surplus\x20sharing\x20in\x20a\x20single\x20Allocator',0x6:'Rate\x20+\x20Surplus\x20sum\x20>\x2010000',0x7:'balance\x20<\x20threshold\x20(insufficient\x20balance\x20to\x20trigger\x20alloc)',0x8:'allocators.allocators\x20is\x20empty',0x9:'payment_info\x20is\x20None\x20when\x20alloc()\x20is\x20called',0xa:'sharing\x20count\x20exceeds\x20MAX_SHARING_COUNT\x20(100)',0xb:'sharing\x20mode\x20is\x20not\x200\x20(Amount)\x20/\x201\x20(Rate)\x20/\x202\x20(Surplus)\x20/\x203\x20(RateGross)\x20/\x204\x20(Formula)',0xc:'Amount\x20sum\x20(fix)\x20<\x20threshold',0xd:'Amount\x20sum\x20(fix)\x20>\x20max',0xe:'distribution\x20computes\x20to\x20zero\x20while\x20the\x20pool\x20still\x20holds\x20funds\x20(or\x20balance\x20is\x200)',0xf:'GuardIdentifier\x20recipient\x20address\x20!=\x20payment_info.for_object\x20anchor\x20(abort\x20fires\x20only\x20when\x20a\x20for_object\x20binding\x20is\x20declared)',0x10:'once-trigger\x20key\x20already\x20consumed\x20—\x20the\x20guard\x20submitted\x20the\x20reserved\x20identifier\x20255\x20and\x20its\x20raw\x20submission\x20bytes\x20were\x20recorded\x20as\x20a\x20(guard,\x20allocator\x20index,\x20raw\x20bytes)\x20dynamic-field\x20key\x20on\x20this\x20Allocation',0x11:'mixed\x20rate\x20bases\x20—\x20one\x20allocator\x20carries\x20both\x20NET\x20Rate\x20and\x20RateGross\x20entries\x20while\x20a\x20fixed\x20Amount\x20total\x20is\x20present\x20(rejected\x20only\x20when\x20fix\x20>\x200;\x20with\x20fix\x20==\x200\x20the\x20two\x20bases\x20coincide\x20and\x20mixing\x20is\x20allowed)',0x12:'RateGross\x20+\x20fixed\x20Amount\x20without\x20a\x20max\x20cap\x20—\x20plan\x20payability\x20unprovable\x20at\x20declaration\x20time',0x13:'guard\x20not\x20bound\x20to\x20any\x20allocator\x20on\x20this\x20Allocation\x20(was\x20a\x20silent\x20no-op\x20success\x20before)',0x14:'allocator\x20append\x20rejected:\x20new\x20Allocators\x20is\x20not\x20a\x20pure\x20extension\x20(prefix/threshold\x20changed)',0x15:'once-for-object\x20slot\x20(identifier\x20254)\x20armed\x20but\x20payment_info\x20declares\x20no\x20for_object\x20binding',0x18:'FormulaSpec\x20rejected:\x20selector\x20is\x20not\x20COUNT(0)/SUM(1),\x20allocator/slot\x20index\x20out\x20of\x20range,\x20or\x20the\x20target\x20sharing\x20slot\x20is\x20not\x20a\x20Formula\x20(mode\x204)\x20leg'};return b[a];}
@@ -26,9 +26,13 @@ export interface RailNodeInput {
26
26
  name: string;
27
27
  semanticRole?: string;
28
28
  }
29
- export type RailFindingCode = "RAIL_TERMINAL_UNCOVERED" | "RAIL_AWARD_EXIT_MISSING" | "RAIL_POLARITY_COLLISION" | "RAIL_DEAD_LITERAL";
29
+ export type RailFindingCode = "RAIL_TERMINAL_UNCOVERED" | "RAIL_AWARD_EXIT_MISSING" | "RAIL_POLARITY_COLLISION" | "RAIL_DEAD_LITERAL" | "RAIL_RULING_WINDOW";
30
+ export type RailFindingLevel = "critical" | "info";
30
31
  export interface RailFinding {
31
32
  code: RailFindingCode;
33
+ level: RailFindingLevel;
32
34
  detail: string;
33
35
  }
34
- export declare function verifyAllocatorRails(guards: RailGuardInput[], nodes: RailNodeInput[]): RailFinding[];
36
+ export declare function verifyAllocatorRails(guards: RailGuardInput[], nodes: RailNodeInput[], opts?: {
37
+ arbitrationBound?: boolean;
38
+ }): RailFinding[];
@@ -1 +1 @@
1
- const SYM_NODE='progress.current',SYM_CLAIMED='order.claimed_by\x20some';function slotValue(a,b){if(b===undefined)return{'value':undefined,'isSubmission':![]};const c=a['find'](d=>d['identifier']===b);if(!c)return{'value':undefined,'isSubmission':![]};return{'value':c['value'],'isSubmission':c['b_submission']===!![]};}function classifyQueryLhs(a){if(a===SYM_NODE)return{'kind':'node'};if(a===SYM_CLAIMED)return{'kind':'claimed'};return{'kind':'unknown'};}function resolveValue(a,b){if(!b||b['type']!=='identifier')return{'known':![]};const c=slotValue(a,b['identifier']);if(c['isSubmission'])return{'known':![]};if(c['value']===undefined)return{'known':![]};return{'known':!![],'value':c['value']};}function evaluate(a,b,d){if(!b||typeof b['type']!=='string')return undefined;switch(b['type']){case'logic_and':{const e=Array['isArray'](b['nodes'])?b['nodes']:[];let f=![];for(const g of e){const h=evaluate(a,g,d);if(h===![])return![];if(h===undefined)f=!![];}return f?undefined:!![];}case'logic_or':{const i=Array['isArray'](b['nodes'])?b['nodes']:[];let j=![];for(const k of i){const l=evaluate(a,k,d);if(l===!![])return!![];if(l===undefined)j=!![];}return j?undefined:![];}case'logic_not':{const m=evaluate(a,b['node'],d);if(m===undefined)return undefined;return!m;}case'logic_equal':{const n=Array['isArray'](b['nodes'])?b['nodes']:[];if(n['length']<0x2)return undefined;const o=classifyQueryLhs(n[0x0]?.['query']),p=resolveValue(a,n[0x1]),q=o['kind']==='unknown'?classifyQueryLhs(n[0x1]?.['query']):o,r=!p['known']&&n[0x1]?.['query']!==undefined?resolveValue(a,n[0x0]):p;if(q['kind']==='node'){if(!r['known']||typeof r['value']!=='string')return undefined;return d['node']===r['value'];}if(q['kind']==='claimed'){if(!r['known']||typeof r['value']!=='boolean')return undefined;return d['claimed']===r['value'];}return undefined;}default:return undefined;}}function satisfiable(a,b,c){return evaluate(a,b,c)!==![];}function findDeadLiterals(a,b,c,d){if(!a||typeof a['type']!=='string')return;if(a['type']==='logic_and'&&Array['isArray'](a['nodes'])){const e=new Map();for(const f of a['nodes']){const g=resolvableEquality(f,b);if(g)e['set'](g['symbol'],g['value']);}for(const h of a['nodes']){const i=resolvableEquality(h,b);if(i){const k=e['get'](i['symbol']);if(k!==undefined&&k!==i['value']){d['push']({'code':'RAIL_DEAD_LITERAL','detail':deadLiteralDetail(c,i['symbol'],k,i['value'])});return;}continue;}const j=findClash(h,b,e);if(j){d['push']({'code':'RAIL_DEAD_LITERAL','detail':deadLiteralDetail(c,j['symbol'],j['pinned'],j['value'])});return;}}for(const l of a['nodes'])findDeadLiterals(l,b,c,d);return;}if(Array['isArray'](a['nodes'])){for(const m of a['nodes'])findDeadLiterals(m,b,c,d);}if(a['node'])findDeadLiterals(a['node'],b,c,d);}function resolvableEquality(c,d){if(!c||c['type']!=='logic_equal'||!Array['isArray'](c['nodes']))return undefined;for(const [e,f]of[[c['nodes'][0x0],c['nodes'][0x1]],[c['nodes'][0x1],c['nodes'][0x0]]]){if(!e||typeof e['query']!=='string')continue;const g=classifyQueryLhs(e['query']);if(g['kind']==='unknown')continue;const h=resolveValue(d,f);if(!h['known'])continue;return{'symbol':g['kind']==='node'?SYM_NODE:SYM_CLAIMED,'value':h['value']};}return undefined;}function findClash(a,b,c){if(!a||typeof a['type']!=='string')return undefined;if(a['type']==='logic_not')return undefined;const d=resolvableEquality(a,b);if(d){const e=c['get'](d['symbol']);if(e!==undefined&&e!==d['value'])return{'symbol':d['symbol'],'pinned':e,'value':d['value']};return undefined;}if(Array['isArray'](a['nodes']))for(const f of a['nodes']){const g=findClash(f,b,c);if(g)return g;}if(a['node'])return findClash(a['node'],b,c);return undefined;}function deadLiteralDetail(a,b,c,d){return'allocator\x20guard\x20\x27'+a+'\x27:\x20one\x20conjunction\x20scope\x20carries\x20'+b+'\x20'+('==\x20'+JSON['stringify'](c)+'\x20and\x20ALSO\x20'+b+'\x20==\x20'+JSON['stringify'](d)+'\x20—\x20the\x20second\x20')+'literal\x20contradicts\x20the\x20first\x20and\x20is\x20a\x20DEAD\x20literal\x20(azx7-mn-261014\x20CR-azx7-01:\x20a\x20pinned\x20'+'node\x20equality\x20made\x20the\x20sibling\x20closed_cancel/item_lost\x20legs\x20unreachable,\x20stranding\x20the\x20'+'escrow\x20at\x20every\x20other\x20terminal).\x20Hoist\x20the\x20node\x20predicate\x20to\x20ONE\x20top-level\x20n-ary\x20logic_or\x20'+'instead\x20of\x20AND-prepending\x20a\x20single-node\x20gate.';}export function verifyAllocatorRails(a,b){const c=[];if(a['length']===0x0||b['length']===0x0)return c;const d=b['filter'](i=>i['semanticRole']==='cancelled'||i['semanticRole']==='final'),e=b['map'](i=>({'node':i['name'],'claimed':!![]}));for(const i of a){if(i['root']===undefined)continue;const j=i['table'];findDeadLiterals(i['root'],j,i['key'],c);}for(const k of d){const l={'node':k['name'],'claimed':![]},m=a['some'](n=>satisfiable(n['table'],n['root'],l));!m&&c['push']({'code':'RAIL_TERMINAL_UNCOVERED','detail':'terminal\x20node\x20\x27'+k['name']+'\x27\x20(role\x20'+k['semanticRole']+')\x20has\x20NO\x20allocator\x20rail\x20'+'satisfiable\x20at\x20claimed_by=none\x20—\x20a\x20normal\x20(unclaimed)\x20order\x20reaching\x20this\x20'+'terminal\x20strands\x20its\x20escrow\x20forever\x20(azx7-mn-261014\x20CR-azx7-01:\x20refund\x20'+'rejected\x20abort\x207\x20at\x20closed_cancel/item_lost;\x20crs-mn-261014\x20F-30:\x20double-'+'negated\x20claimed_by\x20leg\x20bricked\x20the\x20refund\x20at\x20returned).\x20Guards/allocators\x20'+'freeze\x20at\x20publish\x20—\x20fix\x20the\x20rail\x20polarity/node-set\x20BEFORE\x20publishing.'});}const f=a['some'](n=>e['some'](o=>satisfiable(n['table'],n['root'],o)));!f&&c['push']({'code':'RAIL_AWARD_EXIT_MISSING','detail':'no\x20allocator\x20rail\x20is\x20satisfiable\x20at\x20claimed_by=some\x20on\x20ANY\x20machine\x20node\x20—\x20an\x20'+'arbitration-paid\x20order\x20has\x20NO\x20escrow\x20exit\x20(escrow-exit\x20invariant,\x20az-mn-261007).\x20'+'Pair\x20the\x20refund\x20rail\x20with\x20a\x20merchant-recovery\x20allocator\x20asserting\x20order.claimed_by\x20'+'some\x20==\x20true\x20(query\x201570)\x20on\x20the\x20post-delivery\x20node\x20set.'});const h=a['filter'](n=>n['root']!==undefined);for(const n of e){const o=h['some'](q=>q['track']==='refund'&&satisfiable(q['table'],q['root'],n));if(!o)continue;const p=a['some'](q=>claimedTrueLegPasses(q,n));p&&c['push']({'code':'RAIL_POLARITY_COLLISION','detail':'at\x20node\x20\x27'+n['node']+'\x27\x20with\x20claimed_by=some,\x20BOTH\x20a\x20refund-track\x20rail\x20and\x20an\x20'+'award-polarity\x20rail\x20(claimed_by\x20some\x20==\x20true)\x20are\x20satisfiable\x20—\x20the\x20pairing\x20'+'can\x20double-pay\x20the\x20same\x20escrow\x20(crs-mn-261014\x20F-30:\x20the\x20double-negated\x20refund\x20'+'leg\x20passed\x20only\x20AFTER\x20the\x20award\x20paid;\x20dry-run\x20simulated\x20the\x20escrow\x20draining\x20'+'on\x20top\x20of\x20a\x20paid\x20ruling).\x20The\x20refund\x20leg\x20must\x20be\x20logic_equal[query\x20'+'\x27order.claimed_by\x20some\x27,\x20Bool\x20false]\x20—\x20never\x20logic_not(query)==false.'});}return c;}function claimedTrueLegPasses(a,b){const c=a['table'],d={'node':b['node'],'claimed':!![]};return satisfiable(c,a['root'],d)&&!satisfiable(c,a['root'],{'node':b['node'],'claimed':![]});}
1
+ const SYM_NODE='progress.current',SYM_CLAIMED='order.claimed_by\x20some';function slotValue(a,b){if(b===undefined)return{'value':undefined,'isSubmission':![]};const c=a['find'](d=>d['identifier']===b);if(!c)return{'value':undefined,'isSubmission':![]};return{'value':c['value'],'isSubmission':c['b_submission']===!![]};}function classifyQueryLhs(a){if(a===SYM_NODE)return{'kind':'node'};if(a===SYM_CLAIMED)return{'kind':'claimed'};return{'kind':'unknown'};}function resolveValue(a,b){if(!b||b['type']!=='identifier')return{'known':![]};const c=slotValue(a,b['identifier']);if(c['isSubmission'])return{'known':![]};if(c['value']===undefined)return{'known':![]};return{'known':!![],'value':c['value']};}function evaluate(a,b,d){if(!b||typeof b['type']!=='string')return undefined;switch(b['type']){case'logic_and':{const e=Array['isArray'](b['nodes'])?b['nodes']:[];let f=![];for(const g of e){const h=evaluate(a,g,d);if(h===![])return![];if(h===undefined)f=!![];}return f?undefined:!![];}case'logic_or':{const i=Array['isArray'](b['nodes'])?b['nodes']:[];let j=![];for(const k of i){const l=evaluate(a,k,d);if(l===!![])return!![];if(l===undefined)j=!![];}return j?undefined:![];}case'logic_not':{const m=evaluate(a,b['node'],d);if(m===undefined)return undefined;return!m;}case'logic_equal':{const n=Array['isArray'](b['nodes'])?b['nodes']:[];if(n['length']<0x2)return undefined;const o=classifyQueryLhs(n[0x0]?.['query']),p=resolveValue(a,n[0x1]),q=o['kind']==='unknown'?classifyQueryLhs(n[0x1]?.['query']):o,r=!p['known']&&n[0x1]?.['query']!==undefined?resolveValue(a,n[0x0]):p;if(q['kind']==='node'){if(!r['known']||typeof r['value']!=='string')return undefined;return d['node']===r['value'];}if(q['kind']==='claimed'){if(!r['known']||typeof r['value']!=='boolean')return undefined;return d['claimed']===r['value'];}return undefined;}default:return undefined;}}function satisfiable(a,b,c){return evaluate(a,b,c)!==![];}function findDeadLiterals(a,b,c,d){if(!a||typeof a['type']!=='string')return;if(a['type']==='logic_and'&&Array['isArray'](a['nodes'])){const e=new Map();for(const f of a['nodes']){const g=resolvableEquality(f,b);if(g)e['set'](g['symbol'],g['value']);}for(const h of a['nodes']){const i=resolvableEquality(h,b);if(i){const k=e['get'](i['symbol']);if(k!==undefined&&k!==i['value']){d['push']({'code':'RAIL_DEAD_LITERAL','level':'critical','detail':deadLiteralDetail(c,i['symbol'],k,i['value'])});return;}continue;}const j=findClash(h,b,e);if(j){d['push']({'code':'RAIL_DEAD_LITERAL','level':'critical','detail':deadLiteralDetail(c,j['symbol'],j['pinned'],j['value'])});return;}}for(const l of a['nodes'])findDeadLiterals(l,b,c,d);return;}if(Array['isArray'](a['nodes'])){for(const m of a['nodes'])findDeadLiterals(m,b,c,d);}if(a['node'])findDeadLiterals(a['node'],b,c,d);}function resolvableEquality(c,d){if(!c||c['type']!=='logic_equal'||!Array['isArray'](c['nodes']))return undefined;for(const [e,f]of[[c['nodes'][0x0],c['nodes'][0x1]],[c['nodes'][0x1],c['nodes'][0x0]]]){if(!e||typeof e['query']!=='string')continue;const g=classifyQueryLhs(e['query']);if(g['kind']==='unknown')continue;const h=resolveValue(d,f);if(!h['known'])continue;return{'symbol':g['kind']==='node'?SYM_NODE:SYM_CLAIMED,'value':h['value']};}return undefined;}function findClash(a,b,c){if(!a||typeof a['type']!=='string')return undefined;if(a['type']==='logic_not')return undefined;const d=resolvableEquality(a,b);if(d){const e=c['get'](d['symbol']);if(e!==undefined&&e!==d['value'])return{'symbol':d['symbol'],'pinned':e,'value':d['value']};return undefined;}if(Array['isArray'](a['nodes']))for(const f of a['nodes']){const g=findClash(f,b,c);if(g)return g;}if(a['node'])return findClash(a['node'],b,c);return undefined;}function deadLiteralDetail(a,b,c,d){return'allocator\x20guard\x20\x27'+a+'\x27:\x20one\x20conjunction\x20scope\x20carries\x20'+b+'\x20'+('==\x20'+JSON['stringify'](c)+'\x20and\x20ALSO\x20'+b+'\x20==\x20'+JSON['stringify'](d)+'\x20—\x20the\x20second\x20')+'literal\x20contradicts\x20the\x20first\x20and\x20is\x20a\x20DEAD\x20literal\x20(azx7-mn-261014\x20CR-azx7-01:\x20a\x20pinned\x20'+'node\x20equality\x20made\x20the\x20sibling\x20closed_cancel/item_lost\x20legs\x20unreachable,\x20stranding\x20the\x20'+'escrow\x20at\x20every\x20other\x20terminal).\x20Hoist\x20the\x20node\x20predicate\x20to\x20ONE\x20top-level\x20n-ary\x20logic_or\x20'+'instead\x20of\x20AND-prepending\x20a\x20single-node\x20gate.';}function hasArbitrationEvidenceLeg(a){if(!a||typeof a!=='object')return![];const b=a;if(typeof b['query']==='string'){const d=b['query'];return d['startsWith']('arb.')||d['startsWith']('order.dispute');}if(Array['isArray'](b['nodes'])){for(const e of b['nodes'])if(hasArbitrationEvidenceLeg(e))return!![];}if(b['node']&&hasArbitrationEvidenceLeg(b['node']))return!![];return![];}export function verifyAllocatorRails(a,b,c){const d=[];if(a['length']===0x0)return d;if(c?.['arbitrationBound']===!![]){const j=a['filter'](k=>k['track']==='refund'&&k['root']!==undefined&&!hasArbitrationEvidenceLeg(k['root']))['map'](k=>k['key']);j['length']>0x0&&d['push']({'code':'RAIL_RULING_WINDOW','level':'info','detail':'refund\x20rail(s)\x20['+j['join'](',\x20')+']\x20carry\x20no\x20arbitration-side\x20evidence\x20leg\x20'+'(arb.*\x20/\x20order.dispute*)\x20—\x20the\x20\x22ruled\x20but\x20unclaimed\x22\x20window\x20stays\x20open:\x20after\x20a\x20'+'buyer-favored\x20ruling\x20awards\x20compensation\x20but\x20BEFORE\x20the\x20claim/conclude\x20stamps\x20'+'order.claimed_by,\x20the\x20claimed_by-none\x20refund\x20route\x20can\x20still\x20drain\x20the\x20escrow\x20'+'(dual-track\x20overlap\x20is\x20a\x20LEGITIMATE\x20chain-allowed\x20commercial\x20shape,\x20order.move\x20'+'merchant\x27s-choice\x20note\x20—\x20disclosure,\x20not\x20a\x20violation).\x20To\x20close\x20it,\x20gate\x20the\x20rail\x20'+'on\x20ruling\x20evidence\x20(arb.indemnity\x20legs)\x20—\x20buildable\x20ONLY\x20when\x20this\x20rail\x20is\x20reachable\x20'+'exclusively\x20from\x20dispute-state\x20nodes,\x20or\x20sequence\x20the\x20edge\x20behind\x20the\x20claimed_by\x20stamp\x20'+'(tpl_forward_arb_ruling_won/dismissed\x204R-03b\x20form).\x20See\x20pattern.arb_status_escrow_holdback.'});}if(b['length']===0x0)return d;const e=b['filter'](k=>k['semanticRole']==='cancelled'||k['semanticRole']==='final'),f=b['map'](k=>({'node':k['name'],'claimed':!![]}));for(const k of a){if(k['root']===undefined)continue;const l=k['table'];findDeadLiterals(k['root'],l,k['key'],d);}for(const m of e){const n={'node':m['name'],'claimed':![]},o=a['some'](p=>satisfiable(p['table'],p['root'],n));!o&&d['push']({'code':'RAIL_TERMINAL_UNCOVERED','level':'critical','detail':'terminal\x20node\x20\x27'+m['name']+'\x27\x20(role\x20'+m['semanticRole']+')\x20has\x20NO\x20allocator\x20rail\x20'+'satisfiable\x20at\x20claimed_by=none\x20—\x20a\x20normal\x20(unclaimed)\x20order\x20reaching\x20this\x20'+'terminal\x20strands\x20its\x20escrow\x20forever\x20(azx7-mn-261014\x20CR-azx7-01:\x20refund\x20'+'rejected\x20abort\x207\x20at\x20closed_cancel/item_lost;\x20crs-mn-261014\x20F-30:\x20double-'+'negated\x20claimed_by\x20leg\x20bricked\x20the\x20refund\x20at\x20returned).\x20Guards/allocators\x20'+'freeze\x20at\x20publish\x20—\x20fix\x20the\x20rail\x20polarity/node-set\x20BEFORE\x20publishing.'});}const h=a['some'](p=>f['some'](q=>satisfiable(p['table'],p['root'],q)));!h&&d['push']({'code':'RAIL_AWARD_EXIT_MISSING','level':'critical','detail':'no\x20allocator\x20rail\x20is\x20satisfiable\x20at\x20claimed_by=some\x20on\x20ANY\x20machine\x20node\x20—\x20an\x20'+'arbitration-paid\x20order\x20has\x20NO\x20escrow\x20exit\x20(escrow-exit\x20invariant,\x20az-mn-261007).\x20'+'Pair\x20the\x20refund\x20rail\x20with\x20a\x20merchant-recovery\x20allocator\x20asserting\x20order.claimed_by\x20'+'some\x20==\x20true\x20(query\x201570)\x20on\x20the\x20post-delivery\x20node\x20set.\x20R2-05\x20DISMISSAL-STAMP\x20CAUTION\x20'+'(alg26-tn-261026\x20O11):\x20a\x20concluded\x20DISMISSAL\x20(indemnity=0)\x20ALSO\x20stamps\x20order.claimed_by\x20'+'(service.move:1703-1711\x20—\x20permissionless\x20keeper\x20conclude;\x20on\x20protocol\x20>=\x20154\x20the\x20ruled-zero\x20'+'seal\x20closes\x20claimed_by-none\x20refund\x20rails\x20BY\x20DESIGN,\x20F-BS-54/56).\x20A\x20recover\x20rail\x20discriminated\x20'+'ONLY\x20on\x20the\x20bare\x20order\x20stamp\x20routes\x20to\x20its\x20STATIC\x20recipient\x20regardless\x20of\x20the\x20ruling\x20direction\x20—\x20'+'under\x20a\x20dismissal\x20that\x20static\x20recipient\x20can\x20be\x20the\x20LOSING\x20party\x20(O11:\x20assignee\x20took\x200.15\x20after\x20'+'losing).\x20Split\x20the\x20recover\x20rail\x20by\x20arb\x20outcome\x20or\x20bind\x20its\x20recipient\x20to\x20the\x20winning\x20side\x20—\x20'+'discriminate\x20on\x20the\x20arb-side\x20award\x20(indemnity\x20>\x200\x20/\x20award-claimed\x20polarity),\x20never\x20the\x20bare\x20'+'order\x20stamp:\x20\x27claimed_by\x20some\x20⇒\x20recover-safe\x27\x20holds\x20ONLY\x20when\x20indemnity\x20>\x200.'});const i=a['filter'](p=>p['root']!==undefined);for(const p of f){const q=i['some'](u=>u['track']==='refund'&&satisfiable(u['table'],u['root'],p));if(!q)continue;const r=a['some'](u=>claimedTrueLegPasses(u,p));r&&d['push']({'code':'RAIL_POLARITY_COLLISION','level':'critical','detail':'at\x20node\x20\x27'+p['node']+'\x27\x20with\x20claimed_by=some,\x20BOTH\x20a\x20refund-track\x20rail\x20and\x20an\x20'+'award-polarity\x20rail\x20(claimed_by\x20some\x20==\x20true)\x20are\x20satisfiable\x20—\x20the\x20pairing\x20'+'can\x20double-pay\x20the\x20same\x20escrow\x20(crs-mn-261014\x20F-30:\x20the\x20double-negated\x20refund\x20'+'leg\x20passed\x20only\x20AFTER\x20the\x20award\x20paid;\x20dry-run\x20simulated\x20the\x20escrow\x20draining\x20'+'on\x20top\x20of\x20a\x20paid\x20ruling).\x20The\x20refund\x20leg\x20must\x20be\x20logic_equal[query\x20'+'\x27order.claimed_by\x20some\x27,\x20Bool\x20false]\x20—\x20never\x20logic_not(query)==false.'});}return d;}function claimedTrueLegPasses(a,b){const c=a['table'],d={'node':b['node'],'claimed':!![]};return satisfiable(c,a['root'],d)&&!satisfiable(c,a['root'],{'node':b['node'],'claimed':![]});}