@wowok/agent-mcp 3.1.7 → 3.2.0
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.
- package/dist/config/exposure.d.ts +10 -10
- package/dist/config/judgment.d.ts +25 -25
- package/dist/config/rule-engine.d.ts +25 -25
- package/dist/customer/user-preferences.d.ts +2 -2
- package/dist/evaluation/arbitration-game.js +1 -1
- package/dist/evaluation/capability.d.ts +1 -1
- package/dist/evaluation/extract.js +1 -1
- package/dist/evaluation/match-operation.js +1 -1
- package/dist/extensions/industry-pack.d.ts +3 -2
- package/dist/extensions/industry-pack.js +1 -1
- package/dist/extensions/modes.js +1 -1
- package/dist/extensions/registry.js +1 -1
- package/dist/extensions/types.d.ts +1 -0
- package/dist/graph/onchain/analyze.js +1 -1
- package/dist/graph/onchain/analyze.spec.js +1 -1
- package/dist/graph/onchain/edge-schema.js +1 -1
- package/dist/graph/onchain/extract.js +1 -1
- package/dist/graph/onchain/field-manifest.js +1 -1
- package/dist/graph/onchain/project-relationship.js +1 -1
- package/dist/graph/onchain/types.d.ts +1 -1
- package/dist/harness/recover.js +1 -1
- package/dist/keeper/KeeperScan.d.ts +2 -1
- package/dist/keeper/KeeperScan.js +1 -1
- package/dist/keeper/detectors.d.ts +9 -0
- package/dist/keeper/detectors.js +1 -1
- package/dist/keeper/keeper.spec.js +1 -1
- package/dist/keeper/types.d.ts +1 -1
- package/dist/keeper/types.js +1 -1
- package/dist/knowledge/allocation-ledger.d.ts +4 -1
- package/dist/knowledge/allocation-ledger.js +1 -1
- package/dist/knowledge/allocation-puzzle.d.ts +2 -0
- package/dist/knowledge/allocation-puzzle.js +1 -1
- package/dist/knowledge/allocation-risk.d.ts +1 -1
- package/dist/knowledge/allocation-risk.js +1 -1
- package/dist/knowledge/arb-risk.d.ts +3 -1
- package/dist/knowledge/arb-risk.js +1 -1
- package/dist/knowledge/arbitration-ledger.js +1 -1
- package/dist/knowledge/arbitration-risk.js +1 -1
- package/dist/knowledge/arbitration-templates.d.ts +1 -0
- package/dist/knowledge/arbitration-templates.js +1 -1
- package/dist/knowledge/audit-rules.d.ts +13 -2
- package/dist/knowledge/audit-rules.js +1 -1
- package/dist/knowledge/baselines/rules/allocation.json +50 -1
- package/dist/knowledge/baselines/rules/arb.json +20 -1
- package/dist/knowledge/baselines/rules/arbitration.json +27 -0
- package/dist/knowledge/baselines/rules/guard.json +75 -2
- package/dist/knowledge/baselines/rules/machine.json +38 -13
- package/dist/knowledge/baselines/rules/order.json +2 -2
- package/dist/knowledge/builtin-templates.d.ts +3 -1
- package/dist/knowledge/builtin-templates.js +1 -1
- package/dist/knowledge/event-semantics.js +1 -1
- package/dist/knowledge/fund-layer.js +1 -1
- package/dist/knowledge/getting-started.js +1 -1
- package/dist/knowledge/guard-anchor-reach.d.ts +19 -0
- package/dist/knowledge/guard-anchor-reach.js +1 -0
- package/dist/knowledge/guard-bindings.js +1 -1
- package/dist/knowledge/guard-design-patterns.d.ts +1 -1
- package/dist/knowledge/guard-design-patterns.js +1 -1
- package/dist/knowledge/guard-ledger.js +1 -1
- package/dist/knowledge/guard-lint.js +1 -1
- package/dist/knowledge/guard-render.d.ts +6 -0
- package/dist/knowledge/guard-render.js +1 -1
- package/dist/knowledge/guard-risk.js +1 -1
- package/dist/knowledge/guard-submission-prompt.d.ts +6 -0
- package/dist/knowledge/guard-submission-prompt.js +1 -1
- package/dist/knowledge/guard-templates.d.ts +1 -1
- package/dist/knowledge/guard-templates.js +1 -1
- package/dist/knowledge/index.d.ts +4 -4
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/industry-generalizer.js +1 -1
- package/dist/knowledge/industry-registry.d.ts +1 -1
- package/dist/knowledge/industry-registry.js +1 -1
- package/dist/knowledge/jsonrpc-enum.js +1 -1
- package/dist/knowledge/machine-ledger.js +1 -1
- package/dist/knowledge/machine-risk.js +1 -1
- package/dist/knowledge/machine-templates.js +1 -1
- package/dist/knowledge/order-ledger.js +1 -1
- package/dist/knowledge/order-templates.js +1 -1
- package/dist/knowledge/permission-ledger.js +1 -1
- package/dist/knowledge/release-sentinel.d.ts +12 -0
- package/dist/knowledge/release-sentinel.js +1 -0
- package/dist/knowledge/repository-write-semantics.d.ts +27 -0
- package/dist/knowledge/repository-write-semantics.js +1 -0
- package/dist/knowledge/rule-node-analyzers.d.ts +6 -0
- package/dist/knowledge/rule-node-analyzers.js +1 -1
- package/dist/knowledge/safety-rules.d.ts +5 -1
- package/dist/knowledge/safety-rules.js +1 -1
- package/dist/knowledge/scenario-modes.d.ts +10 -1
- package/dist/knowledge/scenario-modes.js +1 -1
- package/dist/knowledge/service-allocation-semantics.d.ts +36 -0
- package/dist/knowledge/service-allocation-semantics.js +1 -0
- package/dist/knowledge/strategy-manuals.d.ts +3 -5
- package/dist/knowledge/strategy-manuals.js +1 -1
- package/dist/knowledge/template-loader.d.ts +28 -12
- package/dist/knowledge/template-loader.js +1 -1
- package/dist/knowledge/template-registry.js +1 -1
- package/dist/knowledge/template-scanner.js +1 -1
- package/dist/knowledge/tools-reference.js +1 -1
- package/dist/knowledge/workflow-guidance.d.ts +26 -0
- package/dist/knowledge/workflow-guidance.js +1 -1
- package/dist/monitor/MonitorLoop.js +1 -1
- package/dist/participation/allocation-advice.d.ts +38 -0
- package/dist/participation/allocation-advice.js +1 -0
- package/dist/participation/radar-core.d.ts +2 -0
- package/dist/persona/types.d.ts +3 -2
- package/dist/persona/types.js +1 -1
- package/dist/playbooks/service-build/business-puzzle.js +1 -1
- package/dist/playbooks/service-build/intent-analyzer.js +1 -1
- package/dist/playbooks/service-build/merchant-guide.d.ts +70 -63
- package/dist/playbooks/service-build/merchant-guide.js +1 -1
- package/dist/playbooks/service-build/migration-planner.js +1 -1
- package/dist/playbooks/service-build/mode-actions.d.ts +5 -0
- package/dist/playbooks/service-build/mode-actions.js +1 -1
- package/dist/playbooks/service-build/participation-radar.js +1 -1
- package/dist/playbooks/service-build/semantic-graph.d.ts +1 -0
- package/dist/playbooks/service-build/semantic-graph.js +1 -1
- package/dist/playbooks/service-build/service-quote.d.ts +2 -0
- package/dist/playbooks/service-build/service-quote.js +1 -0
- package/dist/relationship/derivation.d.ts +1 -1
- package/dist/safety/confirm-gate.js +1 -1
- package/dist/schema/benchmark-migration/index.d.ts +30 -8
- package/dist/schema/benchmark-migration/index.js +1 -1
- package/dist/schema/call/allocation.d.ts +6 -3
- package/dist/schema/call/arbitration.js +1 -1
- package/dist/schema/call/base.js +1 -1
- package/dist/schema/call/guard.d.ts +8 -8
- package/dist/schema/call/machine.d.ts +56 -0
- package/dist/schema/call/machine.js +1 -1
- package/dist/schema/call/order.js +1 -1
- package/dist/schema/call/payment.js +1 -1
- package/dist/schema/call/semantic.js +1 -1
- package/dist/schema/call/service.d.ts +84 -22
- package/dist/schema/call/service.js +1 -1
- package/dist/schema/common/index.js +1 -1
- package/dist/schema/common/tokentype-short-probe.spec.js +1 -0
- package/dist/schema/evaluation/index.d.ts +8 -80
- package/dist/schema/evaluation/index.js +1 -1
- package/dist/schema/goal/index.d.ts +9 -42
- package/dist/schema/goal/planning.d.ts +25 -60
- package/dist/schema/goal/planning.js +1 -1
- package/dist/schema/intent-radar/index.d.ts +2 -20
- package/dist/schema/intent-radar/index.js +1 -1
- package/dist/schema/interaction/index.d.ts +1 -1
- package/dist/schema/keeper/index.d.ts +3 -0
- package/dist/schema/keeper/index.js +1 -1
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/operations.d.ts +74 -14
- package/dist/schema/persona/index.d.ts +279 -384
- package/dist/schema/persona/index.js +1 -1
- package/dist/schema/query/bi.d.ts +149 -10
- package/dist/schema/query/bi.js +1 -1
- package/dist/schema/query/index.d.ts +35 -16
- package/dist/schema/query/index.js +1 -1
- package/dist/schema/schema-query/index.d.ts +4 -4
- package/dist/schema/schema-version.js +1 -1
- package/dist/schema/watch/index.d.ts +2 -2
- package/dist/schema-query-impl/index.d.ts +1 -0
- package/dist/schema-query-impl/index.js +1 -1
- package/dist/schemas/account_operation.output.json +2 -2
- package/dist/schemas/benchmark_migration_operation.output.json +116 -2
- package/dist/schemas/benchmark_migration_operation.schema.json +2 -10
- package/dist/schemas/bridge_operation.output.json +2 -2
- package/dist/schemas/evaluation_operation.schema.json +7 -70
- package/dist/schemas/goal_operation.schema.json +6 -39
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/intent_radar.output.json +4 -20
- package/dist/schemas/keeper_operation.output.json +2 -2
- package/dist/schemas/keeper_operation.schema.json +9 -4
- package/dist/schemas/local_history_operation.output.json +2 -2
- package/dist/schemas/local_info_operation.output.json +2 -2
- package/dist/schemas/local_mark_operation.output.json +2 -2
- package/dist/schemas/messenger_operation.output.json +2 -2
- package/dist/schemas/monitor_events.output.json +2 -2
- package/dist/schemas/monitor_subscription.output.json +2 -2
- package/dist/schemas/onchain_events.output.json +2 -2
- package/dist/schemas/onchain_operations.output.json +6 -6
- package/dist/schemas/onchain_operations.schema.json +227 -54
- package/dist/schemas/onchain_operations_allocation.schema.json +11 -10
- package/dist/schemas/onchain_operations_arbitration.schema.json +13 -13
- package/dist/schemas/onchain_operations_machine.schema.json +27 -5
- package/dist/schemas/onchain_operations_order.schema.json +1 -1
- package/dist/schemas/onchain_operations_payment.schema.json +2 -2
- package/dist/schemas/onchain_operations_reward.schema.json +1 -1
- package/dist/schemas/onchain_operations_service.schema.json +171 -21
- package/dist/schemas/onchain_operations_treasury.schema.json +1 -1
- package/dist/schemas/onchain_table_data.output.json +57 -4
- package/dist/schemas/persona_operation.output.json +11 -88
- package/dist/schemas/persona_operation.schema.json +4 -32
- package/dist/schemas/query_toolkit.output.json +320 -22
- package/dist/schemas/query_toolkit.schema.json +53 -0
- package/dist/tools/handlers/benchmark-migration.js +1 -1
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/dispatch-expectations.spec.js +1 -1
- package/dist/tools/handlers/keeper.d.ts +1 -1
- package/dist/tools/handlers/onchain.js +1 -1
- package/dist/tools/handlers/query.js +1 -1
- package/dist/tools/handlers/schema-query.js +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/move-fn-index.gen.js +1 -1
- package/dist/tools/registry/business.js +1 -1
- package/dist/tools/wrap.js +1 -1
- package/package.json +2 -2
- package/dist/knowledge/alloc-audit-policy.spec.js +0 -1
- package/dist/knowledge/event-semantics.spec.d.ts +0 -1
- package/dist/knowledge/event-semantics.spec.js +0 -1
- package/dist/knowledge/facts-sync.spec.d.ts +0 -1
- package/dist/knowledge/facts-sync.spec.js +0 -1
- package/dist/knowledge/guard-design-patterns.spec.d.ts +0 -1
- package/dist/knowledge/guard-design-patterns.spec.js +0 -1
- package/dist/knowledge/guard-eval.spec.d.ts +0 -1
- package/dist/knowledge/guard-eval.spec.js +0 -1
- package/dist/knowledge/rule-node-analyzers.spec.d.ts +0 -1
- package/dist/knowledge/rule-node-analyzers.spec.js +0 -1
- package/dist/knowledge/safety-rules.extract-amount.spec.d.ts +0 -1
- package/dist/knowledge/safety-rules.extract-amount.spec.js +0 -1
- package/dist/knowledge/template-loader.spec.d.ts +0 -1
- package/dist/knowledge/template-loader.spec.js +0 -1
- package/dist/knowledge/template-scanner.spec.d.ts +0 -1
- package/dist/knowledge/template-scanner.spec.js +0 -1
- /package/dist/{knowledge/alloc-audit-policy.spec.d.ts → schema/common/tokentype-short-probe.spec.d.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateGuardData,MAX_DESCRIPTION_LENGTH,MAX_GUARD_TABLE_ITEM_LENGTH,MAX_NAME_LENGTH,ValueType}from'@wowok/wowok';import{evaluateGuardDraft}from'./guard-eval.js';import{findScene,inferSceneFromAction}from'./guard-ledger.js';import{suggestTemplateForScene}from'./guard-templates.js';const VALUE_TYPE_ID_TO_NAME={[ValueType['Bool']]:'Bool',[ValueType['Address']]:'Address',[ValueType['String']]:'String',[ValueType['U8']]:'U8',[ValueType['U16']]:'U16',[ValueType['U32']]:'U32',[ValueType['U64']]:'U64',[ValueType['U128']]:'U128',[ValueType['U256']]:'U256',[ValueType['VecBool']]:'VecBool',[ValueType['VecAddress']]:'VecAddress',[ValueType['VecString']]:'VecString',[ValueType['VecU8']]:'VecU8',[ValueType['VecU16']]:'VecU16',[ValueType['VecU32']]:'VecU32',[ValueType['VecU64']]:'VecU64',[ValueType['VecU128']]:'VecU128',[ValueType['VecU256']]:'VecU256',[ValueType['VecVecU8']]:'VecVecU8'};function normalizeValueTypeNames(a){if(!a['table']['some'](b=>typeof b['value_type']==='number'))return a;return{...a,'table':a['table']['map'](b=>typeof b['value_type']==='number'?{...b,'value_type':VALUE_TYPE_ID_TO_NAME[b['value_type']]??String(b['value_type'])}:b)};}function deepClone(a){return JSON['parse'](JSON['stringify'](a));}function rootToString(a){return JSON['stringify'](a);}function hasSignerContext(a){const b=rootToString(a);return b['includes']('\x22Signer\x22')||b['includes']('\x22context\x22:\x22Signer\x22')||b['includes']('\x22context\x22:\x20\x22Signer\x22');}function getSubmissionEntries(a){return a['filter'](b=>b['b_submission']===!![]);}function inferValueType(a){if(typeof a==='string'){if(a['startsWith']('0x')&&a['length']>=0x3)return'Address';return'String';}if(typeof a==='number'){if(Number['isInteger'](a)){if(a>=0x0&&a<=0xff)return'U8';if(a>=0x0&&a<=0xffff)return'U16';return'U64';}return'U256';}if(typeof a==='boolean')return'Bool';if(Array['isArray'](a)){if(a['length']>0x0){const b=inferValueType(a[0x0]);if(b==='Address')return'Vec<Address>';if(b==='String')return'Vec<String>';if(b==='Bool')return'Vec<Bool>';}return'Vec<Address>';}return undefined;}function sdkIssueToDiagnostic(a){return{'code':a['code'],'message':a['message'],'severity':a['severity'],'source':'sdk','location':{'path':a['path']},'fix':{'description':'SDK\x20validation\x20failed\x20('+(a['sdk_error']??'InvalidParam')+');\x20manual\x20fix\x20required','auto_fixable':![]}};}async function checkSdkSyntax(a){const b=a['table']['map'](d=>({'identifier':d['identifier'],'b_submission':d['b_submission']??![],'value_type':d['value_type']??'Address','value':d['value'],'name':d['name']??''})),c=await validateGuardData({'description':a['description'],'table':b,'root':a['root'],'rely':a['rely']});return c['map'](sdkIssueToDiagnostic);}function checkSemanticErrors(a){const b=[],{table:c,root:d,binding_hint:e}=a,f=e?findScene(e['host_object']??'',e['binding_field']??''):undefined,g=getSubmissionEntries(c);if(g['length']>0x0&&d&&!hasSignerContext(d)){const h=g['some'](j=>j['value_type']==='Address'),i=f?.['id']==='service_order_allocators_guard'&&e?.['sharing_recipients']!==undefined&&e['sharing_recipients']['length']>0x0&&!e['sharing_recipients']['includes']('Signer');if(h&&!i){const j=g['filter'](k=>k['value_type']==='Address')['map'](k=>c['indexOf'](k));b['push']({'code':'LE-04','message':'Submitted\x20data\x20has\x20no\x20Signer\x20binding\x20(submission\x20forgery\x20risk)','severity':'error','source':'lint','location':{'path':j['map'](k=>'/table/'+k)['join']('\x20→\x20')},'fix':{'description':'Add\x20logic_equal(context(Signer),\x20identifier[N])\x20in\x20root\x20to\x20bind\x20the\x20submitter\x20identity','auto_fixable':![]}});}}if(f?.['id']==='arbitration_voting_guard'){const k=g['some'](l=>['U8','U16','U32','U64','U128','U256']['includes'](l['value_type']??''));if(k){const l=g['filter'](m=>['U8','U16','U32','U64','U128','U256']['includes'](m['value_type']??''))['map'](m=>c['indexOf'](m));b['push']({'code':'LE-05','message':'voting_guard\x20voting\x20weight\x20comes\x20from\x20submitted\x20data\x20(weight\x20forgery\x20risk)','severity':'error','source':'lint','location':{'path':l['map'](m=>'/table/'+m)['join']('\x20→\x20')},'fix':{'description':'Derive\x20arbitrator\x20weights\x20from\x20the\x20Arb\x20object\x20via\x20witness\x20(e.g.\x20105\x20TypeArbArbitration)\x20rather\x20than\x20submitting\x20them\x20directly','auto_fixable':![]}});}}if(f?.['id']==='gen_passport_guard'||e?.['action']==='gen_passport'){const m=rootToString(d);if(m['includes']('1167')||m['includes']('repository.data')){const n=m['includes']('quote_guard');n&&b['push']({'code':'LE-06','message':'repository.data\x20query\x20with\x20quote_guard:\x20rigid\x20verification\x20requirement\x20—\x20ensure\x20Passport\x20includes\x20quote_guard\x20verification\x20with\x20necessary\x20submissions\x20(e.g.,\x20Payment\x20proof)','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'Ensure\x20the\x20quote_guard\x20is\x20verified:\x20user\x20submits\x20Payment\x20via\x20Passport,\x20quote_guard\x20verifies\x20Payment\x20fields,\x20repository\x20data\x20query\x20passes','auto_fixable':![]}});}}if(e?.['host_object']&&f){const o=e['host_object'],p=c['filter'](q=>!q['b_submission']&&q['value_type']==='Address'&&typeof q['value']==='string'&&q['value']['startsWith']('0x')&&q['object_type']===o);if(p['length']>0x0){const q=p['map'](r=>c['indexOf'](r));b['push']({'code':'LE-07','message':'Circular\x20reference\x20uses\x20an\x20address\x20rather\x20than\x20a\x20name\x20(Host\x20Object\x20may\x20not\x20be\x20published\x20yet\x20when\x20the\x20Guard\x20is\x20created)','severity':'error','source':'lint','location':{'path':q['map'](r=>'/table/'+r+'/value')['join']('\x20→\x20')},'fix':{'description':'Change\x20value\x20from\x20an\x20address\x20to\x20an\x20object\x20name\x20(e.g.\x20\x22service1\x22);\x20the\x20SDK\x20will\x20resolve\x20it\x20to\x20an\x20address\x20after\x20the\x20Host\x20Object\x20is\x20published','auto_fixable':![]}});}}return b;}function checkSyntaxHints(a){const b=[],{table:c}=a;(!a['description']||a['description']['trim']()==='')&&b['push']({'code':'SH-01','message':'description\x20is\x20missing\x20or\x20empty','severity':'info','source':'lint','location':{'path':'/description'},'fix':{'description':'Add\x20a\x20description,\x20e.g.\x20\x27Service\x20buy_guard:\x20whitelist\x20validation\x27','auto_fixable':!![]}});for(let d=0x0;d<c['length'];d++){const e=c[d];(!e['name']||e['name']['trim']()==='')&&b['push']({'code':'SH-03','message':'table['+d+']\x20is\x20missing\x20name','severity':'warning','source':'lint','location':{'path':'/table/'+d+'/name'},'fix':{'description':'Add\x20a\x20name,\x20e.g.\x20\x22data\x20entry\x20'+e['identifier']+'\x22','auto_fixable':!![]}});}for(let f=0x0;f<c['length'];f++){const g=c[f];!g['value_type']&&b['push']({'code':'SH-05','message':'table['+f+']\x20is\x20missing\x20value_type','severity':'warning','source':'lint','location':{'path':'/table/'+f+'/value_type'},'fix':{'description':'Infer\x20value_type\x20from\x20value\x20(e.g.\x20Address/String/U64,\x20etc.)','auto_fixable':!![]}});}c['length']>MAX_GUARD_TABLE_ITEM_LENGTH&&b['push']({'code':'SH-07','message':'table\x20entry\x20count\x20'+c['length']+'\x20exceeds\x20the\x20maximum\x20limit\x20'+MAX_GUARD_TABLE_ITEM_LENGTH,'severity':'error','source':'lint','location':{'path':'/table'},'fix':{'description':'Slim\x20down\x20the\x20table\x20by\x20merging\x20similar\x20entries,\x20or\x20split\x20into\x20multiple\x20Guards\x20+\x20rely','auto_fixable':![]}});for(let h=0x0;h<c['length'];h++){c[h]['b_submission']===undefined&&b['push']({'code':'SH-10','message':'table['+h+']\x20b_submission\x20is\x20missing','severity':'info','source':'lint','location':{'path':'/table/'+h+'/b_submission'},'fix':{'description':'Set\x20to\x20false\x20(constant)\x20or\x20true\x20(submitted\x20data)','auto_fixable':!![]}});}for(let j=0x0;j<c['length'];j++){const k=c[j];k['b_submission']===!![]&&k['value']!==undefined&&k['value']!==null&&b['push']({'code':'SH-11','message':'table['+j+']\x20has\x20a\x20redundant\x20value\x20field\x20on\x20b_submission=true\x20entry\x20(the\x20verifier\x20supplies\x20the\x20value\x20at\x20runtime;\x20this\x20value\x20is\x20ignored\x20by\x20BCS\x20encoding\x20and\x20wastes\x20gas)','severity':'warning','source':'lint','location':{'path':'/table/'+j+'/value'},'fix':{'description':'Remove\x20the\x20value\x20field\x20—\x20it\x20is\x20ignored\x20for\x20b_submission=true\x20entries','auto_fixable':!![]}});}return b;}function checkSuggestions(a){const b=[],{root:c,binding_hint:d,table:e,description:f}=a;if(c){const i=rootToString(c);if(i['includes']('vec_contains_address')&&i['includes']('Signer'))b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P04\x20(whitelist\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Refer\x20to\x20the\x20P04\x20Pattern\x20to\x20ensure\x20best\x20practices','auto_fixable':![]}});else{if(i['includes']('logic_equal')&&i['includes']('Signer')){const j=e['some'](k=>!k['b_submission']&&k['value_type']==='Address'&&typeof k['value']==='string'&&k['value']['length']>0x0);j&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P04\x20(whitelist\x20validation\x20—\x20single-address\x20variant)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'P04\x20single-address\x20form;\x20for\x20multi-address\x20scenarios,\x20consider\x20vec_contains_address','auto_fixable':![]}});}}(i['includes']('logic_as_u256_greater')||i['includes']('logic_as_u256_lesser'))&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P02\x20(numeric\x20threshold\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Suitable\x20for\x20amount/quantity\x20threshold\x20validation\x20scenarios','auto_fixable':![]}}),i['includes']('convert_witness')&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P09\x20(witness-derived\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Suitable\x20for\x20cross-object\x20relationship\x20validation\x20(e.g.\x20Order→Progress)','auto_fixable':![]}});}if(d?.['action']){const k=['buy','forward','allocate','claim_reward','vote','dispute','write_repository','submit_progress','gen_passport'];if(k['includes'](d['action'])){const l=inferSceneFromAction(d['action']);if(l){const m=suggestTemplateForScene(l['id']);m&&b['push']({'code':'SG-02','message':'Recommended\x20scene\x20template:\x20'+m['name'],'severity':'hint','source':'lint','location':{'path':'/'},'fix':{'description':'Refer\x20to\x20template\x20'+m['id']+'\x20('+m['example_use_case']+')','auto_fixable':![]}});}}}const g=n=>new TextEncoder()['encode'](n)['length'],h=getSubmissionEntries(e);for(const [n,o]of e['entries']()){const p=o['name']??'';if(p['length']===0x0)continue;if(g(p)>MAX_NAME_LENGTH)b['push']({'code':'SG-03','message':'table['+n+']\x20name\x20is\x20'+g(p)+'\x20BCS\x20characters,\x20maximum\x20is\x20'+MAX_NAME_LENGTH+'.\x20Use\x20a\x20short\x20identifier\x20(e.g.\x20\x27order_id\x27,\x20\x27delivery_node\x27);\x20the\x20human-readable\x20explanation\x20belongs\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field','severity':'warning','source':'lint','location':{'path':'/table/'+n+'/name'},'fix':{'description':'Shorten\x20the\x20name\x20to\x20'+MAX_NAME_LENGTH+'\x20BCS\x20characters\x20or\x20fewer','auto_fixable':![]}});else p['toLowerCase']()['startsWith']('0x')&&b['push']({'code':'SG-03','message':'table['+n+']\x20name\x20must\x20not\x20start\x20with\x20\x220x\x22\x20(reserved\x20for\x20object\x20IDs)','severity':'warning','source':'lint','location':{'path':'/table/'+n+'/name'},'fix':{'description':'Rename\x20the\x20entry\x20without\x20the\x200x\x20prefix','auto_fixable':![]}});}if(h['length']>0x0){const q=(f??'')['trim']();q['length']<0xa&&b['push']({'code':'SG-03','message':'This\x20Guard\x20accepts\x20submitted\x20data\x20('+h['length']+'\x20table\x20'+(h['length']===0x1?'entry':'entries')+'\x20with\x20b_submission=true)\x20but\x20its\x20description\x20is\x20too\x20short\x20for\x20a\x20verifier\x20to\x20know\x20what\x20to\x20submit.\x20Explain\x20the\x20expected\x20submitted\x20data\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field,\x20e.g.\x20\x27user-submitted\x20operation\x20type\x20(return/damage)\x27','severity':'info','source':'lint','location':{'path':'/'},'fix':{'description':'Explain\x20the\x20expected\x20submitted\x20data\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field','auto_fixable':![]}});}if(c){const r=rootToString(c),s=r['includes']('proof.signer'),t=r['includes']('proof.time'),u=r['includes']('calc_string_length'),v=h['some'](w=>w['value_type']==='String');if(s&&t)b['push']({'code':'SG-04','message':'Strict-mode\x20privacy-delivery\x20guard\x20detected\x20(proof.signer\x20+\x20proof.time).\x20'+'Recommended\x20three\x20conditions:\x20Signer==proof.signer\x20(submitter\x20accountability),\x20'+'proof.time>order.time\x20(freshness),\x20order.service==service\x20(project\x20binding).\x20'+'No\x20content\x20verification\x20—\x20only\x20submission\x20responsibility\x20(\x27whoever\x20benefits\x20bears\x20the\x20burden\x20of\x20proof\x27).','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'Ensure\x20all\x20three\x20conditions\x20are\x20present\x20(logic_and).\x20Refer\x20to\x20template\x20tpl_forward_privacy_delivery_proof.\x20'+'Query\x20IDs:\x20proof.signer=1958,\x20proof.time=1960,\x20order.time=1574,\x20order.service=1563.','auto_fixable':![]}});else u&&v&&b['push']({'code':'SG-04','message':'Broad-mode\x20privacy-delivery\x20guard\x20detected\x20(String\x20submission\x20+\x20length\x20check,\x20e.g.\x20Merkle\x20Root\x20length\x20==\x2066).\x20'+'This\x20trusts\x20the\x20submitter\x27s\x20honesty;\x20the\x20counterparty\x20can\x20dispute\x20by\x20checking\x20their\x20own\x20Messenger\x20conversation.\x20'+'Suitable\x20as\x20an\x20arbitration\x20basis,\x20not\x20a\x20fund-flow\x20gate.','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'For\x20stronger\x20assurance,\x20consider\x20strict\x20mode:\x20submit\x20a\x20Proof\x20object\x20address\x20(from\x20messenger.submitChainProof)\x20+\x20'+'Order\x20address,\x20then\x20verify\x20proof.signer/proof.time/order.service.\x20See\x20template\x20tpl_forward_privacy_delivery_proof.','auto_fixable':![]}});}return b;}export function autoFixGuard(a){const b=deepClone(a),c=[];(!b['description']||b['description']['trim']()==='')&&(b['description']='Guard\x20(table:\x20'+b['table']['length']+'\x20items,\x20root:\x20'+(b['root']?.['type']??'unknown')+')',c['push']({'diagnostic_code':'SH-01','description':'Fill\x20in\x20default\x20description','after':b['description'],'path':'/description'}));if(b['description']&&b['description']['length']>MAX_DESCRIPTION_LENGTH){const f=b['description'];b['description']=b['description']['substring'](0x0,MAX_DESCRIPTION_LENGTH),c['push']({'diagnostic_code':'G-001','description':'Truncate\x20description\x20to\x20'+MAX_DESCRIPTION_LENGTH+'\x20characters','before':f['length']+'\x20characters','after':b['description']['length']+'\x20characters','path':'/description'});}for(let g=0x0;g<b['table']['length'];g++){const h=b['table'][g];(!h['name']||h['name']['trim']()==='')&&(h['name']='data\x20entry\x20'+h['identifier'],c['push']({'diagnostic_code':'SH-03','description':'table['+g+']\x20fill\x20in\x20name','after':h['name'],'path':'/table/'+g+'/name'}));}for(let j=0x0;j<b['table']['length'];j++){const k=b['table'][j];if(!k['value_type']&&k['value']!==undefined&&k['value']!==null){const l=inferValueType(k['value']);l&&(k['value_type']=l,c['push']({'diagnostic_code':'SH-05','description':'table['+j+']\x20infer\x20value_type','after':l,'path':'/table/'+j+'/value_type'}));}}const d=new Map();let e=0x0;for(let m=0x0;m<b['table']['length'];m++){const n=b['table'][m];if(!d['has'](n['identifier']))d['set'](n['identifier'],e),n['identifier']!==e&&c['push']({'diagnostic_code':'G-007','description':'table['+m+']\x20identifier\x20'+n['identifier']+'\x20→\x20'+e,'before':String(n['identifier']),'after':String(e),'path':'/table/'+m+'/identifier'}),n['identifier']=e,e++;else{const o=n['identifier'];n['identifier']=e,d['set'](o,e),c['push']({'diagnostic_code':'G-007','description':'table['+m+']\x20identifier\x20'+o+'\x20duplicate\x20→\x20reallocated\x20to\x20'+e,'before':String(o),'after':String(e),'path':'/table/'+m+'/identifier'}),e++;}}for(let p=0x0;p<b['table']['length'];p++){const q=b['table'][p];q['b_submission']===undefined&&(q['b_submission']=![],c['push']({'diagnostic_code':'SH-10','description':'table['+p+']\x20b_submission\x20default\x20set\x20to\x20false','after':'false','path':'/table/'+p+'/b_submission'}));}if(b['rely']?.['guards']&&b['rely']['guards']['length']>0x0){const r=[...new Set(b['rely']['guards'])];r['length']!==b['rely']['guards']['length']&&(c['push']({'diagnostic_code':'G-009','description':'rely\x20deduplicate:\x20'+b['rely']['guards']['length']+'\x20→\x20'+r['length'],'before':JSON['stringify'](b['rely']['guards']),'after':JSON['stringify'](r),'path':'/rely/guards'}),b['rely']['guards']=r);}for(let s=0x0;s<b['table']['length'];s++){const t=b['table'][s];if(t['b_submission']===!![]&&t['value']!==undefined&&t['value']!==null){const u=JSON['stringify'](t['value']);delete t['value'],c['push']({'diagnostic_code':'SH-11','description':'table['+s+']\x20remove\x20redundant\x20value\x20on\x20b_submission=true\x20entry','before':u,'after':'(removed)','path':'/table/'+s+'/value'});}}return{'fixed':b,'actions':c};}export async function lintGuard(a,b){const c=b?.['auto_fix']??!![],d=normalizeValueTypeNames(a),{table:e,root:f,rely:g,binding_hint:h}=d,i=[];let j;const k=await checkSdkSyntax(d);i['push'](...k);const l=checkSemanticErrors(d);i['push'](...l);const m=checkSyntaxHints(d);i['push'](...m);let n,o=[];if(c){const {fixed:w,actions:x}=autoFixGuard(d);x['length']>0x0&&(n=w,o=x);}if(e['length']>0x0&&f){const y=h?findScene(h['host_object']??'',h['binding_field']??''):undefined,z=e['map'](B=>({'identifier':B['identifier'],'b_submission':B['b_submission']??![],'value_type':B['value_type']??'Address','value':B['value'],'name':B['name'],'object_type':B['object_type']})),A=evaluateGuardDraft({'table':z,'root':f,'rely':g,'scene':y,'sharing_recipients':h?.['sharing_recipients']});j=A['assessment'];for(const B of j['risks']){const C=B['level']==='critical'||B['level']==='high'?'error':B['level']==='medium'?'warning':B['level']==='low'?'info':'hint',D=B['evidence']??'',E=D['startsWith']('/')?D:'/';i['push']({'code':B['id'],'message':'['+B['level']+']\x20'+B['title'],'severity':C,'source':'risk','location':{'path':E},'fix':{'description':B['mitigation'],'auto_fixable':![]}});}}const p=checkSuggestions(d);i['push'](...p);const q=i['filter'](F=>F['severity']==='error')['length'],s=i['filter'](F=>F['severity']==='warning')['length'],t=i['filter'](F=>F['severity']==='info'||F['severity']==='hint')['length'],u=q===0x0;let v;if(q>0x0)v='Fix\x20'+q+'\x20error(s)\x20and\x20re-run\x20lint';else s>0x0?v='Consider\x20addressing\x20'+s+'\x20warning(s),\x20then\x20submit\x20to\x20SDK\x20newGuard()\x20for\x20final\x20syntax\x20validation':v='lint\x20passed\x20(no\x20errors);\x20submit\x20to\x20SDK\x20newGuard()\x20for\x20final\x20syntax\x20validation\x20before\x20going\x20on-chain';return{'json_summary':{'table_count':e['length'],'root_type':f?.['type']??'unknown','has_rely':!!g?.['guards']?.['length'],'rely_count':g?.['guards']?.['length']??0x0,'has_description':!!d['description']},'diagnostics':i,'fixed_json':n,'fix_actions':o,'risk_assessment':j,'summary':{'errors':q,'warnings':s,'infos':t,'auto_fixes_applied':o['length'],'ready':u,'next_step':v}};}export async function isGuardReady(a){const b=await lintGuard(a,{'auto_fix':![]});return b['summary']['ready'];}export async function getGuardErrors(a){const b=await lintGuard(a,{'auto_fix':![]});return b['diagnostics']['filter'](c=>c['severity']==='error');}export function formatLintResult(a){const b=[];b['push']('===\x20Guard\x20JSON\x20Lint\x20Report\x20==='),b['push'](''),b['push']('Summary:'),b['push']('\x20\x20Errors:\x20\x20\x20\x20\x20'+a['summary']['errors']),b['push']('\x20\x20Warnings:\x20\x20\x20'+a['summary']['warnings']),b['push']('\x20\x20Infos:\x20\x20\x20\x20\x20\x20'+a['summary']['infos']),b['push']('\x20\x20Auto-fixes:\x20'+a['summary']['auto_fixes_applied']),b['push']('\x20\x20Ready:\x20\x20\x20\x20\x20\x20'+(a['summary']['ready']?'YES':'NO')),b['push']('\x20\x20Next\x20step:\x20\x20'+a['summary']['next_step']),b['push']('');if(a['fix_actions']['length']>0x0){b['push']('---\x20Auto-fix\x20Actions\x20---');for(const g of a['fix_actions']){b['push']('\x20\x20['+g['diagnostic_code']+']\x20'+g['description']),b['push']('\x20\x20\x20\x20Path:\x20'+g['path']),g['before']&&g['after']&&b['push']('\x20\x20\x20\x20'+g['before']+'\x20->\x20'+g['after']);}b['push']('');}const c=a['diagnostics']['filter'](h=>h['severity']==='error'),e=a['diagnostics']['filter'](h=>h['severity']==='warning'),f=a['diagnostics']['filter'](h=>h['severity']==='info'||h['severity']==='hint');if(c['length']>0x0){b['push']('---\x20Errors\x20(must\x20fix)\x20---');for(const h of c){b['push']('\x20\x20['+h['code']+']\x20('+h['source']+')\x20'+h['message']),b['push']('\x20\x20\x20\x20Path:\x20'+h['location']['path']);if(h['fix'])b['push']('\x20\x20\x20\x20Fix:\x20\x20'+h['fix']['description']);}b['push']('');}if(e['length']>0x0){b['push']('---\x20Warnings\x20(consider\x20fixing)\x20---');for(const i of e){b['push']('\x20\x20['+i['code']+']\x20('+i['source']+')\x20'+i['message']),b['push']('\x20\x20\x20\x20Path:\x20'+i['location']['path']);if(i['fix'])b['push']('\x20\x20\x20\x20Fix:\x20\x20'+i['fix']['description']);}b['push']('');}if(f['length']>0x0){b['push']('---\x20Info\x20&\x20Hints\x20---');for(const j of f){b['push']('\x20\x20['+j['code']+']\x20('+j['source']+')\x20'+j['message']),b['push']('\x20\x20\x20\x20Path:\x20'+j['location']['path']);}}return b['join']('\x0a');}
|
|
1
|
+
import{validateGuardData,MAX_DESCRIPTION_LENGTH,MAX_GUARD_TABLE_ITEM_LENGTH,MAX_NAME_LENGTH,ValueType}from'@wowok/wowok';import{evaluateGuardDraft}from'./guard-eval.js';import{findScene,inferSceneFromAction}from'./guard-ledger.js';import{suggestTemplateForScene}from'./guard-templates.js';import{validateGuardTreeShape}from'./guard-render.js';const VALUE_TYPE_ID_TO_NAME={[ValueType['Bool']]:'Bool',[ValueType['Address']]:'Address',[ValueType['String']]:'String',[ValueType['U8']]:'U8',[ValueType['U16']]:'U16',[ValueType['U32']]:'U32',[ValueType['U64']]:'U64',[ValueType['U128']]:'U128',[ValueType['U256']]:'U256',[ValueType['VecBool']]:'VecBool',[ValueType['VecAddress']]:'VecAddress',[ValueType['VecString']]:'VecString',[ValueType['VecU8']]:'VecU8',[ValueType['VecU16']]:'VecU16',[ValueType['VecU32']]:'VecU32',[ValueType['VecU64']]:'VecU64',[ValueType['VecU128']]:'VecU128',[ValueType['VecU256']]:'VecU256',[ValueType['VecVecU8']]:'VecVecU8'};function normalizeValueTypeNames(a){if(!a['table']['some'](b=>typeof b['value_type']==='number'))return a;return{...a,'table':a['table']['map'](b=>typeof b['value_type']==='number'?{...b,'value_type':VALUE_TYPE_ID_TO_NAME[b['value_type']]??String(b['value_type'])}:b)};}function deepClone(a){return JSON['parse'](JSON['stringify'](a));}function rootToString(a){return JSON['stringify'](a);}function hasSignerContext(a){const b=rootToString(a);return b['includes']('\x22Signer\x22')||b['includes']('\x22context\x22:\x22Signer\x22')||b['includes']('\x22context\x22:\x20\x22Signer\x22');}function getSubmissionEntries(a){return a['filter'](b=>b['b_submission']===!![]);}function inferValueType(a){if(typeof a==='string'){if(a['startsWith']('0x')&&a['length']>=0x3)return'Address';return'String';}if(typeof a==='number'){if(Number['isInteger'](a)){if(a>=0x0&&a<=0xff)return'U8';if(a>=0x0&&a<=0xffff)return'U16';return'U64';}return'U256';}if(typeof a==='boolean')return'Bool';if(Array['isArray'](a)){if(a['length']>0x0){const b=inferValueType(a[0x0]);if(b==='Address')return'Vec<Address>';if(b==='String')return'Vec<String>';if(b==='Bool')return'Vec<Bool>';}return'Vec<Address>';}return undefined;}function sdkIssueToDiagnostic(a){return{'code':a['code'],'message':a['message'],'severity':a['severity'],'source':'sdk','location':{'path':a['path']},'fix':{'description':'SDK\x20validation\x20failed\x20('+(a['sdk_error']??'InvalidParam')+');\x20manual\x20fix\x20required','auto_fixable':![]}};}async function checkSdkSyntax(a){const b=validateGuardTreeShape(a['root']);if(b['length']>0x0)return b['map'](f=>({'code':'G-001','message':f['message'],'severity':'error','source':'sdk','location':{'path':f['path']},'fix':{'description':'Unary\x20operators\x20(logic_not,\x20value_type,\x20vec_length,\x20calc_string_length,\x20convert_*)\x20take\x20a\x20single\x20\x27node\x27\x20child;\x20only\x20multi-operand\x20forms\x20(logic_and,\x20logic_or,\x20logic_equal,\x20logic_as_u256_*,\x20calc_number_*,\x20vec_contains_*)\x20take\x20a\x20\x27nodes\x27\x20array.','auto_fixable':![]}}));const c=a['table']['map'](f=>({'identifier':f['identifier'],'b_submission':f['b_submission']??![],'value_type':f['value_type']??'Address','value':f['value'],'name':f['name']??''}));let d;try{d=await validateGuardData({'description':a['description'],'table':c,'root':a['root'],'rely':a['rely']});}catch(f){const g=f?.['message']??String(f),h=/guard tree ([^:]+):/['exec'](g);return[{'code':'G-001','message':g,'severity':'error','source':'sdk','location':{'path':h?toJsonPointer(h[0x1]):'/root'},'fix':{'description':'Repair\x20the\x20tree\x20at\x20the\x20named\x20path:\x20unary\x20operators\x20(logic_not,\x20convert_*,\x20value_type)\x20take\x20a\x20single\x20\x27node\x27\x20child;\x20only\x20multi-operand\x20forms\x20(logic_and,\x20logic_or,\x20logic_equal,\x20calc_*,\x20vec_*)\x20take\x20\x27nodes\x27.','auto_fixable':![]}}];}return d['map'](sdkIssueToDiagnostic);}function toJsonPointer(a){const b=a['replace'](/^\/+/,'');return b['startsWith']('root')?'/'+b:'/root/'+b;}function checkSemanticErrors(a){const b=[],{table:c,root:d,binding_hint:e}=a,f=e?findScene(e['host_object']??'',e['binding_field']??''):undefined,g=getSubmissionEntries(c);if(g['length']>0x0&&d&&!hasSignerContext(d)){const h=g['some'](j=>j['value_type']==='Address'),i=f?.['id']==='service_order_allocators_guard'&&e?.['sharing_recipients']!==undefined&&e['sharing_recipients']['length']>0x0&&!e['sharing_recipients']['includes']('Signer');if(h&&!i){const j=g['filter'](k=>k['value_type']==='Address')['map'](k=>c['indexOf'](k));b['push']({'code':'LE-04','message':'Submitted\x20data\x20has\x20no\x20Signer\x20binding\x20(submission\x20forgery\x20risk)','severity':'error','source':'lint','location':{'path':j['map'](k=>'/table/'+k)['join']('\x20→\x20')},'fix':{'description':'Add\x20logic_equal(context(Signer),\x20identifier[N])\x20in\x20root\x20to\x20bind\x20the\x20submitter\x20identity','auto_fixable':![]}});}}if(f?.['id']==='arbitration_voting_guard'){const k=g['some'](l=>['U8','U16','U32','U64','U128','U256']['includes'](l['value_type']??''));if(k){const l=g['filter'](m=>['U8','U16','U32','U64','U128','U256']['includes'](m['value_type']??''))['map'](m=>c['indexOf'](m));b['push']({'code':'LE-05','message':'voting_guard\x20voting\x20weight\x20comes\x20from\x20submitted\x20data\x20(weight\x20forgery\x20risk)','severity':'error','source':'lint','location':{'path':l['map'](m=>'/table/'+m)['join']('\x20→\x20')},'fix':{'description':'Derive\x20arbitrator\x20weights\x20from\x20the\x20Arb\x20object\x20via\x20witness\x20(e.g.\x20105\x20TypeArbArbitration)\x20rather\x20than\x20submitting\x20them\x20directly','auto_fixable':![]}});}}if(f?.['id']==='gen_passport_guard'||e?.['action']==='gen_passport'){const m=rootToString(d);if(m['includes']('1167')||m['includes']('repository.data')){const n=m['includes']('quote_guard');n&&b['push']({'code':'LE-06','message':'repository.data\x20query\x20with\x20quote_guard:\x20rigid\x20verification\x20requirement\x20—\x20ensure\x20Passport\x20includes\x20quote_guard\x20verification\x20with\x20necessary\x20submissions\x20(e.g.,\x20Payment\x20proof)','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'Ensure\x20the\x20quote_guard\x20is\x20verified:\x20user\x20submits\x20Payment\x20via\x20Passport,\x20quote_guard\x20verifies\x20Payment\x20fields,\x20repository\x20data\x20query\x20passes','auto_fixable':![]}});}}if(e?.['host_object']&&f){const o=e['host_object'],p=c['filter'](q=>!q['b_submission']&&q['value_type']==='Address'&&typeof q['value']==='string'&&q['value']['startsWith']('0x')&&q['object_type']===o);if(p['length']>0x0){const q=p['map'](r=>c['indexOf'](r));b['push']({'code':'LE-07','message':'Circular\x20reference\x20uses\x20an\x20address\x20rather\x20than\x20a\x20name\x20(Host\x20Object\x20may\x20not\x20be\x20published\x20yet\x20when\x20the\x20Guard\x20is\x20created)','severity':'error','source':'lint','location':{'path':q['map'](r=>'/table/'+r+'/value')['join']('\x20→\x20')},'fix':{'description':'Change\x20value\x20from\x20an\x20address\x20to\x20an\x20object\x20name\x20(e.g.\x20\x22service1\x22);\x20the\x20SDK\x20will\x20resolve\x20it\x20to\x20an\x20address\x20after\x20the\x20Host\x20Object\x20is\x20published','auto_fixable':![]}});}}return b;}function checkSyntaxHints(a){const b=[],{table:c}=a;(!a['description']||a['description']['trim']()==='')&&b['push']({'code':'SH-01','message':'description\x20is\x20missing\x20or\x20empty','severity':'info','source':'lint','location':{'path':'/description'},'fix':{'description':'Add\x20a\x20description,\x20e.g.\x20\x27Service\x20buy_guard:\x20whitelist\x20validation\x27','auto_fixable':!![]}});for(let d=0x0;d<c['length'];d++){const e=c[d];(!e['name']||e['name']['trim']()==='')&&b['push']({'code':'SH-03','message':'table['+d+']\x20is\x20missing\x20name','severity':'warning','source':'lint','location':{'path':'/table/'+d+'/name'},'fix':{'description':'Add\x20a\x20name,\x20e.g.\x20\x22data\x20entry\x20'+e['identifier']+'\x22','auto_fixable':!![]}});}for(let f=0x0;f<c['length'];f++){const g=c[f];!g['value_type']&&b['push']({'code':'SH-05','message':'table['+f+']\x20is\x20missing\x20value_type','severity':'warning','source':'lint','location':{'path':'/table/'+f+'/value_type'},'fix':{'description':'Infer\x20value_type\x20from\x20value\x20(e.g.\x20Address/String/U64,\x20etc.)','auto_fixable':!![]}});}c['length']>MAX_GUARD_TABLE_ITEM_LENGTH&&b['push']({'code':'SH-07','message':'table\x20entry\x20count\x20'+c['length']+'\x20exceeds\x20the\x20maximum\x20limit\x20'+MAX_GUARD_TABLE_ITEM_LENGTH,'severity':'error','source':'lint','location':{'path':'/table'},'fix':{'description':'Slim\x20down\x20the\x20table\x20by\x20merging\x20similar\x20entries,\x20or\x20split\x20into\x20multiple\x20Guards\x20+\x20rely','auto_fixable':![]}});for(let h=0x0;h<c['length'];h++){c[h]['b_submission']===undefined&&b['push']({'code':'SH-10','message':'table['+h+']\x20b_submission\x20is\x20missing','severity':'info','source':'lint','location':{'path':'/table/'+h+'/b_submission'},'fix':{'description':'Set\x20to\x20false\x20(constant)\x20or\x20true\x20(submitted\x20data)','auto_fixable':!![]}});}for(let j=0x0;j<c['length'];j++){const k=c[j];k['b_submission']===!![]&&k['value']!==undefined&&k['value']!==null&&b['push']({'code':'SH-11','message':'table['+j+']\x20has\x20a\x20redundant\x20value\x20field\x20on\x20b_submission=true\x20entry\x20(the\x20verifier\x20supplies\x20the\x20value\x20at\x20runtime;\x20this\x20value\x20is\x20ignored\x20by\x20BCS\x20encoding\x20and\x20wastes\x20gas)','severity':'warning','source':'lint','location':{'path':'/table/'+j+'/value'},'fix':{'description':'Remove\x20the\x20value\x20field\x20—\x20it\x20is\x20ignored\x20for\x20b_submission=true\x20entries','auto_fixable':!![]}});}return b;}function checkSuggestions(a){const b=[],{root:c,binding_hint:d,table:e,description:f}=a;if(c){const i=rootToString(c);if(i['includes']('vec_contains_address')&&i['includes']('Signer'))b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P04\x20(whitelist\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Refer\x20to\x20the\x20P04\x20Pattern\x20to\x20ensure\x20best\x20practices','auto_fixable':![]}});else{if(i['includes']('logic_equal')&&i['includes']('Signer')){const j=e['some'](k=>!k['b_submission']&&k['value_type']==='Address'&&typeof k['value']==='string'&&k['value']['length']>0x0);j&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P04\x20(whitelist\x20validation\x20—\x20single-address\x20variant)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'P04\x20single-address\x20form;\x20for\x20multi-address\x20scenarios,\x20consider\x20vec_contains_address','auto_fixable':![]}});}}(i['includes']('logic_as_u256_greater')||i['includes']('logic_as_u256_lesser'))&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P02\x20(numeric\x20threshold\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Suitable\x20for\x20amount/quantity\x20threshold\x20validation\x20scenarios','auto_fixable':![]}}),i['includes']('convert_witness')&&b['push']({'code':'SG-01','message':'Matches\x20Pattern\x20P09\x20(witness-derived\x20validation)','severity':'hint','source':'lint','location':{'path':'/root'},'fix':{'description':'Suitable\x20for\x20cross-object\x20relationship\x20validation\x20(e.g.\x20Order→Progress)','auto_fixable':![]}});}if(d?.['action']){const k=['buy','forward','allocate','claim_reward','vote','dispute','write_repository','submit_progress','gen_passport'];if(k['includes'](d['action'])){const l=inferSceneFromAction(d['action']);if(l){const m=suggestTemplateForScene(l['id']);m&&b['push']({'code':'SG-02','message':'Recommended\x20scene\x20template:\x20'+m['name'],'severity':'hint','source':'lint','location':{'path':'/'},'fix':{'description':'Refer\x20to\x20template\x20'+m['id']+'\x20('+m['example_use_case']+')','auto_fixable':![]}});}}}const g=n=>new TextEncoder()['encode'](n)['length'],h=getSubmissionEntries(e);for(const [n,o]of e['entries']()){const p=o['name']??'';if(p['length']===0x0)continue;if(g(p)>MAX_NAME_LENGTH)b['push']({'code':'SG-03','message':'table['+n+']\x20name\x20is\x20'+g(p)+'\x20BCS\x20characters,\x20maximum\x20is\x20'+MAX_NAME_LENGTH+'.\x20Use\x20a\x20short\x20identifier\x20(e.g.\x20\x27order_id\x27,\x20\x27delivery_node\x27);\x20the\x20human-readable\x20explanation\x20belongs\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field','severity':'warning','source':'lint','location':{'path':'/table/'+n+'/name'},'fix':{'description':'Shorten\x20the\x20name\x20to\x20'+MAX_NAME_LENGTH+'\x20BCS\x20characters\x20or\x20fewer','auto_fixable':![]}});else p['toLowerCase']()['startsWith']('0x')&&b['push']({'code':'SG-03','message':'table['+n+']\x20name\x20must\x20not\x20start\x20with\x20\x220x\x22\x20(reserved\x20for\x20object\x20IDs)','severity':'warning','source':'lint','location':{'path':'/table/'+n+'/name'},'fix':{'description':'Rename\x20the\x20entry\x20without\x20the\x200x\x20prefix','auto_fixable':![]}});}if(h['length']>0x0){const q=(f??'')['trim']();q['length']<0xa&&b['push']({'code':'SG-03','message':'This\x20Guard\x20accepts\x20submitted\x20data\x20('+h['length']+'\x20table\x20'+(h['length']===0x1?'entry':'entries')+'\x20with\x20b_submission=true)\x20but\x20its\x20description\x20is\x20too\x20short\x20for\x20a\x20verifier\x20to\x20know\x20what\x20to\x20submit.\x20Explain\x20the\x20expected\x20submitted\x20data\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field,\x20e.g.\x20\x27user-submitted\x20operation\x20type\x20(return/damage)\x27','severity':'info','source':'lint','location':{'path':'/'},'fix':{'description':'Explain\x20the\x20expected\x20submitted\x20data\x20in\x20the\x20Guard\x27s\x20\x27description\x27\x20field','auto_fixable':![]}});}if(c){const r=rootToString(c),s=r['includes']('proof.signer'),t=r['includes']('proof.time'),u=r['includes']('calc_string_length'),v=h['some'](w=>w['value_type']==='String');if(s&&t)b['push']({'code':'SG-04','message':'Strict-mode\x20privacy-delivery\x20guard\x20detected\x20(proof.signer\x20+\x20proof.time).\x20'+'Recommended\x20three\x20conditions:\x20Signer==proof.signer\x20(submitter\x20accountability),\x20'+'proof.time>order.time\x20(freshness),\x20order.service==service\x20(project\x20binding).\x20'+'No\x20content\x20verification\x20—\x20only\x20submission\x20responsibility\x20(\x27whoever\x20benefits\x20bears\x20the\x20burden\x20of\x20proof\x27).','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'Ensure\x20all\x20three\x20conditions\x20are\x20present\x20(logic_and).\x20Refer\x20to\x20template\x20tpl_forward_privacy_delivery_proof.\x20'+'Query\x20IDs:\x20proof.signer=1958,\x20proof.time=1960,\x20order.time=1574,\x20order.service=1563.','auto_fixable':![]}});else u&&v&&b['push']({'code':'SG-04','message':'Broad-mode\x20privacy-delivery\x20guard\x20detected\x20(String\x20submission\x20+\x20length\x20check,\x20e.g.\x20Merkle\x20Root\x20length\x20==\x2066).\x20'+'This\x20trusts\x20the\x20submitter\x27s\x20honesty;\x20the\x20counterparty\x20can\x20dispute\x20by\x20checking\x20their\x20own\x20Messenger\x20conversation.\x20'+'Suitable\x20as\x20an\x20arbitration\x20basis,\x20not\x20a\x20fund-flow\x20gate.','severity':'info','source':'lint','location':{'path':'/root'},'fix':{'description':'For\x20stronger\x20assurance,\x20consider\x20strict\x20mode:\x20submit\x20a\x20Proof\x20object\x20address\x20(from\x20messenger.submitChainProof)\x20+\x20'+'Order\x20address,\x20then\x20verify\x20proof.signer/proof.time/order.service.\x20See\x20template\x20tpl_forward_privacy_delivery_proof.','auto_fixable':![]}});}return b;}export function autoFixGuard(a){const b=deepClone(a),c=[];(!b['description']||b['description']['trim']()==='')&&(b['description']='Guard\x20(table:\x20'+b['table']['length']+'\x20items,\x20root:\x20'+(b['root']?.['type']??'unknown')+')',c['push']({'diagnostic_code':'SH-01','description':'Fill\x20in\x20default\x20description','after':b['description'],'path':'/description'}));if(b['description']&&b['description']['length']>MAX_DESCRIPTION_LENGTH){const f=b['description'];b['description']=b['description']['substring'](0x0,MAX_DESCRIPTION_LENGTH),c['push']({'diagnostic_code':'G-001','description':'Truncate\x20description\x20to\x20'+MAX_DESCRIPTION_LENGTH+'\x20characters','before':f['length']+'\x20characters','after':b['description']['length']+'\x20characters','path':'/description'});}for(let g=0x0;g<b['table']['length'];g++){const h=b['table'][g];(!h['name']||h['name']['trim']()==='')&&(h['name']='data\x20entry\x20'+h['identifier'],c['push']({'diagnostic_code':'SH-03','description':'table['+g+']\x20fill\x20in\x20name','after':h['name'],'path':'/table/'+g+'/name'}));}for(let j=0x0;j<b['table']['length'];j++){const k=b['table'][j];if(!k['value_type']&&k['value']!==undefined&&k['value']!==null){const l=inferValueType(k['value']);l&&(k['value_type']=l,c['push']({'diagnostic_code':'SH-05','description':'table['+j+']\x20infer\x20value_type','after':l,'path':'/table/'+j+'/value_type'}));}}const d=new Map();let e=0x0;for(let m=0x0;m<b['table']['length'];m++){const n=b['table'][m];if(!d['has'](n['identifier']))d['set'](n['identifier'],e),n['identifier']!==e&&c['push']({'diagnostic_code':'G-007','description':'table['+m+']\x20identifier\x20'+n['identifier']+'\x20→\x20'+e,'before':String(n['identifier']),'after':String(e),'path':'/table/'+m+'/identifier'}),n['identifier']=e,e++;else{const o=n['identifier'];n['identifier']=e,d['set'](o,e),c['push']({'diagnostic_code':'G-007','description':'table['+m+']\x20identifier\x20'+o+'\x20duplicate\x20→\x20reallocated\x20to\x20'+e,'before':String(o),'after':String(e),'path':'/table/'+m+'/identifier'}),e++;}}for(let p=0x0;p<b['table']['length'];p++){const q=b['table'][p];q['b_submission']===undefined&&(q['b_submission']=![],c['push']({'diagnostic_code':'SH-10','description':'table['+p+']\x20b_submission\x20default\x20set\x20to\x20false','after':'false','path':'/table/'+p+'/b_submission'}));}if(b['rely']?.['guards']&&b['rely']['guards']['length']>0x0){const r=[...new Set(b['rely']['guards'])];r['length']!==b['rely']['guards']['length']&&(c['push']({'diagnostic_code':'G-009','description':'rely\x20deduplicate:\x20'+b['rely']['guards']['length']+'\x20→\x20'+r['length'],'before':JSON['stringify'](b['rely']['guards']),'after':JSON['stringify'](r),'path':'/rely/guards'}),b['rely']['guards']=r);}for(let s=0x0;s<b['table']['length'];s++){const t=b['table'][s];if(t['b_submission']===!![]&&t['value']!==undefined&&t['value']!==null){const u=JSON['stringify'](t['value']);delete t['value'],c['push']({'diagnostic_code':'SH-11','description':'table['+s+']\x20remove\x20redundant\x20value\x20on\x20b_submission=true\x20entry','before':u,'after':'(removed)','path':'/table/'+s+'/value'});}}return{'fixed':b,'actions':c};}export async function lintGuard(a,b){const c=b?.['auto_fix']??!![],d=normalizeValueTypeNames(a),{table:e,root:f,rely:g,binding_hint:h}=d,i=[];let j;const k=await checkSdkSyntax(d);i['push'](...k);const l=checkSemanticErrors(d);i['push'](...l);const m=checkSyntaxHints(d);i['push'](...m);let n,o=[];if(c){const {fixed:w,actions:x}=autoFixGuard(d);x['length']>0x0&&(n=w,o=x);}if(e['length']>0x0&&f){const y=h?findScene(h['host_object']??'',h['binding_field']??''):undefined,z=e['map'](B=>({'identifier':B['identifier'],'b_submission':B['b_submission']??![],'value_type':B['value_type']??'Address','value':B['value'],'name':B['name'],'object_type':B['object_type']})),A=evaluateGuardDraft({'table':z,'root':f,'rely':g,'scene':y,'sharing_recipients':h?.['sharing_recipients']});j=A['assessment'];for(const B of j['risks']){const C=B['level']==='critical'||B['level']==='high'?'error':B['level']==='medium'?'warning':B['level']==='low'?'info':'hint',D=B['evidence']??'',E=D['startsWith']('/')?D:'/';i['push']({'code':B['id'],'message':'['+B['level']+']\x20'+B['title'],'severity':C,'source':'risk','location':{'path':E},'fix':{'description':B['mitigation'],'auto_fixable':![]}});}}const p=checkSuggestions(d);i['push'](...p);const q=i['filter'](F=>F['severity']==='error')['length'],s=i['filter'](F=>F['severity']==='warning')['length'],t=i['filter'](F=>F['severity']==='info'||F['severity']==='hint')['length'],u=q===0x0;let v;if(q>0x0)v='Fix\x20'+q+'\x20error(s)\x20and\x20re-run\x20lint';else s>0x0?v='Consider\x20addressing\x20'+s+'\x20warning(s),\x20then\x20submit\x20to\x20SDK\x20newGuard()\x20for\x20final\x20syntax\x20validation':v='lint\x20passed\x20(no\x20errors);\x20submit\x20to\x20SDK\x20newGuard()\x20for\x20final\x20syntax\x20validation\x20before\x20going\x20on-chain';return{'json_summary':{'table_count':e['length'],'root_type':f?.['type']??'unknown','has_rely':!!g?.['guards']?.['length'],'rely_count':g?.['guards']?.['length']??0x0,'has_description':!!d['description']},'diagnostics':i,'fixed_json':n,'fix_actions':o,'risk_assessment':j,'summary':{'errors':q,'warnings':s,'infos':t,'auto_fixes_applied':o['length'],'ready':u,'next_step':v}};}export async function isGuardReady(a){const b=await lintGuard(a,{'auto_fix':![]});return b['summary']['ready'];}export async function getGuardErrors(a){const b=await lintGuard(a,{'auto_fix':![]});return b['diagnostics']['filter'](c=>c['severity']==='error');}export function formatLintResult(a){const b=[];b['push']('===\x20Guard\x20JSON\x20Lint\x20Report\x20==='),b['push'](''),b['push']('Summary:'),b['push']('\x20\x20Errors:\x20\x20\x20\x20\x20'+a['summary']['errors']),b['push']('\x20\x20Warnings:\x20\x20\x20'+a['summary']['warnings']),b['push']('\x20\x20Infos:\x20\x20\x20\x20\x20\x20'+a['summary']['infos']),b['push']('\x20\x20Auto-fixes:\x20'+a['summary']['auto_fixes_applied']),b['push']('\x20\x20Ready:\x20\x20\x20\x20\x20\x20'+(a['summary']['ready']?'YES':'NO')),b['push']('\x20\x20Next\x20step:\x20\x20'+a['summary']['next_step']),b['push']('');if(a['fix_actions']['length']>0x0){b['push']('---\x20Auto-fix\x20Actions\x20---');for(const g of a['fix_actions']){b['push']('\x20\x20['+g['diagnostic_code']+']\x20'+g['description']),b['push']('\x20\x20\x20\x20Path:\x20'+g['path']),g['before']&&g['after']&&b['push']('\x20\x20\x20\x20'+g['before']+'\x20->\x20'+g['after']);}b['push']('');}const c=a['diagnostics']['filter'](h=>h['severity']==='error'),e=a['diagnostics']['filter'](h=>h['severity']==='warning'),f=a['diagnostics']['filter'](h=>h['severity']==='info'||h['severity']==='hint');if(c['length']>0x0){b['push']('---\x20Errors\x20(must\x20fix)\x20---');for(const h of c){b['push']('\x20\x20['+h['code']+']\x20('+h['source']+')\x20'+h['message']),b['push']('\x20\x20\x20\x20Path:\x20'+h['location']['path']);if(h['fix'])b['push']('\x20\x20\x20\x20Fix:\x20\x20'+h['fix']['description']);}b['push']('');}if(e['length']>0x0){b['push']('---\x20Warnings\x20(consider\x20fixing)\x20---');for(const i of e){b['push']('\x20\x20['+i['code']+']\x20('+i['source']+')\x20'+i['message']),b['push']('\x20\x20\x20\x20Path:\x20'+i['location']['path']);if(i['fix'])b['push']('\x20\x20\x20\x20Fix:\x20\x20'+i['fix']['description']);}b['push']('');}if(f['length']>0x0){b['push']('---\x20Info\x20&\x20Hints\x20---');for(const j of f){b['push']('\x20\x20['+j['code']+']\x20('+j['source']+')\x20'+j['message']),b['push']('\x20\x20\x20\x20Path:\x20'+j['location']['path']);}}return b['join']('\x0a');}
|
|
@@ -38,6 +38,12 @@ export interface GuardRenderInput {
|
|
|
38
38
|
} | null;
|
|
39
39
|
}
|
|
40
40
|
export declare function walkGuardTree(root: GuardNodeForRender, visit: (node: GuardNodeForRender) => void): void;
|
|
41
|
+
export declare const GUARD_UNARY_CHILD_TYPES: ReadonlySet<string>;
|
|
42
|
+
export interface GuardTreeIssue {
|
|
43
|
+
path: string;
|
|
44
|
+
message: string;
|
|
45
|
+
}
|
|
46
|
+
export declare function validateGuardTreeShape(root: unknown, path?: string): GuardTreeIssue[];
|
|
41
47
|
export declare function renderGuardMermaid(root: GuardNodeForRender, options?: {
|
|
42
48
|
colored?: boolean;
|
|
43
49
|
}): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function walkGuardTree(a,b){const c=[a];while(c['length']>0x0){const d=c['pop']();if(!d||typeof d!=='object')continue;b(d);if(Array['isArray'](d['nodes']))c['push'](...d['nodes']);if(d['node'])c['push'](d['node']);if(d['nodeLeft'])c['push'](d['nodeLeft']);if(d['nodeRight'])c['push'](d['nodeRight']);if(Array['isArray'](d['parameters']))c['push'](...d['parameters']);if(d['historyIdx'])c['push'](d['historyIdx']);if(d['sessionIdx'])c['push'](d['sessionIdx']);if(d['forwardIdx'])c['push'](d['forwardIdx']);if(d['where'])c['push'](d['where']);if(d['find'])c['push'](d['find']);if(d['objectLeft'])c['push'](d['objectLeft']);if(d['objectRight'])c['push'](d['objectRight']);if(d['recipient'])c['push'](d['recipient']);}}function categorizeNodeType(a){if(a['startsWith']('logic_'))return'decision';if(a==='context')return'context';if(a==='identifier')return'leaf';if(a==='query')return'query';if(a['startsWith']('calc_')||a['startsWith']('convert_'))return'computation';if(a['startsWith']('vec_'))return'computation';if(a['startsWith']('query_reward_')||a['startsWith']('query_progress_'))return'query';return'computation';}function shortNodeLabel(a){const b=a['type'];switch(b){case'logic_and':return'AND';case'logic_or':return'OR';case'logic_not':return'NOT';case'logic_equal':return'==';case'logic_as_u256_equal':return'==#';case'logic_as_u256_greater':return'>';case'logic_as_u256_greater_or_equal':return'>=';case'logic_as_u256_lesser':return'<';case'logic_as_u256_lesser_or_equal':return'<=';case'logic_string_contains':return'contains';case'logic_string_nocase_contains':return'contains~';case'logic_string_nocase_equal':return'==~';case'calc_number_add':return'+';case'calc_number_subtract':return'-';case'calc_number_multiply':return'*';case'calc_number_divide':return'/';case'calc_number_mod':return'%';case'calc_string_length':return'len';case'calc_string_contains':return'contains';case'calc_string_nocase_contains':return'contains~';case'calc_string_nocase_equal':return'==~';case'calc_string_indexof':return'indexOf';case'calc_string_nocase_indexof':return'indexOf~';case'convert_number_address':return'→Addr';case'convert_address_number':return'→Num';case'convert_number_string':return'→Str';case'convert_string_number':return'→Num';case'convert_safe_u8':return'→U8';case'convert_safe_u16':return'→U16';case'convert_safe_u32':return'→U32';case'convert_safe_u64':return'→U64';case'convert_safe_u128':return'→U128';case'convert_safe_u256':return'→U256';case'value_type':return'typeOf';case'vec_length':return'len';case'vec_contains_bool':return'∈?';case'vec_contains_address':return'∈?';case'vec_contains_string':return'∈?';case'vec_contains_string_nocase':return'∈?~';case'vec_contains_number':return'∈?';case'vec_indexof_bool':return'idx';case'vec_indexof_address':return'idx';case'vec_indexof_string':return'idx';case'vec_indexof_string_nocase':return'idx~';case'vec_indexof_number':return'idx';case'query':return'Q:'+(typeof a['query']==='number'?'#'+a['query']:a['query']);case'query_reward_record_count':return'reward.count';case'query_reward_record_exists':return'reward.exists';case'query_reward_record_find':return'reward.find';case'query_progress_history_find':return'history.find';case'query_progress_history_session_find':return'session.find';case'query_progress_history_session_forward_find':return'forward.find';case'query_progress_history_session_count':return'session.count';case'query_progress_history_session_forward_count':return'forward.count';case'query_progress_history_session_forward_retained_submission_count':return'retained.count';case'query_repository_data_count_where':return'repo.count';case'query_repository_data_sum_where':return'repo.sum';case'query_repository_data_find_where':return'repo.find';case'query_repository_data_keys_where':return'repo.keys.where';case'query_repository_policies_keys':return'repo.keys';case'identifier':return'id['+(a['identifier']??'?')+']';case'context':return a['context']??'ctx';default:return b;}}let nodeIdCounter=0x0;function makeNodeId(a){return nodeIdCounter++,a+'_'+nodeIdCounter;}function sanitizeMermaidLabel(a){if(/[<>"\[\]{}()|&]/['test'](a))return'\x22'+a['replace'](/"/g,'\x27')+'\x22';return a;}const GUARD_NODE_COLORS={'control':{'fill':'#3b82f6','stroke':'#1e40af'},'decision':{'fill':'#f59e0b','stroke':'#92400e'},'computation':{'fill':'#8b5cf6','stroke':'#6d28d9'},'query':{'fill':'#06b6d4','stroke':'#0e7490'},'leaf':{'fill':'#6b7280','stroke':'#374151'},'context':{'fill':'#10b981','stroke':'#065f46'}};function colorCategoryForNodeType(a){if(a==='logic_and'||a==='logic_or')return'control';if(a==='logic_not'||a['startsWith']('logic_'))return'decision';if(a['startsWith']('calc_')||a['startsWith']('convert_')||a['startsWith']('vec_'))return'computation';if(a==='query'||a['startsWith']('query_'))return'query';if(a==='identifier')return'leaf';if(a==='context')return'context';return'computation';}export function renderGuardMermaid(a,b){const c=b?.['colored']!==![];nodeIdCounter=0x0;const d=['flowchart\x20TD'];c&&(d['push']('\x20\x20%%\x20Color\x20Legend\x20(BehaviorTree.CPP-inspired\x20semantic\x20roles):'),d['push']('\x20\x20%%\x20\x20\x20blue\x20\x20\x20#3b82f6\x20-\x20control\x20\x20\x20\x20\x20(logic_and,\x20logic_or)'),d['push']('\x20\x20%%\x20\x20\x20amber\x20\x20#f59e0b\x20-\x20decision\x20\x20\x20\x20(logic_not,\x20comparisons)'),d['push']('\x20\x20%%\x20\x20\x20purple\x20#8b5cf6\x20-\x20computation\x20(calc_*,\x20convert_*,\x20vec_*)'),d['push']('\x20\x20%%\x20\x20\x20cyan\x20\x20\x20#06b6d4\x20-\x20query\x20\x20\x20\x20\x20\x20\x20(query,\x20query_*)'),d['push']('\x20\x20%%\x20\x20\x20gray\x20\x20\x20#6b7280\x20-\x20leaf\x20\x20\x20\x20\x20\x20\x20\x20(identifier)'),d['push']('\x20\x20%%\x20\x20\x20green\x20\x20#10b981\x20-\x20context\x20\x20\x20\x20\x20(Signer,\x20Clock,\x20Guard)'),d['push']('\x20\x20%%\x20Node\x20shapes:\x20{}=decision,\x20[]=computation/query,\x20([])=leaf,\x20{{}}=context'));const e=[],f=[],g=[];function h(i,j,k){const l=makeNodeId('n'),m=categorizeNodeType(i['type']),n=shortNodeLabel(i);let o='[',p=']';switch(m){case'decision':o='{',p='}';break;case'context':o='{{',p='}}';break;case'leaf':o='([',p='])';break;case'query':case'computation':default:o='[',p=']';break;}e['push'](''+l+o+sanitizeMermaidLabel(n)+p),g['push']({'id':l,'type':i['type']});j&&(k?f['push']('\x20\x20'+j+'\x20-->\x20'+l+':\x20'+sanitizeMermaidLabel(k)):f['push']('\x20\x20'+j+'\x20-->\x20'+l));i['nodes']&&Array['isArray'](i['nodes'])&&i['nodes']['forEach']((q,r)=>{h(q,l,'['+r+']');});i['node']&&h(i['node'],l,'child');i['nodeLeft']&&h(i['nodeLeft'],l,'left');i['nodeRight']&&h(i['nodeRight'],l,'right');i['parameters']&&Array['isArray'](i['parameters'])&&i['parameters']['forEach']((q,r)=>{h(q,l,'param['+r+']');});if(i['historyIdx'])h(i['historyIdx'],l,'historyIdx');if(i['sessionIdx'])h(i['sessionIdx'],l,'sessionIdx');if(i['forwardIdx'])h(i['forwardIdx'],l,'forwardIdx');if(i['where'])h(i['where'],l,'where');if(i['find'])h(i['find'],l,'find');if(i['objectLeft'])h(i['objectLeft'],l,'objLeft');if(i['objectRight'])h(i['objectRight'],l,'objRight');if(i['recipient'])h(i['recipient'],l,'recipient');return l;}h(a),d['push'](...e['map'](i=>'\x20\x20'+i)),d['push'](...f);if(c){d['push'](''),d['push']('\x20\x20%%\x20Node\x20colors\x20(BehaviorTree.CPP-inspired\x20semantic\x20roles)');for(const {id:i,type:j}of g){const k=colorCategoryForNodeType(j),l=GUARD_NODE_COLORS[k];d['push']('\x20\x20style\x20'+i+'\x20fill:'+l['fill']+',stroke:'+l['stroke']+',color:#fff');}}return d['join']('\x0a');}export function renderGuardTreeIndented(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[];function i(k){const l=k['type'];if(l==='identifier'){const m=c?.['find'](o=>o['identifier']===k['identifier']),n=m?.['name']?'\x20\x22'+m['name']+'\x22':'';return'identifier['+(k['identifier']??'?')+']'+n;}if(l==='context')return'context('+(k['context']??'?')+')';if(l==='query'){const o=k['object']?.['convert_witness'],p=k['object']?.['identifier'],q=o!==undefined?',\x20witness='+o:'',r=p!==undefined?',\x20id['+p+']':'',s=k['parameters']&&k['parameters']['length']>0x0?',\x20params=['+k['parameters']['map'](u=>shortNodeLabel(u))['join'](',\x20')+']':'';return'query('+(typeof k['query']==='number'?'#'+k['query']:k['query'])+r+q+s+')';}return shortNodeLabel(k);}function j(k,l,m){const n='\x20\x20'['repeat'](l),o=l===0x0?'-\x20':'-\x20',p=m?m+':\x20':'',q=!k['nodes']&&!k['node']&&!k['nodeLeft']&&!k['nodeRight']&&!k['parameters']?.['length']&&!k['historyIdx']&&!k['sessionIdx']&&!k['forwardIdx']&&!k['where']&&!k['find']&&!k['objectLeft']&&!k['objectRight']&&!k['recipient'];q?h['push'](''+n+o+p+i(k)):h['push'](''+n+o+p+k['type']);k['nodes']&&Array['isArray'](k['nodes'])&&k['nodes']['forEach']((r,s)=>j(r,l+0x1,'child['+s+']'));k['node']&&j(k['node'],l+0x1,'child');k['nodeLeft']&&j(k['nodeLeft'],l+0x1,'left');k['nodeRight']&&j(k['nodeRight'],l+0x1,'right');k['parameters']&&Array['isArray'](k['parameters'])&&k['parameters']['forEach']((r,s)=>j(r,l+0x1,'param['+s+']'));if(k['historyIdx'])j(k['historyIdx'],l+0x1,'historyIdx');if(k['sessionIdx'])j(k['sessionIdx'],l+0x1,'sessionIdx');if(k['forwardIdx'])j(k['forwardIdx'],l+0x1,'forwardIdx');if(k['where'])j(k['where'],l+0x1,'where');if(k['find'])j(k['find'],l+0x1,'find');if(k['objectLeft'])j(k['objectLeft'],l+0x1,'objLeft');if(k['objectRight'])j(k['objectRight'],l+0x1,'objRight');if(k['recipient'])j(k['recipient'],l+0x1,'recipient');}h['push']('#\x20Guard\x20Tree\x20Definition'),h['push']('');d&&h['push']('**Guard:**\x20'+d);e&&h['push']('**Address:**\x20'+e);c&&h['push']('**Table\x20Entries:**\x20'+c['length']);f&&f['guards']['length']>0x0&&h['push']('**Rely:**\x20'+f['guards']['length']+'\x20guard(s)'+(f['logic_or']?'\x20(logic_or)':'\x20(logic_and)'));h['push'](''),h['push']('##\x20Root'),j(b,0x0);if(c&&c['length']>0x0){h['push'](''),h['push']('##\x20Table'),h['push'](''),h['push']('|\x20identifier\x20|\x20b_submission\x20|\x20value_type\x20|\x20value\x20|\x20name\x20|'),h['push']('|------------|-------------|------------|-------|------|');for(const k of c){const l=k['value']===undefined?'-':String(k['value']),m=l['replace'](/\|/g,'\x5c|')['replace'](/\n/g,'\x20'),n=k['name']??'-';h['push']('|\x20'+k['identifier']+'\x20|\x20'+k['b_submission']+'\x20|\x20'+k['value_type']+'\x20|\x20'+m+'\x20|\x20'+n+'\x20|');}h['push'](''),h['push']('##\x20Table\x20JSON'),h['push'](''),h['push']('```json'),h['push'](JSON['stringify'](c,null,0x2)),h['push']('```');}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('##\x20Rely'),h['push'](''),h['push']('Logic:\x20'+(f['logic_or']?'OR':'AND'));for(const o of f['guards']){h['push']('-\x20'+o);}}return h['push'](''),h['push']('##\x20JSON\x20Definition'),h['push'](''),h['push']('```json'),h['push'](JSON['stringify']({'root':b,'table':c,'guardName':d,'guardAddress':e,'rely':f},null,0x2)),h['push']('```'),h['join']('\x0a');}export function parseGuardTreeIndented(a){const b=[],c=a['matchAll'](/```json\s*\n([\s\S]*?)```/g);let d=null;for(const k of c){d=k[0x1];}if(d)try{const l=JSON['parse'](d['trim']());if(l&&typeof l==='object'){if('root'in l&&l['root']&&typeof l['root']==='object'&&'type'in l['root'])return{'success':!![],'data':l['root'],'errors':[]};if('type'in l)return{'success':!![],'data':l,'errors':[]};}}catch(m){b['push']('JSON\x20code\x20block\x20parse\x20error:\x20'+m['message']);}const f=a['split']('\x0a')['filter'](n=>n['trim']()['startsWith']('-\x20'));if(f['length']===0x0)return{'success':![],'errors':['No\x20outline\x20entries\x20found.\x20Use\x20\x27-\x20\x27\x20prefixed\x20lines\x20or\x20a\x20JSON\x20code\x20block.']};const g=[];let h=null;function i(n){const o=n['match'](/^(\s*)- /);return o?o[0x1]['length']/0x2:0x0;}function j(n){const o=n['replace'](/^\s*- /,'')['trim'](),p=o['match'](/^([^:]+):\s*(.*)$/),q=p?p[0x1]['trim']():undefined,r=p?p[0x2]['trim']():o,s=r['match'](/^identifier\[(\d+)\](?:\s+"(.+)")?$/);if(s)return{'label':q,'node':{'type':'identifier','identifier':parseInt(s[0x1],0xa)}};const t=r['match'](/^context\((\w+)\)$/);if(t)return{'label':q,'node':{'type':'context','context':t[0x1]}};const u=r['match'](/^query\((.+?)\)$/);if(u){const v=u[0x1],w=v['split'](',')['map'](A=>A['trim']()),x=w[0x0]['replace'](/^#/,''),y=/^\d+$/['test'](x),z={'type':'query','query':y?parseInt(x,0xa):x};for(const A of w['slice'](0x1)){const B=A['match'](/^id\[(\d+)\]$/);B&&(z['object']={'identifier':parseInt(B[0x1],0xa)});const C=A['match'](/^witness=(\d+)$/);C&&(z['object']={...z['object']||{},'convert_witness':parseInt(C[0x1],0xa)});}return{'label':q,'node':z};}return{'label':q,'node':{'type':r}};}for(const n of f){const o=i(n),{label:p,node:q}=j(n);if(o===0x0)h=q,g['length']=0x0,g['push']({'node':q,'depth':o});else{while(g['length']>0x0&&g[g['length']-0x1]['depth']>=o){g['pop']();}const r=g[g['length']-0x1];if(!r){b['push']('Orphaned\x20node\x20at\x20depth\x20'+o+':\x20'+n);continue;}if(p){const s=p['match'](/^child\[(\d+)\]$/),t=p['match'](/^param\[(\d+)\]$/);if(s){if(!r['node']['nodes'])r['node']['nodes']=[];r['node']['nodes']['push'](q);}else{if(t){if(!r['node']['parameters'])r['node']['parameters']=[];r['node']['parameters']['push'](q);}else{if(p==='child')r['node']['node']=q;else{if(p==='left')r['node']['nodeLeft']=q;else{if(p==='right')r['node']['nodeRight']=q;else{if(p==='historyIdx')r['node']['historyIdx']=q;else{if(p==='sessionIdx')r['node']['sessionIdx']=q;else{if(p==='forwardIdx')r['node']['forwardIdx']=q;else{if(p==='where')r['node']['where']=q;else{if(p==='find')r['node']['find']=q;else{if(p==='objLeft')r['node']['objectLeft']=q;else{if(p==='objRight')r['node']['objectRight']=q;else p==='recipient'&&(r['node']['recipient']=q);}}}}}}}}}}}}g['push']({'node':q,'depth':o});}}if(!h)return{'success':![],'errors':['No\x20root\x20node\x20found\x20in\x20outline.']};return{'success':!![],'data':h,'errors':b};}export function renderGuardAscii(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[];if(d)h['push']('Guard:\x20'+d);if(e)h['push']('Address:\x20'+e);if(d||e)h['push']('');function i(m){const n=m['type'],o=shortNodeLabel(m);if(n==='identifier'){const p=c?.['find'](u=>u['identifier']===m['identifier']),q=p?'\x20['+(typeof p['value_type']==='string'?p['value_type']:'type='+p['value_type'])+']':'',r=p&&p['value']!==undefined&&!p['b_submission']?',\x20value='+String(p['value']):'',s=p?.['b_submission']?'\x20(submission)':'';return''+o+q+r+s;}if(n==='context')return o+'\x20['+(m['context']??'?')+']';if(n==='query'){const u=m['object']?.['convert_witness'],v=u!==undefined?',\x20witness='+u:'';return''+o+v;}return o;}function j(m){const n=[];m['nodes']&&Array['isArray'](m['nodes'])&&m['nodes']['forEach']((o,p)=>n['push']({'node':o,'label':'child['+p+']'}));if(m['node'])n['push']({'node':m['node'],'label':'child'});if(m['nodeLeft'])n['push']({'node':m['nodeLeft'],'label':'left'});if(m['nodeRight'])n['push']({'node':m['nodeRight'],'label':'right'});m['parameters']&&Array['isArray'](m['parameters'])&&m['parameters']['forEach']((o,p)=>n['push']({'node':o,'label':'param['+p+']'}));if(m['historyIdx'])n['push']({'node':m['historyIdx'],'label':'historyIdx'});if(m['sessionIdx'])n['push']({'node':m['sessionIdx'],'label':'sessionIdx'});if(m['forwardIdx'])n['push']({'node':m['forwardIdx'],'label':'forwardIdx'});if(m['where'])n['push']({'node':m['where'],'label':'where'});if(m['find'])n['push']({'node':m['find'],'label':'find'});if(m['objectLeft'])n['push']({'node':m['objectLeft'],'label':'objLeft'});if(m['objectRight'])n['push']({'node':m['objectRight'],'label':'objRight'});if(m['recipient'])n['push']({'node':m['recipient'],'label':'recipient'});return n;}function k(m,n,o,p){const q=o?'└─\x20':'├─\x20',r=p?p+':\x20':'';h['push'](''+n+q+r+i(m));const s=j(m),t=n+(o?'\x20\x20\x20':'│\x20\x20');s['forEach']((u,v)=>{k(u['node'],t,v===s['length']-0x1,u['label']);});}h['push'](i(b));const l=j(b);l['forEach']((m,n)=>{k(m['node'],'',n===l['length']-0x1,m['label']);});if(c&&c['length']>0x0){h['push'](''),h['push']('Table:');for(const m of c){const n=typeof m['value_type']==='string'?m['value_type']:'type='+m['value_type'],o=m['value']!==undefined&&!m['b_submission']?',\x20value='+String(m['value']):'',p=m['b_submission']?'\x20(submission)':'',q=m['name']?'\x20\x22'+m['name']+'\x22':'';h['push']('\x20\x20id['+m['identifier']+']'+q+':\x20'+n+o+p);}}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('Rely\x20('+(f['logic_or']?'OR':'AND')+'):');for(const r of f['guards']){h['push']('\x20\x20-\x20'+r);}}return h['join']('\x0a');}export function renderGuardMarkmap(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[],i=d?'Guard:\x20'+d:'Guard';h['push']('#\x20'+i);if(e)h['push']('');if(e)h['push']('**Address:**\x20'+e);h['push']('');function j(m,n){return'#'['repeat'](Math['min'](m+0x1,0x6))+'\x20'+n;}function k(m){const n=m['type'],o=shortNodeLabel(m);if(n==='identifier'){const p=c?.['find'](u=>u['identifier']===m['identifier']),q=p?'\x20['+(typeof p['value_type']==='string'?p['value_type']:'type='+p['value_type'])+']':'',r=p&&p['value']!==undefined&&!p['b_submission']?',\x20value='+String(p['value']):'',s=p?.['b_submission']?'\x20(submission)':'';return''+o+q+r+s;}if(n==='context')return o+'\x20['+(m['context']??'?')+']';if(n==='query'){const u=m['object']?.['convert_witness'],v=u!==undefined?',\x20witness='+u:'';return''+o+v;}return o;}function l(m,n,o){const p=o?o+':\x20':'';h['push'](j(n,''+p+k(m)));m['nodes']&&Array['isArray'](m['nodes'])&&m['nodes']['forEach']((q,r)=>l(q,n+0x1,'child['+r+']'));if(m['node'])l(m['node'],n+0x1,'child');if(m['nodeLeft'])l(m['nodeLeft'],n+0x1,'left');if(m['nodeRight'])l(m['nodeRight'],n+0x1,'right');m['parameters']&&Array['isArray'](m['parameters'])&&m['parameters']['forEach']((q,r)=>l(q,n+0x1,'param['+r+']'));if(m['historyIdx'])l(m['historyIdx'],n+0x1,'historyIdx');if(m['sessionIdx'])l(m['sessionIdx'],n+0x1,'sessionIdx');if(m['forwardIdx'])l(m['forwardIdx'],n+0x1,'forwardIdx');if(m['where'])l(m['where'],n+0x1,'where');if(m['find'])l(m['find'],n+0x1,'find');if(m['objectLeft'])l(m['objectLeft'],n+0x1,'objLeft');if(m['objectRight'])l(m['objectRight'],n+0x1,'objRight');if(m['recipient'])l(m['recipient'],n+0x1,'recipient');}h['push'](j(0x1,'Root')),l(b,0x2);if(c&&c['length']>0x0){h['push'](''),h['push']('##\x20Table');for(const m of c){const n=typeof m['value_type']==='string'?m['value_type']:'type='+m['value_type'],o=m['value']!==undefined&&!m['b_submission']?',\x20value='+String(m['value']):'',p=m['b_submission']?'\x20(submission)':'',q=m['name']?'\x20\x22'+m['name']+'\x22':'';h['push']('-\x20id['+m['identifier']+']'+q+':\x20'+n+o+p);}}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('##\x20Rely\x20('+(f['logic_or']?'OR':'AND')+')');for(const r of f['guards']){h['push']('-\x20'+r);}}return h['join']('\x0a');}export function parseGuardTableJSON(a){const b=a['match'](/##\s*Table JSON[^\n]*\n\s*```json\s*\n([\s\S]*?)```/i);if(!b)return null;try{const c=JSON['parse'](b[0x1]['trim']());if(!Array['isArray'](c))return null;return c['filter'](d=>{return d&&typeof d==='object'&&typeof d['identifier']==='number'&&typeof d['b_submission']==='boolean';})['map'](d=>({'identifier':d['identifier'],'name':d['name'],'value_type':d['value_type'],'b_submission':d['b_submission'],'value':d['value']}));}catch{return null;}}
|
|
1
|
+
export function walkGuardTree(a,b){const c=[a];while(c['length']>0x0){const d=c['pop']();if(!d||typeof d!=='object')continue;b(d);if(Array['isArray'](d['nodes']))c['push'](...d['nodes']);if(d['node'])c['push'](d['node']);if(d['nodeLeft'])c['push'](d['nodeLeft']);if(d['nodeRight'])c['push'](d['nodeRight']);if(Array['isArray'](d['parameters']))c['push'](...d['parameters']);if(d['historyIdx'])c['push'](d['historyIdx']);if(d['sessionIdx'])c['push'](d['sessionIdx']);if(d['forwardIdx'])c['push'](d['forwardIdx']);if(d['where'])c['push'](d['where']);if(d['find'])c['push'](d['find']);if(d['objectLeft'])c['push'](d['objectLeft']);if(d['objectRight'])c['push'](d['objectRight']);if(d['recipient'])c['push'](d['recipient']);}}export const GUARD_UNARY_CHILD_TYPES=new Set(['logic_not','value_type','vec_length','calc_string_length','convert_number_address','convert_address_number','convert_number_string','convert_string_number','convert_safe_u8','convert_safe_u16','convert_safe_u32','convert_safe_u64','convert_safe_u128','convert_safe_u256']);export function validateGuardTreeShape(a,b='/root'){const c=[],d=f=>[['node',f['node']],['nodeLeft',f['nodeLeft']],['nodeRight',f['nodeRight']],['historyIdx',f['historyIdx']],['sessionIdx',f['sessionIdx']],['forwardIdx',f['forwardIdx']]],e=(f,g)=>{if(f===undefined||f===null)return;if(Array['isArray'](f)){f['forEach']((j,k)=>e(j,g+'/'+k));return;}if(typeof f!=='object'){c['push']({'path':g,'message':'expected\x20a\x20Guard\x20node\x20object,\x20found\x20'+typeof f});return;}const h=f;if(typeof h['type']!=='string'||h['type']['length']===0x0){c['push']({'path':g,'message':'Guard\x20node\x20is\x20missing\x20its\x20string\x20\x27type\x27\x20(keys:\x20'+(Object['keys'](h)['join'](',\x20')||'none')+')'});return;}if(GUARD_UNARY_CHILD_TYPES['has'](h['type'])){if(h['node']===undefined||h['node']===null){const i=Array['isArray'](h['nodes'])?'\x20—\x20\x27nodes\x27\x20was\x20used,\x20but\x20this\x20operator\x20takes\x20a\x20single\x20\x27node\x27\x20child':'';c['push']({'path':g+'/node','message':'\x27'+h['type']+'\x27\x20requires\x20its\x20\x27node\x27\x20child'+i});}}for(const [j,k]of d(h))e(k,g+'/'+j);if(Array['isArray'](h['nodes']))e(h['nodes'],g+'/nodes');if(Array['isArray'](h['parameters']))e(h['parameters'],g+'/parameters');};return e(a,b),c;}function categorizeNodeType(a){if(a['startsWith']('logic_'))return'decision';if(a==='context')return'context';if(a==='identifier')return'leaf';if(a==='query')return'query';if(a['startsWith']('calc_')||a['startsWith']('convert_'))return'computation';if(a['startsWith']('vec_'))return'computation';if(a['startsWith']('query_reward_')||a['startsWith']('query_progress_'))return'query';return'computation';}function shortNodeLabel(a){const b=a['type'];switch(b){case'logic_and':return'AND';case'logic_or':return'OR';case'logic_not':return'NOT';case'logic_equal':return'==';case'logic_as_u256_equal':return'==#';case'logic_as_u256_greater':return'>';case'logic_as_u256_greater_or_equal':return'>=';case'logic_as_u256_lesser':return'<';case'logic_as_u256_lesser_or_equal':return'<=';case'logic_string_contains':return'contains';case'logic_string_nocase_contains':return'contains~';case'logic_string_nocase_equal':return'==~';case'calc_number_add':return'+';case'calc_number_subtract':return'-';case'calc_number_multiply':return'*';case'calc_number_divide':return'/';case'calc_number_mod':return'%';case'calc_string_length':return'len';case'calc_string_contains':return'contains';case'calc_string_nocase_contains':return'contains~';case'calc_string_nocase_equal':return'==~';case'calc_string_indexof':return'indexOf';case'calc_string_nocase_indexof':return'indexOf~';case'convert_number_address':return'→Addr';case'convert_address_number':return'→Num';case'convert_number_string':return'→Str';case'convert_string_number':return'→Num';case'convert_safe_u8':return'→U8';case'convert_safe_u16':return'→U16';case'convert_safe_u32':return'→U32';case'convert_safe_u64':return'→U64';case'convert_safe_u128':return'→U128';case'convert_safe_u256':return'→U256';case'value_type':return'typeOf';case'vec_length':return'len';case'vec_contains_bool':return'∈?';case'vec_contains_address':return'∈?';case'vec_contains_string':return'∈?';case'vec_contains_string_nocase':return'∈?~';case'vec_contains_number':return'∈?';case'vec_indexof_bool':return'idx';case'vec_indexof_address':return'idx';case'vec_indexof_string':return'idx';case'vec_indexof_string_nocase':return'idx~';case'vec_indexof_number':return'idx';case'query':return'Q:'+(typeof a['query']==='number'?'#'+a['query']:a['query']);case'query_reward_record_count':return'reward.count';case'query_reward_record_exists':return'reward.exists';case'query_reward_record_find':return'reward.find';case'query_progress_history_find':return'history.find';case'query_progress_history_session_find':return'session.find';case'query_progress_history_session_forward_find':return'forward.find';case'query_progress_history_session_count':return'session.count';case'query_progress_history_session_forward_count':return'forward.count';case'query_progress_history_session_forward_retained_submission_count':return'retained.count';case'query_repository_data_count_where':return'repo.count';case'query_repository_data_sum_where':return'repo.sum';case'query_repository_data_find_where':return'repo.find';case'query_repository_data_keys_where':return'repo.keys.where';case'query_repository_policies_keys':return'repo.keys';case'identifier':return'id['+(a['identifier']??'?')+']';case'context':return a['context']??'ctx';default:return b;}}let nodeIdCounter=0x0;function makeNodeId(a){return nodeIdCounter++,a+'_'+nodeIdCounter;}function sanitizeMermaidLabel(a){if(/[<>"\[\]{}()|&]/['test'](a))return'\x22'+a['replace'](/"/g,'\x27')+'\x22';return a;}const GUARD_NODE_COLORS={'control':{'fill':'#3b82f6','stroke':'#1e40af'},'decision':{'fill':'#f59e0b','stroke':'#92400e'},'computation':{'fill':'#8b5cf6','stroke':'#6d28d9'},'query':{'fill':'#06b6d4','stroke':'#0e7490'},'leaf':{'fill':'#6b7280','stroke':'#374151'},'context':{'fill':'#10b981','stroke':'#065f46'}};function colorCategoryForNodeType(a){if(a==='logic_and'||a==='logic_or')return'control';if(a==='logic_not'||a['startsWith']('logic_'))return'decision';if(a['startsWith']('calc_')||a['startsWith']('convert_')||a['startsWith']('vec_'))return'computation';if(a==='query'||a['startsWith']('query_'))return'query';if(a==='identifier')return'leaf';if(a==='context')return'context';return'computation';}export function renderGuardMermaid(a,b){const c=b?.['colored']!==![];nodeIdCounter=0x0;const d=['flowchart\x20TD'];c&&(d['push']('\x20\x20%%\x20Color\x20Legend\x20(BehaviorTree.CPP-inspired\x20semantic\x20roles):'),d['push']('\x20\x20%%\x20\x20\x20blue\x20\x20\x20#3b82f6\x20-\x20control\x20\x20\x20\x20\x20(logic_and,\x20logic_or)'),d['push']('\x20\x20%%\x20\x20\x20amber\x20\x20#f59e0b\x20-\x20decision\x20\x20\x20\x20(logic_not,\x20comparisons)'),d['push']('\x20\x20%%\x20\x20\x20purple\x20#8b5cf6\x20-\x20computation\x20(calc_*,\x20convert_*,\x20vec_*)'),d['push']('\x20\x20%%\x20\x20\x20cyan\x20\x20\x20#06b6d4\x20-\x20query\x20\x20\x20\x20\x20\x20\x20(query,\x20query_*)'),d['push']('\x20\x20%%\x20\x20\x20gray\x20\x20\x20#6b7280\x20-\x20leaf\x20\x20\x20\x20\x20\x20\x20\x20(identifier)'),d['push']('\x20\x20%%\x20\x20\x20green\x20\x20#10b981\x20-\x20context\x20\x20\x20\x20\x20(Signer,\x20Clock,\x20Guard)'),d['push']('\x20\x20%%\x20Node\x20shapes:\x20{}=decision,\x20[]=computation/query,\x20([])=leaf,\x20{{}}=context'));const e=[],f=[],g=[];function h(i,j,k){const l=makeNodeId('n'),m=categorizeNodeType(i['type']),n=shortNodeLabel(i);let o='[',p=']';switch(m){case'decision':o='{',p='}';break;case'context':o='{{',p='}}';break;case'leaf':o='([',p='])';break;case'query':case'computation':default:o='[',p=']';break;}e['push'](''+l+o+sanitizeMermaidLabel(n)+p),g['push']({'id':l,'type':i['type']});j&&(k?f['push']('\x20\x20'+j+'\x20-->\x20'+l+':\x20'+sanitizeMermaidLabel(k)):f['push']('\x20\x20'+j+'\x20-->\x20'+l));i['nodes']&&Array['isArray'](i['nodes'])&&i['nodes']['forEach']((q,r)=>{h(q,l,'['+r+']');});i['node']&&h(i['node'],l,'child');i['nodeLeft']&&h(i['nodeLeft'],l,'left');i['nodeRight']&&h(i['nodeRight'],l,'right');i['parameters']&&Array['isArray'](i['parameters'])&&i['parameters']['forEach']((q,r)=>{h(q,l,'param['+r+']');});if(i['historyIdx'])h(i['historyIdx'],l,'historyIdx');if(i['sessionIdx'])h(i['sessionIdx'],l,'sessionIdx');if(i['forwardIdx'])h(i['forwardIdx'],l,'forwardIdx');if(i['where'])h(i['where'],l,'where');if(i['find'])h(i['find'],l,'find');if(i['objectLeft'])h(i['objectLeft'],l,'objLeft');if(i['objectRight'])h(i['objectRight'],l,'objRight');if(i['recipient'])h(i['recipient'],l,'recipient');return l;}h(a),d['push'](...e['map'](i=>'\x20\x20'+i)),d['push'](...f);if(c){d['push'](''),d['push']('\x20\x20%%\x20Node\x20colors\x20(BehaviorTree.CPP-inspired\x20semantic\x20roles)');for(const {id:i,type:j}of g){const k=colorCategoryForNodeType(j),l=GUARD_NODE_COLORS[k];d['push']('\x20\x20style\x20'+i+'\x20fill:'+l['fill']+',stroke:'+l['stroke']+',color:#fff');}}return d['join']('\x0a');}export function renderGuardTreeIndented(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[];function i(k){const l=k['type'];if(l==='identifier'){const m=c?.['find'](o=>o['identifier']===k['identifier']),n=m?.['name']?'\x20\x22'+m['name']+'\x22':'';return'identifier['+(k['identifier']??'?')+']'+n;}if(l==='context')return'context('+(k['context']??'?')+')';if(l==='query'){const o=k['object']?.['convert_witness'],p=k['object']?.['identifier'],q=o!==undefined?',\x20witness='+o:'',r=p!==undefined?',\x20id['+p+']':'',s=k['parameters']&&k['parameters']['length']>0x0?',\x20params=['+k['parameters']['map'](u=>shortNodeLabel(u))['join'](',\x20')+']':'';return'query('+(typeof k['query']==='number'?'#'+k['query']:k['query'])+r+q+s+')';}return shortNodeLabel(k);}function j(k,l,m){const n='\x20\x20'['repeat'](l),o=l===0x0?'-\x20':'-\x20',p=m?m+':\x20':'',q=!k['nodes']&&!k['node']&&!k['nodeLeft']&&!k['nodeRight']&&!k['parameters']?.['length']&&!k['historyIdx']&&!k['sessionIdx']&&!k['forwardIdx']&&!k['where']&&!k['find']&&!k['objectLeft']&&!k['objectRight']&&!k['recipient'];q?h['push'](''+n+o+p+i(k)):h['push'](''+n+o+p+k['type']);k['nodes']&&Array['isArray'](k['nodes'])&&k['nodes']['forEach']((r,s)=>j(r,l+0x1,'child['+s+']'));k['node']&&j(k['node'],l+0x1,'child');k['nodeLeft']&&j(k['nodeLeft'],l+0x1,'left');k['nodeRight']&&j(k['nodeRight'],l+0x1,'right');k['parameters']&&Array['isArray'](k['parameters'])&&k['parameters']['forEach']((r,s)=>j(r,l+0x1,'param['+s+']'));if(k['historyIdx'])j(k['historyIdx'],l+0x1,'historyIdx');if(k['sessionIdx'])j(k['sessionIdx'],l+0x1,'sessionIdx');if(k['forwardIdx'])j(k['forwardIdx'],l+0x1,'forwardIdx');if(k['where'])j(k['where'],l+0x1,'where');if(k['find'])j(k['find'],l+0x1,'find');if(k['objectLeft'])j(k['objectLeft'],l+0x1,'objLeft');if(k['objectRight'])j(k['objectRight'],l+0x1,'objRight');if(k['recipient'])j(k['recipient'],l+0x1,'recipient');}h['push']('#\x20Guard\x20Tree\x20Definition'),h['push']('');d&&h['push']('**Guard:**\x20'+d);e&&h['push']('**Address:**\x20'+e);c&&h['push']('**Table\x20Entries:**\x20'+c['length']);f&&f['guards']['length']>0x0&&h['push']('**Rely:**\x20'+f['guards']['length']+'\x20guard(s)'+(f['logic_or']?'\x20(logic_or)':'\x20(logic_and)'));h['push'](''),h['push']('##\x20Root'),j(b,0x0);if(c&&c['length']>0x0){h['push'](''),h['push']('##\x20Table'),h['push'](''),h['push']('|\x20identifier\x20|\x20b_submission\x20|\x20value_type\x20|\x20value\x20|\x20name\x20|'),h['push']('|------------|-------------|------------|-------|------|');for(const k of c){const l=k['value']===undefined?'-':String(k['value']),m=l['replace'](/\|/g,'\x5c|')['replace'](/\n/g,'\x20'),n=k['name']??'-';h['push']('|\x20'+k['identifier']+'\x20|\x20'+k['b_submission']+'\x20|\x20'+k['value_type']+'\x20|\x20'+m+'\x20|\x20'+n+'\x20|');}h['push'](''),h['push']('##\x20Table\x20JSON'),h['push'](''),h['push']('```json'),h['push'](JSON['stringify'](c,null,0x2)),h['push']('```');}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('##\x20Rely'),h['push'](''),h['push']('Logic:\x20'+(f['logic_or']?'OR':'AND'));for(const o of f['guards']){h['push']('-\x20'+o);}}return h['push'](''),h['push']('##\x20JSON\x20Definition'),h['push'](''),h['push']('```json'),h['push'](JSON['stringify']({'root':b,'table':c,'guardName':d,'guardAddress':e,'rely':f},null,0x2)),h['push']('```'),h['join']('\x0a');}export function parseGuardTreeIndented(a){const b=[],c=a['matchAll'](/```json\s*\n([\s\S]*?)```/g);let d=null;for(const k of c){d=k[0x1];}if(d)try{const l=JSON['parse'](d['trim']());if(l&&typeof l==='object'){if('root'in l&&l['root']&&typeof l['root']==='object'&&'type'in l['root'])return{'success':!![],'data':l['root'],'errors':[]};if('type'in l)return{'success':!![],'data':l,'errors':[]};}}catch(m){b['push']('JSON\x20code\x20block\x20parse\x20error:\x20'+m['message']);}const f=a['split']('\x0a')['filter'](n=>n['trim']()['startsWith']('-\x20'));if(f['length']===0x0)return{'success':![],'errors':['No\x20outline\x20entries\x20found.\x20Use\x20\x27-\x20\x27\x20prefixed\x20lines\x20or\x20a\x20JSON\x20code\x20block.']};const g=[];let h=null;function i(n){const o=n['match'](/^(\s*)- /);return o?o[0x1]['length']/0x2:0x0;}function j(n){const o=n['replace'](/^\s*- /,'')['trim'](),p=o['match'](/^([^:]+):\s*(.*)$/),q=p?p[0x1]['trim']():undefined,r=p?p[0x2]['trim']():o,s=r['match'](/^identifier\[(\d+)\](?:\s+"(.+)")?$/);if(s)return{'label':q,'node':{'type':'identifier','identifier':parseInt(s[0x1],0xa)}};const t=r['match'](/^context\((\w+)\)$/);if(t)return{'label':q,'node':{'type':'context','context':t[0x1]}};const u=r['match'](/^query\((.+?)\)$/);if(u){const v=u[0x1],w=v['split'](',')['map'](A=>A['trim']()),x=w[0x0]['replace'](/^#/,''),y=/^\d+$/['test'](x),z={'type':'query','query':y?parseInt(x,0xa):x};for(const A of w['slice'](0x1)){const B=A['match'](/^id\[(\d+)\]$/);B&&(z['object']={'identifier':parseInt(B[0x1],0xa)});const C=A['match'](/^witness=(\d+)$/);C&&(z['object']={...z['object']||{},'convert_witness':parseInt(C[0x1],0xa)});}return{'label':q,'node':z};}return{'label':q,'node':{'type':r}};}for(const n of f){const o=i(n),{label:p,node:q}=j(n);if(o===0x0)h=q,g['length']=0x0,g['push']({'node':q,'depth':o});else{while(g['length']>0x0&&g[g['length']-0x1]['depth']>=o){g['pop']();}const r=g[g['length']-0x1];if(!r){b['push']('Orphaned\x20node\x20at\x20depth\x20'+o+':\x20'+n);continue;}if(p){const s=p['match'](/^child\[(\d+)\]$/),t=p['match'](/^param\[(\d+)\]$/);if(s){if(!r['node']['nodes'])r['node']['nodes']=[];r['node']['nodes']['push'](q);}else{if(t){if(!r['node']['parameters'])r['node']['parameters']=[];r['node']['parameters']['push'](q);}else{if(p==='child')r['node']['node']=q;else{if(p==='left')r['node']['nodeLeft']=q;else{if(p==='right')r['node']['nodeRight']=q;else{if(p==='historyIdx')r['node']['historyIdx']=q;else{if(p==='sessionIdx')r['node']['sessionIdx']=q;else{if(p==='forwardIdx')r['node']['forwardIdx']=q;else{if(p==='where')r['node']['where']=q;else{if(p==='find')r['node']['find']=q;else{if(p==='objLeft')r['node']['objectLeft']=q;else{if(p==='objRight')r['node']['objectRight']=q;else p==='recipient'&&(r['node']['recipient']=q);}}}}}}}}}}}}g['push']({'node':q,'depth':o});}}if(!h)return{'success':![],'errors':['No\x20root\x20node\x20found\x20in\x20outline.']};return{'success':!![],'data':h,'errors':b};}export function renderGuardAscii(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[];if(d)h['push']('Guard:\x20'+d);if(e)h['push']('Address:\x20'+e);if(d||e)h['push']('');function i(m){const n=m['type'],o=shortNodeLabel(m);if(n==='identifier'){const p=c?.['find'](u=>u['identifier']===m['identifier']),q=p?'\x20['+(typeof p['value_type']==='string'?p['value_type']:'type='+p['value_type'])+']':'',r=p&&p['value']!==undefined&&!p['b_submission']?',\x20value='+String(p['value']):'',s=p?.['b_submission']?'\x20(submission)':'';return''+o+q+r+s;}if(n==='context')return o+'\x20['+(m['context']??'?')+']';if(n==='query'){const u=m['object']?.['convert_witness'],v=u!==undefined?',\x20witness='+u:'';return''+o+v;}return o;}function j(m){const n=[];m['nodes']&&Array['isArray'](m['nodes'])&&m['nodes']['forEach']((o,p)=>n['push']({'node':o,'label':'child['+p+']'}));if(m['node'])n['push']({'node':m['node'],'label':'child'});if(m['nodeLeft'])n['push']({'node':m['nodeLeft'],'label':'left'});if(m['nodeRight'])n['push']({'node':m['nodeRight'],'label':'right'});m['parameters']&&Array['isArray'](m['parameters'])&&m['parameters']['forEach']((o,p)=>n['push']({'node':o,'label':'param['+p+']'}));if(m['historyIdx'])n['push']({'node':m['historyIdx'],'label':'historyIdx'});if(m['sessionIdx'])n['push']({'node':m['sessionIdx'],'label':'sessionIdx'});if(m['forwardIdx'])n['push']({'node':m['forwardIdx'],'label':'forwardIdx'});if(m['where'])n['push']({'node':m['where'],'label':'where'});if(m['find'])n['push']({'node':m['find'],'label':'find'});if(m['objectLeft'])n['push']({'node':m['objectLeft'],'label':'objLeft'});if(m['objectRight'])n['push']({'node':m['objectRight'],'label':'objRight'});if(m['recipient'])n['push']({'node':m['recipient'],'label':'recipient'});return n;}function k(m,n,o,p){const q=o?'└─\x20':'├─\x20',r=p?p+':\x20':'';h['push'](''+n+q+r+i(m));const s=j(m),t=n+(o?'\x20\x20\x20':'│\x20\x20');s['forEach']((u,v)=>{k(u['node'],t,v===s['length']-0x1,u['label']);});}h['push'](i(b));const l=j(b);l['forEach']((m,n)=>{k(m['node'],'',n===l['length']-0x1,m['label']);});if(c&&c['length']>0x0){h['push'](''),h['push']('Table:');for(const m of c){const n=typeof m['value_type']==='string'?m['value_type']:'type='+m['value_type'],o=m['value']!==undefined&&!m['b_submission']?',\x20value='+String(m['value']):'',p=m['b_submission']?'\x20(submission)':'',q=m['name']?'\x20\x22'+m['name']+'\x22':'';h['push']('\x20\x20id['+m['identifier']+']'+q+':\x20'+n+o+p);}}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('Rely\x20('+(f['logic_or']?'OR':'AND')+'):');for(const r of f['guards']){h['push']('\x20\x20-\x20'+r);}}return h['join']('\x0a');}export function renderGuardMarkmap(a){const {root:b,table:c,guardName:d,guardAddress:e,rely:f}=a,h=[],i=d?'Guard:\x20'+d:'Guard';h['push']('#\x20'+i);if(e)h['push']('');if(e)h['push']('**Address:**\x20'+e);h['push']('');function j(m,n){return'#'['repeat'](Math['min'](m+0x1,0x6))+'\x20'+n;}function k(m){const n=m['type'],o=shortNodeLabel(m);if(n==='identifier'){const p=c?.['find'](u=>u['identifier']===m['identifier']),q=p?'\x20['+(typeof p['value_type']==='string'?p['value_type']:'type='+p['value_type'])+']':'',r=p&&p['value']!==undefined&&!p['b_submission']?',\x20value='+String(p['value']):'',s=p?.['b_submission']?'\x20(submission)':'';return''+o+q+r+s;}if(n==='context')return o+'\x20['+(m['context']??'?')+']';if(n==='query'){const u=m['object']?.['convert_witness'],v=u!==undefined?',\x20witness='+u:'';return''+o+v;}return o;}function l(m,n,o){const p=o?o+':\x20':'';h['push'](j(n,''+p+k(m)));m['nodes']&&Array['isArray'](m['nodes'])&&m['nodes']['forEach']((q,r)=>l(q,n+0x1,'child['+r+']'));if(m['node'])l(m['node'],n+0x1,'child');if(m['nodeLeft'])l(m['nodeLeft'],n+0x1,'left');if(m['nodeRight'])l(m['nodeRight'],n+0x1,'right');m['parameters']&&Array['isArray'](m['parameters'])&&m['parameters']['forEach']((q,r)=>l(q,n+0x1,'param['+r+']'));if(m['historyIdx'])l(m['historyIdx'],n+0x1,'historyIdx');if(m['sessionIdx'])l(m['sessionIdx'],n+0x1,'sessionIdx');if(m['forwardIdx'])l(m['forwardIdx'],n+0x1,'forwardIdx');if(m['where'])l(m['where'],n+0x1,'where');if(m['find'])l(m['find'],n+0x1,'find');if(m['objectLeft'])l(m['objectLeft'],n+0x1,'objLeft');if(m['objectRight'])l(m['objectRight'],n+0x1,'objRight');if(m['recipient'])l(m['recipient'],n+0x1,'recipient');}h['push'](j(0x1,'Root')),l(b,0x2);if(c&&c['length']>0x0){h['push'](''),h['push']('##\x20Table');for(const m of c){const n=typeof m['value_type']==='string'?m['value_type']:'type='+m['value_type'],o=m['value']!==undefined&&!m['b_submission']?',\x20value='+String(m['value']):'',p=m['b_submission']?'\x20(submission)':'',q=m['name']?'\x20\x22'+m['name']+'\x22':'';h['push']('-\x20id['+m['identifier']+']'+q+':\x20'+n+o+p);}}if(f&&f['guards']['length']>0x0){h['push'](''),h['push']('##\x20Rely\x20('+(f['logic_or']?'OR':'AND')+')');for(const r of f['guards']){h['push']('-\x20'+r);}}return h['join']('\x0a');}export function parseGuardTableJSON(a){const b=a['match'](/##\s*Table JSON[^\n]*\n\s*```json\s*\n([\s\S]*?)```/i);if(!b)return null;try{const c=JSON['parse'](b[0x1]['trim']());if(!Array['isArray'](c))return null;return c['filter'](d=>{return d&&typeof d==='object'&&typeof d['identifier']==='number'&&typeof d['b_submission']==='boolean';})['map'](d=>({'identifier':d['identifier'],'name':d['name'],'value_type':d['value_type'],'b_submission':d['b_submission'],'value':d['value']}));}catch{return null;}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GUARDQUERY}from'@wowok/wowok';import{isUnboundSignerTheft}from'./recipient-constraint.js';import{factoryRulePack,getJudgmentDoc}from'../config/judgment.js';import{evaluateRuleBook}from'../config/rule-engine.js';function rootRaw(a){try{return JSON['stringify'](a)??'';}catch{return'';}}function hasSignerCheck(a){return a['includes']('\x22Signer\x22');}function hasClockCheck(a){return a['includes']('\x22Clock\x22');}function hasGuardSelfRef(a){return a['includes']('\x22Guard\x22');}function hasWitness(a){return a['includes']('\x22convert_witness\x22');}function extractWitnessCodes(a){const b=[],c=rootRaw(a),d=c['matchAll'](/"convert_witness"\s*:\s*(\d+)/g);for(const e of d){const f=parseInt(e[0x1],0xa);if(f>=0x64&&f<=0x6c)b['push'](f);}return b;}const WITNESS_CHAIN={0x64:['Order','Progress'],0x65:['Order','Machine'],0x66:['Order','Service'],0x67:['Progress','Machine'],0x68:['Arb','Order'],0x69:['Arb','Arbitration'],0x6a:['Arb','Order','Progress'],0x6b:['Arb','Order','Service'],0x6c:['Arb','Order','Machine']};function extractWitnessIdentifierPairs(a){const b=[],c=new WeakSet();function d(e){if(e===null||typeof e!=='object')return;if(c['has'](e))return;c['add'](e);typeof e['convert_witness']==='number'&&typeof e['identifier']==='number'&&b['push']({'code':e['convert_witness'],'identifier':e['identifier']});for(const f of Object['keys'](e)){const g=e[f];if(Array['isArray'](g)){for(const h of g)d(h);}else g!==null&&typeof g==='object'&&d(g);}}return d(a),b;}function getChildNodes(a){if(!a||typeof a!=='object')return[];const b=[];if(Array['isArray'](a['nodes']))b['push'](...a['nodes']);if(a['left'])b['push'](a['left']);if(a['right'])b['push'](a['right']);if(a['vec'])b['push'](a['vec']);if(a['target'])b['push'](a['target']);if(a['object']&&typeof a['object']==='object')b['push'](a['object']);if(Array['isArray'](a['parameters']))b['push'](...a['parameters']);return b['filter'](d=>d&&typeof d==='object');}function findSignerLogicEqualNodes(a){const b=[];function c(d,e){if(!d||typeof d!=='object')return;if(d['type']==='logic_equal'){const f=Array['isArray'](d['nodes'])?d['nodes']:d['left']&&d['right']?[d['left'],d['right']]:[];if(f['length']===0x2){const g=f['findIndex'](h=>h?.['type']==='context'&&h?.['context']==='Signer');g>=0x0&&b['push']({'node':d,'parentType':e,'otherOperand':f[0x1-g]});}}for(const h of getChildNodes(d)){c(h,d['type']);}}return c(a,null),b;}function detectLevel1StrictBinding(a,b){const c=findSignerLogicEqualNodes(a);for(const d of c){const e=d['otherOperand'];if(e?.['type']==='identifier'){const f=b['find'](g=>g['identifier']===e['identifier']);if(f&&!f['b_submission']&&f['value_type']==='Address'&&typeof f['value']==='string'&&f['value']['length']>0x0)return{'detected':!![],'entry':{'identifier':f['identifier'],'value':f['value'],'name':f['name']}};}}return{'detected':![]};}function isSignerCheckInLogicOr(a){const b=findSignerLogicEqualNodes(a);return b['some'](c=>c['parentType']==='logic_or');}const QUERY_INVARIANT_MAP=((()=>{const a=new Map();for(const b of GUARDQUERY){b['invariant']!==undefined&&a['set'](b['id'],b['invariant']);}return a;})());function extractQueryIds(a){const b=[],c=rootRaw(a),d=c['matchAll'](/"query"\s*:\s*(\d+)/g);for(const f of d){const g=parseInt(f[0x1],0xa);if(!b['includes'](g))b['push'](g);}const e=c['matchAll'](/"query"\s*:\s*"([^"]+)"/g);for(const h of e){const i=h[0x1],j=GUARDQUERY['find'](k=>k['name']===i);if(j&&!b['includes'](j['id']))b['push'](j['id']);}return b;}function rootAllQueriesNonZero(a){const b=extractQueryIds(a);if(b['length']===0x0)return![];return b['every'](c=>QUERY_INVARIANT_MAP['has'](c));}const REENTRANCY_SPECS=[{'sceneId':'reward_claim','level':'critical','existsPrimitives':[0x64d],'countPrimitives':[0x64c],'addressPrimitives':[0x65a],'rationale':'Guard\x20pass\x20distributes\x20reward\x20funds\x20to\x20the\x20Claimant\x20AND\x20creates\x20a\x20reward_record,\x20but\x20the\x20Guard\x20conditions\x20(identity,\x20time,\x20node\x20state)\x20do\x20NOT\x20naturally\x20invalidate\x20after\x20a\x20claim.\x20'+'Without\x20an\x20explicit\x20anti-reentrancy\x20primitive,\x20the\x20same\x20Claimant\x20can\x20repeatedly\x20pass\x20the\x20Guard\x20and\x20DRAIN\x20THE\x20ENTIRE\x20POOL.\x20'+'This\x20is\x20the\x20most\x20severe\x20reentrancy\x20scene\x20—\x20direct\x20fund\x20loss.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and\x20with\x20existing\x20conditions):\x0a'+'\x20\x20-\x20logic_not(query(\x27reward.record\x20has\x27,\x20object=reward,\x20parameters=[claimant_address]))\x20—\x20RECOMMENDED\x20(per-user\x20Bool\x20check)\x0a'+'\x20\x20-\x20logic_equal([query(\x27reward.record\x20count\x27,\x20object=reward),\x20identifier(N)])\x20where\x20table[N].value=0\x20—\x20total-claim\x20count\x20is\x200\x0a'+'\x20\x20-\x20logic_not(query(\x27reward.record.find_first\x27,\x20object=reward,\x20where={...}))\x20—\x20no\x20matching\x20record\x20found\x0a'+'Reference\x20template:\x20MyShop_Advanced\x20Guard\x207\x20condition\x204\x20(logic_not(query_reward_record_exists(where.storeFromId=order_id)))'},{'sceneId':'arbitration_voting_guard','level':'critical','existsPrimitives':[0x57c,0x57e],'countPrimitives':[0x57d],'addressPrimitives':[],'rationale':'Guard\x20pass\x20counts\x20the\x20vote\x20with\x20the\x20extracted\x20weight.\x20Without\x20anti-reentrancy,\x20the\x20same\x20voter\x20can\x20vote\x20MULTIPLE\x20times,\x20'+'multiplying\x20their\x20weight\x20and\x20skewing\x20the\x20arbitration\x20result\x20—\x20which\x20directly\x20determines\x20fund\x20ownership\x20via\x20compensation.\x20'+'The\x20voter\x27s\x20eligibility\x20(identity,\x20reputation)\x20does\x20NOT\x20naturally\x20invalidate\x20after\x20voting.\x20'+'Note:\x20arb.voted_count\x20(1403)\x20is\x20total\x20voter\x20count\x20(NOT\x20per-voter)\x20and\x20does\x20NOT\x20serve\x20as\x20an\x20anti-reentrancy\x20primitive\x20for\x20an\x20individual\x20voter.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and):\x0a'+'\x20\x20-\x20logic_not(query(\x27arb.voted\x20has\x27,\x20object=arb,\x20parameters=[voter_address]))\x20—\x20RECOMMENDED\x20(per-voter\x20Bool)\x0a'+'\x20\x20-\x20logic_not(query(\x27arb.voted.agree\x20has\x27,\x20object=arb,\x20parameters=[voter_address,\x20proposition_index]))\x20—\x20per-voter-per-proposition\x0a'+'\x20\x20-\x20logic_equal([query(\x27arb.voted.agree\x20count\x27,\x20object=arb,\x20parameters=[voter_address]),\x20identifier(N)])\x20where\x20table[N].value=0'},{'sceneId':'arbitration_usage_guard','level':'high','existsPrimitives':[0x61d],'countPrimitives':[0x61c],'addressPrimitives':[],'rationale':'Guard\x20pass\x20creates\x20a\x20new\x20Arb\x20case.\x20Without\x20anti-reentrancy,\x20a\x20customer\x20can\x20create\x20multiple\x20Arb\x20cases\x20for\x20the\x20SAME\x20Order\x20'+'(up\x20to\x20MAX_DISPUTE_COUNT=10),\x20harassing\x20the\x20counterparty\x20and\x20inflating\x20arbitration\x20system\x20load.\x20'+'Not\x20direct\x20fund\x20loss,\x20but\x20severe\x20system\x20abuse.\x20Filing\x20a\x20dispute\x20deduplicates\x20by\x20Arb\x20address\x20but\x20does\x20NOT\x20prevent\x20multiple\x20distinct\x20Arbs.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and):\x0a'+'\x20\x20-\x20logic_not(query(\x27order.dispute\x20has\x27,\x20object=order,\x20parameters=[existing_arb_address]))\x20—\x20per-Arb\x20check\x0a'+'\x20\x20-\x20logic_equal([query(\x27order.dispute\x20count\x27,\x20object=order),\x20identifier(N)])\x20where\x20table[N].value=0\x20—\x20STRICT:\x20block\x20any\x20prior\x20dispute\x0a'+'\x20\x20-\x20logic_as_u256_less_or_equal([query(\x27order.dispute\x20count\x27,\x20object=order),\x20identifier(N)])\x20where\x20table[N].value=K\x20—\x20LENIENT:\x20allow\x20up\x20to\x20K\x20disputes'},{'sceneId':'service_order_allocators_guard','level':'low','existsPrimitives':[0x620],'countPrimitives':[],'addressPrimitives':[0x621],'rationale':'Protocol-level\x20protection:\x20attaching\x20an\x20Allocation\x20to\x20an\x20Order\x20asserts\x20ONE\x20Allocation\x20per\x20Order\x20(E_ALLOCATION_ALREADY_SPECIFIED).\x20'+'After\x20alloc()\x20executes,\x20typical\x20Rate-mode\x20allocators\x20(sum=10000)\x20and\x20Surplus-mode\x20allocators\x20drain\x20balance\x20to\x200,\x20making\x20reentrancy\x20unprofitable.\x20'+'EDGE\x20CASE:\x20Amount-mode-only\x20allocators\x20(no\x20Surplus,\x20total\x20<\x20full\x20balance)\x20leave\x20remainder;\x20a\x20second\x20alloc()\x20could\x20extract\x20more\x20—\x20mitigated\x20by\x20preferring\x20Rate/Surplus\x20modes.\x20'+'External\x20deposit\x20via\x20receive()\x20is\x20possible\x20but\x20irrational\x20(attacker\x20funds\x20the\x20Allocation\x20they\x20attack).','mitigation':'Default:\x20no\x20action\x20needed\x20(protocol-level\x20guard).\x20IF\x20using\x20Amount-mode-only\x20allocators\x20without\x20Surplus:\x20'+'consider\x20adding\x20logic_not(query(\x27order.allocation\x20some\x27,\x20object=order))\x20OR\x20switch\x20to\x20Rate/Surplus\x20mode\x20to\x20drain\x20balance\x20completely.'},{'sceneId':'service_buy_guard','level':'low','existsPrimitives':[],'countPrimitives':[],'addressPrimitives':[],'rationale':'Each\x20purchase\x20creates\x20a\x20fresh\x20Order;\x20no\x20existing\x20Order\x20state\x20is\x20modified.\x20Default:\x20no\x20reentrancy\x20risk.\x20'+'IF\x20business\x20intent\x20is\x20\x27limit\x20one\x20purchase\x20per\x20user\x27\x20(limited-edition\x20goods,\x20whitelist\x20single-buy),\x20an\x20anti-reentrancy\x20check\x20is\x20REQUIRED\x20'+'but\x20no\x20direct\x20GUARDQUERY\x20primitive\x20exists\x20for\x20per-user\x20purchase\x20history.','mitigation':'IF\x20limit-purchase\x20intent:\x20record\x20purchases\x20in\x20a\x20Repository\x20and\x20add\x20logic_not(query(\x27repository.data\x20has\x27,\x20...))\x20to\x20root;\x20'+'OR\x20revoke\x20EntityRegistrar\x20membership\x20after\x20first\x20buy;\x20OR\x20use\x20an\x20off-chain\x20allowlist\x20with\x20on-chain\x20Merkle\x20proof.'},{'sceneId':'repository_write_guard','level':'low','existsPrimitives':[0x48e],'countPrimitives':[],'addressPrimitives':[],'rationale':'Default\x20writes\x20are\x20idempotent\x20(same\x20ID\x20overwrites,\x20different\x20ID\x20appends);\x20no\x20fund\x20flow.\x20'+'IF\x20business\x20intent\x20is\x20\x27one\x20write\x20per\x20ID\x27\x20(voting,\x20immutable\x20credential,\x20single-attestation),\x20an\x20anti-reentrancy\x20check\x20is\x20needed.','mitigation':'IF\x20one-write-per-ID\x20intent:\x20add\x20logic_not(query(\x27repository.data\x20has\x27,\x20object=repository,\x20parameters=[policy_name,\x20user_or_object_id]))\x20to\x20root.'},{'sceneId':'gen_passport_guard','level':'low','existsPrimitives':[],'countPrimitives':[],'addressPrimitives':[],'rationale':'Each\x20gen_passport\x20call\x20generates\x20an\x20independent\x20Passport\x20(one\x20Passport\x20per\x20operation).\x20'+'Multiple\x20Passports\x20for\x20the\x20same\x20user\x20are\x20usually\x20valid\x20(each\x20serves\x20a\x20different\x20subsequent\x20operation).\x20'+'IF\x20business\x20intent\x20is\x20\x27one\x20active\x20Passport\x20per\x20user\x27,\x20an\x20anti-reentrancy\x20check\x20is\x20needed\x20but\x20no\x20direct\x20GUARDQUERY\x20primitive\x20exists.','mitigation':'IF\x20one-passport-per-user\x20intent:\x20use\x20off-chain\x20tracking\x20or\x20a\x20Repository\x20to\x20record\x20issued\x20Passport\x20IDs.'}],QUERY_TYPE_ALIASES=new Map([['query_reward_record_exists',0x64d],['query_reward_record_count',0x64c],['query_reward_record_find',0x65a],['query_progress_history_find',0x4fa],['query_progress_history_session_find',0x4fb],['query_progress_history_session_forward_find',0x4fc],['query_progress_history_session_count',0x4f9],['query_progress_history_session_forward_count',0x4ee],['query_repository_data_count_where',0x495],['query_repository_data_sum_where',0x496],['query_repository_policies_keys',0x497],['query_repository_data_find_where',0x498],['query_repository_data_keys_where',0x499]]);function detectReentrancyProtection(a,b,c){const d=new Set([...c['existsPrimitives'],...c['countPrimitives'],...c['addressPrimitives']]);if(d['size']===0x0)return{'state':'absent','evidence':'No\x20anti-reentrancy\x20primitive\x20available\x20in\x20GUARDQUERY\x20for\x20this\x20scene'};const e=new Map(),f=new Map();for(const p of d){const q=GUARDQUERY['find'](r=>r['id']===p);q&&(e['set'](p,q['name']),f['set'](q['name'],p));}const g=Array['from'](f['keys']());function h(r){if(!r||typeof r!=='object')return-0x1;if(typeof r['query']==='number'&&d['has'](r['query']))return r['query'];if(typeof r['query']==='string'&&f['has'](r['query']))return f['get'](r['query']);if(typeof r['type']==='string'&&QUERY_TYPE_ALIASES['has'](r['type'])){const s=QUERY_TYPE_ALIASES['get'](r['type']);if(d['has'](s))return s;}if(typeof r['type']==='string'&&f['has'](r['type']))return f['get'](r['type']);return-0x1;}function i(r){if(!r||typeof r!=='object')return![];if(typeof r['type']==='string'&&['number','u8','u16','u32','u64','u128','u256']['includes'](r['type']))return r['value']===0x0||r['value']==='0'||r['value']===0x0n;if(r['type']==='identifier'&&typeof r['identifier']==='number'){const s=b['find'](t=>t['identifier']===r['identifier']);if(s&&!s['b_submission'])return s['value']===0x0||s['value']==='0'||s['value']===0x0n;}return![];}function j(r,s){if(!r||typeof r!=='object')return[];const t=[];if(Array['isArray'](r['nodes']))for(const u of r['nodes']){if(u!==s)t['push'](u);}if(r['left']&&r['left']!==s)t['push'](r['left']);if(r['right']&&r['right']!==s)t['push'](r['right']);return t['filter'](v=>v&&typeof v==='object');}let k=![],l=![],m='',n='';function o(r,s){if(!r||typeof r!=='object')return;const t=h(r);if(t>=0x0){k=!![];const v=e['get'](t)??'query_'+t;n=v;const w=s?.['type']??null;let x=![];const y=c['existsPrimitives']['includes'](t),z=c['addressPrimitives']['includes'](t),A=c['countPrimitives']['includes'](t);(y||z)&&w==='logic_not'&&(x=!![]);if(A&&w==='logic_equal'){const B=j(s,r);B['some'](C=>i(C))&&(x=!![]);}if(x)l=!![];else{if(!m){const C=A?'logic_equal\x20with\x20a\x20zero\x20operand':'logic_not';m='Primitive\x20\x22'+v+'\x22\x20found\x20but\x20its\x20immediate\x20parent\x20is\x20'+(w??'root')+'\x20(expected\x20'+C+').\x20The\x20primitive\x20is\x20present\x20but\x20does\x20NOT\x20actually\x20prevent\x20reentrancy\x20—\x20this\x20is\x20a\x20false\x20sense\x20of\x20security.';}}}const u=[];if(Array['isArray'](r['nodes']))u['push'](...r['nodes']);if(r['left'])u['push'](r['left']);if(r['right'])u['push'](r['right']);if(r['node'])u['push'](r['node']);if(r['vec'])u['push'](r['vec']);if(r['target'])u['push'](r['target']);if(r['object']&&typeof r['object']==='object')u['push'](r['object']);if(Array['isArray'](r['parameters']))u['push'](...r['parameters']);for(const D of u){D&&typeof D==='object'&&o(D,r);}}o(a,null);if(l)return{'state':'protected','evidence':'Anti-reentrancy\x20primitive\x20\x22'+n+'\x22\x20is\x20properly\x20wrapped','foundPrimitiveName':n};if(k)return{'state':'pseudo','evidence':m,'foundPrimitiveName':n};return{'state':'absent','evidence':'No\x20anti-reentrancy\x20primitive\x20found\x20in\x20root.\x20Expected\x20one\x20of:\x20'+g['join'](',\x20')};}export function guardRiskFacts(a){const b={},c=rootRaw(a?.['root']),d=c['toLowerCase'](),f=Array['isArray'](a?.['table'])?a['table']:[],g=a?.['scene'],h=a?.['rely'];b['has_signer_check']=hasSignerCheck(c),b['has_clock_check']=hasClockCheck(c),b['has_guard_self_ref']=hasGuardSelfRef(c),b['has_witness']=hasWitness(c),b['queries_repository']=d['includes']('repository'),b['queries_progress']=d['includes']('progress'),b['root_has_query']=d['includes']('\x22query\x22'),b['root_has_clock_token']=d['includes']('clock'),b['root_has_calc_number_add']=d['includes']('calc_number_add'),b['root_has_logic_string_contains']=d['includes']('logic_string_contains'),b['root_has_logic_string_nocase']=d['includes']('logic_string_nocase'),b['root_has_logic_as_u256_greater_or_equal']=d['includes']('logic_as_u256_greater_or_equal'),b['root_has_logic_as_u256_greater']=d['includes']('logic_as_u256_greater'),b['root_has_logic_equal']=c['includes']('\x22logic_equal\x22'),b['root_has_logic_not_equal']=c['includes']('\x22logic_not_equal\x22'),b['logic_and_count']=(d['match'](/"logic_and"/g)||[])['length'],b['root_is_identifier']=a?.['root']?.['type']==='identifier';const i=b['root_is_identifier']?f['find'](z=>z['identifier']===a['root']['identifier']):undefined;b['root_identifier_is_submission']=i?.['b_submission']??![];const j=extractQueryIds(a?.['root']);b['root_query_ids_csv']=j['join'](',\x20'),b['root_has_progress_current_query']=j['includes'](0x4e5);const k=f['some'](z=>z['b_submission']);b['has_submission']=k;const l=f['filter'](z=>!z['b_submission']&&z['value_type']==='Address'&&z['value']);l['length']>0x0&&(b['const_addr_count']=l['length'],b['const_addr_list']=l['map'](z=>'#'+z['identifier']+'='+z['value'])['join'](',\x20'));const m=f['filter'](z=>!z['b_submission']&&z['value_type']==='Address'&&typeof z['value']==='string'&&(z['value']['toLowerCase']()==='0xaab'||z['value']['toLowerCase']()==='0xaaa'));if(m['length']>0x0){b['sys_addr_list']=m['map'](A=>'#'+A['identifier']+'='+A['value']+'('+A['name']+')')['join'](',\x20');const z=m['find'](A=>A['value']==='0xaab'&&A['name']&&!A['name']['toLowerCase']()['includes']('registrar')||A['value']==='0xaaa'&&A['name']&&!A['name']['toLowerCase']()['includes']('linker'));b['sys_addr_wrong']=z!==undefined;}const n=extractWitnessCodes(a?.['root']),o=n['filter'](A=>[0x6a,0x6b,0x6c]['includes'](A));if(o['length']>0x0){const A={0x6a:'Arb→Progress\x20(two\x20hops:\x20arb.order\x20→\x20order.progress)',0x6b:'Arb→Machine\x20(two\x20hops:\x20arb.order\x20→\x20order.machine)',0x6c:'Arb→Service\x20(two\x20hops:\x20arb.order\x20→\x20order.service)'};b['witness_multihop_codes']=o,b['witness_multihop_csv']=o['join'](',\x20'),b['witness_multihop_names_block']=o['map'](B=>'\x20\x20-\x20'+B+':\x20'+A[B])['join']('\x0a');}const p=extractWitnessIdentifierPairs(a?.['root']),q=p['filter'](B=>B['code']>=0x64&&B['code']<=0x6c);if(q['length']>0x0){const B=[],C=[];for(const {code:E,identifier:F}of q){const G=WITNESS_CHAIN[E];if(!G)continue;const H=G[0x0],I=f['find'](K=>K['identifier']===F);if(!I)continue;const J=E+'\x20('+G['join']('→')+')';I['object_type']?I['object_type']!==H&&B['push']('witness\x20'+J+'\x20references\x20#'+F+'\x20'+('but\x20object_type='+I['object_type']+'\x20(expected\x20'+H+')')):C['push']('witness\x20'+J+'\x20references\x20#'+F+'\x20'+('but\x20object_type\x20is\x20not\x20set\x20(expected\x20'+H+')'));if(G['length']===0x3){const K=G[0x1],L=f['some'](M=>M['object_type']===K);!L&&C['push']('witness\x20'+J+'\x20multi-hop\x20chain\x20expects\x20intermediate\x20'+(K+'\x20in\x20table,\x20but\x20no\x20entry\x20with\x20object_type='+K+'\x20found'));}}const D=[...B,...C];D['length']>0x0&&(b['rc2_02_issue_count']=D['length'],b['rc2_02_has_hard_mismatch']=B['length']>0x0,b['rc2_02_evidence_lines']=D['map'](M=>'\x20\x20-\x20'+M)['join']('\x0a'),b['rc2_02_evidence_csv']=D['join'](';\x20'));}if(b['has_witness']){const M=d['includes']('repository')&&d['includes']('\x22query\x22'),N=d['includes']('progress_history')&&d['includes']('\x22query\x22');if(M||N){const O=d['includes']('convert_number_address')||d['includes']('convert_address_number')||d['includes']('convert_u256')||d['includes']('convert_string');b['rc2_04_queries_repo']=M,b['rc2_04_queries_progress_history']=N,b['rc2_04_has_conversion']=O,b['rc2_04_conversion_note']=O?'\x0aThe\x20current\x20Guard\x20already\x20uses\x20type\x20conversion\x20nodes,\x20but\x20ensure\x20the\x20conversion\x20direction\x20is\x20correct.':'\x0aWarning:\x20no\x20type\x20conversion\x20node\x20detected\x20in\x20the\x20current\x20Guard;\x20parameter\x20type\x20mismatch\x20risk\x20may\x20exist.',b['rc2_04_conversion_evidence']=O?'Type\x20conversion\x20node\x20in\x20use':'No\x20type\x20conversion\x20node\x20detected';}}b['scene_present']=g!==undefined;g&&(b['scene_id']=g['id'],b['scene_host_object']=g['host_object'],b['scene_binding_field']=g['binding_field'],b['scene_mutable_after_publish']=g['mutable_after_publish']);b['rc3_01_sharing_exempt']=g?.['id']==='service_order_allocators_guard'&&Array['isArray'](a?.['sharing_recipients'])&&a['sharing_recipients']['length']>0x0&&!a['sharing_recipients']['includes']('Signer');if(g?.['binding_field']==='voting_guard'){const P=f['filter'](Q=>Q['b_submission']&&['U8','U16','U32','U64','U128','U256']['includes'](Q['value_type']));P['length']>0x0&&(b['rc3_02_numeric_count']=P['length'],b['rc3_02_numeric_list']=P['map'](Q=>'#'+Q['identifier']+'('+Q['value_type']+')')['join'](',\x20'));}const r=f['filter'](Q=>Q['b_submission']&&Q['value_type']==='Address');if(r['length']>0x0){b['rc3_03_submitted_addr_count']=r['length'];const Q=r['filter'](R=>!R['object_type']);b['rc3_03_no_type_count']=Q['length'],b['rc3_03_evidence']=Q['length']>0x0?'Missing\x20object_type:\x20'+Q['map'](R=>'#'+R['identifier'])['join'](',\x20'):'Annotated:\x20'+r['map'](R=>'#'+R['identifier']+'='+R['object_type'])['join'](',\x20');}if(r['length']>0x0){const R=n['some'](Y=>[0x64,0x65,0x66]['includes'](Y)),S=n['some'](Y=>[0x67]['includes'](Y)),T=n['some'](Y=>[0x68,0x69,0x6a,0x6b,0x6c]['includes'](Y)),U=r['filter'](Y=>Y['object_type']==='Order'||R&&!Y['object_type']),V=r['filter'](Y=>Y['object_type']==='Progress'||S&&!Y['object_type']),W=r['filter'](Y=>Y['object_type']==='Arb'||T&&!Y['object_type']),X=U['length']>0x0||V['length']>0x0||W['length']>0x0;if(X){const Y=['machine_forward_guard','service_order_allocators_guard','arbitration_usage_guard','arbitration_voting_guard','reward_claim','progress_submission_guard'],Z=g?.['id'],a0=!Z||Y['includes'](Z);if(a0){const a1=new Set([0x61b,0x618,0x4e2,0x57a,0x579]),a2=j['some'](a3=>a1['has'](a3));if(!a2){const a3=[];for(const a4 of U){a3['push']('#'+a4['identifier']+(a4['object_type']?'(Order)':'(inferred\x20Order\x20via\x20witness\x20100-102)'));}for(const a5 of V){a3['push']('#'+a5['identifier']+(a5['object_type']?'(Progress)':'(inferred\x20Progress\x20via\x20witness\x20103)'));}for(const a6 of W){a3['push']('#'+a6['identifier']+(a6['object_type']?'(Arb)':'(inferred\x20Arb\x20via\x20witness\x20104-108)'));}b['rc3_05_applies']=!![],b['rc3_05_critical']=Z!==undefined&&(Z==='machine_forward_guard'||Z==='service_order_allocators_guard'),b['rc3_05_unbound_csv']=a3['join'](',\x20'),b['rc3_05_scene_label']=Z??'unknown\x20scene\x20(conservative\x20flag)';}}}}if(g?.['id']==='service_order_allocators_guard'&&!b['has_signer_check']){const a7=a?.['sharing_recipients'],a8=a7!==undefined&&a7['length']>0x0,a9=a8&&a7['includes']('Signer');if(!(a8&&!a9)){const aa=isUnboundSignerTheft({'recipient_is_signer':a9,'caller_identity_constrained':![]});b['rc3_06_applies']=!![],b['rc3_06_signer_sharing']=aa,b['rc3_06_recipients_label']=a8?'['+a7['join'](',\x20')+']':'(not\x20provided\x20—\x20conservative\x20flag)',b['rc3_06_title_suffix']=a9?'sharing.who=Signer\x20confirmed\x20—\x20anyone\x20can\x20steal\x20100%\x20of\x20funds':'if\x20sharing.who=Signer,\x20anyone\x20can\x20steal\x20100%\x20of\x20funds',b['rc3_06_level_rationale']=aa?'Signer\x20sharing\x20confirmed\x20→\x20critical':'sharing\x20hint\x20absent\x20→\x20conservative\x20medium';}}if(b['has_signer_check']){const ab=c['includes']('\x22logic_equal\x22'),ac=c['includes']('\x22logic_not_equal\x22');b['rc4_01_comparison_detail']=(ab?'logic_equal(==)':'')+'\x20'+(ac?'logic_not_equal(!=)':''),b['rc4_01_comparison_ops']=(ab?'==':'')+'\x20'+(ac?'!=':'');}if(b['has_clock_check']){const ad=d['includes']('logic_as_u256_greater_or_equal'),ae=d['includes']('logic_as_u256_greater');(ad||ae)&&(b['rc4_02_has_greater_or_equal']=ad,b['rc4_02_has_greater']=ae,b['rc4_02_comparison_ops']=(ad?'>=':'')+'\x20'+(ae?'>':''));}if(b['has_signer_check']&&!isSignerCheckInLogicOr(a?.['root'])){const af=detectLevel1StrictBinding(a?.['root'],f);if(af['detected']&&af['entry']){const ag=af['entry'];b['rc4_04_detected']=!![],b['rc4_04_entry_identifier']=ag['identifier'],b['rc4_04_entry_value']=ag['value'],b['rc4_04_entry_detail']='b_submission=false,\x20value=\x22'+ag['value']+'\x22'+(ag['name']?',\x20name=\x22'+ag['name']+'\x22':'');}}const s=rootAllQueriesNonZero(a?.['root']),t=()=>{const ah=j['filter'](ai=>!QUERY_INVARIANT_MAP['has'](ai));if(ah['length']===0x0)return'';return'Queries\x20without\x20non-zero\x20invariant:\x20'+ah['map'](ai=>{const aj=GUARDQUERY['find'](ak=>ak['id']===ai);return aj?aj['id']+'\x20('+aj['name']+')':''+ai;})['join'](',\x20');};b['root_has_logic_as_u256_greater_or_equal']&&d['includes']('\x22clock\x22')&&b['root_has_calc_number_add']&&b['root_has_query']&&!s&&(b['rx1_01_trigger']=!![],b['rx1_01_evidence']=t()||'Baseline\x20query\x20may\x20return\x200');b['root_has_logic_as_u256_greater']&&b['root_has_query']&&!s&&(b['rx1_02_trigger']=!![],b['rx1_02_evidence']=t()||'Query\x20may\x20return\x200');const u=Array['isArray'](h?.['guards'])?h['guards']:[];b['rely_guards_count']=u['length'],b['rely_is_or']=h?.['logic_or']===!![],b['rely_logic']=h?.['logic_or']?'OR':'AND';const v=d['includes']('repository')&&d['includes']('\x22query\x22'),w=f['some'](ah=>ah['b_submission']&&ah['value_type']==='Address'&&ah['object_type']==='Repository'),x=v&&w;b['rx1_11_self_rep_false']=x,b['rx1_11_warning_tail']=x?'\x0aWarning:\x20the\x20current\x20Guard\x20itself\x20queries\x20repository.data\x20and\x20the\x20Repository\x20address\x20comes\x20from\x20submission,\x20'+'so\x20its\x20own\x20rep=false\x20and\x20cannot\x20be\x20depended\x20on\x20by\x20other\x20Guards.':'',b['rx1_11_evidence']=x?'Self\x20rep=false\x20(repository.data\x20query\x20depends\x20on\x20submission)':'Self\x20rep\x20status\x20to\x20be\x20confirmed';if(k){const ah=f['filter'](aj=>aj['b_submission']),ai=ah['filter'](aj=>(aj['name']??'')==='');ai['length']>0x0&&(b['rx1_12_vague_count']=ai['length'],b['rx1_12_vague_csv']=ai['map'](aj=>'identifier='+aj['identifier']+',\x20name=\x22'+(aj['name']??'')+'\x22')['join'](';\x20'));}if(g){const aj=f['find'](ak=>!ak['b_submission']&&ak['value_type']==='Address'&&ak['object_type']===g['host_object']);aj&&(b['rx1_13_detected']=!![],b['rx1_13_identifier']=aj['identifier']);}const y=REENTRANCY_SPECS['find'](ak=>ak['sceneId']===g?.['id']);if(y){const ak=detectReentrancyProtection(a?.['root'],f,y);ak['state']!=='protected'&&(b['reentry_applicable']=!![],b['reentry_state']=ak['state'],b['reentry_scene_id']=y['sceneId'],b['reentry_rationale']=y['rationale'],b['reentry_mitigation']=y['mitigation'],ak['state']==='pseudo'&&(b['reentry_found_primitive']=ak['foundPrimitiveName']??''),b['reentry_evidence']=ak['evidence']);}return b;}function guardRuleBook(){const a=getJudgmentDoc()['rules']['domains']['guard'];if(!a)throw new Error('factory\x20rule\x20pack\x20\x27guard\x27\x20missing\x20—\x20broken\x20installation');return a['rules'];}function dataSourceClassFor(a){if(a['startsWith']('R-C1-'))return'type1_onchain_constant';if(a['startsWith']('R-C2-'))return'type2_witness_derived';if(a['startsWith']('R-C3-'))return'type3_submitted_object';if(a['startsWith']('R-C4-'))return'type4_system_context';return'cross_type';}function findingToGuardRisk(a){return{'id':a['rule_id'],'data_source_class':dataSourceClassFor(a['rule_id']),'level':a['level'],'category':a['dimension']??'data_source_trust','title':a['title'],'description':a['description'],'affected_stakeholders':a['stakeholders']??[],'scenario':a['scenario']??'','mitigation':a['mitigation']??'',...a['evidence']!==undefined?{'evidence':a['evidence']}:{},...a['exposure']!=null?{'exposure':a['exposure']}:{}};}export function runGuardRulePack(a){const b=guardRuleBook();let c;try{c=guardRiskFacts(a);}catch{return[];}return evaluateRuleBook(b,c)['findings']['map'](findingToGuardRisk);}export function assembleGuardAssessment(a,b){const c=getOverallRiskLevel(b),d={};for(const h of b){d[h['data_source_class']]=(d[h['data_source_class']]??0x0)+0x1;}const e=generateStakeholderAdvice(b,a['scene']),f=b['some'](i=>i['level']==='critical')||b['filter'](i=>i['level']==='high')['length']>=0x2,g=generateGuardSummary(a);return{'guard_summary':g,'scene':a['scene'],'risks':b,'overall_risk':c,'risks_by_data_source':d,'stakeholder_advice':e,'needs_human_review':f};}function getOverallRiskLevel(a){if(a['some'](b=>b['level']==='critical'))return'critical';if(a['some'](b=>b['level']==='high'))return'high';if(a['some'](b=>b['level']==='medium'))return'medium';return'low';}function generateStakeholderAdvice(a,b){const c={};for(const d of a){for(const e of d['affected_stakeholders']){if(!c[e])c[e]=[];c[e]['push']('['+d['level']['toUpperCase']()+']\x20'+d['title']+':\x20'+d['mitigation']);}}if(b)switch(b['binding_field']){case'buy_guard':if(!c['customer'])c['customer']=[];c['customer']['push']('Before\x20purchase,\x20verify\x20the\x20buy_guard\x20logic\x20to\x20ensure\x20your\x20identity/credentials\x20can\x20pass\x20validation');break;case'order_allocators':if(!c['provider'])c['provider']=[];c['provider']['push']('Verify\x20the\x20order_allocators\x20ordering\x20to\x20ensure\x20your\x20Allocator\x20will\x20not\x20be\x20skipped\x20by\x20preceding\x20conditions');break;case'voting_guard':if(!c['arbitrator'])c['arbitrator']=[];c['arbitrator']['push']('Confirm\x20the\x20voting\x20weight\x20source\x20is\x20trustworthy;\x20prefer\x20querying\x20EntityRegistrar\x20rather\x20than\x20user-submitted\x20data');break;case'Forward.guard':if(!c['customer'])c['customer']=[];c['customer']['push']('Verify\x20the\x20Forward.guard\x20conditions\x20to\x20ensure\x20you\x20can\x20satisfy\x20the\x20advancement\x20criteria\x20and\x20avoid\x20locked\x20funds');break;}return c;}function generateGuardSummary(a){const b=[];b['push']('table\x20entries:\x20'+a['table']['length']);const c=a['table']['filter'](d=>d['b_submission'])['length'];return b['push']('submitted\x20data:\x20'+c+'\x20entries'),b['push']('root\x20type:\x20'+(a['root']?.['type']??'unknown')),a['rely']&&b['push']('rely:\x20'+a['rely']['guards']['length']+'\x20dependencies\x20('+(a['rely']['logic_or']?'OR':'AND')+')'),b['join'](',\x20');}export function getRiskSummary(a){return{'risk_count':a['risks']['length'],'critical_count':a['risks']['filter'](b=>b['level']==='critical')['length'],'high_count':a['risks']['filter'](b=>b['level']==='high')['length'],'needs_human_review':a['needs_human_review'],'top_risks':a['risks']['filter'](b=>b['level']==='critical'||b['level']==='high')['slice'](0x0,0x3)['map'](b=>b['title'])};}export function getRiskRulesCount(){return factoryRulePack('guard')?.['rules']['length']??0x0;}export const RISK_RULES=((()=>{const a=factoryRulePack('guard');if(!a)return[];return a['rules']['map'](b=>({'id':b['rule_id'],'data_source_class':dataSourceClassFor(b['rule_id']),'trigger':b['trigger']??'','check':c=>{const d=guardRuleBook()['find'](f=>f['rule_id']===b['rule_id']);if(!d)return null;const {findings:e}=evaluateRuleBook([d],guardRiskFacts(c));return e['length']>0x0?findingToGuardRisk(e[0x0]):null;}}));})());
|
|
1
|
+
import{GUARDQUERY}from'@wowok/wowok';import{isUnboundSignerTheft}from'./recipient-constraint.js';import{factoryRulePack,getJudgmentDoc}from'../config/judgment.js';import{evaluateRuleBook}from'../config/rule-engine.js';function rootRaw(a){try{return JSON['stringify'](a)??'';}catch{return'';}}function hasSignerCheck(a){return a['includes']('\x22Signer\x22');}function hasClockCheck(a){return a['includes']('\x22Clock\x22');}function hasGuardSelfRef(a){return a['includes']('\x22Guard\x22');}function hasWitness(a){return a['includes']('\x22convert_witness\x22');}function extractWitnessCodes(a){const b=[],c=rootRaw(a),d=c['matchAll'](/"convert_witness"\s*:\s*(\d+)/g);for(const e of d){const f=parseInt(e[0x1],0xa);if(f>=0x64&&f<=0x6c)b['push'](f);}return b;}const WITNESS_CHAIN={0x64:['Order','Progress'],0x65:['Order','Machine'],0x66:['Order','Service'],0x67:['Progress','Machine'],0x68:['Arb','Order'],0x69:['Arb','Arbitration'],0x6a:['Arb','Order','Progress'],0x6b:['Arb','Order','Service'],0x6c:['Arb','Order','Machine']};function extractWitnessIdentifierPairs(a){const b=[],c=new WeakSet();function d(e){if(e===null||typeof e!=='object')return;if(c['has'](e))return;c['add'](e);typeof e['convert_witness']==='number'&&typeof e['identifier']==='number'&&b['push']({'code':e['convert_witness'],'identifier':e['identifier']});for(const f of Object['keys'](e)){const g=e[f];if(Array['isArray'](g)){for(const h of g)d(h);}else g!==null&&typeof g==='object'&&d(g);}}return d(a),b;}function getChildNodes(a){if(!a||typeof a!=='object')return[];const b=[];if(Array['isArray'](a['nodes']))b['push'](...a['nodes']);if(a['left'])b['push'](a['left']);if(a['right'])b['push'](a['right']);if(a['vec'])b['push'](a['vec']);if(a['target'])b['push'](a['target']);if(a['object']&&typeof a['object']==='object')b['push'](a['object']);if(Array['isArray'](a['parameters']))b['push'](...a['parameters']);return b['filter'](d=>d&&typeof d==='object');}function findSignerLogicEqualNodes(a){const b=[];function c(d,e){if(!d||typeof d!=='object')return;if(d['type']==='logic_equal'){const f=Array['isArray'](d['nodes'])?d['nodes']:d['left']&&d['right']?[d['left'],d['right']]:[];if(f['length']===0x2){const g=f['findIndex'](h=>h?.['type']==='context'&&h?.['context']==='Signer');g>=0x0&&b['push']({'node':d,'parentType':e,'otherOperand':f[0x1-g]});}}for(const h of getChildNodes(d)){c(h,d['type']);}}return c(a,null),b;}function detectLevel1StrictBinding(a,b){const c=findSignerLogicEqualNodes(a);for(const d of c){const e=d['otherOperand'];if(e?.['type']==='identifier'){const f=b['find'](g=>g['identifier']===e['identifier']);if(f&&!f['b_submission']&&f['value_type']==='Address'&&typeof f['value']==='string'&&f['value']['length']>0x0)return{'detected':!![],'entry':{'identifier':f['identifier'],'value':f['value'],'name':f['name']}};}}return{'detected':![]};}function isSignerCheckInLogicOr(a){const b=findSignerLogicEqualNodes(a);return b['some'](c=>c['parentType']==='logic_or');}const QUERY_INVARIANT_MAP=((()=>{const a=new Map();for(const b of GUARDQUERY){b['invariant']!==undefined&&a['set'](b['id'],b['invariant']);}return a;})());function extractQueryIds(a){const b=[],c=rootRaw(a),d=c['matchAll'](/"query"\s*:\s*(\d+)/g);for(const f of d){const g=parseInt(f[0x1],0xa);if(!b['includes'](g))b['push'](g);}const e=c['matchAll'](/"query"\s*:\s*"([^"]+)"/g);for(const h of e){const i=h[0x1],j=GUARDQUERY['find'](k=>k['name']===i);if(j&&!b['includes'](j['id']))b['push'](j['id']);}return b;}function rootAllQueriesNonZero(a){const b=extractQueryIds(a);if(b['length']===0x0)return![];return b['every'](c=>QUERY_INVARIANT_MAP['has'](c));}const REENTRANCY_SPECS=[{'sceneId':'reward_claim','level':'critical','existsPrimitives':[0x64d],'countPrimitives':[0x64c],'addressPrimitives':[0x65a],'rationale':'Guard\x20pass\x20distributes\x20reward\x20funds\x20to\x20the\x20Claimant\x20AND\x20creates\x20a\x20reward_record,\x20but\x20the\x20Guard\x20conditions\x20(identity,\x20time,\x20node\x20state)\x20do\x20NOT\x20naturally\x20invalidate\x20after\x20a\x20claim.\x20'+'Without\x20an\x20explicit\x20anti-reentrancy\x20primitive,\x20the\x20same\x20Claimant\x20can\x20repeatedly\x20pass\x20the\x20Guard\x20and\x20DRAIN\x20THE\x20ENTIRE\x20POOL.\x20'+'This\x20is\x20the\x20most\x20severe\x20reentrancy\x20scene\x20—\x20direct\x20fund\x20loss.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and\x20with\x20existing\x20conditions):\x0a'+'\x20\x20-\x20logic_not(query(\x27reward.record\x20has\x27,\x20object=reward,\x20parameters=[claimant_address]))\x20—\x20RECOMMENDED\x20(per-user\x20Bool\x20check)\x0a'+'\x20\x20-\x20logic_equal([query(\x27reward.record\x20count\x27,\x20object=reward),\x20identifier(N)])\x20where\x20table[N].value=0\x20—\x20total-claim\x20count\x20is\x200\x0a'+'\x20\x20-\x20logic_not(query(\x27reward.record.find_first\x27,\x20object=reward,\x20where={...}))\x20—\x20no\x20matching\x20record\x20found\x0a'+'Reference\x20template:\x20MyShop_Advanced\x20Guard\x207\x20condition\x204\x20(logic_not(query_reward_record_exists(where.storeFromId=order_id)))'},{'sceneId':'arbitration_voting_guard','level':'critical','existsPrimitives':[0x57c,0x57e],'countPrimitives':[0x57d],'addressPrimitives':[],'rationale':'Guard\x20pass\x20counts\x20the\x20vote\x20with\x20the\x20extracted\x20weight.\x20Without\x20anti-reentrancy,\x20the\x20same\x20voter\x20can\x20vote\x20MULTIPLE\x20times,\x20'+'multiplying\x20their\x20weight\x20and\x20skewing\x20the\x20arbitration\x20result\x20—\x20which\x20directly\x20determines\x20fund\x20ownership\x20via\x20compensation.\x20'+'The\x20voter\x27s\x20eligibility\x20(identity,\x20reputation)\x20does\x20NOT\x20naturally\x20invalidate\x20after\x20voting.\x20'+'Note:\x20arb.voted_count\x20(1403)\x20is\x20total\x20voter\x20count\x20(NOT\x20per-voter)\x20and\x20does\x20NOT\x20serve\x20as\x20an\x20anti-reentrancy\x20primitive\x20for\x20an\x20individual\x20voter.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and):\x0a'+'\x20\x20-\x20logic_not(query(\x27arb.voted\x20has\x27,\x20object=arb,\x20parameters=[voter_address]))\x20—\x20RECOMMENDED\x20(per-voter\x20Bool)\x0a'+'\x20\x20-\x20logic_not(query(\x27arb.voted.agree\x20has\x27,\x20object=arb,\x20parameters=[voter_address,\x20proposition_index]))\x20—\x20per-voter-per-proposition\x0a'+'\x20\x20-\x20logic_equal([query(\x27arb.voted.agree\x20count\x27,\x20object=arb,\x20parameters=[voter_address]),\x20identifier(N)])\x20where\x20table[N].value=0'},{'sceneId':'arbitration_usage_guard','level':'high','existsPrimitives':[0x61d],'countPrimitives':[0x61c],'addressPrimitives':[],'rationale':'Guard\x20pass\x20creates\x20a\x20new\x20Arb\x20case.\x20Without\x20anti-reentrancy,\x20a\x20customer\x20can\x20create\x20multiple\x20Arb\x20cases\x20for\x20the\x20SAME\x20Order\x20'+'(up\x20to\x20MAX_DISPUTE_COUNT=10),\x20harassing\x20the\x20counterparty\x20and\x20inflating\x20arbitration\x20system\x20load.\x20'+'Not\x20direct\x20fund\x20loss,\x20but\x20severe\x20system\x20abuse.\x20Filing\x20a\x20dispute\x20deduplicates\x20by\x20Arb\x20address\x20but\x20does\x20NOT\x20prevent\x20multiple\x20distinct\x20Arbs.','mitigation':'Add\x20ONE\x20of\x20the\x20following\x20to\x20the\x20root\x20(wrapped\x20in\x20logic_and):\x0a'+'\x20\x20-\x20logic_not(query(\x27order.dispute\x20has\x27,\x20object=order,\x20parameters=[existing_arb_address]))\x20—\x20per-Arb\x20check\x0a'+'\x20\x20-\x20logic_equal([query(\x27order.dispute\x20count\x27,\x20object=order),\x20identifier(N)])\x20where\x20table[N].value=0\x20—\x20STRICT:\x20block\x20any\x20prior\x20dispute\x0a'+'\x20\x20-\x20logic_as_u256_less_or_equal([query(\x27order.dispute\x20count\x27,\x20object=order),\x20identifier(N)])\x20where\x20table[N].value=K\x20—\x20LENIENT:\x20allow\x20up\x20to\x20K\x20disputes'},{'sceneId':'service_order_allocators_guard','level':'low','existsPrimitives':[0x620],'countPrimitives':[],'addressPrimitives':[0x621],'rationale':'Protocol-level\x20protection:\x20attaching\x20an\x20Allocation\x20to\x20an\x20Order\x20asserts\x20ONE\x20Allocation\x20per\x20Order\x20(E_ALLOCATION_ALREADY_SPECIFIED).\x20'+'After\x20alloc()\x20executes,\x20typical\x20Rate-mode\x20allocators\x20(sum=10000)\x20and\x20Surplus-mode\x20allocators\x20drain\x20balance\x20to\x200,\x20making\x20reentrancy\x20unprofitable.\x20'+'EDGE\x20CASE:\x20Amount-mode-only\x20allocators\x20(no\x20Surplus,\x20total\x20<\x20full\x20balance)\x20leave\x20remainder;\x20a\x20second\x20alloc()\x20could\x20extract\x20more\x20—\x20mitigated\x20by\x20preferring\x20Rate/RateGross/Surplus\x20modes.\x20'+'External\x20deposit\x20via\x20receive()\x20is\x20possible\x20but\x20irrational\x20(attacker\x20funds\x20the\x20Allocation\x20they\x20attack).','mitigation':'Default:\x20no\x20action\x20needed\x20(protocol-level\x20guard).\x20IF\x20using\x20Amount-mode-only\x20allocators\x20without\x20Surplus:\x20'+'consider\x20adding\x20logic_not(query(\x27order.allocation\x20some\x27,\x20object=order))\x20OR\x20switch\x20to\x20Rate/Surplus\x20mode\x20to\x20drain\x20balance\x20completely.'},{'sceneId':'service_buy_guard','level':'low','existsPrimitives':[],'countPrimitives':[],'addressPrimitives':[],'rationale':'Each\x20purchase\x20creates\x20a\x20fresh\x20Order;\x20no\x20existing\x20Order\x20state\x20is\x20modified.\x20Default:\x20no\x20reentrancy\x20risk.\x20'+'IF\x20business\x20intent\x20is\x20\x27limit\x20one\x20purchase\x20per\x20user\x27\x20(limited-edition\x20goods,\x20whitelist\x20single-buy),\x20an\x20anti-reentrancy\x20check\x20is\x20REQUIRED\x20'+'but\x20no\x20direct\x20GUARDQUERY\x20primitive\x20exists\x20for\x20per-user\x20purchase\x20history.','mitigation':'IF\x20limit-purchase\x20intent:\x20record\x20purchases\x20in\x20a\x20Repository\x20and\x20add\x20logic_not(query(\x27repository.data\x20has\x27,\x20...))\x20to\x20root;\x20'+'OR\x20revoke\x20EntityRegistrar\x20membership\x20after\x20first\x20buy;\x20OR\x20use\x20an\x20off-chain\x20allowlist\x20with\x20on-chain\x20Merkle\x20proof.'},{'sceneId':'repository_write_guard','level':'low','existsPrimitives':[0x48e],'countPrimitives':[],'addressPrimitives':[],'rationale':'Default\x20writes\x20are\x20idempotent\x20(same\x20ID\x20overwrites,\x20different\x20ID\x20appends);\x20no\x20fund\x20flow.\x20'+'IF\x20business\x20intent\x20is\x20\x27one\x20write\x20per\x20ID\x27\x20(voting,\x20immutable\x20credential,\x20single-attestation),\x20an\x20anti-reentrancy\x20check\x20is\x20needed.','mitigation':'IF\x20one-write-per-ID\x20intent:\x20add\x20logic_not(query(\x27repository.data\x20has\x27,\x20object=repository,\x20parameters=[policy_name,\x20user_or_object_id]))\x20to\x20root.'},{'sceneId':'gen_passport_guard','level':'low','existsPrimitives':[],'countPrimitives':[],'addressPrimitives':[],'rationale':'Each\x20gen_passport\x20call\x20generates\x20an\x20independent\x20Passport\x20(one\x20Passport\x20per\x20operation).\x20'+'Multiple\x20Passports\x20for\x20the\x20same\x20user\x20are\x20usually\x20valid\x20(each\x20serves\x20a\x20different\x20subsequent\x20operation).\x20'+'IF\x20business\x20intent\x20is\x20\x27one\x20active\x20Passport\x20per\x20user\x27,\x20an\x20anti-reentrancy\x20check\x20is\x20needed\x20but\x20no\x20direct\x20GUARDQUERY\x20primitive\x20exists.','mitigation':'IF\x20one-passport-per-user\x20intent:\x20use\x20off-chain\x20tracking\x20or\x20a\x20Repository\x20to\x20record\x20issued\x20Passport\x20IDs.'}],QUERY_TYPE_ALIASES=new Map([['query_reward_record_exists',0x64d],['query_reward_record_count',0x64c],['query_reward_record_find',0x65a],['query_progress_history_find',0x4fa],['query_progress_history_session_find',0x4fb],['query_progress_history_session_forward_find',0x4fc],['query_progress_history_session_count',0x4f9],['query_progress_history_session_forward_count',0x4ee],['query_repository_data_count_where',0x495],['query_repository_data_sum_where',0x496],['query_repository_policies_keys',0x497],['query_repository_data_find_where',0x498],['query_repository_data_keys_where',0x499]]);function detectReentrancyProtection(a,b,c){const d=new Set([...c['existsPrimitives'],...c['countPrimitives'],...c['addressPrimitives']]);if(d['size']===0x0)return{'state':'absent','evidence':'No\x20anti-reentrancy\x20primitive\x20available\x20in\x20GUARDQUERY\x20for\x20this\x20scene'};const e=new Map(),f=new Map();for(const p of d){const q=GUARDQUERY['find'](r=>r['id']===p);q&&(e['set'](p,q['name']),f['set'](q['name'],p));}const g=Array['from'](f['keys']());function h(r){if(!r||typeof r!=='object')return-0x1;if(typeof r['query']==='number'&&d['has'](r['query']))return r['query'];if(typeof r['query']==='string'&&f['has'](r['query']))return f['get'](r['query']);if(typeof r['type']==='string'&&QUERY_TYPE_ALIASES['has'](r['type'])){const s=QUERY_TYPE_ALIASES['get'](r['type']);if(d['has'](s))return s;}if(typeof r['type']==='string'&&f['has'](r['type']))return f['get'](r['type']);return-0x1;}function i(r){if(!r||typeof r!=='object')return![];if(typeof r['type']==='string'&&['number','u8','u16','u32','u64','u128','u256']['includes'](r['type']))return r['value']===0x0||r['value']==='0'||r['value']===0x0n;if(r['type']==='identifier'&&typeof r['identifier']==='number'){const s=b['find'](t=>t['identifier']===r['identifier']);if(s&&!s['b_submission'])return s['value']===0x0||s['value']==='0'||s['value']===0x0n;}return![];}function j(r,s){if(!r||typeof r!=='object')return[];const t=[];if(Array['isArray'](r['nodes']))for(const u of r['nodes']){if(u!==s)t['push'](u);}if(r['left']&&r['left']!==s)t['push'](r['left']);if(r['right']&&r['right']!==s)t['push'](r['right']);return t['filter'](v=>v&&typeof v==='object');}let k=![],l=![],m='',n='';function o(r,s){if(!r||typeof r!=='object')return;const t=h(r);if(t>=0x0){k=!![];const v=e['get'](t)??'query_'+t;n=v;const w=s?.['type']??null;let x=![];const y=c['existsPrimitives']['includes'](t),z=c['addressPrimitives']['includes'](t),A=c['countPrimitives']['includes'](t);(y||z)&&w==='logic_not'&&(x=!![]);if(A&&w==='logic_equal'){const B=j(s,r);B['some'](C=>i(C))&&(x=!![]);}if(x)l=!![];else{if(!m){const C=A?'logic_equal\x20with\x20a\x20zero\x20operand':'logic_not';m='Primitive\x20\x22'+v+'\x22\x20found\x20but\x20its\x20immediate\x20parent\x20is\x20'+(w??'root')+'\x20(expected\x20'+C+').\x20The\x20primitive\x20is\x20present\x20but\x20does\x20NOT\x20actually\x20prevent\x20reentrancy\x20—\x20this\x20is\x20a\x20false\x20sense\x20of\x20security.';}}}const u=[];if(Array['isArray'](r['nodes']))u['push'](...r['nodes']);if(r['left'])u['push'](r['left']);if(r['right'])u['push'](r['right']);if(r['node'])u['push'](r['node']);if(r['vec'])u['push'](r['vec']);if(r['target'])u['push'](r['target']);if(r['object']&&typeof r['object']==='object')u['push'](r['object']);if(Array['isArray'](r['parameters']))u['push'](...r['parameters']);for(const D of u){D&&typeof D==='object'&&o(D,r);}}o(a,null);if(l)return{'state':'protected','evidence':'Anti-reentrancy\x20primitive\x20\x22'+n+'\x22\x20is\x20properly\x20wrapped','foundPrimitiveName':n};if(k)return{'state':'pseudo','evidence':m,'foundPrimitiveName':n};return{'state':'absent','evidence':'No\x20anti-reentrancy\x20primitive\x20found\x20in\x20root.\x20Expected\x20one\x20of:\x20'+g['join'](',\x20')};}function stableKey(a){if(a===null||typeof a!=='object')return JSON['stringify'](a)??'null';if(Array['isArray'](a))return'['+a['map'](stableKey)['join'](',')+']';const b=a;return'{'+Object['keys'](b)['sort']()['map'](c=>JSON['stringify'](c)+':'+stableKey(b[c]))['join'](',')+'}';}function readsContext(a){return rootRaw(a)['includes']('\x22context\x22');}const NUMERIC_VALUE_TYPE=/^u(?:8|16|32|64|128|256)$/i,NUMERIC_NODE_TYPES=new Set(['calc_number_add','calc_number_multiply','calc_number_subtract','calc_number_divide','calc_number_mod','convert_address_number','convert_string_number','convert_safe_u8','convert_safe_u16','convert_safe_u32','convert_safe_u64','convert_safe_u128','convert_safe_u256','vec_length','calc_string_length']),REFLEXIVE_TRUE_OPS=new Set(['logic_equal','logic_as_u256_equal','logic_string_nocase_equal','calc_string_nocase_equal','logic_string_contains','calc_string_contains','logic_string_nocase_contains','calc_string_nocase_contains']),REFLEXIVE_FALSE_OPS=new Set(['logic_not_equal','logic_as_u256_greater','logic_as_u256_lesser']);function tableEntryOf(a,b){if(!a||a['type']!=='identifier')return undefined;return b['find'](c=>c['identifier']===a['identifier']);}function staticValueType(a,b){if(!a||typeof a!=='object'||typeof a['type']!=='string')return undefined;if(a['type']==='identifier')return tableEntryOf(a,b)?.['value_type'];const c=QUERY_TYPE_ALIASES['get'](a['type']),d=a['type']==='query'?a['query']:c;if(d!==undefined){const e=GUARDQUERY['find'](f=>f['id']===d||typeof d==='string'&&f['name']===d);if(e)return String(e['return']);}return NUMERIC_NODE_TYPES['has'](a['type'])?'U64':undefined;}function constantNumber(a,b){const c=tableEntryOf(a,b);if(!c||c['b_submission'])return undefined;if(!NUMERIC_VALUE_TYPE['test'](String(c['value_type'])))return undefined;const d=String(c['value']??'')['trim']();if(!/^\d+$/['test'](d))return undefined;try{return BigInt(d);}catch{return undefined;}}function foldCertainOutcome(c,d,e=0x0){if(e>0x40||!c||typeof c!=='object'||typeof c['type']!=='string')return undefined;const f=Array['isArray'](c['nodes'])?c['nodes']:[],g=i=>foldCertainOutcome(i,d,e+0x1),h=()=>f['length']>0x0?f['map'](g):undefined;switch(c['type']){case'identifier':{const i=tableEntryOf(c,d);if(!i||i['b_submission'])return undefined;if(/^bool$/i['test'](String(i['value_type']))){const j=String(i['value']??'')['trim']()['toLowerCase']();if(j==='true'||j==='false')return{'outcome':j,'reason':'table\x20entry\x20#'+i['identifier']+'\x20is\x20the\x20constant\x20Bool\x20'+j};}return undefined;}case'logic_and':{const k=h();if(!k)return undefined;const l=k['find'](m=>m?.['outcome']==='false');if(l)return{'outcome':'false','reason':'a\x20logic_and\x20branch\x20is\x20always\x20false:\x20'+l['reason']};if(k['every'](m=>m?.['outcome']==='true'))return{'outcome':'true','reason':'every\x20logic_and\x20branch\x20is\x20always\x20true:\x20'+(k[0x0]?.['reason']??'')};return undefined;}case'logic_or':{const m=h();if(!m)return undefined;const n=m['find'](o=>o?.['outcome']==='true');if(n)return{'outcome':'true','reason':'a\x20logic_or\x20branch\x20is\x20always\x20true:\x20'+n['reason']};if(m['every'](o=>o?.['outcome']==='false'))return{'outcome':'false','reason':'every\x20logic_or\x20branch\x20is\x20always\x20false'};return undefined;}case'logic_not':{const o=g(c['node']);if(!o)return undefined;return{'outcome':o['outcome']==='true'?'false':'true','reason':'logic_not\x20of\x20'+(o['outcome']==='true'?'an\x20always-true':'an\x20always-false')+'\x20expression:\x20'+o['reason']};}default:{if(f['length']<0x2)return undefined;const p=new Set(f['map'](stableKey));if(p['size']===0x1&&!readsContext(f[0x0])&&!rootRaw(f[0x0])['includes']('\x22query\x22')){if(REFLEXIVE_TRUE_OPS['has'](c['type']))return{'outcome':'true','reason':c['type']+'\x20compares\x20the\x20same\x20operand\x20to\x20itself\x20(identifier/constant\x20subtree\x20'+stableKey(f[0x0])['slice'](0x0,0x50)+')\x20—\x20it\x20can\x20never\x20reject'};if(REFLEXIVE_FALSE_OPS['has'](c['type']))return{'outcome':'false','reason':c['type']+'\x20compares\x20the\x20same\x20operand\x20to\x20itself\x20—\x20it\x20can\x20never\x20pass'};}const q=f['map'](s=>constantNumber(s,d)),r=c['type']==='logic_as_u256_greater_or_equal'?0x1:c['type']==='logic_as_u256_lesser_or_equal'?0x0:-0x1;if(r>=0x0&&f['length']===0x2){const s=0x1-r,t=f[s],u=staticValueType(t,d);if(q[r]===0x0n&&q[s]===undefined&&u!==undefined&&NUMERIC_VALUE_TYPE['test'](String(u))&&!readsContext(t))return{'outcome':'true','reason':c['type']+'\x20against\x20the\x20constant\x200\x20on\x20an\x20unsigned\x20('+u+')\x20operand\x20—\x20every\x20U-value\x20satisfies\x20it'};}if(q['length']===0x2&&q[0x0]!==undefined&&q[0x1]!==undefined){const v=q[0x0],w=q[0x1],x={'logic_equal':v===w,'logic_as_u256_equal':v===w,'logic_not_equal':v!==w,'logic_as_u256_greater':v>w,'logic_as_u256_greater_or_equal':v>=w,'logic_as_u256_lesser':v<w,'logic_as_u256_lesser_or_equal':v<=w};if(c['type']in x)return{'outcome':x[c['type']]?'true':'false','reason':c['type']+'\x20folds\x20on\x20two\x20constant\x20operands\x20('+v['toString']()+'\x20vs\x20'+w['toString']()+')'};}return undefined;}}}export function guardRiskFacts(a){const b={},c=rootRaw(a?.['root']),d=c['toLowerCase'](),f=Array['isArray'](a?.['table'])?a['table']:[],g=a?.['scene'],h=a?.['rely'];b['has_signer_check']=hasSignerCheck(c),b['has_clock_check']=hasClockCheck(c),b['has_guard_self_ref']=hasGuardSelfRef(c),b['has_witness']=hasWitness(c),b['queries_repository']=d['includes']('repository'),b['queries_progress']=d['includes']('progress'),b['root_has_query']=d['includes']('\x22query\x22'),b['root_has_clock_token']=d['includes']('clock'),b['root_has_calc_number_add']=d['includes']('calc_number_add'),b['root_has_logic_string_contains']=d['includes']('logic_string_contains'),b['root_has_logic_string_nocase']=d['includes']('logic_string_nocase'),b['root_has_logic_as_u256_greater_or_equal']=d['includes']('logic_as_u256_greater_or_equal'),b['root_has_logic_as_u256_greater']=d['includes']('logic_as_u256_greater'),b['root_has_logic_equal']=c['includes']('\x22logic_equal\x22'),b['root_has_logic_not_equal']=c['includes']('\x22logic_not_equal\x22'),b['logic_and_count']=(d['match'](/"logic_and"/g)||[])['length'],b['root_is_identifier']=a?.['root']?.['type']==='identifier';const i=b['root_is_identifier']?f['find'](C=>C['identifier']===a['root']['identifier']):undefined;b['root_identifier_is_submission']=i?.['b_submission']??![];const j=extractQueryIds(a?.['root']);b['root_query_ids_csv']=j['join'](',\x20'),b['root_has_progress_current_query']=j['includes'](0x4e5),b['queries_arb_status']=d['includes']('arb.status'),b['arb_status_transient_gate']=b['queries_arb_status']&&f['some'](C=>!C['b_submission']&&/^u(8|16|32|64|128|256)$/i['test'](String(C['value_type']))&&Number(C['value'])===0x5);const k=f['some'](C=>C['b_submission']);b['has_submission']=k;const l=f['filter'](C=>!C['b_submission']&&C['value_type']==='Address'&&C['value']);l['length']>0x0&&(b['const_addr_count']=l['length'],b['const_addr_list']=l['map'](C=>'#'+C['identifier']+'='+C['value'])['join'](',\x20'));const m=f['filter'](C=>!C['b_submission']&&C['value_type']==='Address'&&typeof C['value']==='string'&&(C['value']['toLowerCase']()==='0xaab'||C['value']['toLowerCase']()==='0xaaa'));if(m['length']>0x0){b['sys_addr_list']=m['map'](D=>'#'+D['identifier']+'='+D['value']+'('+D['name']+')')['join'](',\x20');const C=m['find'](D=>D['value']==='0xaab'&&D['name']&&!D['name']['toLowerCase']()['includes']('registrar')||D['value']==='0xaaa'&&D['name']&&!D['name']['toLowerCase']()['includes']('linker'));b['sys_addr_wrong']=C!==undefined;}const n=extractWitnessCodes(a?.['root']),o=n['filter'](D=>[0x6a,0x6b,0x6c]['includes'](D));if(o['length']>0x0){const D={0x6a:'Arb→Progress\x20(two\x20hops:\x20arb.order\x20→\x20order.progress)',0x6b:'Arb→Machine\x20(two\x20hops:\x20arb.order\x20→\x20order.machine)',0x6c:'Arb→Service\x20(two\x20hops:\x20arb.order\x20→\x20order.service)'};b['witness_multihop_codes']=o,b['witness_multihop_csv']=o['join'](',\x20'),b['witness_multihop_names_block']=o['map'](E=>'\x20\x20-\x20'+E+':\x20'+D[E])['join']('\x0a');}const p=extractWitnessIdentifierPairs(a?.['root']),q=p['filter'](E=>E['code']>=0x64&&E['code']<=0x6c);if(q['length']>0x0){const E=[],F=[];for(const {code:H,identifier:I}of q){const J=WITNESS_CHAIN[H];if(!J)continue;const K=J[0x0],L=f['find'](N=>N['identifier']===I);if(!L)continue;const M=H+'\x20('+J['join']('→')+')';L['object_type']?L['object_type']!==K&&E['push']('witness\x20'+M+'\x20references\x20#'+I+'\x20'+('but\x20object_type='+L['object_type']+'\x20(expected\x20'+K+')')):F['push']('witness\x20'+M+'\x20references\x20#'+I+'\x20'+('but\x20object_type\x20is\x20not\x20set\x20(expected\x20'+K+')'));if(J['length']===0x3){const N=J[0x1],O=f['some'](P=>P['object_type']===N);!O&&F['push']('witness\x20'+M+'\x20multi-hop\x20chain\x20expects\x20intermediate\x20'+(N+'\x20in\x20table,\x20but\x20no\x20entry\x20with\x20object_type='+N+'\x20found'));}}const G=[...E,...F];G['length']>0x0&&(b['rc2_02_issue_count']=G['length'],b['rc2_02_has_hard_mismatch']=E['length']>0x0,b['rc2_02_evidence_lines']=G['map'](P=>'\x20\x20-\x20'+P)['join']('\x0a'),b['rc2_02_evidence_csv']=G['join'](';\x20'));}if(b['has_witness']){const P=d['includes']('repository')&&d['includes']('\x22query\x22'),Q=d['includes']('progress_history')&&d['includes']('\x22query\x22');if(P||Q){const R=d['includes']('convert_number_address')||d['includes']('convert_address_number')||d['includes']('convert_u256')||d['includes']('convert_string');b['rc2_04_queries_repo']=P,b['rc2_04_queries_progress_history']=Q,b['rc2_04_has_conversion']=R,b['rc2_04_conversion_note']=R?'\x0aThe\x20current\x20Guard\x20already\x20uses\x20type\x20conversion\x20nodes,\x20but\x20ensure\x20the\x20conversion\x20direction\x20is\x20correct.':'\x0aWarning:\x20no\x20type\x20conversion\x20node\x20detected\x20in\x20the\x20current\x20Guard;\x20parameter\x20type\x20mismatch\x20risk\x20may\x20exist.',b['rc2_04_conversion_evidence']=R?'Type\x20conversion\x20node\x20in\x20use':'No\x20type\x20conversion\x20node\x20detected';}}b['scene_present']=g!==undefined;g&&(b['scene_id']=g['id'],b['scene_host_object']=g['host_object'],b['scene_binding_field']=g['binding_field'],b['scene_mutable_after_publish']=g['mutable_after_publish']);b['rc3_01_sharing_exempt']=g?.['id']==='service_order_allocators_guard'&&Array['isArray'](a?.['sharing_recipients'])&&a['sharing_recipients']['length']>0x0&&!a['sharing_recipients']['includes']('Signer');if(g?.['binding_field']==='voting_guard'){const S=f['filter'](T=>T['b_submission']&&['U8','U16','U32','U64','U128','U256']['includes'](T['value_type']));S['length']>0x0&&(b['rc3_02_numeric_count']=S['length'],b['rc3_02_numeric_list']=S['map'](T=>'#'+T['identifier']+'('+T['value_type']+')')['join'](',\x20'));}const r=f['filter'](T=>T['b_submission']&&T['value_type']==='Address');if(r['length']>0x0){b['rc3_03_submitted_addr_count']=r['length'];const T=r['filter'](U=>!U['object_type']);b['rc3_03_no_type_count']=T['length'],b['rc3_03_evidence']=T['length']>0x0?'Missing\x20object_type:\x20'+T['map'](U=>'#'+U['identifier'])['join'](',\x20'):'Annotated:\x20'+r['map'](U=>'#'+U['identifier']+'='+U['object_type'])['join'](',\x20');}if(r['length']>0x0){const U=n['some'](a1=>[0x64,0x65,0x66]['includes'](a1)),V=n['some'](a1=>[0x67]['includes'](a1)),W=n['some'](a1=>[0x68,0x69,0x6a,0x6b,0x6c]['includes'](a1)),X=r['filter'](a1=>a1['object_type']==='Order'||U&&!a1['object_type']),Y=r['filter'](a1=>a1['object_type']==='Progress'||V&&!a1['object_type']),Z=r['filter'](a1=>a1['object_type']==='Arb'||W&&!a1['object_type']),a0=X['length']>0x0||Y['length']>0x0||Z['length']>0x0;if(a0){const a1=['machine_forward_guard','service_order_allocators_guard','arbitration_usage_guard','arbitration_voting_guard','reward_claim','progress_submission_guard'],a2=g?.['id'],a3=!a2||a1['includes'](a2);if(a3){const a4=new Set([0x61b,0x618,0x4e2,0x57a,0x579]),a5=j['some'](a6=>a4['has'](a6));if(!a5){const a6=[];for(const a7 of X){a6['push']('#'+a7['identifier']+(a7['object_type']?'(Order)':'(inferred\x20Order\x20via\x20witness\x20100-102)'));}for(const a8 of Y){a6['push']('#'+a8['identifier']+(a8['object_type']?'(Progress)':'(inferred\x20Progress\x20via\x20witness\x20103)'));}for(const a9 of Z){a6['push']('#'+a9['identifier']+(a9['object_type']?'(Arb)':'(inferred\x20Arb\x20via\x20witness\x20104-108)'));}b['rc3_05_applies']=!![],b['rc3_05_critical']=a2!==undefined&&(a2==='machine_forward_guard'||a2==='service_order_allocators_guard'),b['rc3_05_unbound_csv']=a6['join'](',\x20'),b['rc3_05_scene_label']=a2??'unknown\x20scene\x20(conservative\x20flag)';}}}}if(g?.['id']==='service_order_allocators_guard'&&!b['has_signer_check']){const aa=a?.['sharing_recipients'],ab=aa!==undefined&&aa['length']>0x0,ac=ab&&aa['includes']('Signer');if(!(ab&&!ac)){const ad=isUnboundSignerTheft({'recipient_is_signer':ac,'caller_identity_constrained':![]});b['rc3_06_applies']=!![],b['rc3_06_signer_sharing']=ad,b['rc3_06_recipients_label']=ab?'['+aa['join'](',\x20')+']':'(not\x20provided\x20—\x20conservative\x20flag)',b['rc3_06_title_suffix']=ac?'sharing.who=Signer\x20confirmed\x20—\x20anyone\x20can\x20steal\x20100%\x20of\x20funds':'if\x20sharing.who=Signer,\x20anyone\x20can\x20steal\x20100%\x20of\x20funds',b['rc3_06_level_rationale']=ad?'Signer\x20sharing\x20confirmed\x20→\x20critical':'sharing\x20hint\x20absent\x20→\x20conservative\x20medium';}}if(b['has_signer_check']){const ae=c['includes']('\x22logic_equal\x22'),af=c['includes']('\x22logic_not_equal\x22');b['rc4_01_comparison_detail']=(ae?'logic_equal(==)':'')+'\x20'+(af?'logic_not_equal(!=)':''),b['rc4_01_comparison_ops']=(ae?'==':'')+'\x20'+(af?'!=':'');}if(b['has_clock_check']){const ag=d['includes']('logic_as_u256_greater_or_equal'),ah=d['includes']('logic_as_u256_greater');(ag||ah)&&(b['rc4_02_has_greater_or_equal']=ag,b['rc4_02_has_greater']=ah,b['rc4_02_comparison_ops']=(ag?'>=':'')+'\x20'+(ah?'>':''));}if(b['has_signer_check']&&!isSignerCheckInLogicOr(a?.['root'])){const ai=detectLevel1StrictBinding(a?.['root'],f);if(ai['detected']&&ai['entry']){const aj=ai['entry'];b['rc4_04_detected']=!![],b['rc4_04_entry_identifier']=aj['identifier'],b['rc4_04_entry_value']=aj['value'],b['rc4_04_entry_detail']='b_submission=false,\x20value=\x22'+aj['value']+'\x22'+(aj['name']?',\x20name=\x22'+aj['name']+'\x22':'');}}const s=rootAllQueriesNonZero(a?.['root']),t=()=>{const ak=j['filter'](al=>!QUERY_INVARIANT_MAP['has'](al));if(ak['length']===0x0)return'';return'Queries\x20without\x20non-zero\x20invariant:\x20'+ak['map'](al=>{const am=GUARDQUERY['find'](an=>an['id']===al);return am?am['id']+'\x20('+am['name']+')':''+al;})['join'](',\x20');};b['root_has_logic_as_u256_greater_or_equal']&&d['includes']('\x22clock\x22')&&b['root_has_calc_number_add']&&b['root_has_query']&&!s&&(b['rx1_01_trigger']=!![],b['rx1_01_evidence']=t()||'Baseline\x20query\x20may\x20return\x200');b['root_has_logic_as_u256_greater']&&b['root_has_query']&&!s&&(b['rx1_02_trigger']=!![],b['rx1_02_evidence']=t()||'Query\x20may\x20return\x200');const u=Array['isArray'](h?.['guards'])?h['guards']:[];b['rely_guards_count']=u['length'],b['rely_is_or']=h?.['logic_or']===!![],b['rely_logic']=h?.['logic_or']?'OR':'AND';const v=d['includes']('repository')&&d['includes']('\x22query\x22'),w=f['some'](ak=>ak['b_submission']&&ak['value_type']==='Address'&&ak['object_type']==='Repository'),x=v&&w;b['rx1_11_self_rep_false']=x,b['rx1_11_warning_tail']=x?'\x0aWarning:\x20the\x20current\x20Guard\x20itself\x20queries\x20repository.data\x20and\x20the\x20Repository\x20address\x20comes\x20from\x20submission,\x20'+'so\x20its\x20own\x20rep=false\x20and\x20cannot\x20be\x20depended\x20on\x20by\x20other\x20Guards.':'',b['rx1_11_evidence']=x?'Self\x20rep=false\x20(repository.data\x20query\x20depends\x20on\x20submission)':'Self\x20rep\x20status\x20to\x20be\x20confirmed';if(k){const ak=f['filter'](am=>am['b_submission']),al=ak['filter'](am=>(am['name']??'')==='');al['length']>0x0&&(b['rx1_12_vague_count']=al['length'],b['rx1_12_vague_csv']=al['map'](am=>'identifier='+am['identifier']+',\x20name=\x22'+(am['name']??'')+'\x22')['join'](';\x20'));}if(g){const am=f['find'](an=>!an['b_submission']&&an['value_type']==='Address'&&an['object_type']===g['host_object']);am&&(b['rx1_13_detected']=!![],b['rx1_13_identifier']=am['identifier']);}const y=REENTRANCY_SPECS['find'](an=>an['sceneId']===g?.['id']);if(y){const an=detectReentrancyProtection(a?.['root'],f,y);an['state']!=='protected'&&(b['reentry_applicable']=!![],b['reentry_state']=an['state'],b['reentry_scene_id']=y['sceneId'],b['reentry_rationale']=y['rationale'],b['reentry_mitigation']=y['mitigation'],an['state']==='pseudo'&&(b['reentry_found_primitive']=an['foundPrimitiveName']??''),b['reentry_evidence']=an['evidence']);}const z=foldCertainOutcome(a?.['root'],f),A=z?.['outcome']==='true';b['tree_folds_always_true']=A;z&&z['outcome']==='false'&&(b['tree_folds_always_false']=!![],b['tree_folds_always_false_reason']=z['reason']);if(A)b['tree_folds_always_true_reason']=z['reason'];const B=g?.['binding_field']==='write_guard'||g?.['id']==='repository_write_guard';return b['write_guard_scene']=B,B&&(b['write_guard_no_identity_check']=!b['has_signer_check'],b['write_guard_open']=A||!b['has_signer_check']),b;}function guardRuleBook(){const a=getJudgmentDoc()['rules']['domains']['guard'];if(!a)throw new Error('factory\x20rule\x20pack\x20\x27guard\x27\x20missing\x20—\x20broken\x20installation');return a['rules'];}function dataSourceClassFor(a){if(a['startsWith']('R-C1-'))return'type1_onchain_constant';if(a['startsWith']('R-C2-'))return'type2_witness_derived';if(a['startsWith']('R-C3-'))return'type3_submitted_object';if(a['startsWith']('R-C4-'))return'type4_system_context';return'cross_type';}function findingToGuardRisk(a){return{'id':a['rule_id'],'data_source_class':dataSourceClassFor(a['rule_id']),'level':a['level'],'category':a['dimension']??'data_source_trust','title':a['title'],'description':a['description'],'affected_stakeholders':a['stakeholders']??[],'scenario':a['scenario']??'','mitigation':a['mitigation']??'',...a['evidence']!==undefined?{'evidence':a['evidence']}:{},...a['exposure']!=null?{'exposure':a['exposure']}:{}};}export function runGuardRulePack(a){const b=guardRuleBook();let c;try{c=guardRiskFacts(a);}catch{return[];}return evaluateRuleBook(b,c)['findings']['map'](findingToGuardRisk);}export function assembleGuardAssessment(a,b){const c=getOverallRiskLevel(b),d={};for(const h of b){d[h['data_source_class']]=(d[h['data_source_class']]??0x0)+0x1;}const e=generateStakeholderAdvice(b,a['scene']),f=b['some'](i=>i['level']==='critical')||b['filter'](i=>i['level']==='high')['length']>=0x2,g=generateGuardSummary(a);return{'guard_summary':g,'scene':a['scene'],'risks':b,'overall_risk':c,'risks_by_data_source':d,'stakeholder_advice':e,'needs_human_review':f};}function getOverallRiskLevel(a){if(a['some'](b=>b['level']==='critical'))return'critical';if(a['some'](b=>b['level']==='high'))return'high';if(a['some'](b=>b['level']==='medium'))return'medium';return'low';}function generateStakeholderAdvice(a,b){const c={};for(const d of a){for(const e of d['affected_stakeholders']){if(!c[e])c[e]=[];c[e]['push']('['+d['level']['toUpperCase']()+']\x20'+d['title']+':\x20'+d['mitigation']);}}if(b)switch(b['binding_field']){case'buy_guard':if(!c['customer'])c['customer']=[];c['customer']['push']('Before\x20purchase,\x20verify\x20the\x20buy_guard\x20logic\x20to\x20ensure\x20your\x20identity/credentials\x20can\x20pass\x20validation');break;case'order_allocators':if(!c['provider'])c['provider']=[];c['provider']['push']('Verify\x20the\x20order_allocators\x20ordering\x20to\x20ensure\x20your\x20Allocator\x20will\x20not\x20be\x20skipped\x20by\x20preceding\x20conditions');break;case'voting_guard':if(!c['arbitrator'])c['arbitrator']=[];c['arbitrator']['push']('Confirm\x20the\x20voting\x20weight\x20source\x20is\x20trustworthy;\x20prefer\x20querying\x20EntityRegistrar\x20rather\x20than\x20user-submitted\x20data');break;case'Forward.guard':if(!c['customer'])c['customer']=[];c['customer']['push']('Verify\x20the\x20Forward.guard\x20conditions\x20to\x20ensure\x20you\x20can\x20satisfy\x20the\x20advancement\x20criteria\x20and\x20avoid\x20locked\x20funds');break;}return c;}function generateGuardSummary(a){const b=[];b['push']('table\x20entries:\x20'+a['table']['length']);const c=a['table']['filter'](d=>d['b_submission'])['length'];return b['push']('submitted\x20data:\x20'+c+'\x20entries'),b['push']('root\x20type:\x20'+(a['root']?.['type']??'unknown')),a['rely']&&b['push']('rely:\x20'+a['rely']['guards']['length']+'\x20dependencies\x20('+(a['rely']['logic_or']?'OR':'AND')+')'),b['join'](',\x20');}export function getRiskSummary(a){return{'risk_count':a['risks']['length'],'critical_count':a['risks']['filter'](b=>b['level']==='critical')['length'],'high_count':a['risks']['filter'](b=>b['level']==='high')['length'],'needs_human_review':a['needs_human_review'],'top_risks':a['risks']['filter'](b=>b['level']==='critical'||b['level']==='high')['slice'](0x0,0x3)['map'](b=>b['title'])};}export function getRiskRulesCount(){return factoryRulePack('guard')?.['rules']['length']??0x0;}export const RISK_RULES=((()=>{const a=factoryRulePack('guard');if(!a)return[];return a['rules']['map'](b=>({'id':b['rule_id'],'data_source_class':dataSourceClassFor(b['rule_id']),'trigger':b['trigger']??'','check':c=>{const d=guardRuleBook()['find'](f=>f['rule_id']===b['rule_id']);if(!d)return null;const {findings:e}=evaluateRuleBook([d],guardRiskFacts(c));return e['length']>0x0?findingToGuardRisk(e[0x0]):null;}}));})());
|
|
@@ -40,5 +40,11 @@ export interface SubmissionContext {
|
|
|
40
40
|
action?: GuardAction;
|
|
41
41
|
extra?: Record<string, string>;
|
|
42
42
|
}
|
|
43
|
+
export declare function buildSubmissionFillExample(guardTarget: string, fields: Array<{
|
|
44
|
+
identifier: number;
|
|
45
|
+
name: string;
|
|
46
|
+
value_type: string;
|
|
47
|
+
suggested_value?: string;
|
|
48
|
+
}>): string;
|
|
43
49
|
export declare function generateGuardSubmissionPrompt(guardRef: string, ctx: SubmissionContext): Promise<GuardSubmissionPrompt | undefined>;
|
|
44
50
|
export declare function formatSubmissionPrompt(prompt: GuardSubmissionPrompt): string;
|