@wowok/agent-mcp 3.2.3 → 3.2.6

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 (130) hide show
  1. package/dist/chain-semantics/field-capability.js +1 -1
  2. package/dist/chain-semantics/freeze-map.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/communication/proof-reuse.d.ts +9 -0
  6. package/dist/communication/proof-reuse.js +1 -0
  7. package/dist/composition/blueprint-view.d.ts +64 -0
  8. package/dist/composition/blueprint-view.js +1 -0
  9. package/dist/evaluation/builtins/graph-service.spec.js +1 -1
  10. package/dist/evaluation/engine.js +1 -1
  11. package/dist/experience/realtime-feedback.js +1 -1
  12. package/dist/extensions/industry-pack.d.ts +1 -0
  13. package/dist/extensions/industry-pack.js +1 -1
  14. package/dist/extensions/modes.js +1 -1
  15. package/dist/extensions/registry.d.ts +1 -2
  16. package/dist/extensions/registry.js +1 -1
  17. package/dist/graph/onchain/expand.js +1 -1
  18. package/dist/graph/onchain/exposure.js +1 -1
  19. package/dist/graph/onchain/facts.js +1 -1
  20. package/dist/harness/recover.js +1 -1
  21. package/dist/knowledge/allocation-ledger.js +1 -1
  22. package/dist/knowledge/audit-rules.d.ts +2 -0
  23. package/dist/knowledge/audit-rules.js +1 -1
  24. package/dist/knowledge/baselines/rules/allocation.json +5 -5
  25. package/dist/knowledge/baselines/rules/arb.json +1 -1
  26. package/dist/knowledge/baselines/rules/guard.json +9 -9
  27. package/dist/knowledge/baselines/rules/machine.json +5 -5
  28. package/dist/knowledge/baselines/rules/order.json +1 -1
  29. package/dist/knowledge/builtin-templates.d.ts +2 -1
  30. package/dist/knowledge/builtin-templates.js +1 -1
  31. package/dist/knowledge/entity-recipient-guard.js +1 -1
  32. package/dist/knowledge/getting-started.js +1 -1
  33. package/dist/knowledge/guard-bindings.js +1 -1
  34. package/dist/knowledge/guard-design-patterns.d.ts +1 -1
  35. package/dist/knowledge/guard-design-patterns.js +1 -1
  36. package/dist/knowledge/guard-ledger.js +1 -1
  37. package/dist/knowledge/guard-risk.js +1 -1
  38. package/dist/knowledge/guard-templates.d.ts +1 -1
  39. package/dist/knowledge/guard-templates.js +1 -1
  40. package/dist/knowledge/index.js +1 -1
  41. package/dist/knowledge/industry-generalizer.js +1 -1
  42. package/dist/knowledge/industry-registry.js +1 -1
  43. package/dist/knowledge/jsonrpc-enum.js +1 -1
  44. package/dist/knowledge/machine-ledger.js +1 -1
  45. package/dist/knowledge/machine-templates.js +1 -1
  46. package/dist/knowledge/order-ledger.js +1 -1
  47. package/dist/knowledge/progress-ledger.js +1 -1
  48. package/dist/knowledge/scenario-modes.d.ts +3 -4
  49. package/dist/knowledge/scenario-modes.js +1 -1
  50. package/dist/knowledge/service-ledger.js +1 -1
  51. package/dist/knowledge/service-templates.js +1 -1
  52. package/dist/knowledge/template-loader.d.ts +8 -2
  53. package/dist/knowledge/template-loader.js +1 -1
  54. package/dist/knowledge/template-registry.js +1 -1
  55. package/dist/knowledge/template-scanner.js +1 -1
  56. package/dist/knowledge/template-validation.d.ts +2 -0
  57. package/dist/knowledge/template-validation.js +1 -0
  58. package/dist/monitor/MonitorLoop.js +1 -1
  59. package/dist/participation/radar-core.js +1 -1
  60. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  61. package/dist/playbooks/service-build/game-theory.d.ts +2 -2
  62. package/dist/playbooks/service-build/game-theory.js +1 -1
  63. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  64. package/dist/playbooks/service-build/merchant-guide.d.ts +54 -11
  65. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  66. package/dist/playbooks/service-build/mode-actions.js +1 -1
  67. package/dist/playbooks/service-build/object-panorama.js +1 -1
  68. package/dist/playbooks/service-build/participation-radar.js +1 -1
  69. package/dist/playbooks/service-build/relationship-profile.js +1 -1
  70. package/dist/playbooks/service-build/reverse-mapping-nk4.spec.d.ts +1 -0
  71. package/dist/playbooks/service-build/reverse-mapping-nk4.spec.js +1 -0
  72. package/dist/playbooks/service-build/reverse-mapping.d.ts +24 -0
  73. package/dist/playbooks/service-build/reverse-mapping.js +1 -1
  74. package/dist/playbooks/service-build/service-panorama.js +1 -1
  75. package/dist/playbooks/service-build/service-quote.js +1 -1
  76. package/dist/playbooks/service-build/service-quote.spec.d.ts +1 -0
  77. package/dist/playbooks/service-build/service-quote.spec.js +1 -0
  78. package/dist/playbooks/service-build/workflow-design-assessment.d.ts +2 -2
  79. package/dist/playbooks/service-build/workflow-design-assessment.js +1 -1
  80. package/dist/review/index.js +1 -1
  81. package/dist/safety/confirm-gate.js +1 -1
  82. package/dist/schema/call/arbitration.js +1 -1
  83. package/dist/schema/call/base.d.ts +4 -0
  84. package/dist/schema/call/base.js +1 -1
  85. package/dist/schema/call/bridge.d.ts +1 -0
  86. package/dist/schema/call/error-codes.d.ts +1 -1
  87. package/dist/schema/call/error-codes.js +1 -1
  88. package/dist/schema/call/handler.js +1 -1
  89. package/dist/schema/call/machine.js +1 -1
  90. package/dist/schema/call/semantic.js +1 -1
  91. package/dist/schema/call/service.d.ts +14 -0
  92. package/dist/schema/call/service.js +1 -1
  93. package/dist/schema/common/index.js +1 -1
  94. package/dist/schema/goal/planning.js +1 -1
  95. package/dist/schema/interaction/index.d.ts +1 -1
  96. package/dist/schema/local/index.d.ts +10 -0
  97. package/dist/schema/local/index.js +1 -1
  98. package/dist/schema/operations.d.ts +7 -0
  99. package/dist/schema/query/bi.d.ts +26 -0
  100. package/dist/schema/query/bi.js +1 -1
  101. package/dist/schema/schema-version.js +1 -1
  102. package/dist/schema-query-impl/index.js +1 -1
  103. package/dist/schemas/account_operation.output.json +1 -0
  104. package/dist/schemas/bridge_operation.output.json +1 -0
  105. package/dist/schemas/goal_operation.schema.json +1 -1
  106. package/dist/schemas/index.json +1 -1
  107. package/dist/schemas/local_cache_operation.output.json +1 -0
  108. package/dist/schemas/local_history_operation.output.json +1 -0
  109. package/dist/schemas/local_info_operation.output.json +1 -0
  110. package/dist/schemas/local_mark_operation.output.json +1 -0
  111. package/dist/schemas/onchain_operations.output.json +1 -0
  112. package/dist/schemas/onchain_operations.schema.json +40 -5
  113. package/dist/schemas/onchain_operations_arbitration.schema.json +1 -1
  114. package/dist/schemas/onchain_operations_machine.schema.json +1 -1
  115. package/dist/schemas/onchain_operations_service.schema.json +38 -3
  116. package/dist/schemas/query_toolkit.output.json +91 -7
  117. package/dist/tools/handlers/benchmark-migration.d.ts +2 -13
  118. package/dist/tools/handlers/benchmark-migration.js +1 -1
  119. package/dist/tools/handlers/config.js +1 -1
  120. package/dist/tools/handlers/industry-pack.js +1 -1
  121. package/dist/tools/handlers/messenger.js +1 -1
  122. package/dist/tools/handlers/onchain.js +1 -1
  123. package/dist/tools/handlers/query.js +1 -1
  124. package/dist/tools/move-fn-index.gen.js +1 -1
  125. package/dist/tools/registry/agent.js +1 -1
  126. package/dist/tools/wip-deploy-assist.js +1 -1
  127. package/dist/tools/wrap.js +1 -1
  128. package/package.json +2 -2
  129. package/dist/playbooks/service-build/semantic-graph.d.ts +0 -99
  130. package/dist/playbooks/service-build/semantic-graph.js +0 -1
@@ -1 +1 @@
1
- import{initServicePuzzleFromIntent,initMachinePuzzleFromIntent,initAllocationPuzzleFromIntent,initTreasuryPuzzleFromIntent,initArbitrationPuzzleFromIntent,initRewardPuzzleFromIntent,initProgressPuzzleFromIntent,initOrderPuzzleFromIntent,initPuzzleFromIntent as a310a,checkServicePuzzleCompleteness,checkMachinePuzzleCompleteness,checkAllocationPuzzleCompleteness,checkTreasuryPuzzleCompleteness,checkArbitrationPuzzleCompleteness,checkRewardPuzzleCompleteness,checkProgressPuzzleCompleteness,checkOrderPuzzleCompleteness,checkPuzzleCompleteness as a310b}from'../../knowledge/index.js';import{initPuzzleFromIntent as a310c,checkPuzzleCompleteness as a310d}from'../../knowledge/permission-puzzle.js';const KEYWORD_TABLE=[{'category':'Product/Service','keywords_zh':['product','selling','sell','sales','store','open\x20shop'],'keywords_en':['sell','product','sale','shop','store'],'objects':['service','order','progress'],'required_level':'R','scene_id':'retail'},{'category':'Subscription','keywords_zh':['subscription','cycle','renewal'],'keywords_en':['subscribe','recurring','subscription'],'objects':['service','machine','reward'],'required_level':'C','scene_id':'subscription'},{'category':'Rental','keywords_zh':['rent','lease','return'],'keywords_en':['rent','lease','return'],'objects':['service','machine','arb'],'required_level':'C','scene_id':'rental_return'},{'category':'Trust','keywords_zh':['deposit','pledge','verify','trust'],'keywords_en':['deposit','trust','verify'],'objects':['guard','permission','treasury'],'required_level':'R','scene_id':'trust_deposit'},{'category':'Funds','keywords_zh':['split','collect','share\x20profit','income','incentive'],'keywords_en':['split','revenue','reward'],'objects':['allocation','treasury','reward'],'required_level':'R','scene_id':'revenue_split'},{'category':'Workflow','keywords_zh':['node','stage','process','workflow'],'keywords_en':['workflow','stage','node'],'objects':['machine','progress'],'required_level':'R','scene_id':'workflow'},{'category':'Dispute','keywords_zh':['arbitration','refund','conflict','rights\x20protection'],'keywords_en':['arbitration','refund','dispute'],'objects':['arb','proof'],'required_level':'C','scene_id':'arbitration_dispute'},{'category':'Contact','keywords_zh':['customer\x20service','contact','communication'],'keywords_en':['contact','support','im'],'objects':['contact'],'required_level':'C','scene_id':'contact_im'},{'category':'Data','keywords_zh':['evidence','record','data'],'keywords_en':['evidence','record','data'],'objects':['repository','proof'],'required_level':'C','scene_id':'evidence_record'},{'category':'User\x20Profile','keywords_zh':['personal\x20info','preference','privacy'],'keywords_en':['personal','profile','privacy'],'objects':['personal','contact'],'required_level':'OPTIONAL','scene_id':'user_profile'},{'category':'Demand\x20Submission','keywords_zh':['demand','publish','inquiry'],'keywords_en':['demand','request','inquiry'],'objects':['demand'],'required_level':'OPTIONAL','scene_id':'demand_inquiry'}],INDUSTRY_KEYWORDS=[{'industry':'freelance','words':['freelance','outsourcing','freelance','gig']},{'industry':'rental','words':['rental','lease','rental','rent']},{'industry':'education','words':['education','course','training','education','course']},{'industry':'travel','words':['travel','tour','itinerary','travel','trip']},{'industry':'subscription','words':['subscription','cycle','subscription','recurring']}];function buildPuzzleDispatch(){const a=(c,d)=>{try{return c(d);}catch{return undefined;}},b=(c,d)=>{if(!c)return{'missing':[],'complete':![],'next_step':'init\x20failed'};try{return d(c);}catch{return{'missing':[],'complete':![],'next_step':'check\x20failed'};}};return{'service':{'init':c=>a(initServicePuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkServicePuzzleCompleteness)},'machine':{'init':c=>a(initMachinePuzzleFromIntent,c),'check':c=>b(c,checkMachinePuzzleCompleteness)},'allocation':{'init':c=>a(initAllocationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkAllocationPuzzleCompleteness)},'treasury':{'init':c=>a(initTreasuryPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkTreasuryPuzzleCompleteness)},'arb':{'init':c=>a(initArbitrationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkArbitrationPuzzleCompleteness)},'reward':{'init':c=>a(initRewardPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkRewardPuzzleCompleteness)},'progress':{'init':c=>a(initProgressPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkProgressPuzzleCompleteness)},'order':{'init':c=>a(initOrderPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkOrderPuzzleCompleteness)},'permission':{'init':c=>a(a310c,{'primary_goal':c}),'check':c=>b(c,a310d)},'guard':{'init':c=>a(a310a,{'primary_goal':c}),'check':c=>b(c,a310b)}};}export function extractKeywords(a){if(!a||typeof a!=='string')return[];const b=[];for(const c of KEYWORD_TABLE){const d=[...c['keywords_zh'],...c['keywords_en']];for(const e of d){try{const f=new RegExp(escapeRegex(e),'gi'),g=(a['match'](f)||[])['length'];g>0x0&&b['push']({'keyword':e,'category':c['category'],'matched_objects':[...c['objects']],'required_level':c['required_level'],'match_count':g});}catch{}}}return b['sort']((h,i)=>i['match_count']-h['match_count']),b;}function escapeRegex(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}export function resolveIndustry(a,b){const c=((a??'')+'\x20'+(b??''))['toLowerCase']();for(const d of INDUSTRY_KEYWORDS){for(const e of d['words']){if(c['includes'](e['toLowerCase']()))return d['industry'];}}return'general';}export function identifyObjects(a,b){if(b['length']===0x0)return{'primary':'service','secondary':['permission','machine','progress'],'scenes':[{'object':'service','scene_id':'general'}]};const c=b['find'](i=>i['required_level']==='R'),d=(c??b[0x0])['matched_objects'][0x0],e=new Set([d]),f=[];for(const i of b){for(const j of i['matched_objects']){!e['has'](j)&&(e['add'](j),f['push'](j));}}const g=[],h=new Set();for(const k of KEYWORD_TABLE){const l=b['find'](n=>n['category']===k['category']);if(!l)continue;if(h['has'](k['scene_id']))continue;h['add'](k['scene_id']),g['push']({'object':k['objects'][0x0],'scene_id':k['scene_id']});}return{'primary':d,'secondary':f,'scenes':g};}export function analyzeBusinessIntent(a){const b=[];if(!a||!a['user_intent']||typeof a['user_intent']!=='string')return{'intent_parsed':{'primary_object':'service','secondary_objects':[],'detected_scenes':[],'industry':'general','keyword_matches':[]},'puzzles':{},'overall_completeness':'empty','next_step':'Please\x20provide\x20a\x20non-empty\x20business\x20intent.','recommended_creation_order':[],'warnings':['input.user_intent\x20is\x20empty']};const c=a['user_intent'],e=extractKeywords(c),f=resolveIndustry(c,a['industry']),{primary:g,secondary:h,scenes:i}=identifyObjects(c,e);let j=[g,...h];if(a['target_objects']&&a['target_objects']['length']>0x0){const p=a['target_objects']['filter'](q=>['service','machine','guard','permission','reward','arb','progress','treasury','demand','repository','contact','order','allocation','personal','payment','proof']['includes'](q));if(p['length']>0x0)j=p;}const k=buildPuzzleDispatch(),l={};for(const q of j){const r=k[q];if(!r){b['push']('No\x20puzzle\x20module\x20for\x20\x27'+q+'\x27\x20—\x20skipped\x20(L3\x20object)');continue;}const s=r['init'](c),t=s?r['check'](s):undefined,u=extractMissingDimensions(t);l[q]={'puzzle':s,'completeness':t,'missing_dimensions':u},!s&&b['push']('Puzzle\x20init\x20failed\x20for\x20\x27'+q+'\x27');}const m=aggregatePuzzleCompleteness(l),n=suggestNextPuzzleStep({'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':'','recommended_creation_order':[],'warnings':b}),o=['permission','progress','machine','guard','allocation','service'];return{'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':n,'recommended_creation_order':o,'warnings':b};}function extractMissingDimensions(a){if(!a||typeof a!=='object')return[];const b=a,d=b['missing'];if(Array['isArray'](d))return d['map'](f=>String(f));const e=b['missing_details'];if(Array['isArray'](e))return e['map'](f=>String(f?.['dimension']??f));return[];}export function aggregatePuzzleCompleteness(a){const b=Object['values'](a??{});if(b['length']===0x0)return'empty';const c=b['filter'](f=>!f['puzzle'])['length'];if(c===b['length'])return'empty';const d=b['reduce']((f,g)=>f+(g['missing_dimensions']?.['length']??0x0),0x0);if(d===0x0)return'complete';return'partial';}export function suggestNextPuzzleStep(a){if(!a)return'No\x20result\x20to\x20suggest\x20from.';if(a['overall_completeness']==='complete')return'All\x20puzzle\x20dimensions\x20are\x20complete\x20—\x20ready\x20for\x20risk\x20calibration\x20(stage\x203).';if(a['overall_completeness']==='empty')return'No\x20puzzle\x20has\x20been\x20initialized.\x20Provide\x20more\x20concrete\x20business\x20intent\x20so\x20the\x20primary\x20object\x20can\x20be\x20identified.';const b=['permission','treasury','allocation','guard','machine','service','order','progress','arb','reward','proof','repository','demand','contact','personal','payment'],d=a['puzzles']??{},e=b['filter'](f=>d[f]);for(const f of e){const g=d[f];if(!g)continue;const h=g['missing_dimensions']??[];if(h['length']===0x0)continue;const i=g['completeness'],j=i&&typeof i==='object'?i['next_step']:undefined;if(typeof j==='string'&&j['trim']())return'['+f+']\x20'+j;return'['+f+']\x20Complete\x20dimension'+(h['length']>0x1?'s':'')+'\x20'+h['join'](',\x20')+'\x20to\x20advance\x20the\x20puzzle.';}return'Continue\x20dialog\x20to\x20fill\x20remaining\x20pending\x20fields.';}
1
+ import{initServicePuzzleFromIntent,initMachinePuzzleFromIntent,initAllocationPuzzleFromIntent,initTreasuryPuzzleFromIntent,initArbitrationPuzzleFromIntent,initRewardPuzzleFromIntent,initProgressPuzzleFromIntent,initOrderPuzzleFromIntent,initPuzzleFromIntent as a313a,checkServicePuzzleCompleteness,checkMachinePuzzleCompleteness,checkAllocationPuzzleCompleteness,checkTreasuryPuzzleCompleteness,checkArbitrationPuzzleCompleteness,checkRewardPuzzleCompleteness,checkProgressPuzzleCompleteness,checkOrderPuzzleCompleteness,checkPuzzleCompleteness as a313b}from'../../knowledge/index.js';import{initPuzzleFromIntent as a313c,checkPuzzleCompleteness as a313d}from'../../knowledge/permission-puzzle.js';const KEYWORD_TABLE=[{'category':'Product/Service','keywords_zh':['product','selling','sell','sales','store','open\x20shop'],'keywords_en':['sell','product','sale','shop','store'],'objects':['service','order','progress'],'required_level':'R','scene_id':'retail'},{'category':'Subscription','keywords_zh':['subscription','cycle','renewal'],'keywords_en':['subscribe','recurring','subscription'],'objects':['service','machine','reward'],'required_level':'C','scene_id':'subscription'},{'category':'Rental','keywords_zh':['rent','lease','return'],'keywords_en':['rent','lease','return'],'objects':['service','machine','arb'],'required_level':'C','scene_id':'rental_return'},{'category':'Trust','keywords_zh':['deposit','pledge','verify','trust'],'keywords_en':['deposit','trust','verify'],'objects':['guard','permission','treasury'],'required_level':'R','scene_id':'trust_deposit'},{'category':'Funds','keywords_zh':['split','collect','share\x20profit','income','incentive'],'keywords_en':['split','revenue','reward'],'objects':['allocation','treasury','reward'],'required_level':'R','scene_id':'revenue_split'},{'category':'Workflow','keywords_zh':['node','stage','process','workflow'],'keywords_en':['workflow','stage','node'],'objects':['machine','progress'],'required_level':'R','scene_id':'workflow'},{'category':'Dispute','keywords_zh':['arbitration','refund','conflict','rights\x20protection'],'keywords_en':['arbitration','refund','dispute'],'objects':['arb','proof'],'required_level':'C','scene_id':'arbitration_dispute'},{'category':'Contact','keywords_zh':['customer\x20service','contact','communication'],'keywords_en':['contact','support','im'],'objects':['contact'],'required_level':'C','scene_id':'contact_im'},{'category':'Data','keywords_zh':['evidence','record','data'],'keywords_en':['evidence','record','data'],'objects':['repository','proof'],'required_level':'C','scene_id':'evidence_record'},{'category':'User\x20Profile','keywords_zh':['personal\x20info','preference','privacy'],'keywords_en':['personal','profile','privacy'],'objects':['personal','contact'],'required_level':'OPTIONAL','scene_id':'user_profile'},{'category':'Demand\x20Submission','keywords_zh':['demand','publish','inquiry'],'keywords_en':['demand','request','inquiry'],'objects':['demand'],'required_level':'OPTIONAL','scene_id':'demand_inquiry'}],INDUSTRY_KEYWORDS=[{'industry':'freelance','words':['freelance','outsourcing','freelance','gig']},{'industry':'rental','words':['rental','lease','rental','rent']},{'industry':'education','words':['education','course','training','education','course']},{'industry':'travel','words':['travel','tour','itinerary','travel','trip']},{'industry':'subscription','words':['subscription','cycle','subscription','recurring']}];function buildPuzzleDispatch(){const a=(c,d)=>{try{return c(d);}catch{return undefined;}},b=(c,d)=>{if(!c)return{'missing':[],'complete':![],'next_step':'init\x20failed'};try{return d(c);}catch{return{'missing':[],'complete':![],'next_step':'check\x20failed'};}};return{'service':{'init':c=>a(initServicePuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkServicePuzzleCompleteness)},'machine':{'init':c=>a(initMachinePuzzleFromIntent,c),'check':c=>b(c,checkMachinePuzzleCompleteness)},'allocation':{'init':c=>a(initAllocationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkAllocationPuzzleCompleteness)},'treasury':{'init':c=>a(initTreasuryPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkTreasuryPuzzleCompleteness)},'arb':{'init':c=>a(initArbitrationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkArbitrationPuzzleCompleteness)},'reward':{'init':c=>a(initRewardPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkRewardPuzzleCompleteness)},'progress':{'init':c=>a(initProgressPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkProgressPuzzleCompleteness)},'order':{'init':c=>a(initOrderPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkOrderPuzzleCompleteness)},'permission':{'init':c=>a(a313c,{'primary_goal':c}),'check':c=>b(c,a313d)},'guard':{'init':c=>a(a313a,{'primary_goal':c}),'check':c=>b(c,a313b)}};}export function extractKeywords(a){if(!a||typeof a!=='string')return[];const b=[];for(const c of KEYWORD_TABLE){const d=[...c['keywords_zh'],...c['keywords_en']];for(const e of d){try{const f=new RegExp(escapeRegex(e),'gi'),g=(a['match'](f)||[])['length'];g>0x0&&b['push']({'keyword':e,'category':c['category'],'matched_objects':[...c['objects']],'required_level':c['required_level'],'match_count':g});}catch{}}}return b['sort']((h,i)=>i['match_count']-h['match_count']),b;}function escapeRegex(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}export function resolveIndustry(a,b){const c=((a??'')+'\x20'+(b??''))['toLowerCase']();for(const d of INDUSTRY_KEYWORDS){for(const e of d['words']){if(c['includes'](e['toLowerCase']()))return d['industry'];}}return'general';}export function identifyObjects(a,b){if(b['length']===0x0)return{'primary':'service','secondary':['permission','machine','progress'],'scenes':[{'object':'service','scene_id':'general'}]};const c=b['find'](i=>i['required_level']==='R'),d=(c??b[0x0])['matched_objects'][0x0],e=new Set([d]),f=[];for(const i of b){for(const j of i['matched_objects']){!e['has'](j)&&(e['add'](j),f['push'](j));}}const g=[],h=new Set();for(const k of KEYWORD_TABLE){const l=b['find'](n=>n['category']===k['category']);if(!l)continue;if(h['has'](k['scene_id']))continue;h['add'](k['scene_id']),g['push']({'object':k['objects'][0x0],'scene_id':k['scene_id']});}return{'primary':d,'secondary':f,'scenes':g};}export function analyzeBusinessIntent(a){const b=[];if(!a||!a['user_intent']||typeof a['user_intent']!=='string')return{'intent_parsed':{'primary_object':'service','secondary_objects':[],'detected_scenes':[],'industry':'general','keyword_matches':[]},'puzzles':{},'overall_completeness':'empty','next_step':'Please\x20provide\x20a\x20non-empty\x20business\x20intent.','recommended_creation_order':[],'warnings':['input.user_intent\x20is\x20empty']};const c=a['user_intent'],e=extractKeywords(c),f=resolveIndustry(c,a['industry']),{primary:g,secondary:h,scenes:i}=identifyObjects(c,e);let j=[g,...h];if(a['target_objects']&&a['target_objects']['length']>0x0){const p=a['target_objects']['filter'](q=>['service','machine','guard','permission','reward','arb','progress','treasury','demand','repository','contact','order','allocation','personal','payment','proof']['includes'](q));if(p['length']>0x0)j=p;}const k=buildPuzzleDispatch(),l={};for(const q of j){const r=k[q];if(!r){b['push']('No\x20puzzle\x20module\x20for\x20\x27'+q+'\x27\x20—\x20skipped\x20(L3\x20object)');continue;}const s=r['init'](c),t=s?r['check'](s):undefined,u=extractMissingDimensions(t);l[q]={'puzzle':s,'completeness':t,'missing_dimensions':u},!s&&b['push']('Puzzle\x20init\x20failed\x20for\x20\x27'+q+'\x27');}const m=aggregatePuzzleCompleteness(l),n=suggestNextPuzzleStep({'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':'','recommended_creation_order':[],'warnings':b}),o=['permission','progress','machine','guard','allocation','service'];return{'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':n,'recommended_creation_order':o,'warnings':b};}function extractMissingDimensions(a){if(!a||typeof a!=='object')return[];const b=a,d=b['missing'];if(Array['isArray'](d))return d['map'](f=>String(f));const e=b['missing_details'];if(Array['isArray'](e))return e['map'](f=>String(f?.['dimension']??f));return[];}export function aggregatePuzzleCompleteness(a){const b=Object['values'](a??{});if(b['length']===0x0)return'empty';const c=b['filter'](f=>!f['puzzle'])['length'];if(c===b['length'])return'empty';const d=b['reduce']((f,g)=>f+(g['missing_dimensions']?.['length']??0x0),0x0);if(d===0x0)return'complete';return'partial';}export function suggestNextPuzzleStep(a){if(!a)return'No\x20result\x20to\x20suggest\x20from.';if(a['overall_completeness']==='complete')return'All\x20puzzle\x20dimensions\x20are\x20complete\x20—\x20ready\x20for\x20risk\x20calibration\x20(stage\x203).';if(a['overall_completeness']==='empty')return'No\x20puzzle\x20has\x20been\x20initialized.\x20Provide\x20more\x20concrete\x20business\x20intent\x20so\x20the\x20primary\x20object\x20can\x20be\x20identified.';const b=['permission','treasury','allocation','guard','machine','service','order','progress','arb','reward','proof','repository','demand','contact','personal','payment'],d=a['puzzles']??{},e=b['filter'](f=>d[f]);for(const f of e){const g=d[f];if(!g)continue;const h=g['missing_dimensions']??[];if(h['length']===0x0)continue;const i=g['completeness'],j=i&&typeof i==='object'?i['next_step']:undefined;if(typeof j==='string'&&j['trim']())return'['+f+']\x20'+j;return'['+f+']\x20Complete\x20dimension'+(h['length']>0x1?'s':'')+'\x20'+h['join'](',\x20')+'\x20to\x20advance\x20the\x20puzzle.';}return'Continue\x20dialog\x20to\x20fill\x20remaining\x20pending\x20fields.';}
@@ -1,4 +1,4 @@
1
- import type { SemanticObjectGraph } from "./semantic-graph.js";
1
+ import type { Blueprint } from "../../composition/blueprint-view.js";
2
2
  import type { BusinessIntent } from "./intent-analyzer.js";
3
3
  import type { BusinessModuleId } from "../../extensions/business-modules.js";
4
4
  export type GameScenario = "merchant_may_deliver_late" | "merchant_may_abandon" | "customer_may_deny_acceptance" | "customer_may_false_claim" | "supplier_may_not_deliver";
@@ -40,4 +40,4 @@ export interface GameTheoryReport {
40
40
  summary: string;
41
41
  }
42
42
  export declare const GAME_THEORY_CONSTRAINTS: GameTheoryConstraint[];
43
- export declare function checkGameTheoryConstraints(graph: SemanticObjectGraph, intent: BusinessIntent): GameTheoryReport;
43
+ export declare function checkGameTheoryConstraints(graph: Blueprint, intent: BusinessIntent): GameTheoryReport;
@@ -1 +1 @@
1
- export const GAME_THEORY_CONSTRAINTS=[{'scenario':'merchant_may_deliver_late','conflict':'Merchant\x20incentive:\x20collect\x20payment\x20fast,\x20deliver\x20at\x20own\x20pace\x20(or\x20never).\x20User\x20bears\x20schedule\x20risk\x20with\x20no\x20leverage\x20once\x20funds\x20leave\x20their\x20wallet.','userProtection':{'mechanism':'Milestone\x20escrow\x20—\x20funds\x20locked\x20in\x20Order,\x20released\x20per\x20verified\x20milestone','object':'Order\x20+\x20Allocation','guard':'milestone\x20forward\x20guard\x20verifies\x20deliverable\x20before\x20release'},'merchantConstraint':{'requiredDeposit':!![],'timeoutPenalty':'compensation_fund\x20covers\x20refund\x20for\x20unstarted\x20milestones'},'evaluationMetric':'timeout_protection','mitigationSignals':[['edge:has_order_allocators','node:main_machine'],['module:milestone_escrow']],'mitigatingModules':['milestone_escrow','refund_guarantee'],'recommendation':'Adopt\x20milestone_escrow\x20module:\x20bind\x20order_allocators\x20+\x20Machine\x20so\x20funds\x20release\x20only\x20per\x20verified\x20milestone.\x20Add\x20compensation_fund\x20for\x20late-delivery\x20refunds.'},{'scenario':'merchant_may_abandon','conflict':'Merchant\x20incentive:\x20maximize\x20intake\x20then\x20abandon\x20the\x20service\x20(exit\x20scam).\x20User\x20has\x20no\x20recourse\x20without\x20locked\x20funds\x20or\x20deposit.','userProtection':{'mechanism':'Escrow\x20+\x20compensation\x20fund\x20—\x20user\x20refunds\x20from\x20on-chain\x20fund\x20even\x20if\x20merchant\x20vanishes','object':'Service.compensation_fund\x20+\x20Order','guard':'refund_guard\x20validates\x20claim\x20conditions'},'merchantConstraint':{'requiredDeposit':!![],'requiredArbitration':!![]},'evaluationMetric':'escrow_quality','mitigationSignals':[['edge:has_order_allocators','module:refund_guarantee'],['module:refund_guarantee','node:main_arbitration']],'mitigatingModules':['refund_guarantee','milestone_escrow','reputation_on_chain'],'recommendation':'Adopt\x20refund_guarantee\x20module:\x20compensation_fund_add\x20>\x200\x20with\x20refund_guard.\x20Escrow\x20via\x20order_allocators\x20prevents\x20merchant\x20from\x20touching\x20funds\x20before\x20delivery.'},{'scenario':'customer_may_deny_acceptance','conflict':'Customer\x20incentive:\x20withhold\x20acceptance\x20confirmation\x20to\x20delay\x20payment\x20indefinitely\x20while\x20using\x20the\x20deliverable.\x20Merchant\x27s\x20funds\x20stay\x20locked.','userProtection':{'mechanism':'Accept\x20timeout\x20—\x20after\x20N\x20days\x20without\x20response,\x20order\x20auto-advances\x20(adminUnhold)\x20and\x20merchant\x20gets\x20paid','object':'Machine\x20forward\x20+\x20Progress','guard':'time_guard\x20on\x20accept\x20forward'},'merchantConstraint':{'timeoutPenalty':'user\x20silence\x20past\x20timeout\x20=\x20implicit\x20acceptance'},'evaluationMetric':'timeout_protection','mitigationSignals':[['module:accept_timeout_protection'],['node:guard_accept_timeout_protection']],'mitigatingModules':['accept_timeout_protection'],'recommendation':'Adopt\x20accept_timeout_protection\x20module:\x20time_guard\x20on\x20the\x20accept\x20forward\x20(e.g.\x207\x20days)\x20+\x20PROGRESS_UNHOLD\x20permission\x20so\x20the\x20workflow\x20auto-advances\x20on\x20customer\x20silence.'},{'scenario':'customer_may_false_claim','conflict':'Customer\x20incentive:\x20claim\x20non-delivery\x20or\x20defect\x20to\x20obtain\x20refund\x20while\x20keeping\x20the\x20goods/service.\x20Merchant\x20loses\x20both\x20deliverable\x20and\x20payment.','userProtection':{'mechanism':'WIP\x20provenance\x20—\x20delivery\x20hash\x20committed\x20on-chain\x20before/at\x20delivery;\x20independent\x20arbitration\x20verifies\x20evidence','object':'Repository\x20+\x20Arbitration','guard':'Guard\x20compares\x20proof.signer/proof.time\x20against\x20committed\x20WIP\x20hash'},'merchantConstraint':{'requiredProof':'wip_hash\x20committed\x20to\x20Repository\x20before\x20fund\x20release','requiredArbitration':!![]},'evaluationMetric':'proof_integrity','mitigationSignals':[['node:main_repository','node:main_arbitration'],['module:wip_provenance','node:main_arbitration']],'mitigatingModules':['wip_provenance','independent_arbitration','damage_attestation'],'recommendation':'Adopt\x20wip_provenance\x20+\x20independent_arbitration\x20modules:\x20Repository\x20stores\x20WIP\x20hashes\x20as\x20tamper-proof\x20delivery\x20evidence;\x20Arbitration\x20(independent\x20Permission)\x20resolves\x20false\x20claims\x20against\x20on-chain\x20proof.'},{'scenario':'supplier_may_not_deliver','conflict':'Supplier\x20incentive:\x20accept\x20sub-order\x20payment\x20terms\x20then\x20under-deliver,\x20leaving\x20the\x20merchant\x20liable\x20to\x20the\x20end\x20customer.\x20Multi-party\x20opacity\x20hides\x20the\x20failure\x20point.','userProtection':{'mechanism':'Supplier\x20visibility\x20—\x20Demand\x20+\x20sub-order\x20flow\x20with\x20multi-tier\x20Allocation;\x20each\x20tier\x20paid\x20only\x20on\x20its\x20own\x20verified\x20delivery','object':'Demand\x20+\x20Allocation\x20(multi-tier)','guard':'per-tier\x20release\x20guard'},'merchantConstraint':{'requiredProof':'sub-delivery\x20proof\x20per\x20Allocation\x20tier'},'evaluationMetric':'supplier_visibility','mitigationSignals':[['module:supplier_collaboration'],['module:multi_tier_allocation']],'mitigatingModules':['supplier_collaboration','multi_tier_allocation'],'recommendation':'Adopt\x20supplier_collaboration\x20module:\x20publish\x20Demand\x20referencing\x20the\x20main\x20Service,\x20split\x20Allocation\x20across\x20tiers\x20so\x20each\x20supplier\x20is\x20paid\x20only\x20for\x20verified\x20sub-delivery.'}];function evalSignal(a,b,c){const [d,e]=a['split'](':',0x2);switch(d){case'node':return b['nodes']['some'](f=>f['id']===e);case'edge':return b['edges']['some'](f=>f['relation']===e);case'module':return b['adoptedModules']['includes'](e);case'type':return b['nodes']['some'](f=>f['type']===e);case'trust':{const f=c['trust'];return f[e]===!![]||typeof f[e]==='string'&&f[e]!=='none';}default:return![];}}export function checkGameTheoryConstraints(a,b){const d=[];for(const h of GAME_THEORY_CONSTRAINTS){let i=null,j=[],k=-0x1;for(const l of h['mitigationSignals']){const m=l['filter'](o=>evalSignal(o,a,b));if(m['length']===l['length']){i=l;break;}const n=m['length']/l['length'];m['length']>0x0&&n>k&&(k=n,j=m);}d['push']({'scenario':h['scenario'],'conflict':h['conflict'],'covered':i!==null,'matchedSignals':i??[],'partialSignals':i?[]:j,'userProtection':h['userProtection']['mechanism']+'\x20('+h['userProtection']['object']+(h['userProtection']['guard']?',\x20guard:\x20'+h['userProtection']['guard']:'')+')','evaluationMetric':h['evaluationMetric'],'recommendation':i?undefined:h['recommendation']});}const e=d['filter'](o=>o['covered']),f=d['filter'](o=>!o['covered']),g=[];return a['edges']['some'](o=>o['relation']==='has_order_allocators')&&g['push']('Milestone\x20escrow:\x20funds\x20locked\x20in\x20Order,\x20released\x20per\x20verified\x20milestone\x20—\x20merchant\x20paid\x20for\x20delivery,\x20user\x20pays\x20for\x20value'),a['adoptedModules']['includes']('accept_timeout_protection')&&g['push']('Accept\x20timeout:\x20customer\x20silence\x20past\x20N\x20days\x20=\x20implicit\x20acceptance\x20—\x20merchant\x20protected\x20from\x20payment\x20stalling'),a['nodes']['some'](o=>o['id']==='main_repository')&&g['push']('WIP\x20provenance:\x20delivery\x20hash\x20on-chain\x20—\x20false\x20claims\x20verifiable\x20against\x20tamper-proof\x20evidence'),a['nodes']['some'](o=>o['id']==='main_arbitration')&&g['push']('Micro-arbitration:\x20Guard-weighted\x20voting\x20with\x20independent\x20Permission\x20—\x20low-cost\x20dispute\x20resolution\x20without\x20platform\x20fees'),a['adoptedModules']['includes']('reputation_on_chain')&&g['push']('On-chain\x20reputation:\x20both\x20sides\x27\x20behavior\x20permanently\x20recorded\x20—\x20future\x20transactions\x20price\x20the\x20risk'),{'results':d,'coveredCount':e['length'],'totalCount':d['length'],'exposedScenarios':f['map'](o=>o['scenario']),'wowAlignments':g,'summary':f['length']===0x0?'All\x20'+d['length']+'\x20adversarial\x20scenarios\x20have\x20on-chain\x20mitigations.':f['length']+'/'+d['length']+'\x20adversarial\x20scenarios\x20EXPOSED:\x20'+f['map'](o=>o['scenario'])['join'](',\x20')+'.\x20Apply\x20the\x20recommendations\x20to\x20align\x20incentives.'};}
1
+ export const GAME_THEORY_CONSTRAINTS=[{'scenario':'merchant_may_deliver_late','conflict':'Merchant\x20incentive:\x20collect\x20payment\x20fast,\x20deliver\x20at\x20own\x20pace\x20(or\x20never).\x20User\x20bears\x20schedule\x20risk\x20with\x20no\x20leverage\x20once\x20funds\x20leave\x20their\x20wallet.','userProtection':{'mechanism':'Milestone\x20escrow\x20—\x20funds\x20locked\x20in\x20Order,\x20released\x20per\x20verified\x20milestone','object':'Order\x20+\x20Allocation','guard':'milestone\x20forward\x20guard\x20verifies\x20deliverable\x20before\x20release'},'merchantConstraint':{'requiredDeposit':!![],'timeoutPenalty':'compensation_fund\x20covers\x20refund\x20for\x20unstarted\x20milestones'},'evaluationMetric':'timeout_protection','mitigationSignals':[['edge:has_order_allocators','node:main_machine'],['module:milestone_escrow']],'mitigatingModules':['milestone_escrow','refund_guarantee'],'recommendation':'Adopt\x20milestone_escrow\x20module:\x20bind\x20order_allocators\x20+\x20Machine\x20so\x20funds\x20release\x20only\x20per\x20verified\x20milestone.\x20Add\x20compensation_fund\x20for\x20late-delivery\x20refunds.'},{'scenario':'merchant_may_abandon','conflict':'Merchant\x20incentive:\x20maximize\x20intake\x20then\x20abandon\x20the\x20service\x20(exit\x20scam).\x20User\x20has\x20no\x20recourse\x20without\x20locked\x20funds\x20or\x20deposit.','userProtection':{'mechanism':'Escrow\x20+\x20compensation\x20fund\x20—\x20user\x20refunds\x20from\x20on-chain\x20fund\x20even\x20if\x20merchant\x20vanishes','object':'Service.compensation_fund\x20+\x20Order','guard':'refund_guard\x20validates\x20claim\x20conditions'},'merchantConstraint':{'requiredDeposit':!![],'requiredArbitration':!![]},'evaluationMetric':'escrow_quality','mitigationSignals':[['edge:has_order_allocators','module:refund_guarantee'],['module:refund_guarantee','node:main_arbitration']],'mitigatingModules':['refund_guarantee','milestone_escrow','reputation_on_chain'],'recommendation':'Adopt\x20refund_guarantee\x20module:\x20compensation_fund_add\x20>\x200\x20with\x20refund_guard.\x20Escrow\x20via\x20order_allocators\x20prevents\x20merchant\x20from\x20touching\x20funds\x20before\x20delivery.'},{'scenario':'customer_may_deny_acceptance','conflict':'Customer\x20incentive:\x20withhold\x20acceptance\x20confirmation\x20to\x20delay\x20payment\x20indefinitely\x20while\x20using\x20the\x20deliverable.\x20Merchant\x27s\x20funds\x20stay\x20locked.','userProtection':{'mechanism':'Accept\x20timeout\x20—\x20after\x20N\x20days\x20without\x20response,\x20order\x20auto-advances\x20(adminUnhold)\x20and\x20merchant\x20gets\x20paid','object':'Machine\x20forward\x20+\x20Progress','guard':'time_guard\x20on\x20accept\x20forward'},'merchantConstraint':{'timeoutPenalty':'user\x20silence\x20past\x20timeout\x20=\x20implicit\x20acceptance'},'evaluationMetric':'timeout_protection','mitigationSignals':[['module:accept_timeout_protection'],['node:guard_accept_timeout_protection']],'mitigatingModules':['accept_timeout_protection'],'recommendation':'Adopt\x20accept_timeout_protection\x20module:\x20time_guard\x20on\x20the\x20accept\x20forward\x20(e.g.\x207\x20days)\x20+\x20PROGRESS_UNHOLD\x20permission\x20so\x20the\x20workflow\x20auto-advances\x20on\x20customer\x20silence.'},{'scenario':'customer_may_false_claim','conflict':'Customer\x20incentive:\x20claim\x20non-delivery\x20or\x20defect\x20to\x20obtain\x20refund\x20while\x20keeping\x20the\x20goods/service.\x20Merchant\x20loses\x20both\x20deliverable\x20and\x20payment.','userProtection':{'mechanism':'WIP\x20provenance\x20—\x20delivery\x20hash\x20committed\x20on-chain\x20before/at\x20delivery;\x20independent\x20arbitration\x20verifies\x20evidence','object':'Repository\x20+\x20Arbitration','guard':'Guard\x20compares\x20proof.signer/proof.time\x20against\x20committed\x20WIP\x20hash'},'merchantConstraint':{'requiredProof':'wip_hash\x20committed\x20to\x20Repository\x20before\x20fund\x20release','requiredArbitration':!![]},'evaluationMetric':'proof_integrity','mitigationSignals':[['node:main_repository','node:main_arbitration'],['module:wip_provenance','node:main_arbitration']],'mitigatingModules':['wip_provenance','independent_arbitration','damage_attestation'],'recommendation':'Adopt\x20wip_provenance\x20+\x20independent_arbitration\x20modules:\x20Repository\x20stores\x20WIP\x20hashes\x20as\x20tamper-proof\x20delivery\x20evidence;\x20Arbitration\x20(independent\x20Permission)\x20resolves\x20false\x20claims\x20against\x20on-chain\x20proof.'},{'scenario':'supplier_may_not_deliver','conflict':'Supplier\x20incentive:\x20accept\x20sub-order\x20payment\x20terms\x20then\x20under-deliver,\x20leaving\x20the\x20merchant\x20liable\x20to\x20the\x20end\x20customer.\x20Multi-party\x20opacity\x20hides\x20the\x20failure\x20point.','userProtection':{'mechanism':'Supplier\x20visibility\x20—\x20Demand\x20+\x20sub-order\x20flow\x20with\x20multi-tier\x20Allocation;\x20each\x20tier\x20paid\x20only\x20on\x20its\x20own\x20verified\x20delivery','object':'Demand\x20+\x20Allocation\x20(multi-tier)','guard':'per-tier\x20release\x20guard'},'merchantConstraint':{'requiredProof':'sub-delivery\x20proof\x20per\x20Allocation\x20tier'},'evaluationMetric':'supplier_visibility','mitigationSignals':[['module:supplier_collaboration'],['module:multi_tier_allocation']],'mitigatingModules':['supplier_collaboration','multi_tier_allocation'],'recommendation':'Adopt\x20supplier_collaboration\x20module:\x20publish\x20Demand\x20referencing\x20the\x20main\x20Service,\x20split\x20Allocation\x20across\x20tiers\x20so\x20each\x20supplier\x20is\x20paid\x20only\x20for\x20verified\x20sub-delivery.'}];function evalSignal(a,b,c){const [d,e]=a['split'](':',0x2);switch(d){case'node':return b['nodes']['some'](f=>f['id']===e||f['id']===e['replace'](/^main_/,''));case'edge':return b['edges']['some'](f=>f['relation']===e);case'module':return b['adoptedModules']['includes'](e);case'type':return b['nodes']['some'](f=>f['type']===e);case'trust':{const f=c['trust'];return f[e]===!![]||typeof f[e]==='string'&&f[e]!=='none';}default:return![];}}export function checkGameTheoryConstraints(a,b){const d=[];for(const h of GAME_THEORY_CONSTRAINTS){let i=null,j=[],k=-0x1;for(const l of h['mitigationSignals']){const m=l['filter'](o=>evalSignal(o,a,b));if(m['length']===l['length']){i=l;break;}const n=m['length']/l['length'];m['length']>0x0&&n>k&&(k=n,j=m);}d['push']({'scenario':h['scenario'],'conflict':h['conflict'],'covered':i!==null,'matchedSignals':i??[],'partialSignals':i?[]:j,'userProtection':h['userProtection']['mechanism']+'\x20('+h['userProtection']['object']+(h['userProtection']['guard']?',\x20guard:\x20'+h['userProtection']['guard']:'')+')','evaluationMetric':h['evaluationMetric'],'recommendation':i?undefined:h['recommendation']});}const e=d['filter'](o=>o['covered']),f=d['filter'](o=>!o['covered']),g=[];return a['edges']['some'](o=>o['relation']==='has_order_allocators')&&g['push']('Milestone\x20escrow:\x20funds\x20locked\x20in\x20Order,\x20released\x20per\x20verified\x20milestone\x20—\x20merchant\x20paid\x20for\x20delivery,\x20user\x20pays\x20for\x20value'),a['adoptedModules']['includes']('accept_timeout_protection')&&g['push']('Accept\x20timeout:\x20customer\x20silence\x20past\x20N\x20days\x20=\x20implicit\x20acceptance\x20—\x20merchant\x20protected\x20from\x20payment\x20stalling'),a['nodes']['some'](o=>o['id']==='repository')&&g['push']('WIP\x20provenance:\x20delivery\x20hash\x20on-chain\x20—\x20false\x20claims\x20verifiable\x20against\x20tamper-proof\x20evidence'),a['nodes']['some'](o=>o['id']==='arbitration')&&g['push']('Micro-arbitration:\x20Guard-weighted\x20voting\x20with\x20independent\x20Permission\x20—\x20low-cost\x20dispute\x20resolution\x20without\x20platform\x20fees'),a['adoptedModules']['includes']('reputation_on_chain')&&g['push']('On-chain\x20reputation:\x20both\x20sides\x27\x20behavior\x20permanently\x20recorded\x20—\x20future\x20transactions\x20price\x20the\x20risk'),{'results':d,'coveredCount':e['length'],'totalCount':d['length'],'exposedScenarios':f['map'](o=>o['scenario']),'wowAlignments':g,'summary':f['length']===0x0?'All\x20'+d['length']+'\x20adversarial\x20scenarios\x20have\x20on-chain\x20mitigations.':f['length']+'/'+d['length']+'\x20adversarial\x20scenarios\x20EXPOSED:\x20'+f['map'](o=>o['scenario'])['join'](',\x20')+'.\x20Apply\x20the\x20recommendations\x20to\x20align\x20incentives.'};}
@@ -1 +1 @@
1
- import{Config,LocalMark,query_objects,objectTypeFromAddress,ObjectType}from'@wowok/wowok';import{resolveAddress as a318a}from'../../tools/handlers/name-resolution.js';import{fetchMachineNodes,buildMachineGraph}from'./machine-nodes.js';import{batchQueryObjectsByIds,fetchObjectLinkerTx,ringWindowSaturated}from'../../graph/onchain/sdk-batch.js';export async function handleMachinePanorama(a){const b=a['object_address'];if(!b)throw new Error('\x27object_address\x27\x20is\x20required\x20for\x20machine_panorama');let c=a['context_network']??undefined;const d=[];let f=await a318a(b,'machine'),g=null;try{if(!c)c=await Config['Instance']()['network_get']();const x=await query_objects({'objects':[f],'network':c});g=x?.['objects']?.[0x0]??null;if(!g&&a['context_network']){const y=await Config['Instance']()['network_get']();if(y&&y!==c){const z=await query_objects({'objects':[f],'network':y,'no_cache':!![]}),A=z?.['objects']?.[0x0]??null;A&&(g=A,c=y);}}}catch(B){throw new Error('Failed\x20to\x20query\x20Machine\x20'+f+'\x20on\x20'+c+':\x20'+(''+(B instanceof Error?B['message']:String(B))));}if(!g)throw new Error('Machine\x20'+f+'\x20not\x20found\x20on\x20'+c+'.\x20It\x20may\x20not\x20exist\x20on\x20this\x20network.');f=g['object']??f;let h=null,j=[];try{const C=await LocalMark['Instance']()['list']({'address':f});C['length']>0x0&&(h=C[0x0]['name']??null,j=(C[0x0]['tags']??[])['map'](D=>String(D)));}catch{d['push']('head:\x20LocalMark\x20lookup\x20failed');}let k={'nodes':[],'edges':[]};try{const D=await fetchMachineNodes(f,c,!![]);k=buildMachineGraph(D);}catch{d['push']('graph:\x20node\x20fetch\x20failed\x20(non-blocking)');}if(typeof g['permission']==='string'&&g['permission'])try{const E=await query_objects({'objects':[g['permission']],'network':c}),F=E?.['objects']?.[0x0]??null,G=Array['isArray'](F?.['perm_remark'])?F['perm_remark']:Array['isArray'](F?.['remark'])?F['remark']:[],H=G['map'](I=>({'index':typeof I?.['index']==='number'?I['index']:parseInt(I?.['index'],0xa),'remark':typeof I?.['remark']==='string'?I['remark']:''}))['filter'](I=>Number['isFinite'](I['index']));k['permission']={'address':g['permission'],'remarks':H};}catch{d['push']('graph:\x20permission\x20read\x20failed\x20(non-blocking)');}const l=[];let m=0x0,n=null,p=null,q=0x0,s=![],u=[];try{const I=await fetchObjectLinkerTx(f,c,!![]),J=I?.['items']??[];s=ringWindowSaturated(J['length']);const K=new Map();for(const R of J){const S=typeof R?.['who']==='string'?R['who']['toLowerCase']():'';if(!S||S==='0x0')continue;if(!objectTypeFromAddress(S))continue;const T=typeof R?.['time']==='number'?R['time']:null,U=K['get'](S);K['set'](S,U==null?T:T==null?U:Math['max'](U,T));}q=K['size'];const L=new Map();for(const [V,W]of K){const X=String(objectTypeFromAddress(V)),Y=L['get'](X)??[];Y['push']({'address':V,'time':W}),L['set'](X,Y);}for(const Z of L['values']()){Z['sort']((a0,a1)=>(a1['time']??0x0)-(a0['time']??0x0));}const M=['Progress','Allocation','Payment','Guard'];u=[];for(const a0 of M){const a1=L['get'](a0);a1&&a1['length']>0x0&&(u['push']({'label':a0,'items':a1}),L['delete'](a0));}for(const [a2,a3]of L){if(a3['length']>0x0)u['push']({'label':a2,'items':a3});}const N=J['filter'](a4=>objectTypeFromAddress(a4['who'])===ObjectType['Progress']);m=N['length'];for(const a4 of N){if(typeof a4?.['time']==='number'){if(n===null||a4['time']<n)n=a4['time'];if(p===null||a4['time']>p)p=a4['time'];}}const O=N['slice'](-0x3)['reverse'](),P=O['map'](a5=>a5['who']),Q=new Map();if(P['length']>0x0)try{const a5=await batchQueryObjectsByIds(P,c,!![]);for(const a6 of a5){if(a6?.['object'])Q['set'](a6['object'],a6);}}catch{d['push']('progresses:\x20detail\x20fetch\x20failed');}for(const a7 of O){const a8=typeof a7?.['who']==='string'?a7['who']:'';if(!a8)continue;const a9=Q['get'](a8);l['push']({'progress':a8,'name':null,'current':a9?.['current']??null,'task':a9?.['task']??null,'history_count':typeof a9?.['history_count']==='number'?a9['history_count']:null,'current_time':typeof a9?.['current_time']==='number'?a9['current_time']:null,'created_at':typeof a7?.['time']==='number'?a7['time']:null});}}catch{d['push']('progresses:\x20global-table\x20lookup\x20failed\x20(non-blocking)');}const w='Analyze\x20ALL\x20workflow\x20progresses\x20of\x20Machine\x20'+f+'\x20('+c+')\x20one\x20by\x20one,\x20newest\x20first.\x20'+('The\x20progresses\x20live\x20in\x20the\x20machine\x27s\x20FIFO\x20tx-linker\x20window\x20holding\x20at\x20most\x205200\x20newest\x20entries\x20—\x20the\x20retained\x20count\x20is\x20a\x20lower\x20bound\x20when\x20the\x20window\x20is\x20saturated\x20(currently\x20'+m+(s?',\x20saturated':'')+').\x20')+'For\x20each\x20progress\x20call\x20object_panorama\x20with\x20the\x20progress\x27s\x20FULL\x200x\x20address\x20(collect\x20the\x20addresses\x20from\x20the\x20same\x20reverse-index\x20source;\x20work\x20newest-first)\x20and\x20render\x20ONE\x20table\x20row\x20per\x20progress:\x20'+'progress\x20address\x20chip\x20(first\x20column)\x20|\x20current\x20node\x20|\x20task\x20|\x20history\x20events\x20|\x20last\x20activity\x20(local\x20date)\x20|\x20registered\x20(local\x20date).\x20'+'Close\x20with\x20the\x203\x20most\x20valuable\x20patterns\x20across\x20the\x20rows\x20(stuck\x20nodes,\x20age\x20of\x20active\x20progresses,\x20throughput).\x20Progresses\x20only\x20—\x20do\x20not\x20re-analyze\x20the\x20Machine\x20graph\x20itself.';return{'action':'machine_panorama','machineAddress':f,'network':String(c),'head':{'name':h,'tags':j,'description':typeof g['description']==='string'?g['description']:null,'published':typeof g['bPublished']==='boolean'?g['bPublished']:null,'paused':typeof g['bPaused']==='boolean'?g['bPaused']:null},'fields':{'permission':g['permission']??null,'um':g['um']??null,'node_count':k['nodes']['length']>0x0?k['nodes']['length']:typeof g['node_count']==='number'?g['node_count']+0x1:null,'onchain_table_node_count':typeof g['node_count']==='number'?g['node_count']:k['nodes']['length']>0x0?k['nodes']['length']-0x1:null,'consensus_repositories':Array['isArray'](g['consensus_repositories'])?g['consensus_repositories']:[]},'graph':k,'progresses':{'count':m,'window_saturated':s,'preview_truncated':m>l['length'],'stats':{'first_created_ms':n,'last_created_ms':p},...m>l['length']?{'drilldown':{'total_count':m,'analyzed_count':l['length'],'prompt':w}}:{},'items':l},'related':{'count':q,'window_saturated':s,'groups':u},'data_gaps':d};}
1
+ import{Config,LocalMark,query_objects,objectTypeFromAddress,ObjectType}from'@wowok/wowok';import{resolveAddress as a321a}from'../../tools/handlers/name-resolution.js';import{fetchMachineNodes,buildMachineGraph}from'./machine-nodes.js';import{batchQueryObjectsByIds,fetchObjectLinkerTx,ringWindowSaturated}from'../../graph/onchain/sdk-batch.js';export async function handleMachinePanorama(a){const b=a['object_address'];if(!b)throw new Error('\x27object_address\x27\x20is\x20required\x20for\x20machine_panorama');let c=a['context_network']??undefined;const d=[];let f=await a321a(b,'machine'),g=null;try{if(!c)c=await Config['Instance']()['network_get']();const x=await query_objects({'objects':[f],'network':c});g=x?.['objects']?.[0x0]??null;if(!g&&a['context_network']){const y=await Config['Instance']()['network_get']();if(y&&y!==c){const z=await query_objects({'objects':[f],'network':y,'no_cache':!![]}),A=z?.['objects']?.[0x0]??null;A&&(g=A,c=y);}}}catch(B){throw new Error('Failed\x20to\x20query\x20Machine\x20'+f+'\x20on\x20'+c+':\x20'+(''+(B instanceof Error?B['message']:String(B))));}if(!g)throw new Error('Machine\x20'+f+'\x20not\x20found\x20on\x20'+c+'.\x20It\x20may\x20not\x20exist\x20on\x20this\x20network.');f=g['object']??f;let h=null,j=[];try{const C=await LocalMark['Instance']()['list']({'address':f});C['length']>0x0&&(h=C[0x0]['name']??null,j=(C[0x0]['tags']??[])['map'](D=>String(D)));}catch{d['push']('head:\x20LocalMark\x20lookup\x20failed');}let k={'nodes':[],'edges':[]};try{const D=await fetchMachineNodes(f,c,!![]);k=buildMachineGraph(D);}catch{d['push']('graph:\x20node\x20fetch\x20failed\x20(non-blocking)');}if(typeof g['permission']==='string'&&g['permission'])try{const E=await query_objects({'objects':[g['permission']],'network':c}),F=E?.['objects']?.[0x0]??null,G=Array['isArray'](F?.['perm_remark'])?F['perm_remark']:Array['isArray'](F?.['remark'])?F['remark']:[],H=G['map'](I=>({'index':typeof I?.['index']==='number'?I['index']:parseInt(I?.['index'],0xa),'remark':typeof I?.['remark']==='string'?I['remark']:''}))['filter'](I=>Number['isFinite'](I['index']));k['permission']={'address':g['permission'],'remarks':H};}catch{d['push']('graph:\x20permission\x20read\x20failed\x20(non-blocking)');}const l=[];let m=0x0,n=null,p=null,q=0x0,s=![],u=[];try{const I=await fetchObjectLinkerTx(f,c,!![]),J=I?.['items']??[];s=ringWindowSaturated(J['length']);const K=new Map();for(const R of J){const S=typeof R?.['who']==='string'?R['who']['toLowerCase']():'';if(!S||S==='0x0')continue;if(!objectTypeFromAddress(S))continue;const T=typeof R?.['time']==='number'?R['time']:null,U=K['get'](S);K['set'](S,U==null?T:T==null?U:Math['max'](U,T));}q=K['size'];const L=new Map();for(const [V,W]of K){const X=String(objectTypeFromAddress(V)),Y=L['get'](X)??[];Y['push']({'address':V,'time':W}),L['set'](X,Y);}for(const Z of L['values']()){Z['sort']((a0,a1)=>(a1['time']??0x0)-(a0['time']??0x0));}const M=['Progress','Allocation','Payment','Guard'];u=[];for(const a0 of M){const a1=L['get'](a0);a1&&a1['length']>0x0&&(u['push']({'label':a0,'items':a1}),L['delete'](a0));}for(const [a2,a3]of L){if(a3['length']>0x0)u['push']({'label':a2,'items':a3});}const N=J['filter'](a4=>objectTypeFromAddress(a4['who'])===ObjectType['Progress']);m=N['length'];for(const a4 of N){if(typeof a4?.['time']==='number'){if(n===null||a4['time']<n)n=a4['time'];if(p===null||a4['time']>p)p=a4['time'];}}const O=N['slice'](-0x3)['reverse'](),P=O['map'](a5=>a5['who']),Q=new Map();if(P['length']>0x0)try{const a5=await batchQueryObjectsByIds(P,c,!![]);for(const a6 of a5){if(a6?.['object'])Q['set'](a6['object'],a6);}}catch{d['push']('progresses:\x20detail\x20fetch\x20failed');}for(const a7 of O){const a8=typeof a7?.['who']==='string'?a7['who']:'';if(!a8)continue;const a9=Q['get'](a8);l['push']({'progress':a8,'name':null,'current':a9?.['current']??null,'task':a9?.['task']??null,'history_count':typeof a9?.['history_count']==='number'?a9['history_count']:null,'current_time':typeof a9?.['current_time']==='number'?a9['current_time']:null,'created_at':typeof a7?.['time']==='number'?a7['time']:null});}}catch{d['push']('progresses:\x20global-table\x20lookup\x20failed\x20(non-blocking)');}const w='Analyze\x20ALL\x20workflow\x20progresses\x20of\x20Machine\x20'+f+'\x20('+c+')\x20one\x20by\x20one,\x20newest\x20first.\x20'+('The\x20progresses\x20live\x20in\x20the\x20machine\x27s\x20FIFO\x20tx-linker\x20window\x20holding\x20at\x20most\x205200\x20newest\x20entries\x20—\x20the\x20retained\x20count\x20is\x20a\x20lower\x20bound\x20when\x20the\x20window\x20is\x20saturated\x20(currently\x20'+m+(s?',\x20saturated':'')+').\x20')+'For\x20each\x20progress\x20call\x20object_panorama\x20with\x20the\x20progress\x27s\x20FULL\x200x\x20address\x20(collect\x20the\x20addresses\x20from\x20the\x20same\x20reverse-index\x20source;\x20work\x20newest-first)\x20and\x20render\x20ONE\x20table\x20row\x20per\x20progress:\x20'+'progress\x20address\x20chip\x20(first\x20column)\x20|\x20current\x20node\x20|\x20task\x20|\x20history\x20events\x20|\x20last\x20activity\x20(local\x20date)\x20|\x20registered\x20(local\x20date).\x20'+'Close\x20with\x20the\x203\x20most\x20valuable\x20patterns\x20across\x20the\x20rows\x20(stuck\x20nodes,\x20age\x20of\x20active\x20progresses,\x20throughput).\x20Progresses\x20only\x20—\x20do\x20not\x20re-analyze\x20the\x20Machine\x20graph\x20itself.';return{'action':'machine_panorama','machineAddress':f,'network':String(c),'head':{'name':h,'tags':j,'description':typeof g['description']==='string'?g['description']:null,'published':typeof g['bPublished']==='boolean'?g['bPublished']:null,'paused':typeof g['bPaused']==='boolean'?g['bPaused']:null},'fields':{'permission':g['permission']??null,'um':g['um']??null,'node_count':k['nodes']['length']>0x0?k['nodes']['length']:typeof g['node_count']==='number'?g['node_count']+0x1:null,'onchain_table_node_count':typeof g['node_count']==='number'?g['node_count']:k['nodes']['length']>0x0?k['nodes']['length']-0x1:null,'consensus_repositories':Array['isArray'](g['consensus_repositories'])?g['consensus_repositories']:[]},'graph':k,'progresses':{'count':m,'window_saturated':s,'preview_truncated':m>l['length'],'stats':{'first_created_ms':n,'last_created_ms':p},...m>l['length']?{'drilldown':{'total_count':m,'analyzed_count':l['length'],'prompt':w}}:{},'items':l},'related':{'count':q,'window_saturated':s,'groups':u},'data_gaps':d};}
@@ -1,6 +1,6 @@
1
1
  import { type BusinessIntent, type DeliverableDefinition, type PaymentIntent, type TrustIntent } from "./intent-analyzer.js";
2
2
  import { type BusinessModuleId } from "../../extensions/business-modules.js";
3
- import type { IndustryMode } from "../../extensions/index.js";
3
+ import type { IndustryTemplate } from "../../knowledge/template-loader.js";
4
4
  export interface GuideState {
5
5
  intent_text: string;
6
6
  confirmed_industry?: string;
@@ -29,7 +29,7 @@ export interface MerchantGuideInput {
29
29
  trust?: Record<string, unknown>;
30
30
  adopted_module_ids?: string[];
31
31
  };
32
- mode_prior_override?: IndustryMode;
32
+ template_override?: IndustryTemplate;
33
33
  name_base?: string;
34
34
  }
35
35
  export interface PostDeployStep {
@@ -66,7 +66,7 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
66
66
  blueprint: {
67
67
  nodes: {
68
68
  id: string;
69
- type: import("./namespace.js").ProjectObjectType;
69
+ type: string;
70
70
  purpose: string;
71
71
  }[];
72
72
  edges: {
@@ -76,11 +76,18 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
76
76
  required: boolean;
77
77
  }[];
78
78
  };
79
- evaluation_preview: import("./semantic-graph.js").EvaluationPreview | undefined;
79
+ evaluation_preview: {
80
+ estimatedRiskScore: number;
81
+ estimatedTrustScore: number;
82
+ estimatedCompletenessScore: number;
83
+ keyRisks: string[];
84
+ strengths: string[];
85
+ moduleBoosts: {};
86
+ };
80
87
  graph_validation: {
81
88
  valid: boolean;
82
89
  hard_violations: {
83
- id: string;
90
+ id: "PLAN_DUP_STEP" | "PLAN_UNKNOWN_KIND" | "PLAN_REF_UNKNOWN" | "PLAN_REF_FORWARD" | "PLAN_PUBLISH_TARGET" | "PLAN_PROSE_GUARD" | "PLAN_MACHINE_NODES" | "PLAN_REQUIRES_UNKNOWN";
84
91
  description: string;
85
92
  fix: string;
86
93
  }[];
@@ -97,11 +104,15 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
97
104
  reason: string | undefined;
98
105
  estimated_score_boost: number;
99
106
  }[];
100
- blocking_issues: {
107
+ blocking_issues: ({
101
108
  module: BusinessModuleId;
102
109
  missing_constraints: string[] | undefined;
103
110
  fix: string | undefined;
104
- }[];
111
+ } | {
112
+ module: string;
113
+ missing_constraints: import("../../composition/compile.js").CompileBlockerCode[];
114
+ fix: string;
115
+ })[];
105
116
  deploy_time_checks: string[];
106
117
  recipient_design_guidance: {
107
118
  id: "entity" | "signer" | "submitted_object" | "constrained_submission";
@@ -147,6 +158,18 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
147
158
  post_deploy_steps: PostDeployStep[];
148
159
  warnings: string[];
149
160
  next_action: string;
161
+ plan: import("../../composition/plan.js").Plan;
162
+ audit: {
163
+ issues: import("../../composition/plan.js").PlanIssue[];
164
+ findings: import("../../config/rule-engine.js").RuleBookFinding[];
165
+ blocking: boolean;
166
+ score: number;
167
+ };
168
+ reflux: {
169
+ applied: import("../../composition/reflux.js").PlanPatch[];
170
+ blocks: import("../../composition/reflux.js").RefluxBlock[];
171
+ iterations: number;
172
+ };
150
173
  time_anchor_instructions?: string[] | undefined;
151
174
  action: "merchant_guide";
152
175
  current_step: number;
@@ -186,8 +209,8 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
186
209
  time_anchors?: Record<string, string> | undefined;
187
210
  name: string;
188
211
  display_name: string;
189
- source: import("../../knowledge/industry-registry.js").IndustrySource;
190
- risk_appetite: import("../../extensions/types.js").RiskAppetite;
212
+ source: "builtin" | "custom";
213
+ risk_appetite: "medium";
191
214
  key_risk: string;
192
215
  machine_shape: {
193
216
  semantic_role?: "active" | "draft" | "delivered" | "final" | "cancelled" | undefined;
@@ -200,8 +223,28 @@ export declare function handleMerchantGuide(v: MerchantGuideInput): Promise<{
200
223
  host: "reward" | "service" | "arbitration" | "machine" | "repository";
201
224
  purpose: string;
202
225
  }[];
203
- allocator: import("../../knowledge/scenario-modes.js").ModeAllocatorStrategy;
204
- risk_constraints: import("../../extensions/types.js").ModeRiskConstraints;
226
+ allocator: {
227
+ recipient: "fixed" | "entity" | "signer";
228
+ count: number;
229
+ mode: "amount" | "surplus" | "rate";
230
+ description: string;
231
+ recipient_key?: string | undefined;
232
+ refund_track?: "order_anchored" | undefined;
233
+ once_per_order?: boolean | undefined;
234
+ rows?: {
235
+ track: "refund" | "settlement";
236
+ recipient: "entity" | "signer" | "guard_identifier";
237
+ mode: "amount" | "surplus" | "rate";
238
+ recipient_key?: string | undefined;
239
+ value?: string | number | undefined;
240
+ value_from?: string | undefined;
241
+ fix?: string | number | undefined;
242
+ fix_from?: string | undefined;
243
+ guard_key?: string | undefined;
244
+ note?: string | undefined;
245
+ }[] | undefined;
246
+ };
247
+ risk_constraints: Record<string, unknown>;
205
248
  build_notes: string[];
206
249
  } | undefined;
207
250
  intent_draft?: undefined;
@@ -1 +1 @@
1
- import{analyzeIntent}from'./intent-analyzer.js';import{buildSemanticGraph,validateGraph}from'./semantic-graph.js';import{checkGameTheoryConstraints}from'./game-theory.js';import{assessWorkflowDesign}from'./workflow-design-assessment.js';import{CORE_BUSINESS_MODULES,getBusinessModule,recommendModules,checkModuleConstraints}from'../../extensions/business-modules.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{LOCAL_MODE_OWNER}from'./mode-actions.js';import{recipientDesignGuidance}from'../../knowledge/recipient-constraint.js';function derivePlanSatisfiedConstraints(a,b){const c=new Set(),d=h=>a['edges']['some'](i=>i['relation']===h),e=h=>a['nodes']['some'](i=>i['id']===h),f=h=>a['nodes']['some'](i=>i['type']===h),g=h=>a['adoptedModules']['includes'](h);if(d('has_order_allocators'))c['add']('order_allocators_bound');if(d('uses_machine'))c['add']('machine_bound_before_publish');if(d('has_arbitration'))c['add']('arbitration_bound_to_service');if(e('main_machine'))c['add']('machine_published');if(e('main_repository'))c['add']('repository_published');if(e('main_service'))c['add']('service_published');e('arb_permission')&&e('main_permission')&&c['add']('arbitration_permission_independent');g('independent_arbitration')&&e('guard_independent_arbitration')&&c['add']('voting_guard_configured');g('accept_timeout_protection')&&(c['add']('time_guard_configured'),c['add']('adminUnhold_permission'));g('milestone_escrow')&&f('guard')&&c['add']('milestone_forward_guarded');if(e('main_allocation')&&b['payment']['allocation']&&b['payment']['allocation']['length']>0x0){c['add']('allocators_configured');const h=b['payment']['allocation']['reduce']((j,k)=>j+k['percentage'],0x0);if(Math['abs'](h-0x64)<0.001)c['add']('sharing_sum_100');const i=b['payment']['allocation']['find'](j=>j['recipient']==='platform');if(i&&i['percentage']===0x0)c['add']('platform_fee_zero');g('supplier_collaboration')&&(c['add']('allocation_sharing_configured'),c['add']('demand_configured'));}return g('wip_provenance')&&e('main_repository')&&c['add']('wip_hash_before_delivery'),g('subscription_with_proof')&&e('main_repository')&&(c['add']('delivery_guard_per_cycle'),c['add']('repository_updated')),g('damage_attestation')&&(c['add']('pre_rental_hash'),c['add']('post_rental_hash')),g('refund_guarantee')&&(c['add']('compensation_fund_positive'),c['add']('refund_guard_configured')),c;}function deriveDeployTimeChecks(a){const b=[];return a['nodes']['some'](c=>c['id']==='main_machine')&&b['push']('Machine\x20published\x20AND\x20bound\x20to\x20Service\x20BEFORE\x20Service.publish\x20(machine\x20is\x20immutable\x20after\x20publish)'),a['edges']['some'](c=>c['relation']==='has_order_allocators')&&(b['push']('Service.order_allocators\x20bound\x20(verify\x20via\x20query_objects\x20after\x20publish\x20—\x20order_allocators\x20is\x20FROZEN\x20at\x20publish)'),b['push']('Settlement\x20is\x20NOT\x20triggered\x20by\x20reaching\x20a\x20Machine\x20node\x20alone\x20—\x20an\x20explicit\x20alloc_by_guard\x20call\x20(keeper\x20or\x20merchant)\x20fires\x20the\x20settlement\x20Allocator\x20once\x20its\x20Guard\x20passes.\x20Declare\x20the\x20node->allocator\x20trigger\x20(which\x20terminal\x20node\x20unlocks\x20settlement)\x20and\x20schedule\x20the\x20keeper\x20step;\x20otherwise\x20orders\x20stall\x20at\x20the\x20settle\x20node\x20with\x20allocation_state=pending')),(a['adoptedModules']['includes']('refund_guarantee')||a['nodes']['some'](c=>c['id']==='main_arbitration'))&&b['push']('compensation_fund\x20MUST\x20be\x20topped\x20up\x20BEFORE\x20any\x20payout:\x20a\x20claim\x20against\x20an\x20empty\x20fund\x20aborts\x20(service.move\x20E_COMPENSATION_NOT_MATCH).\x20Add\x20a\x20compensation_fund_add\x20step\x20sized\x20>=\x203x\x20the\x20highest\x20single\x20order\x20(3x\x20IS\x20the\x20chain\x27s\x20hard\x20award\x20ceiling,\x20MAX_INDEMNITY_MULTIPLE)\x20and\x20verify\x20the\x20on-chain\x20balance\x20before\x20going\x20live'),a['nodes']['some'](c=>c['id']==='main_arbitration')&&(b['push']('Arbitration.permission\x20!=\x20Service.permission\x20on-chain\x20(E_ARBITRATION_PERMISSION_CONFLICT=33)'),b['push']('A\x20freshly\x20created\x20Arbitration\x20defaults\x20to\x20PAUSED\x20—\x20unpause\x20it\x20(arbitration\x20activation)\x20before\x20the\x20first\x20case\x20can\x20be\x20filed,\x20otherwise\x20dispute\x20filing\x20aborts')),a['nodes']['some'](c=>c['id']==='main_repository')&&b['push']('Repository\x20published\x20and\x20Guard\x20write\x20validation\x20configured'),b['push']('After\x20materialization,\x20confirm\x20the\x20on-chain\x20state\x20matches\x20this\x20plan\x20(query_toolkit\x20query_type=\x27service_panorama\x27)'),b;}function derivePostDeploySteps(a){const b=[];return(a['adoptedModules']['includes']('refund_guarantee')||a['nodes']['some'](c=>c['id']==='main_arbitration'))&&b['push']({'order':b['length']+0x1,'id':'compensation_fund_topup','title':'Top\x20up\x20the\x20compensation\x20fund','when':'After\x20the\x20Service\x20object\x20is\x20created,\x20BEFORE\x20the\x20service\x20goes\x20live\x20(before\x20the\x20first\x20order)','action':'Call\x20compensation_fund_add\x20sized\x20>=\x203x\x20the\x20highest\x20single\x20order\x20(3x\x20=\x20the\x20chain\x27s\x20hard\x20award\x20ceiling,\x20MAX_INDEMNITY_MULTIPLE;\x20above\x203x\x20only\x20buys\x20headroom\x20for\x20concurrent\x20claims),\x20then\x20verify\x20the\x20on-chain\x20fund\x20balance\x20via\x20query_objects','tool_hint':'onchain_operations\x20(service.compensation_fund_add)','failure_if_skipped':'a\x20compensation\x20claim\x20against\x20an\x20empty\x20fund\x20aborts\x20(E_COMPENSATION_NOT_MATCH,\x20testnet\x20lesson\x20R-4)'}),a['nodes']['some'](c=>c['id']==='main_arbitration')&&b['push']({'order':b['length']+0x1,'id':'arbitration_unpause','title':'Activate\x20the\x20Arbitration\x20(unpause)','when':'Immediately\x20after\x20the\x20Arbitration\x20object\x20is\x20created,\x20before\x20the\x20first\x20dispute\x20is\x20filed','action':'Unpause/activate\x20the\x20Arbitration\x20so\x20dispute\x20filing\x20is\x20accepted;\x20keep\x20its\x20Permission\x20distinct\x20from\x20the\x20Service\x20Permission\x20(E_ARBITRATION_PERMISSION_CONFLICT=33)','tool_hint':'onchain_operations\x20(arbitration\x20activation)','failure_if_skipped':'a\x20freshly\x20created\x20Arbitration\x20defaults\x20to\x20PAUSED\x20—\x20dispute\x20filing\x20aborts\x20(testnet\x20lesson\x20R-5)'}),a['edges']['some'](c=>c['relation']==='has_order_allocators')&&b['push']({'order':b['length']+0x1,'id':'settlement_alloc_by_guard','title':'Fire\x20settlement\x20via\x20alloc_by_guard\x20(keeper/merchant\x20step)','when':'Recurring\x20—\x20after\x20EACH\x20order\x20reaches\x20its\x20settlement\x20terminal\x20node\x20(declare\x20which\x20node\x20unlocks\x20settlement)','action':'Call\x20alloc_by_guard\x20on\x20the\x20order\x27s\x20allocation\x20with\x20the\x20settlement\x20Guard;\x20reaching\x20the\x20Machine\x20node\x20alone\x20does\x20NOT\x20settle\x20(allocation_state\x20stays\x20pending)','tool_hint':'onchain_operations\x20(allocation.alloc_by_guard);\x20schedule\x20as\x20a\x20keeper\x20step','failure_if_skipped':'orders\x20stall\x20at\x20the\x20settle\x20node\x20with\x20funds\x20locked\x20in\x20escrow\x20(testnet\x20lesson\x20R-2)'}),b['push']({'order':b['length']+0x1,'id':'verify_service_panorama','title':'Verify\x20the\x20on-chain\x20state\x20matches\x20the\x20plan','when':'After\x20all\x20creation\x20steps\x20and\x20the\x20steps\x20above\x20are\x20done','action':'Run\x20the\x20service\x20panorama\x20query\x20and\x20diff\x20it\x20against\x20this\x20plan\x27s\x20blueprint/creation_plan','tool_hint':'query_toolkit\x20query_type=\x27service_panorama\x27','failure_if_skipped':'plan/chain\x20drift\x20(missing\x20binding,\x20wrong\x20allocator\x20order)\x20stays\x20undetected\x20until\x20an\x20order\x20hits\x20it'}),b;}function buildCreationPlan(a){const b=[],c=new Map(a['nodes']['map'](k=>[k['id'],k])),f=new Map();for(const k of a['nodes'])f['set'](k['id'],new Set());for(const l of a['edges']){if(!f['has'](l['from'])||!c['has'](l['to']))continue;const m=l['relation']==='has_guard'?l['to']:l['from'],o=l['relation']==='has_guard'?l['from']:l['to'];if(m===o||!f['has'](m))continue;f['get'](m)['add'](o);}for(const p of a['nodes']){for(const q of Object['values'](p['config'])){q['type']==='address_ref'&&q['targetId']!==p['id']&&f['has'](q['targetId'])&&f['get'](p['id'])['add'](q['targetId']);}}const g=a['nodes']['filter'](r=>r['type']==='service')['map'](r=>r['id']);if(g['length']>0x0)for(const r of a['nodes']){if(r['type']!=='guard')continue;const s=f['get'](r['id']);if(s===undefined)continue;for(const t of g)s['add'](t);}const h=new Map([...f]['map'](([u,v])=>[u,[...v]])),i=[],j=new Map(f);while(j['size']>0x0){const u=[...j['entries']()]['filter'](([,v])=>v['size']===0x0)['map'](([v])=>v);if(u['length']===0x0){i['push'](...j['keys']());break;}u['sort']();for(const v of u){i['push'](v),j['delete'](v);for(const w of j['values']())w['delete'](v);}}return i['forEach']((x,y)=>{const z=c['get'](x),A=z['config']['name'];b['push']({'order':y+0x1,'node_id':x,'object_type':z['type'],'suggested_name':A?.['type']==='string'?A['value']:x,'depends_on':h['get'](x)??[],'operation_hint':'Create\x20'+z['type']+'\x20via\x20onchain_operations,\x20then\x20configure.\x20Purpose:\x20'+z['purpose']});}),b;}async function resolveModePrior(a){if(!a)return undefined;const b=getIndustryModeRegistry(),c=await b['getUserMode'](a,LOCAL_MODE_OWNER);return c??b['getMode'](a);}export async function handleMerchantGuide(a){const b=a['guide_state']??{'intent_text':''},c=a['guide_confirm']??{},d={'intent_text':(a['intent']??b['intent_text']??'')['trim'](),'confirmed_industry':c['industry']??b['confirmed_industry'],'currency':c['currency']??b['currency'],'deliverables':c['deliverables']??b['deliverables'],'payment_override':c['payment']??b['payment_override'],'trust_override':c['trust']??b['trust_override'],'adopted_module_ids':c['adopted_module_ids']??b['adopted_module_ids']};for(const u of Object['keys'](d)){if(d[u]===undefined)delete d[u];}if(!d['intent_text'])throw new Error('merchant_guide\x20requires\x20\x27intent\x27\x20(business\x20description)\x20for\x20Step\x201.\x20'+'Example:\x20intent=\x27I\x20want\x20to\x20offer\x20online\x20design\x20service\x20with\x20milestone\x20payments\x27.\x20'+'Pass\x20the\x20returned\x20guide_state\x20back\x20UNCHANGED\x20on\x20subsequent\x20calls,\x20plus\x20guide_confirm\x20for\x20merchant\x20decisions.');const e=await analyzeIntent(d['intent_text'],{'preferredIndustry':d['confirmed_industry'],'currency':d['currency']});if(!d['confirmed_industry'])return{'action':'merchant_guide','current_step':0x2,'step_name':'Industry\x20Matching','guide_state':d,'intent_draft':e['intent'],'industry_options':{'inferred':e['inferredIndustry'],'confidence':e['industryConfidence'],'similar':e['similarIndustries']},'warnings':e['warnings'],'next_action':'Confirm\x20the\x20industry\x20by\x20calling\x20merchant_guide\x20again\x20with\x20guide_state\x20(UNCHANGED)\x20'+('plus\x20guide_confirm={\x20industry:\x20\x27<one\x20of:\x20'+e['similarIndustries']['join'](',\x20')+'\x20—\x20or\x20any\x20other\x20industry\x20id>\x27\x20}')};const f={...e['intent'],'industry':d['confirmed_industry'],'deliverables':d['deliverables']??e['intent']['deliverables'],'payment':{...e['intent']['payment'],...d['payment_override']??{}},'trust':{...e['intent']['trust'],...d['trust_override']??{}}},g=d['adopted_module_ids']?d['adopted_module_ids']['map'](w=>getBusinessModule(w))['filter'](w=>!!w):recommendModules(d['confirmed_industry'],d['intent_text'],{'maxModules':0x5}),h=a['mode_prior_override']??await resolveModePrior(d['confirmed_industry']),i=buildSemanticGraph(f,g,h,{'paymentExplicit':!!(d['payment_override']||d['trust_override']),'nameBase':a['name_base']}),j=validateGraph(i),l=derivePlanSatisfiedConstraints(i,f),m=g['map'](w=>checkModuleConstraints(w,l)),n=deriveDeployTimeChecks(i),o=derivePostDeploySteps(i),p=i['edges']['some'](w=>w['relation']==='has_order_allocators')?recipientDesignGuidance()['map'](w=>({'id':w['id'],'move_recipient':w['move_recipient'],'semantics':w['semantics'],'required_constraints':w['required_constraints'],'finding_if_unmet':w['finding_if_unmet']})):undefined,q=m['filter'](w=>!w['adopted']),r=checkGameTheoryConstraints(i,f),s=assessWorkflowDesign(i),t=buildCreationPlan(i);return{'action':'merchant_guide','current_step':q['length']>0x0?0x9:0xa,'step_name':q['length']>0x0?'Harness\x20Check\x20(issues\x20found)':'Submission\x20Plan\x20Ready','guide_state':{...d,'adopted_module_ids':g['map'](w=>w['id'])},'intent':{'intent_type':f['intent'],'industry':f['industry'],'roles':f['roles'],'deliverables':f['deliverables'],'payment':f['payment'],'trust':f['trust']},'adopted_modules':g['map'](w=>({'id':w['id'],'name':w['name'],'description':w['description'],'requires_keeper':w['requiresKeeper'],'keeper_hint':w['keeperHint'],'user_protections':w['userProtections'],'merchant_obligations':w['merchantObligations']})),'mode_prior':h?{'name':h['name'],'display_name':h['display_name'],'source':h['source'],'risk_appetite':h['risk_appetite'],'key_risk':h['key_risk'],'machine_shape':h['machine_shape']['map'](w=>({'name':w['name'],'role':w['role'],...w['operator']?{'operator':w['operator']}:{},...w['semantic_role']?{'semantic_role':w['semantic_role']}:{}})),'guards':h['guards']['map'](w=>({'template_id':w['template_id'],'host':w['host'],'purpose':w['purpose']})),'allocator':h['allocator'],'risk_constraints':h['risk_constraints'],'build_notes':h['build_notes']??[],...h['time_anchors']?{'time_anchors':h['time_anchors']}:{}}:undefined,...h?.['time_anchors']?{'time_anchor_instructions':Object['entries'](h['time_anchors'])['map'](([w,x])=>{const y=x==='order.time'?'\x20(order-creation\x20time\x20—\x20PRE-checkout\x20branches\x20only;\x20a\x20post-checkout\x20window\x20anchored\x20here\x20is\x20unreachable)':x==='progress.current_time'?'\x20(entry\x20time\x20of\x20the\x20window\x27s\x20source\x20node\x20—\x20witness-derived\x20via\x20OrderProgress,\x20one\x20Guard\x20serves\x20every\x20order)':x==='absolute_date'?'\x20(per-order\x20instance\x20Guard\x20—\x20the\x20absolute\x20date\x20differs\x20per\x20booking)':'';return'Time\x20windows\x20for\x20\x27'+w+'\x27\x20anchor\x20to\x20'+x+y;})}:{},'blueprint':{'nodes':i['nodes']['map'](w=>({'id':w['id'],'type':w['type'],'purpose':w['purpose']})),'edges':i['edges']['map'](w=>({'from':w['from'],'to':w['to'],'relation':w['relation'],'required':w['required']}))},'evaluation_preview':i['evaluationPreview'],'graph_validation':{'valid':j['valid'],'hard_violations':j['hardViolations']['map'](w=>({'id':w['id'],'description':w['description'],'fix':w['fixSuggestion']})),'soft_notes':j['softViolations']['map'](w=>({'id':w['id'],'description':w['description']}))},'harness_check':{'module_constraints':m['map'](w=>({'module':w['module'],'plan_satisfied':w['adopted'],'missing':w['missingConstraints'],'reason':w['reason'],'estimated_score_boost':w['estimatedScoreBoost']})),'blocking_issues':q['map'](w=>({'module':w['module'],'missing_constraints':w['missingConstraints'],'fix':w['reason']})),'deploy_time_checks':n,'recipient_design_guidance':p},'game_theory':{'summary':r['summary'],'coverage':r['coveredCount']+'/'+r['totalCount'],'exposed_scenarios':r['exposedScenarios'],'wow_alignments':r['wowAlignments'],'scenarios':r['results']['map'](w=>({'scenario':w['scenario'],'covered':w['covered'],'conflict':w['conflict'],'user_protection':w['userProtection'],'evaluation_metric':w['evaluationMetric'],'recommendation':w['recommendation']}))},'workflow_design_assessment':{'score':s['score'],'summary':s['summary'],'findings':s['findings']['map'](w=>({'kind':w['kind'],'severity':w['severity'],'message':w['message'],'fix':w['fix']})),'checks':s['checks']['map'](w=>({'id':w['id'],'dimension':w['dimension'],'passed':w['passed'],'severity':w['severity'],'message':w['message'],'fix':w['fix']}))},'creation_plan':t,'post_deploy_steps':o,'warnings':e['warnings'],'next_action':q['length']>0x0?'Resolve\x20the\x20blocking_issues\x20above\x20(adjust\x20guide_confirm\x20payment/trust/modules,\x20or\x20accept\x20and\x20drop\x20the\x20affected\x20module\x20via\x20guide_confirm.adopted_module_ids),\x20then\x20call\x20merchant_guide\x20again.':'Plan\x20ready.\x20Materialize:\x20create\x20the\x20objects\x20in\x20creation_plan\x20order\x20via\x20onchain_operations,\x20then\x20run\x20post_deploy_steps\x20in\x20order\x20(compensation\x20fund\x20top-up,\x20arbitration\x20unpause,\x20per-order\x20settlement\x20via\x20alloc_by_guard).'};}export function listBusinessModules(){return CORE_BUSINESS_MODULES['map'](a=>({'id':a['id'],'name':a['name'],'description':a['description'],'industry_fit':a['industryFit'],'addresses_pain_points':a['addressesPainPoints'],'requires_keeper':a['requiresKeeper']}));}
1
+ import{analyzeIntent}from'./intent-analyzer.js';import{compileTemplate}from'../../composition/compile.js';import{reflux,auditScore}from'../../composition/reflux.js';import{planBlueprint}from'../../composition/blueprint-view.js';import{checkGameTheoryConstraints}from'./game-theory.js';import{assessWorkflowDesign}from'./workflow-design-assessment.js';import{CORE_BUSINESS_MODULES,getBusinessModule,recommendModules,checkModuleConstraints}from'../../extensions/business-modules.js';import{recipientDesignGuidance}from'../../knowledge/recipient-constraint.js';import{getTemplate,getTemplatesByIndustry}from'../../knowledge/template-loader.js';function derivePlanSatisfiedConstraints(a,b){const c=new Set(),d=i=>a['edges']['some'](j=>j['relation']===i),e=i=>a['nodes']['some'](j=>j['id']===i),f=i=>a['nodes']['some'](j=>j['type']===i),g=i=>a['adoptedModules']['includes'](i);if(d('has_order_allocators'))c['add']('order_allocators_bound');if(d('uses_machine'))c['add']('machine_bound_before_publish');if(d('has_arbitration'))c['add']('arbitration_bound_to_service');if(e('machine'))c['add']('machine_published');if(e('repository'))c['add']('repository_published');if(e('service'))c['add']('service_published');e('permission_arb')&&e('permission')&&c['add']('arbitration_permission_independent');g('independent_arbitration')&&a['nodes']['some'](i=>i['id']['includes']('guard')&&i['id']['includes']('arbitration'))&&c['add']('voting_guard_configured');g('accept_timeout_protection')&&(c['add']('time_guard_configured'),c['add']('adminUnhold_permission'));g('milestone_escrow')&&f('guard')&&c['add']('milestone_forward_guarded');const h=d('has_order_allocators');if(h&&b['payment']['allocation']&&b['payment']['allocation']['length']>0x0){c['add']('allocators_configured');const i=b['payment']['allocation']['reduce']((k,l)=>k+l['percentage'],0x0);if(Math['abs'](i-0x64)<0.001)c['add']('sharing_sum_100');const j=b['payment']['allocation']['find'](k=>k['recipient']==='platform');if(j&&j['percentage']===0x0)c['add']('platform_fee_zero');g('supplier_collaboration')&&(c['add']('allocation_sharing_configured'),c['add']('demand_configured'));}return g('wip_provenance')&&e('repository')&&c['add']('wip_hash_before_delivery'),g('subscription_with_proof')&&e('repository')&&(c['add']('delivery_guard_per_cycle'),c['add']('repository_updated')),g('damage_attestation')&&(c['add']('pre_rental_hash'),c['add']('post_rental_hash')),g('refund_guarantee')&&(c['add']('compensation_fund_positive'),c['add']('refund_guard_configured')),c;}function deriveDeployTimeChecks(a){const b=[];return a['nodes']['some'](c=>c['id']==='machine')&&b['push']('Machine\x20published\x20AND\x20bound\x20to\x20Service\x20BEFORE\x20Service.publish\x20(machine\x20is\x20immutable\x20after\x20publish)'),a['edges']['some'](c=>c['relation']==='has_order_allocators')&&(b['push']('Service.order_allocators\x20bound\x20(verify\x20via\x20query_objects\x20after\x20publish\x20—\x20order_allocators\x20is\x20FROZEN\x20at\x20publish)'),b['push']('Settlement\x20is\x20NOT\x20triggered\x20by\x20reaching\x20a\x20Machine\x20node\x20alone\x20—\x20an\x20explicit\x20alloc_by_guard\x20call\x20(keeper\x20or\x20merchant)\x20fires\x20the\x20settlement\x20Allocator\x20once\x20its\x20Guard\x20passes.\x20Declare\x20the\x20node->allocator\x20trigger\x20(which\x20terminal\x20node\x20unlocks\x20settlement)\x20and\x20schedule\x20the\x20keeper\x20step;\x20otherwise\x20orders\x20stall\x20at\x20the\x20settle\x20node\x20with\x20allocation_state=pending')),(a['adoptedModules']['includes']('refund_guarantee')||a['nodes']['some'](c=>c['id']==='arbitration'))&&b['push']('compensation_fund\x20MUST\x20be\x20topped\x20up\x20BEFORE\x20any\x20payout:\x20a\x20claim\x20against\x20an\x20empty\x20fund\x20aborts\x20(service.move\x20E_COMPENSATION_NOT_MATCH).\x20Add\x20a\x20compensation_fund_add\x20step\x20sized\x20>=\x203x\x20the\x20highest\x20single\x20order\x20(3x\x20IS\x20the\x20chain\x27s\x20hard\x20award\x20ceiling,\x20MAX_INDEMNITY_MULTIPLE)\x20and\x20verify\x20the\x20on-chain\x20balance\x20before\x20going\x20live'),a['nodes']['some'](c=>c['id']==='arbitration')&&(b['push']('Arbitration.permission\x20!=\x20Service.permission\x20on-chain\x20(E_ARBITRATION_PERMISSION_CONFLICT=33)'),b['push']('A\x20freshly\x20created\x20Arbitration\x20defaults\x20to\x20PAUSED\x20—\x20unpause\x20it\x20(arbitration\x20activation)\x20before\x20the\x20first\x20case\x20can\x20be\x20filed,\x20otherwise\x20dispute\x20filing\x20aborts')),a['nodes']['some'](c=>c['id']==='repository')&&b['push']('Repository\x20published\x20and\x20Guard\x20write\x20validation\x20configured'),b['push']('After\x20materialization,\x20confirm\x20the\x20on-chain\x20state\x20matches\x20this\x20plan\x20(query_toolkit\x20query_type=\x27service_panorama\x27)'),b;}function derivePostDeploySteps(a){const b=[];return(a['adoptedModules']['includes']('refund_guarantee')||a['nodes']['some'](c=>c['id']==='arbitration'))&&b['push']({'order':b['length']+0x1,'id':'compensation_fund_topup','title':'Top\x20up\x20the\x20compensation\x20fund','when':'After\x20the\x20Service\x20object\x20is\x20created,\x20BEFORE\x20the\x20service\x20goes\x20live\x20(before\x20the\x20first\x20order)','action':'Call\x20compensation_fund_add\x20sized\x20>=\x203x\x20the\x20highest\x20single\x20order\x20(3x\x20=\x20the\x20chain\x27s\x20hard\x20award\x20ceiling,\x20MAX_INDEMNITY_MULTIPLE;\x20above\x203x\x20only\x20buys\x20headroom\x20for\x20concurrent\x20claims),\x20then\x20verify\x20the\x20on-chain\x20fund\x20balance\x20via\x20query_objects','tool_hint':'onchain_operations\x20(service.compensation_fund_add)','failure_if_skipped':'a\x20compensation\x20claim\x20against\x20an\x20empty\x20fund\x20aborts\x20(E_COMPENSATION_NOT_MATCH,\x20testnet\x20lesson\x20R-4)'}),a['nodes']['some'](c=>c['id']==='arbitration')&&b['push']({'order':b['length']+0x1,'id':'arbitration_unpause','title':'Activate\x20the\x20Arbitration\x20(unpause)','when':'Immediately\x20after\x20the\x20Arbitration\x20object\x20is\x20created,\x20before\x20the\x20first\x20dispute\x20is\x20filed','action':'Unpause/activate\x20the\x20Arbitration\x20so\x20dispute\x20filing\x20is\x20accepted;\x20keep\x20its\x20Permission\x20distinct\x20from\x20the\x20Service\x20Permission\x20(E_ARBITRATION_PERMISSION_CONFLICT=33)','tool_hint':'onchain_operations\x20(arbitration\x20activation)','failure_if_skipped':'a\x20freshly\x20created\x20Arbitration\x20defaults\x20to\x20PAUSED\x20—\x20dispute\x20filing\x20aborts\x20(testnet\x20lesson\x20R-5)'}),a['edges']['some'](c=>c['relation']==='has_order_allocators')&&b['push']({'order':b['length']+0x1,'id':'settlement_alloc_by_guard','title':'Fire\x20settlement\x20via\x20alloc_by_guard\x20(keeper/merchant\x20step)','when':'Recurring\x20—\x20after\x20EACH\x20order\x20reaches\x20its\x20settlement\x20terminal\x20node\x20(declare\x20which\x20node\x20unlocks\x20settlement)','action':'Call\x20alloc_by_guard\x20on\x20the\x20order\x27s\x20allocation\x20with\x20the\x20settlement\x20Guard;\x20reaching\x20the\x20Machine\x20node\x20alone\x20does\x20NOT\x20settle\x20(allocation_state\x20stays\x20pending)','tool_hint':'onchain_operations\x20(allocation.alloc_by_guard);\x20schedule\x20as\x20a\x20keeper\x20step','failure_if_skipped':'orders\x20stall\x20at\x20the\x20settle\x20node\x20with\x20funds\x20locked\x20in\x20escrow\x20(testnet\x20lesson\x20R-2)'}),b['push']({'order':b['length']+0x1,'id':'verify_service_panorama','title':'Verify\x20the\x20on-chain\x20state\x20matches\x20the\x20plan','when':'After\x20all\x20creation\x20steps\x20and\x20the\x20steps\x20above\x20are\x20done','action':'Run\x20the\x20service\x20panorama\x20query\x20and\x20diff\x20it\x20against\x20this\x20plan\x27s\x20blueprint/creation_plan','tool_hint':'query_toolkit\x20query_type=\x27service_panorama\x27','failure_if_skipped':'plan/chain\x20drift\x20(missing\x20binding,\x20wrong\x20allocator\x20order)\x20stays\x20undetected\x20until\x20an\x20order\x20hits\x20it'}),b;}function buildCreationPlan(a){const b=[],c=new Map(a['nodes']['map'](k=>[k['id'],k])),f=new Map();for(const k of a['nodes'])f['set'](k['id'],new Set());for(const l of a['edges']){if(!f['has'](l['from'])||!c['has'](l['to']))continue;const m=l['relation']==='has_guard'?l['to']:l['from'],o=l['relation']==='has_guard'?l['from']:l['to'];if(m===o||!f['has'](m))continue;f['get'](m)['add'](o);}for(const p of a['nodes']){for(const q of Object['values'](p['config'])){q['type']==='address_ref'&&q['targetId']!==p['id']&&f['has'](q['targetId'])&&f['get'](p['id'])['add'](q['targetId']);}}const g=a['nodes']['filter'](r=>r['type']==='service')['map'](r=>r['id']);if(g['length']>0x0)for(const r of a['nodes']){if(r['type']!=='guard')continue;const s=f['get'](r['id']);if(s===undefined)continue;for(const t of g)s['add'](t);}const h=new Map([...f]['map'](([u,v])=>[u,[...v]])),i=[],j=new Map(f);while(j['size']>0x0){const u=[...j['entries']()]['filter'](([,v])=>v['size']===0x0)['map'](([v])=>v);if(u['length']===0x0){i['push'](...j['keys']());break;}u['sort']();for(const v of u){i['push'](v),j['delete'](v);for(const w of j['values']())w['delete'](v);}}return i['forEach']((x,y)=>{const z=c['get'](x),A=z['config']['name'];b['push']({'order':y+0x1,'node_id':x,'object_type':z['type'],'suggested_name':A?.['type']==='string'?A['value']:x,'depends_on':h['get'](x)??[],'operation_hint':'Create\x20'+z['type']+'\x20via\x20onchain_operations,\x20then\x20configure.\x20Purpose:\x20'+z['purpose']});}),b;}function resolveTemplate(a){if(!a)return undefined;const b=getTemplate(a);if(b)return b;const c=getTemplatesByIndustry(a);if(c['length']>0x0)return c[0x0];return undefined;}export async function handleMerchantGuide(a){const b=a['guide_state']??{'intent_text':''},c=a['guide_confirm']??{},d={'intent_text':(a['intent']??b['intent_text']??'')['trim'](),'confirmed_industry':c['industry']??b['confirmed_industry'],'currency':c['currency']??b['currency'],'deliverables':c['deliverables']??b['deliverables'],'payment_override':c['payment']??b['payment_override'],'trust_override':c['trust']??b['trust_override'],'adopted_module_ids':c['adopted_module_ids']??b['adopted_module_ids']};for(const D of Object['keys'](d)){if(d[D]===undefined)delete d[D];}if(!d['intent_text'])throw new Error('merchant_guide\x20requires\x20\x27intent\x27\x20(business\x20description)\x20for\x20Step\x201.\x20'+'Example:\x20intent=\x27I\x20want\x20to\x20offer\x20online\x20design\x20service\x20with\x20milestone\x20payments\x27.\x20'+'Pass\x20the\x20returned\x20guide_state\x20back\x20UNCHANGED\x20on\x20subsequent\x20calls,\x20plus\x20guide_confirm\x20for\x20merchant\x20decisions.');const e=await analyzeIntent(d['intent_text'],{'preferredIndustry':d['confirmed_industry'],'currency':d['currency']});if(!d['confirmed_industry'])return{'action':'merchant_guide','current_step':0x2,'step_name':'Industry\x20Matching','guide_state':d,'intent_draft':e['intent'],'industry_options':{'inferred':e['inferredIndustry'],'confidence':e['industryConfidence'],'similar':e['similarIndustries']},'warnings':e['warnings'],'next_action':'Confirm\x20the\x20industry\x20by\x20calling\x20merchant_guide\x20again\x20with\x20guide_state\x20(UNCHANGED)\x20'+('plus\x20guide_confirm={\x20industry:\x20\x27<one\x20of:\x20'+e['similarIndustries']['join'](',\x20')+'\x20—\x20or\x20any\x20other\x20industry\x20id>\x27\x20}')};const f={...e['intent'],'industry':d['confirmed_industry'],'deliverables':d['deliverables']??e['intent']['deliverables'],'payment':{...e['intent']['payment'],...d['payment_override']??{}},'trust':{...e['intent']['trust'],...d['trust_override']??{}}},g=d['adopted_module_ids']?d['adopted_module_ids']['map'](E=>getBusinessModule(E))['filter'](E=>!!E):recommendModules(d['confirmed_industry'],d['intent_text'],{'maxModules':0x5}),h=a['template_override']??resolveTemplate(d['confirmed_industry']);if(!h)throw new Error('No\x20compilable\x20template\x20found\x20for\x20industry\x20\x27'+d['confirmed_industry']+'\x27.\x20'+'Register\x20a\x20template\x20via\x20industry_pack_operation\x20or\x20pass\x20template_override\x20explicitly.');const i={'currency':d['currency']??f['payment']['currency'],...d['payment_override']?{'payment':d['payment_override']}:{},...d['trust_override']?{'trust':d['trust_override']}:{},...d['deliverables']?{'deliverables':d['deliverables']}:{},...d['adopted_module_ids']?{'adopted_module_ids':d['adopted_module_ids']}:{}},j={};for(const E of g){for(const F of E['templateRefs']){F['object_type']==='guard'&&(j[F['template_id']]={'kind':'template','template_id':F['template_id']});}}const l=compileTemplate(h,i,{'nameBase':a['name_base']??h['id'],'intent':d['intent_text'],'guardResolutions':j}),m=reflux(l['plan']),n=m['plan'],o=m['audit'],p=auditScore(o),q=planBlueprint(n,f,g['map'](G=>G['id'])),r=l['blockers']['map'](G=>({'module':'template','missing_constraints':[G['code']],'fix':G['detail']})),s=derivePlanSatisfiedConstraints(q,f),t=g['map'](G=>checkModuleConstraints(G,s)),u=deriveDeployTimeChecks(q),w=derivePostDeploySteps(q),x=q['edges']['some'](G=>G['relation']==='has_order_allocators')?recipientDesignGuidance()['map'](G=>({'id':G['id'],'move_recipient':G['move_recipient'],'semantics':G['semantics'],'required_constraints':G['required_constraints'],'finding_if_unmet':G['finding_if_unmet']})):undefined,y=[...t['filter'](G=>!G['adopted']),...r],z=checkGameTheoryConstraints(q,f),A=assessWorkflowDesign(q),B=buildCreationPlan(q),C=h?{'name':h['id'],'display_name':h['variant']+'\x20archetype\x20('+h['industry']+')','source':a['template_override']?'custom':'builtin','risk_appetite':'medium','key_risk':h['key_risk'],'machine_shape':h['machine_shape']['map'](G=>({'name':G['name'],'role':G['role'],...G['operator']?{'operator':G['operator']}:{},...G['semantic_role']?{'semantic_role':G['semantic_role']}:{}})),'guards':h['guards']['map'](G=>({'template_id':G['template_id'],'host':G['host'],'purpose':G['purpose']})),'allocator':h['allocator'],'risk_constraints':{},'build_notes':h['build_notes']??[],...h['time_anchors']?{'time_anchors':h['time_anchors']}:{}}:undefined;return{'action':'merchant_guide','current_step':y['length']>0x0?0x9:0xa,'step_name':y['length']>0x0?'Harness\x20Check\x20(issues\x20found)':'Submission\x20Plan\x20Ready','guide_state':{...d,'adopted_module_ids':g['map'](G=>G['id'])},'intent':{'intent_type':f['intent'],'industry':f['industry'],'roles':f['roles'],'deliverables':f['deliverables'],'payment':f['payment'],'trust':f['trust']},'adopted_modules':g['map'](G=>({'id':G['id'],'name':G['name'],'description':G['description'],'requires_keeper':G['requiresKeeper'],'keeper_hint':G['keeperHint'],'user_protections':G['userProtections'],'merchant_obligations':G['merchantObligations']})),'mode_prior':C,...C?.['time_anchors']?{'time_anchor_instructions':Object['entries'](C['time_anchors'])['map'](([G,H])=>{const I=H==='order.time'?'\x20(order-creation\x20time\x20—\x20PRE-checkout\x20branches\x20only;\x20a\x20post-checkout\x20window\x20anchored\x20here\x20is\x20unreachable)':H==='progress.current_time'?'\x20(entry\x20time\x20of\x20the\x20window\x27s\x20source\x20node\x20—\x20witness-derived\x20via\x20OrderProgress,\x20one\x20Guard\x20serves\x20every\x20order)':H==='absolute_date'?'\x20(per-order\x20instance\x20Guard\x20—\x20the\x20absolute\x20date\x20differs\x20per\x20booking)':'';return'Time\x20windows\x20for\x20\x27'+G+'\x27\x20anchor\x20to\x20'+H+I;})}:{},'blueprint':{'nodes':q['nodes']['map'](G=>({'id':G['id'],'type':G['type'],'purpose':G['purpose']})),'edges':q['edges']['map'](G=>({'from':G['from'],'to':G['to'],'relation':G['relation'],'required':G['required']}))},'evaluation_preview':{'estimatedRiskScore':p,'estimatedTrustScore':Math['max'](0x0,0x64-p),'estimatedCompletenessScore':Math['min'](0x64,0x1e+g['length']*0x8),'keyRisks':o['findings']['filter'](G=>G['level']==='critical'||G['level']==='high')['map'](G=>G['title']),'strengths':o['findings']['filter'](G=>G['level']==='info')['map'](G=>G['title']),'moduleBoosts':{}},'graph_validation':{'valid':o['issues']['length']===0x0,'hard_violations':o['issues']['map'](G=>({'id':G['code'],'description':G['detail'],'fix':'Fix\x20the\x20Plan\x20structure'})),'soft_notes':o['findings']['filter'](G=>G['level']==='medium'||G['level']==='low')['map'](G=>({'id':G['rule_id'],'description':G['title']}))},'harness_check':{'module_constraints':t['map'](G=>({'module':G['module'],'plan_satisfied':G['adopted'],'missing':G['missingConstraints'],'reason':G['reason'],'estimated_score_boost':G['estimatedScoreBoost']})),'blocking_issues':[...t['filter'](G=>!G['adopted'])['map'](G=>({'module':G['module'],'missing_constraints':G['missingConstraints'],'fix':G['reason']})),...r['map'](G=>({'module':G['module'],'missing_constraints':G['missing_constraints'],'fix':G['fix']}))],'deploy_time_checks':u,'recipient_design_guidance':x},'game_theory':{'summary':z['summary'],'coverage':z['coveredCount']+'/'+z['totalCount'],'exposed_scenarios':z['exposedScenarios'],'wow_alignments':z['wowAlignments'],'scenarios':z['results']['map'](G=>({'scenario':G['scenario'],'covered':G['covered'],'conflict':G['conflict'],'user_protection':G['userProtection'],'evaluation_metric':G['evaluationMetric'],'recommendation':G['recommendation']}))},'workflow_design_assessment':{'score':A['score'],'summary':A['summary'],'findings':A['findings']['map'](G=>({'kind':G['kind'],'severity':G['severity'],'message':G['message'],'fix':G['fix']})),'checks':A['checks']['map'](G=>({'id':G['id'],'dimension':G['dimension'],'passed':G['passed'],'severity':G['severity'],'message':G['message'],'fix':G['fix']}))},'creation_plan':B,'post_deploy_steps':w,'warnings':e['warnings'],'next_action':y['length']>0x0?'Resolve\x20the\x20blocking_issues\x20above\x20(adjust\x20guide_confirm\x20payment/trust/modules,\x20or\x20accept\x20and\x20drop\x20the\x20affected\x20module\x20via\x20guide_confirm.adopted_module_ids),\x20then\x20call\x20merchant_guide\x20again.':'Plan\x20ready.\x20Materialize:\x20create\x20the\x20objects\x20in\x20creation_plan\x20order\x20via\x20onchain_operations,\x20then\x20run\x20post_deploy_steps\x20in\x20order\x20(compensation\x20fund\x20top-up,\x20arbitration\x20unpause,\x20per-order\x20settlement\x20via\x20alloc_by_guard).','plan':n,'audit':{'issues':o['issues'],'findings':o['findings'],'blocking':o['blocking'],'score':p},'reflux':{'applied':m['applied'],'blocks':m['blocks'],'iterations':m['iterations']}};}export function listBusinessModules(){return CORE_BUSINESS_MODULES['map'](a=>({'id':a['id'],'name':a['name'],'description':a['description'],'industry_fit':a['industryFit'],'addresses_pain_points':a['addressesPainPoints'],'requires_keeper':a['requiresKeeper']}));}
@@ -1 +1 @@
1
- import{getIndustryModeRegistry,getMetricRegistry,getConstraintRegistry}from'../../extensions/index.js';import{inferTraitsFromDescription,findSimilarIndustries,detectDomainPriors,filterConsistentIndustries}from'../../knowledge/industry-generalizer.js';import{resolveObjective,buildStrategyIntent,suggestLevers}from'../../persona/strategy-intent.js';export const LOCAL_MODE_OWNER='local';function locationSensitivity(a){if(a['has_logistics'])return'logistics';if(a['pure_digital'])return'near';return'strict';}const RM1_11_NODE_REGEX=/(^|_)(disputed?|arbitration|arb)(_|$)|^(refund|refunded|deposit_refunded|deposit_deducted|cancel|cancelled)$/i;function validateMachineShape(a,b){const c=[];if(!Array['isArray'](a))return c;const d=new Set();for(const e of a){const f=e?.['name'];if(typeof f!=='string'||!f){c['push'](b+':\x20every\x20node\x20must\x20have\x20a\x20non-empty\x20string\x20\x27name\x27');continue;}d['has'](f)&&c['push'](b+':\x20duplicate\x20node\x20name\x20\x27'+f+'\x27\x20(R-M1-10)'),d['add'](f),RM1_11_NODE_REGEX['test'](f)&&c['push'](b+':\x20node\x20\x27'+f+'\x27\x20violates\x20R-M1-11\x20—\x20dispute/refund\x20flows\x20must\x20NOT\x20be\x20'+'modeled\x20as\x20Machine\x20nodes.\x20Disputes\x20flow\x20through\x20Service.arbitrations\x20→\x20Arbitration.dispute()\x20'+'independently\x20of\x20the\x20Machine.\x20Use\x20business-state\x20nodes\x20(e.g.\x20\x27cancelled\x27,\x20\x27return_approved\x27)\x20'+'and\x20route\x20fund\x20refunds\x20via\x20Allocator\x20triggered\x20by\x20those\x20states.');}return c;}function modeLevers(a){const b=[];return(a['capabilities_used']['some'](d=>d['startsWith']('reward.'))||a['flywheel']?.['rewardStrategy']&&a['flywheel']['rewardStrategy']!=='User-defined')&&b['push']('reward'),(a['flywheel']?.['discountStrategy']&&a['flywheel']['discountStrategy']!=='User-defined'||a['config_overrides']?.['service']?.['first_order_discount']===!![])&&b['push']('discount'),(a['capabilities_used']['includes']('guard.validate_buy')||a['guards']['some'](c=>c['template_id']['includes']('buy')))&&b['push']('buy_guard'),a['capabilities_used']['includes']('machine.node_topology')&&a['machine_shape']['length']>0x0&&b['push']('machine_design'),b;}function resolveStrategyObjectives(a){const b=typeof a==='string'?[a]:a??[],c=new Set();for(const d of b){const e=resolveObjective(d);if(e)c['add'](e);}return[...c];}const TRAIT_OBJECTIVE_PRIORS=[{'when':a=>a['trust_sensitivity']==='high'||a['regulatory_intensity']==='high','objective':'buyer_screening','metrics':['dispute_rate','claim_rate'],'target':'buyer\x20eligibility\x20gate\x20covers\x20every\x20party\x20whose\x20identity\x20the\x20trade\x20depends\x20on'},{'when':a=>a['long_cycle'],'objective':'gross_margin_control','metrics':['acceptance_rate','cycle_days'],'target':'margin\x20held\x20across\x20the\x20full\x20delivery\x20cycle,\x20not\x20per\x20milestone'},{'when':a=>a['consumption_frequency']==='frequent','objective':'sales_priority','metrics':['order_volume','repeat_rate'],'target':'repeat-purchase\x20order\x20volume\x20over\x20the\x20next\x2030\x20days'},{'when':a=>a['avg_ticket_size']==='large'||a['deposit_required'],'objective':'profit_priority','metrics':['gross_margin','escrow_balance'],'target':'per-order\x20margin\x20first;\x20the\x20ticket\x20is\x20large\x20enough\x20that\x20margin\x20dominates\x20volume'},{'when':a=>a['has_logistics'],'objective':'gross_margin_control','metrics':['fulfilment_cost_ratio','on_time_rate'],'target':'fulfilment\x20cost\x20held\x20inside\x20the\x20declared\x20merchant\x20share'}];function traitDerivedObjectives(a,b=0x2){const c=[],d=new Set();for(const e of TRAIT_OBJECTIVE_PRIORS){if(c['length']>=b)break;if(d['has'](e['objective']))continue;if(!e['when'](a))continue;d['add'](e['objective']),c['push']({'objective':e['objective'],'metrics':[...e['metrics']],'target':e['target']});}return c;}export function handleRecommendIndustry(a){const b=(a['intent']??a['project_description']??a['project_name']??'')['trim']();if(!b)throw new Error('recommend_industry\x20requires\x20\x27intent\x27\x20(business\x20description\x20text).\x20'+'Example:\x20intent=\x27I\x20rent\x20cameras\x20to\x20photographers\x20with\x20deposit\x20and\x20damage\x20inspection\x27.');const c=inferTraitsFromDescription(b),d=detectDomainPriors(b),e=new Set(d['flatMap'](y=>y['industries'])),f=new Map();for(const y of d){for(const z of y['industries']){f['set'](z,Math['min'](0.25,(f['get'](z)??0x0)+y['boost']));}}const g=findSimilarIndustries(c['traits'],undefined,{'trait_confidence':c['trait_confidence']}),h=g['map'](A=>{const B=f['get'](A['industry'])??0x0;if(B===0x0)return A;const C=Math['min'](0x1,Number((A['similarity']+B)['toFixed'](0x4)));return{...A,'similarity':C,'trait_distance':Number((0x1-C)['toFixed'](0x4)),'domain_prior':!![]};}),{consistent:i,inconsistent:j}=filterConsistentIndustries(h,c['traits'],c['trait_confidence']),k=j['map'](A=>({'industry':A['industry'],'contradicted_requirements':A['contradictions']['map'](B=>B['trait']+'='+String(B['value'])+'\x20('+B['reason']+')')}));i['sort']((A,B)=>B['similarity']-A['similarity']||A['industry']['localeCompare'](B['industry']));const l=i['slice'](0x0,0x3),m=resolveStrategyObjectives(a['strategy']),n=m['map'](A=>buildStrategyIntent(A)),o=n['length']>0x0||c['confidence']===0x0?[]:traitDerivedObjectives(c['traits'])['map'](A=>buildStrategyIntent(A['objective'],A['target'],A['metrics'])),q=[...n,...o],r=[...new Set(q['flatMap'](A=>A['levers']))],s=getIndustryModeRegistry(),t=l['map'](A=>{const B=s['getMode'](A['industry']),C=B?modeLevers(B):[],D=r['filter'](F=>C['includes'](F)),E=r['length']>0x0?{'score':D['length']/r['length'],'matched_levers':D,'missing_levers':r['filter'](F=>!C['includes'](F))}:undefined;return{'industry':A['industry'],'similarity':A['similarity'],'trait_distance':A['trait_distance'],'matched_traits':A['matched_traits'],'contradicted_traits':A['contradicted_traits']??[],'evidenced_traits':A['evidenced_traits']??[],'domain_prior':e['has'](A['industry'])?!![]:undefined,'requirement_support':A['requirement_support'],'location_sensitivity':B?locationSensitivity(B['traits']):'strict','trust_selling_points':B?B['flywheel']?.['trustSellingPoints']??[]:[],'build_notes':B?.['build_notes']??[],'strategy_alignment':E};});r['length']>0x0&&t['sort']((A,B)=>{const C=A['similarity']*0.7+(A['strategy_alignment']?.['score']??0x0)*0.3,D=B['similarity']*0.7+(B['strategy_alignment']?.['score']??0x0)*0.3;return D-C;});const u=t[0x0],w=d['length']>0x0?'\x20Domain\x20prior\x20applied:\x20'+d['map'](A=>A['domain']+'\x20('+A['matched_keywords']['slice'](0x0,0x6)['join']('/')+')')['join'](';\x20')+'.':'',x=k['length']>0x0?'\x20Excluded\x20'+k['length']+'\x20industry\x20mode(s)\x20whose\x20required\x20traits\x20the\x20inference\x20contradicts:\x20'+k['map'](A=>A['industry']+'\x20['+A['contradicted_requirements']['join'](';\x20')+']')['join']('\x20|\x20')+'.':'';return{'action':'recommend_industry','intent':b,'inferred_traits':c['traits'],'inference_confidence':c['confidence'],'matched_keywords':c['matched_keywords'],'domain_priors':d,'strategy_intents':q,'lever_suggestions':q['flatMap'](A=>suggestLevers(A)),'recommendations':t,'excluded_by_consistency':k,'hint':u?'Top\x20match:\x20\x27'+u['industry']+'\x27\x20(similarity\x20'+(u['similarity']*0x64)['toFixed'](0x0)+'%'+(r['length']>0x0?',\x20strategy\x20alignment\x20'+((u['strategy_alignment']?.['score']??0x0)*0x64)['toFixed'](0x0)+'%':'')+').\x20Use\x20it\x20to\x20shape\x20the\x20build\x20—\x20run\x20goal_operation\x20action=\x27merchant_guide\x27\x20(or\x20\x27analyze_intent\x27)\x20with\x20this\x20industry\x20context,\x20'+'or\x20choose\x20another\x20industry\x20from\x20\x27recommendations\x27.'+w+x:'No\x20similar\x20industry\x20found.\x20Shape\x20the\x20build\x20from\x20scratch\x20via\x20goal_operation\x20action=\x27merchant_guide\x27.'+w};}export async function handleListModes(){const a=getIndustryModeRegistry(),b=a['listModes']()['filter'](d=>d['source']==='builtin')['map'](d=>({'name':d['name'],'display_name':d['display_name'],'version':d['version'],'key_risk':d['key_risk'],'machine_nodes':d['machine_shape']['map'](e=>e['name']),'buyer_action_nodes':d['machine_shape']['filter'](e=>e['operator']==='order_payer')['map'](e=>e['name']),'similar_industries':d['similar_industries']??[],'location_sensitivity':locationSensitivity(d['traits']),'trust_selling_points':d['flywheel']?.['trustSellingPoints']??[],'build_notes':d['build_notes']??[]})),c=(await a['listUserModes'](LOCAL_MODE_OWNER))['map'](d=>({'name':d['name'],'display_name':d['display_name'],'version':d['version'],'derived_from':d['derived_from']??null,'key_risk':d['key_risk'],'machine_nodes':d['machine_shape']['map'](e=>e['name']),'buyer_action_nodes':d['machine_shape']['filter'](e=>e['operator']==='order_payer')['map'](e=>e['name']),'location_sensitivity':locationSensitivity(d['traits']),'trust_selling_points':d['flywheel']?.['trustSellingPoints']??[],'build_notes':d['build_notes']??[],'evolution_history':(d['evolution_history']??[])['map'](e=>({'version':e['version'],'changed_at':e['changed_at'],'changes':e['changes']}))}));return{'action':'list_modes','builtin_modes':b,'user_modes':c,'owner':LOCAL_MODE_OWNER,'hint':'Use\x20a\x20builtin\x20mode\x20name\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build\x20(see\x20recommend_industry\x20/\x20merchant_guide).\x20'+'Use\x20derive_user_mode\x20to\x20customize\x20a\x20builtin\x20mode,\x20or\x20register_user_mode\x20for\x20a\x20fully\x20custom\x20mode.\x20'+'User\x20modes\x20are\x20referenced\x20as\x20\x27<name>\x27\x20in\x20derive/evolve/unregister\x20actions.'};}export async function handleDeriveUserMode(a){const b=requireField(a['mode_source'],'mode_source'),c=requireField(a['mode_name'],'mode_name'),d=a['mode_changes']??{},e=validateMachineShape(d['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('derive_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=await f['deriveMode'](b,d,LOCAL_MODE_OWNER,c,a['mode_display_name']);if(!g)throw new Error('derive_user_mode\x20failed:\x20source\x20mode\x20\x27'+b+'\x27\x20not\x20found,\x20or\x20name\x20\x27'+c+'\x27\x20conflicts\x20'+'with\x20a\x20builtin/existing\x20user\x20mode.\x20Call\x20list_modes\x20to\x20see\x20available\x20names.');return{'action':'derive_user_mode','mode':summarizeUserMode(g),'hint':'Mode\x20\x27'+c+'\x27\x20derived\x20from\x20\x27'+b+'\x27.\x20Use\x20it\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build.\x20'+'Iterate\x20with\x20evolve_user_mode.'};}export async function handleEvolveUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=requireField(a['mode_change_description'],'mode_change_description'),d=a['mode_changes']??{},e=validateMachineShape(d['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('evolve_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=await f['evolveMode'](b,d,LOCAL_MODE_OWNER,c,a['mode_bump_version']??!![]);if(!g)throw new Error('evolve_user_mode\x20failed:\x20user\x20mode\x20\x27'+b+'\x27\x20not\x20found\x20for\x20owner\x20\x27'+LOCAL_MODE_OWNER+'\x27.\x20'+'Call\x20list_modes\x20to\x20see\x20your\x20modes.');return{'action':'evolve_user_mode','mode':summarizeUserMode(g),'hint':'Mode\x20\x27'+b+'\x27\x20evolved\x20to\x20'+g['version']+'.\x20Evolution\x20history\x20recorded.'};}export async function handleRegisterUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=a['mode_changes']??{},d=[];(!Array['isArray'](c['machine_shape'])||c['machine_shape']['length']===0x0)&&d['push']('machine_shape\x20(non-empty\x20array\x20of\x20{name,\x20role})');(typeof c['key_risk']!=='string'||!c['key_risk'])&&d['push']('key_risk\x20(string\x20describing\x20the\x20industry\x27s\x20key\x20risk)');if(d['length']>0x0)throw new Error('register_user_mode\x20requires\x20these\x20fields\x20in\x20mode_changes:\x20'+d['join'](',\x20')+'.\x20'+'Tip:\x20derive_user_mode\x20from\x20a\x20builtin\x20mode\x20is\x20usually\x20easier\x20than\x20registering\x20from\x20scratch.');const e=validateMachineShape(c['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('register_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=f['getMode']('general');if(!g)throw new Error('Builtin\x20mode\x20\x27general\x27\x20not\x20registered\x20—\x20cannot\x20build\x20custom\x20mode\x20defaults');const h={...g,...c,'name':b,'display_name':a['mode_display_name']??b,'version':'v1','source':'custom','owner':LOCAL_MODE_OWNER,'derived_from':undefined,'evolution_history':[]},i=await f['registerUserMode'](h,LOCAL_MODE_OWNER);if(!i)throw new Error('register_user_mode\x20failed:\x20name\x20\x27'+b+'\x27\x20conflicts\x20with\x20a\x20builtin/existing\x20user\x20mode,\x20'+'or\x20payload\x20is\x20invalid.\x20Call\x20list_modes\x20to\x20see\x20available\x20names.');return{'action':'register_user_mode','mode':summarizeUserMode(h),'hint':'Custom\x20mode\x20\x27'+b+'\x27\x20registered.\x20Use\x20it\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build.'};}export async function handleUnregisterUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=getIndustryModeRegistry(),d=await c['unregisterUserMode'](b,LOCAL_MODE_OWNER);if(!d)throw new Error('unregister_user_mode\x20failed:\x20user\x20mode\x20\x27'+b+'\x27\x20not\x20found\x20for\x20owner\x20\x27'+LOCAL_MODE_OWNER+'\x27.');return{'action':'unregister_user_mode','removed':!![],'mode_name':b};}export async function handleRegisterCustomMetric(a){const b=requireField(a['metric_id'],'metric_id'),c=requireField(a['metric_display_name'],'metric_display_name'),d=requireField(a['metric_description'],'metric_description'),e=requireField(a['metric_type'],'metric_type'),f=requireField(a['metric_scale'],'metric_scale'),g=await getMetricRegistry()['registerCustomMetric'](b,c,d,e,f,LOCAL_MODE_OWNER,a['metric_weight']);if(!g)throw new Error('register_custom_metric\x20failed:\x20metric_id\x20\x27'+b+'\x27\x20already\x20exists\x20or\x20fields\x20are\x20invalid.');return{'action':'register_custom_metric','metric':{'metric_id':b,'display_name':c,'description':d,'type':e,'scale':f,'weight':a['metric_weight']??0x1,'scope':'custom','owner':LOCAL_MODE_OWNER},'hint':'Custom\x20metric\x20\x27'+b+'\x27\x20registered\x20globally\x20and\x20persisted\x20(survives\x20restart)\x20—\x20all\x20modes\x20reference\x20it\x20in\x20evaluation.'};}export async function handleUnregisterCustomMetric(a){const b=requireField(a['metric_id'],'metric_id'),c=await getMetricRegistry()['unregisterMetric'](b,LOCAL_MODE_OWNER);if(!c)throw new Error('unregister_custom_metric\x20failed:\x20custom\x20metric\x20\x27'+b+'\x27\x20not\x20found\x20(builtin\x20metrics\x20cannot\x20be\x20deleted).\x20'+'Call\x20list_metrics_constraints\x20with\x20scope_filter=\x27custom\x27\x20to\x20see\x20deletable\x20metrics.');return{'action':'unregister_custom_metric','removed':!![],'metric_id':b};}export async function handleRegisterCustomConstraint(a){const b=requireField(a['constraint_id'],'constraint_id'),c=requireField(a['constraint_display_name'],'constraint_display_name'),d=requireField(a['constraint_description'],'constraint_description'),e=a['constraint_rule'];if(!e||typeof e!=='object'||!('type'in e))throw new Error('constraint_rule\x20is\x20required\x20and\x20must\x20be\x20one\x20of:\x20'+'{type:\x27capability_required\x27,\x20capability_id}\x20|\x20{type:\x27capability_forbidden\x27,\x20capability_id}\x20|\x20'+'{type:\x27numeric_limit\x27,\x20field,\x20max?,\x20min?}\x20|\x20{type:\x27condition_required\x27,\x20condition,\x20ai_evaluated:true}');const f=await getConstraintRegistry()['registerCustomConstraint'](b,c,d,e,LOCAL_MODE_OWNER,a['constraint_severity']??'soft',a['constraint_on_violation']??'warn');if(!f)throw new Error('register_custom_constraint\x20failed:\x20constraint_id\x20\x27'+b+'\x27\x20already\x20exists\x20or\x20rule\x20is\x20invalid.');return{'action':'register_custom_constraint','constraint':{'constraint_id':b,'display_name':c,'description':d,'rule':e,'severity':a['constraint_severity']??'soft','on_violation':a['constraint_on_violation']??'warn','scope':'custom','owner':LOCAL_MODE_OWNER},'hint':'Custom\x20constraint\x20\x27'+b+'\x27\x20registered\x20and\x20persisted\x20(survives\x20restart).\x20\x27hard\x27\x20constraints\x20mark\x20a\x20mode\x20not\x20applicable\x20on\x20violation;\x20\x27soft\x27\x20only\x20warn.'};}export async function handleUnregisterCustomConstraint(a){const b=requireField(a['constraint_id'],'constraint_id'),c=await getConstraintRegistry()['unregisterConstraint'](b,LOCAL_MODE_OWNER);if(!c)throw new Error('unregister_custom_constraint\x20failed:\x20custom\x20constraint\x20\x27'+b+'\x27\x20not\x20found\x20(builtin\x20constraints\x20cannot\x20be\x20deleted).\x20'+'Call\x20list_metrics_constraints\x20with\x20scope_filter=\x27custom\x27\x20to\x20see\x20deletable\x20constraints.');return{'action':'unregister_custom_constraint','removed':!![],'constraint_id':b};}export async function handleListMetricsConstraints(a){const b=(await getMetricRegistry()['listMetrics']({'type':a['metric_type_filter'],'scope':a['scope_filter']}))['map'](d=>({'metric_id':d['metric_id'],'display_name':d['display_name'],'description':d['description'],'type':d['type'],'scale':d['scale'],'weight':d['weight'],'scope':d['scope']})),c=(await getConstraintRegistry()['listConstraints']({'scope':a['scope_filter']}))['map'](d=>({'constraint_id':d['constraint_id'],'display_name':d['display_name'],'description':d['description'],'rule':d['rule'],'severity':d['severity'],'on_violation':d['on_violation'],'scope':d['scope']}));return{'action':'list_metrics_constraints','metrics':b,'constraints':c,'hint':'Register\x20custom\x20entries\x20via\x20register_custom_metric\x20/\x20register_custom_constraint;\x20'+'delete\x20via\x20unregister_custom_metric\x20/\x20unregister_custom_constraint\x20(custom\x20only).\x20'+'Custom\x20entries\x20are\x20persisted\x20and\x20survive\x20restart.\x20'+'Filter\x20with\x20metric_type_filter\x20(\x27risk\x27|\x27benefit\x27)\x20or\x20scope_filter\x20(\x27builtin\x27|\x27custom\x27).'};}function requireField(a,b){if(a===undefined||a===null||typeof a==='string'&&!a['trim']())throw new Error('\x27'+b+'\x27\x20is\x20required\x20for\x20this\x20action');return a;}function summarizeUserMode(a){return{'name':a['name'],'display_name':a['display_name'],'version':a['version'],'derived_from':a['derived_from']??null,'owner':a['owner'],'key_risk':a['key_risk'],'machine_nodes':a['machine_shape']['map'](b=>b['name']),'buyer_action_nodes':a['machine_shape']['filter'](b=>b['operator']==='order_payer')['map'](b=>b['name']),'location_sensitivity':locationSensitivity(a['traits']),'trust_selling_points':a['flywheel']?.['trustSellingPoints']??[],'build_notes':a['build_notes']??[],'evolution_history':(a['evolution_history']??[])['map'](b=>({'version':b['version'],'changed_at':b['changed_at'],'changes':b['changes']}))};}
1
+ import{getIndustryModeRegistry,getMetricRegistry,getConstraintRegistry}from'../../extensions/index.js';import{inferTraitsFromDescription,findSimilarIndustries,detectDomainPriors,filterConsistentIndustries}from'../../knowledge/industry-generalizer.js';import{resolveObjective,buildStrategyIntent,suggestLevers}from'../../persona/strategy-intent.js';import{ANTI_PATTERN_NODE_REGEX}from'../../knowledge/audit-rules.js';export const LOCAL_MODE_OWNER='local';function locationSensitivity(a){if(a['has_logistics'])return'logistics';if(a['pure_digital'])return'near';return'strict';}function validateMachineShape(a,b){const c=[];if(!Array['isArray'](a))return c;const d=new Set();for(const e of a){const f=e?.['name'];if(typeof f!=='string'||!f){c['push'](b+':\x20every\x20node\x20must\x20have\x20a\x20non-empty\x20string\x20\x27name\x27');continue;}d['has'](f)&&c['push'](b+':\x20duplicate\x20node\x20name\x20\x27'+f+'\x27\x20(R-M1-10)'),d['add'](f),ANTI_PATTERN_NODE_REGEX['test'](f)&&c['push'](b+':\x20node\x20\x27'+f+'\x27\x20violates\x20R-M1-11\x20—\x20dispute/refund\x20flows\x20must\x20NOT\x20be\x20'+'modeled\x20as\x20Machine\x20nodes.\x20Disputes\x20flow\x20through\x20Service.arbitrations\x20→\x20Arbitration.dispute()\x20'+'independently\x20of\x20the\x20Machine.\x20Use\x20business-state\x20nodes\x20(e.g.\x20\x27cancel_requested\x27,\x20\x27closed_cancel\x27)\x20'+'and\x20route\x20fund\x20refunds\x20via\x20Allocator\x20triggered\x20by\x20those\x20states.\x20Bare\x20fund-terminal\x20names\x20'+'(\x27refund\x27,\x20\x27cancelled\x27,\x20…)\x20are\x20rejected\x20here\x20—\x20only\x20the\x20template\x20scanner\x20can\x20exempt\x20them,\x20'+'when\x20the\x20refund\x20allocator\x27s\x20guard\x20provably\x20anchors\x20to\x20that\x20state.');}return c;}function modeLevers(a){const b=[];return(a['capabilities_used']['some'](d=>d['startsWith']('reward.'))||a['flywheel']?.['rewardStrategy']&&a['flywheel']['rewardStrategy']!=='User-defined')&&b['push']('reward'),(a['flywheel']?.['discountStrategy']&&a['flywheel']['discountStrategy']!=='User-defined'||a['config_overrides']?.['service']?.['first_order_discount']===!![])&&b['push']('discount'),(a['capabilities_used']['includes']('guard.validate_buy')||a['guards']['some'](c=>c['template_id']['includes']('buy')))&&b['push']('buy_guard'),a['capabilities_used']['includes']('machine.node_topology')&&a['machine_shape']['length']>0x0&&b['push']('machine_design'),b;}function resolveStrategyObjectives(a){const b=typeof a==='string'?[a]:a??[],c=new Set();for(const d of b){const e=resolveObjective(d);if(e)c['add'](e);}return[...c];}const TRAIT_OBJECTIVE_PRIORS=[{'when':a=>a['trust_sensitivity']==='high'||a['regulatory_intensity']==='high','objective':'buyer_screening','metrics':['dispute_rate','claim_rate'],'target':'buyer\x20eligibility\x20gate\x20covers\x20every\x20party\x20whose\x20identity\x20the\x20trade\x20depends\x20on'},{'when':a=>a['long_cycle'],'objective':'gross_margin_control','metrics':['acceptance_rate','cycle_days'],'target':'margin\x20held\x20across\x20the\x20full\x20delivery\x20cycle,\x20not\x20per\x20milestone'},{'when':a=>a['consumption_frequency']==='frequent','objective':'sales_priority','metrics':['order_volume','repeat_rate'],'target':'repeat-purchase\x20order\x20volume\x20over\x20the\x20next\x2030\x20days'},{'when':a=>a['avg_ticket_size']==='large'||a['deposit_required'],'objective':'profit_priority','metrics':['gross_margin','escrow_balance'],'target':'per-order\x20margin\x20first;\x20the\x20ticket\x20is\x20large\x20enough\x20that\x20margin\x20dominates\x20volume'},{'when':a=>a['has_logistics'],'objective':'gross_margin_control','metrics':['fulfilment_cost_ratio','on_time_rate'],'target':'fulfilment\x20cost\x20held\x20inside\x20the\x20declared\x20merchant\x20share'}];function traitDerivedObjectives(a,b=0x2){const c=[],d=new Set();for(const e of TRAIT_OBJECTIVE_PRIORS){if(c['length']>=b)break;if(d['has'](e['objective']))continue;if(!e['when'](a))continue;d['add'](e['objective']),c['push']({'objective':e['objective'],'metrics':[...e['metrics']],'target':e['target']});}return c;}export function handleRecommendIndustry(a){const b=(a['intent']??a['project_description']??a['project_name']??'')['trim']();if(!b)throw new Error('recommend_industry\x20requires\x20\x27intent\x27\x20(business\x20description\x20text).\x20'+'Example:\x20intent=\x27I\x20rent\x20cameras\x20to\x20photographers\x20with\x20deposit\x20and\x20damage\x20inspection\x27.');const c=inferTraitsFromDescription(b),d=detectDomainPriors(b),e=new Set(d['flatMap'](y=>y['industries'])),f=new Map();for(const y of d){for(const z of y['industries']){f['set'](z,Math['min'](0.25,(f['get'](z)??0x0)+y['boost']));}}const g=findSimilarIndustries(c['traits'],undefined,{'trait_confidence':c['trait_confidence']}),h=g['map'](A=>{const B=f['get'](A['industry'])??0x0;if(B===0x0)return A;const C=Math['min'](0x1,Number((A['similarity']+B)['toFixed'](0x4)));return{...A,'similarity':C,'trait_distance':Number((0x1-C)['toFixed'](0x4)),'domain_prior':!![]};}),{consistent:i,inconsistent:j}=filterConsistentIndustries(h,c['traits'],c['trait_confidence']),k=j['map'](A=>({'industry':A['industry'],'contradicted_requirements':A['contradictions']['map'](B=>B['trait']+'='+String(B['value'])+'\x20('+B['reason']+')')}));i['sort']((A,B)=>B['similarity']-A['similarity']||A['industry']['localeCompare'](B['industry']));const l=i['slice'](0x0,0x3),m=resolveStrategyObjectives(a['strategy']),n=m['map'](A=>buildStrategyIntent(A)),o=n['length']>0x0||c['confidence']===0x0?[]:traitDerivedObjectives(c['traits'])['map'](A=>buildStrategyIntent(A['objective'],A['target'],A['metrics'])),q=[...n,...o],r=[...new Set(q['flatMap'](A=>A['levers']))],s=getIndustryModeRegistry(),t=l['map'](A=>{const B=s['getMode'](A['industry']),C=B?modeLevers(B):[],D=r['filter'](F=>C['includes'](F)),E=r['length']>0x0?{'score':D['length']/r['length'],'matched_levers':D,'missing_levers':r['filter'](F=>!C['includes'](F))}:undefined;return{'industry':A['industry'],'similarity':A['similarity'],'trait_distance':A['trait_distance'],'matched_traits':A['matched_traits'],'contradicted_traits':A['contradicted_traits']??[],'evidenced_traits':A['evidenced_traits']??[],'domain_prior':e['has'](A['industry'])?!![]:undefined,'requirement_support':A['requirement_support'],'location_sensitivity':B?locationSensitivity(B['traits']):'strict','trust_selling_points':B?B['flywheel']?.['trustSellingPoints']??[]:[],'build_notes':B?.['build_notes']??[],'strategy_alignment':E};});r['length']>0x0&&t['sort']((A,B)=>{const C=A['similarity']*0.7+(A['strategy_alignment']?.['score']??0x0)*0.3,D=B['similarity']*0.7+(B['strategy_alignment']?.['score']??0x0)*0.3;return D-C;});const u=t[0x0],w=d['length']>0x0?'\x20Domain\x20prior\x20applied:\x20'+d['map'](A=>A['domain']+'\x20('+A['matched_keywords']['slice'](0x0,0x6)['join']('/')+')')['join'](';\x20')+'.':'',x=k['length']>0x0?'\x20Excluded\x20'+k['length']+'\x20industry\x20mode(s)\x20whose\x20required\x20traits\x20the\x20inference\x20contradicts:\x20'+k['map'](A=>A['industry']+'\x20['+A['contradicted_requirements']['join'](';\x20')+']')['join']('\x20|\x20')+'.':'';return{'action':'recommend_industry','intent':b,'inferred_traits':c['traits'],'inference_confidence':c['confidence'],'matched_keywords':c['matched_keywords'],'domain_priors':d,'strategy_intents':q,'lever_suggestions':q['flatMap'](A=>suggestLevers(A)),'recommendations':t,'excluded_by_consistency':k,'hint':u?'Top\x20match:\x20\x27'+u['industry']+'\x27\x20(similarity\x20'+(u['similarity']*0x64)['toFixed'](0x0)+'%'+(r['length']>0x0?',\x20strategy\x20alignment\x20'+((u['strategy_alignment']?.['score']??0x0)*0x64)['toFixed'](0x0)+'%':'')+').\x20Use\x20it\x20to\x20shape\x20the\x20build\x20—\x20run\x20goal_operation\x20action=\x27merchant_guide\x27\x20(or\x20\x27analyze_intent\x27)\x20with\x20this\x20industry\x20context,\x20'+'or\x20choose\x20another\x20industry\x20from\x20\x27recommendations\x27.'+w+x:'No\x20similar\x20industry\x20found.\x20Shape\x20the\x20build\x20from\x20scratch\x20via\x20goal_operation\x20action=\x27merchant_guide\x27.'+w};}export async function handleListModes(){const a=getIndustryModeRegistry(),b=a['listModes']()['filter'](d=>d['source']==='builtin')['map'](d=>({'name':d['name'],'display_name':d['display_name'],'version':d['version'],'key_risk':d['key_risk'],'machine_nodes':d['machine_shape']['map'](e=>e['name']),'buyer_action_nodes':d['machine_shape']['filter'](e=>e['operator']==='order_payer')['map'](e=>e['name']),'similar_industries':d['similar_industries']??[],'location_sensitivity':locationSensitivity(d['traits']),'trust_selling_points':d['flywheel']?.['trustSellingPoints']??[],'build_notes':d['build_notes']??[]})),c=(await a['listUserModes'](LOCAL_MODE_OWNER))['map'](d=>({'name':d['name'],'display_name':d['display_name'],'version':d['version'],'derived_from':d['derived_from']??null,'key_risk':d['key_risk'],'machine_nodes':d['machine_shape']['map'](e=>e['name']),'buyer_action_nodes':d['machine_shape']['filter'](e=>e['operator']==='order_payer')['map'](e=>e['name']),'location_sensitivity':locationSensitivity(d['traits']),'trust_selling_points':d['flywheel']?.['trustSellingPoints']??[],'build_notes':d['build_notes']??[],'evolution_history':(d['evolution_history']??[])['map'](e=>({'version':e['version'],'changed_at':e['changed_at'],'changes':e['changes']}))}));return{'action':'list_modes','builtin_modes':b,'user_modes':c,'owner':LOCAL_MODE_OWNER,'hint':'Use\x20a\x20builtin\x20mode\x20name\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build\x20(see\x20recommend_industry\x20/\x20merchant_guide).\x20'+'Use\x20derive_user_mode\x20to\x20customize\x20a\x20builtin\x20mode,\x20or\x20register_user_mode\x20for\x20a\x20fully\x20custom\x20mode.\x20'+'User\x20modes\x20are\x20referenced\x20as\x20\x27<name>\x27\x20in\x20derive/evolve/unregister\x20actions.'};}export async function handleDeriveUserMode(a){const b=requireField(a['mode_source'],'mode_source'),c=requireField(a['mode_name'],'mode_name'),d=a['mode_changes']??{},e=validateMachineShape(d['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('derive_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=await f['deriveMode'](b,d,LOCAL_MODE_OWNER,c,a['mode_display_name']);if(!g)throw new Error('derive_user_mode\x20failed:\x20source\x20mode\x20\x27'+b+'\x27\x20not\x20found,\x20or\x20name\x20\x27'+c+'\x27\x20conflicts\x20'+'with\x20a\x20builtin/existing\x20user\x20mode.\x20Call\x20list_modes\x20to\x20see\x20available\x20names.');return{'action':'derive_user_mode','mode':summarizeUserMode(g),'hint':'Mode\x20\x27'+c+'\x27\x20derived\x20from\x20\x27'+b+'\x27.\x20Use\x20it\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build.\x20'+'Iterate\x20with\x20evolve_user_mode.'};}export async function handleEvolveUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=requireField(a['mode_change_description'],'mode_change_description'),d=a['mode_changes']??{},e=validateMachineShape(d['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('evolve_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=await f['evolveMode'](b,d,LOCAL_MODE_OWNER,c,a['mode_bump_version']??!![]);if(!g)throw new Error('evolve_user_mode\x20failed:\x20user\x20mode\x20\x27'+b+'\x27\x20not\x20found\x20for\x20owner\x20\x27'+LOCAL_MODE_OWNER+'\x27.\x20'+'Call\x20list_modes\x20to\x20see\x20your\x20modes.');return{'action':'evolve_user_mode','mode':summarizeUserMode(g),'hint':'Mode\x20\x27'+b+'\x27\x20evolved\x20to\x20'+g['version']+'.\x20Evolution\x20history\x20recorded.'};}export async function handleRegisterUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=a['mode_changes']??{},d=[];(!Array['isArray'](c['machine_shape'])||c['machine_shape']['length']===0x0)&&d['push']('machine_shape\x20(non-empty\x20array\x20of\x20{name,\x20role})');(typeof c['key_risk']!=='string'||!c['key_risk'])&&d['push']('key_risk\x20(string\x20describing\x20the\x20industry\x27s\x20key\x20risk)');if(d['length']>0x0)throw new Error('register_user_mode\x20requires\x20these\x20fields\x20in\x20mode_changes:\x20'+d['join'](',\x20')+'.\x20'+'Tip:\x20derive_user_mode\x20from\x20a\x20builtin\x20mode\x20is\x20usually\x20easier\x20than\x20registering\x20from\x20scratch.');const e=validateMachineShape(c['machine_shape'],'mode_changes.machine_shape');if(e['length']>0x0)throw new Error('register_user_mode\x20blocked:\x0a'+e['join']('\x0a'));const f=getIndustryModeRegistry(),g=f['getMode']('general');if(!g)throw new Error('Builtin\x20mode\x20\x27general\x27\x20not\x20registered\x20—\x20cannot\x20build\x20custom\x20mode\x20defaults');const h={...g,...c,'name':b,'display_name':a['mode_display_name']??b,'version':'v1','source':'custom','owner':LOCAL_MODE_OWNER,'derived_from':undefined,'evolution_history':[]},i=await f['registerUserMode'](h,LOCAL_MODE_OWNER);if(!i)throw new Error('register_user_mode\x20failed:\x20name\x20\x27'+b+'\x27\x20conflicts\x20with\x20a\x20builtin/existing\x20user\x20mode,\x20'+'or\x20payload\x20is\x20invalid.\x20Call\x20list_modes\x20to\x20see\x20available\x20names.');return{'action':'register_user_mode','mode':summarizeUserMode(h),'hint':'Custom\x20mode\x20\x27'+b+'\x27\x20registered.\x20Use\x20it\x20as\x20the\x20industry/mode\x20context\x20for\x20your\x20build.'};}export async function handleUnregisterUserMode(a){const b=requireField(a['mode_name'],'mode_name'),c=getIndustryModeRegistry(),d=await c['unregisterUserMode'](b,LOCAL_MODE_OWNER);if(!d)throw new Error('unregister_user_mode\x20failed:\x20user\x20mode\x20\x27'+b+'\x27\x20not\x20found\x20for\x20owner\x20\x27'+LOCAL_MODE_OWNER+'\x27.');return{'action':'unregister_user_mode','removed':!![],'mode_name':b};}export async function handleRegisterCustomMetric(a){const b=requireField(a['metric_id'],'metric_id'),c=requireField(a['metric_display_name'],'metric_display_name'),d=requireField(a['metric_description'],'metric_description'),e=requireField(a['metric_type'],'metric_type'),f=requireField(a['metric_scale'],'metric_scale'),g=await getMetricRegistry()['registerCustomMetric'](b,c,d,e,f,LOCAL_MODE_OWNER,a['metric_weight']);if(!g)throw new Error('register_custom_metric\x20failed:\x20metric_id\x20\x27'+b+'\x27\x20already\x20exists\x20or\x20fields\x20are\x20invalid.');return{'action':'register_custom_metric','metric':{'metric_id':b,'display_name':c,'description':d,'type':e,'scale':f,'weight':a['metric_weight']??0x1,'scope':'custom','owner':LOCAL_MODE_OWNER},'hint':'Custom\x20metric\x20\x27'+b+'\x27\x20registered\x20globally\x20and\x20persisted\x20(survives\x20restart)\x20—\x20all\x20modes\x20reference\x20it\x20in\x20evaluation.'};}export async function handleUnregisterCustomMetric(a){const b=requireField(a['metric_id'],'metric_id'),c=await getMetricRegistry()['unregisterMetric'](b,LOCAL_MODE_OWNER);if(!c)throw new Error('unregister_custom_metric\x20failed:\x20custom\x20metric\x20\x27'+b+'\x27\x20not\x20found\x20(builtin\x20metrics\x20cannot\x20be\x20deleted).\x20'+'Call\x20list_metrics_constraints\x20with\x20scope_filter=\x27custom\x27\x20to\x20see\x20deletable\x20metrics.');return{'action':'unregister_custom_metric','removed':!![],'metric_id':b};}export async function handleRegisterCustomConstraint(a){const b=requireField(a['constraint_id'],'constraint_id'),c=requireField(a['constraint_display_name'],'constraint_display_name'),d=requireField(a['constraint_description'],'constraint_description'),e=a['constraint_rule'];if(!e||typeof e!=='object'||!('type'in e))throw new Error('constraint_rule\x20is\x20required\x20and\x20must\x20be\x20one\x20of:\x20'+'{type:\x27capability_required\x27,\x20capability_id}\x20|\x20{type:\x27capability_forbidden\x27,\x20capability_id}\x20|\x20'+'{type:\x27numeric_limit\x27,\x20field,\x20max?,\x20min?}\x20|\x20{type:\x27condition_required\x27,\x20condition,\x20ai_evaluated:true}');const f=await getConstraintRegistry()['registerCustomConstraint'](b,c,d,e,LOCAL_MODE_OWNER,a['constraint_severity']??'soft',a['constraint_on_violation']??'warn');if(!f)throw new Error('register_custom_constraint\x20failed:\x20constraint_id\x20\x27'+b+'\x27\x20already\x20exists\x20or\x20rule\x20is\x20invalid.');return{'action':'register_custom_constraint','constraint':{'constraint_id':b,'display_name':c,'description':d,'rule':e,'severity':a['constraint_severity']??'soft','on_violation':a['constraint_on_violation']??'warn','scope':'custom','owner':LOCAL_MODE_OWNER},'hint':'Custom\x20constraint\x20\x27'+b+'\x27\x20registered\x20and\x20persisted\x20(survives\x20restart).\x20\x27hard\x27\x20constraints\x20mark\x20a\x20mode\x20not\x20applicable\x20on\x20violation;\x20\x27soft\x27\x20only\x20warn.'};}export async function handleUnregisterCustomConstraint(a){const b=requireField(a['constraint_id'],'constraint_id'),c=await getConstraintRegistry()['unregisterConstraint'](b,LOCAL_MODE_OWNER);if(!c)throw new Error('unregister_custom_constraint\x20failed:\x20custom\x20constraint\x20\x27'+b+'\x27\x20not\x20found\x20(builtin\x20constraints\x20cannot\x20be\x20deleted).\x20'+'Call\x20list_metrics_constraints\x20with\x20scope_filter=\x27custom\x27\x20to\x20see\x20deletable\x20constraints.');return{'action':'unregister_custom_constraint','removed':!![],'constraint_id':b};}export async function handleListMetricsConstraints(a){const b=(await getMetricRegistry()['listMetrics']({'type':a['metric_type_filter'],'scope':a['scope_filter']}))['map'](d=>({'metric_id':d['metric_id'],'display_name':d['display_name'],'description':d['description'],'type':d['type'],'scale':d['scale'],'weight':d['weight'],'scope':d['scope']})),c=(await getConstraintRegistry()['listConstraints']({'scope':a['scope_filter']}))['map'](d=>({'constraint_id':d['constraint_id'],'display_name':d['display_name'],'description':d['description'],'rule':d['rule'],'severity':d['severity'],'on_violation':d['on_violation'],'scope':d['scope']}));return{'action':'list_metrics_constraints','metrics':b,'constraints':c,'hint':'Register\x20custom\x20entries\x20via\x20register_custom_metric\x20/\x20register_custom_constraint;\x20'+'delete\x20via\x20unregister_custom_metric\x20/\x20unregister_custom_constraint\x20(custom\x20only).\x20'+'Custom\x20entries\x20are\x20persisted\x20and\x20survive\x20restart.\x20'+'Filter\x20with\x20metric_type_filter\x20(\x27risk\x27|\x27benefit\x27)\x20or\x20scope_filter\x20(\x27builtin\x27|\x27custom\x27).'};}function requireField(a,b){if(a===undefined||a===null||typeof a==='string'&&!a['trim']())throw new Error('\x27'+b+'\x27\x20is\x20required\x20for\x20this\x20action');return a;}function summarizeUserMode(a){return{'name':a['name'],'display_name':a['display_name'],'version':a['version'],'derived_from':a['derived_from']??null,'owner':a['owner'],'key_risk':a['key_risk'],'machine_nodes':a['machine_shape']['map'](b=>b['name']),'buyer_action_nodes':a['machine_shape']['filter'](b=>b['operator']==='order_payer')['map'](b=>b['name']),'location_sensitivity':locationSensitivity(a['traits']),'trust_selling_points':a['flywheel']?.['trustSellingPoints']??[],'build_notes':a['build_notes']??[],'evolution_history':(a['evolution_history']??[])['map'](b=>({'version':b['version'],'changed_at':b['changed_at'],'changes':b['changes']}))};}