@wowok/agent-mcp 3.2.4 → 3.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/composition/blueprint-view.d.ts +64 -0
- package/dist/composition/blueprint-view.js +1 -0
- package/dist/evaluation/builtins/graph-service.spec.js +1 -1
- package/dist/evaluation/engine.js +1 -1
- package/dist/experience/realtime-feedback.js +1 -1
- package/dist/extensions/industry-pack.d.ts +1 -0
- package/dist/extensions/industry-pack.js +1 -1
- package/dist/extensions/modes.js +1 -1
- package/dist/extensions/registry.d.ts +1 -2
- package/dist/extensions/registry.js +1 -1
- package/dist/graph/onchain/expand.js +1 -1
- package/dist/graph/onchain/exposure.js +1 -1
- package/dist/graph/onchain/facts.js +1 -1
- package/dist/harness/recover.js +1 -1
- package/dist/knowledge/audit-rules.d.ts +2 -0
- package/dist/knowledge/audit-rules.js +1 -1
- package/dist/knowledge/baselines/rules/allocation.json +5 -5
- package/dist/knowledge/baselines/rules/arb.json +1 -1
- package/dist/knowledge/baselines/rules/guard.json +9 -9
- package/dist/knowledge/baselines/rules/machine.json +5 -5
- package/dist/knowledge/baselines/rules/order.json +1 -1
- package/dist/knowledge/builtin-templates.d.ts +2 -1
- package/dist/knowledge/builtin-templates.js +1 -1
- package/dist/knowledge/entity-recipient-guard.js +1 -1
- package/dist/knowledge/getting-started.js +1 -1
- package/dist/knowledge/guard-design-patterns.js +1 -1
- package/dist/knowledge/guard-risk.js +1 -1
- package/dist/knowledge/guard-templates.d.ts +1 -1
- package/dist/knowledge/guard-templates.js +1 -1
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/industry-generalizer.js +1 -1
- package/dist/knowledge/industry-registry.js +1 -1
- package/dist/knowledge/jsonrpc-enum.js +1 -1
- package/dist/knowledge/order-ledger.js +1 -1
- package/dist/knowledge/scenario-modes.d.ts +2 -4
- package/dist/knowledge/scenario-modes.js +1 -1
- package/dist/knowledge/service-ledger.js +1 -1
- package/dist/knowledge/service-templates.js +1 -1
- package/dist/knowledge/template-loader.d.ts +7 -2
- 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/template-validation.d.ts +2 -0
- package/dist/knowledge/template-validation.js +1 -0
- package/dist/monitor/MonitorLoop.js +1 -1
- package/dist/playbooks/service-build/business-puzzle.js +1 -1
- package/dist/playbooks/service-build/game-theory.d.ts +2 -2
- package/dist/playbooks/service-build/game-theory.js +1 -1
- package/dist/playbooks/service-build/machine-panorama.js +1 -1
- package/dist/playbooks/service-build/merchant-guide.d.ts +54 -11
- package/dist/playbooks/service-build/merchant-guide.js +1 -1
- package/dist/playbooks/service-build/mode-actions.js +1 -1
- package/dist/playbooks/service-build/object-panorama.js +1 -1
- package/dist/playbooks/service-build/participation-radar.js +1 -1
- package/dist/playbooks/service-build/relationship-profile.js +1 -1
- package/dist/playbooks/service-build/reverse-mapping-nk4.spec.d.ts +1 -0
- package/dist/playbooks/service-build/reverse-mapping-nk4.spec.js +1 -0
- package/dist/playbooks/service-build/reverse-mapping.d.ts +24 -0
- package/dist/playbooks/service-build/reverse-mapping.js +1 -1
- package/dist/playbooks/service-build/service-panorama.js +1 -1
- package/dist/playbooks/service-build/service-quote.js +1 -1
- package/dist/playbooks/service-build/workflow-design-assessment.d.ts +2 -2
- package/dist/playbooks/service-build/workflow-design-assessment.js +1 -1
- package/dist/review/index.js +1 -1
- package/dist/safety/confirm-gate.js +1 -1
- package/dist/schema/call/handler.js +1 -1
- package/dist/schema/call/semantic.js +1 -1
- package/dist/schema/call/service.d.ts +14 -0
- package/dist/schema/call/service.js +1 -1
- package/dist/schema/common/index.js +1 -1
- package/dist/schema/goal/planning.js +1 -1
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/operations.d.ts +7 -0
- package/dist/schema/schema-version.js +1 -1
- package/dist/schema-query-impl/index.js +1 -1
- package/dist/schemas/goal_operation.schema.json +1 -1
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/onchain_operations.schema.json +37 -2
- package/dist/schemas/onchain_operations_service.schema.json +37 -2
- package/dist/tools/handlers/benchmark-migration.d.ts +2 -13
- package/dist/tools/handlers/benchmark-migration.js +1 -1
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/industry-pack.js +1 -1
- package/dist/tools/handlers/onchain.js +1 -1
- package/dist/tools/handlers/query.js +1 -1
- package/dist/tools/registry/agent.js +1 -1
- package/dist/tools/wip-deploy-assist.js +1 -1
- package/package.json +2 -2
- package/dist/playbooks/service-build/semantic-graph.d.ts +0 -99
- package/dist/playbooks/service-build/semantic-graph.js +0 -1
|
@@ -160,6 +160,13 @@ export declare const OnchainOperationsSchema: z.ZodPreprocess<z.ZodDiscriminated
|
|
|
160
160
|
transferable: z.ZodBoolean;
|
|
161
161
|
}, z.core.$strict>>;
|
|
162
162
|
discount_destroy: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
163
|
+
discount_send: z.ZodOptional<z.ZodObject<{
|
|
164
|
+
discounts: z.ZodArray<z.ZodString>;
|
|
165
|
+
recipient: z.ZodObject<{
|
|
166
|
+
name_or_address: z.ZodOptional<z.ZodString>;
|
|
167
|
+
local_mark_first: z.ZodOptional<z.ZodBoolean>;
|
|
168
|
+
}, z.core.$strict>;
|
|
169
|
+
}, z.core.$strict>>;
|
|
163
170
|
customer_required: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
164
171
|
order_allocators: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
|
|
165
172
|
description: z.ZodString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a415a from'@wowok/wowok';const SDK_SCHEMA_VERSION=a415a['SCHEMA_VERSION']??'1.0.0',checkSchemaCompatibility=a415a['checkSchemaCompatibility']??((a,b)=>({'compatible':!![]}));export const MCP_SCHEMA_VERSION='1.0.0';export function getSchemaVersions(){return{'sdk':SDK_SCHEMA_VERSION,'mcp':MCP_SCHEMA_VERSION};}export function checkClientSchemaCompatibility(a,b={}){const c=getSchemaVersions(),d={'compatible':!![],'warnings':[],'errors':[],'versions':c,'client_version':a};if(!a)return d;const e=checkSchemaCompatibility(a,c['sdk']);if(!e['compatible']){d['compatible']=![];const g='SDK\x20schema\x20incompatibility:\x20'+e['reason'];b['mode']==='strict'?d['errors']['push'](g):d['warnings']['push'](g);}const f=checkSchemaCompatibility(a,c['mcp']);if(!f['compatible']){d['compatible']=![];const h='MCP\x20schema\x20incompatibility:\x20'+f['reason'];b['mode']==='strict'?d['errors']['push'](h):d['warnings']['push'](h);}return d;}export function attachSchemaWarning(a,b){if(b['warnings']['length']===0x0&&b['errors']['length']===0x0)return a;const c=[];b['warnings']['length']>0x0&&c['push'](...b['warnings']);b['errors']['length']>0x0&&c['push'](...b['errors']);const d=a['semantic']?{...a['semantic'],'warnings':[...a['semantic']['warnings']||[],...c]}:undefined;return{...a,'semantic':d,'schema_warning':{'compatible':b['compatible'],'warnings':c,'client_version':b['client_version'],'server_versions':b['versions']}};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync,existsSync,writeFileSync,mkdirSync}from'fs';import{resolve,join,dirname}from'path';import{fileURLToPath}from'url';import{TOOLS_REFERENCE,getToolReference,searchToolReference,getToolSequence}from'../knowledge/tools-reference.js';import{GUARD_DESIGN_PATTERNS,getGuardDesignPattern,GUARD_DESIGN_PATTERNS_VERSION,GUARD_SCHEMA_NOTES}from'../knowledge/guard-design-patterns.js';import{OBJECT_REUSE_RULES,CREATE_VS_MODIFY_PATTERN,IMMUTABILITY_RULES,OPERATION_TYPE_CLASSIFICATION,OPERATION_CLASS_META,NAMING_CONVENTIONS,SAFETY_RULES_VERSION}from'../knowledge/safety-rules.js';import{listTemplates as a425a,getTemplateDetail,instantiateTemplate,getTemplateCounts,TEMPLATE_OBJECT_TYPES}from'../knowledge/template-registry.js';import{lintGuard,formatLintResult}from'../knowledge/guard-lint.js';import{renderGuardTreeIndented,renderGuardMermaid,walkGuardTree}from'../knowledge/guard-render.js';import{getGuardQueryByIdOrName}from'../schema/utils/guard-query-utils.js';const __filename=fileURLToPath(import.meta.url),__dirname=fileURLToPath(new URL('.',import.meta.url)),SCHEMAS_DIR=resolve(__dirname,'../../dist/schemas'),GUARD_TEMPLATES_PATH_SCRIPTS=resolve(__dirname,'../../scripts/guard-templates.json'),GUARD_TEMPLATES_PATH_DIST=resolve(__dirname,'../../dist/schemas/guard-templates.json'),GUARD_TEMPLATES_PATH=existsSync(GUARD_TEMPLATES_PATH_SCRIPTS)?GUARD_TEMPLATES_PATH_SCRIPTS:GUARD_TEMPLATES_PATH_DIST,WORKSPACE_TMP_DIR=resolve(process['cwd'](),'.trae','tmp');export function areSchemasAvailable(){return existsSync(SCHEMAS_DIR)&&existsSync(join(SCHEMAS_DIR,'index.json'));}export function getSchemaIndex(){try{const a=join(SCHEMAS_DIR,'index.json');if(!existsSync(a))return null;const b=readFileSync(a,'utf-8');return JSON['parse'](b);}catch{return null;}}export function listSchemas(){const a=getSchemaIndex();if(!a)return[];return[...a['tools']||[],...a['operations']||[]];}export function getSchema(a){try{let b=join(SCHEMAS_DIR,a+'.schema.json');!existsSync(b)&&(b=join(SCHEMAS_DIR,a+'.json'));if(!existsSync(b))return null;const c=readFileSync(b,'utf-8'),d=JSON['parse'](c);return resolveSchemaRefs(d);}catch{return null;}}export function getOutputSchema(a){try{const b=join(SCHEMAS_DIR,a+'.output.json');if(!existsSync(b))return null;const c=readFileSync(b,'utf-8'),d=JSON['parse'](c);return resolveSchemaRefs(d);}catch{return null;}}export function getGuardTemplates(a){try{if(!existsSync(GUARD_TEMPLATES_PATH))return null;const b=readFileSync(GUARD_TEMPLATES_PATH,'utf-8'),c=JSON['parse'](b);if(!a)return{'version':c['version'],'description':c['description'],'templates':(c['templates']||[])['map'](e=>({'name':e['name'],'title':e['title'],'description':e['description'],'use_case':e['use_case']})),'query_reference':c['query_reference'],'node_return_types':c['node_return_types']};const d=(c['templates']||[])['find'](e=>e['name']===a);if(!d)return null;return d;}catch{return null;}}export function getSchemaField(a,b){const c=getSchema(a);if(!c)return null;const d=b['split']('.')['filter'](Boolean);let e=c;for(const f of d){if(!e||typeof e!=='object')return null;if(e['properties']&&f in e['properties']){e=e['properties'][f];continue;}if(e['items']&&typeof e['items']==='object'){if(/^\d+$/['test'](f)){e=e['items'];continue;}if(e['items']['properties']&&f in e['items']['properties']){e=e['items']['properties'][f];continue;}}if(Array['isArray'](e['oneOf'])||Array['isArray'](e['anyOf'])){const g=e['oneOf']??e['anyOf'];for(const h of g){if(h&&typeof h==='object'&&h['properties']&&f in h['properties']){e=h['properties'][f];break;}}continue;}if(f in e){e=e[f];continue;}return null;}return e;}function resolveSchemaRefs(a,b=new Set()){if(!a||typeof a!=='object')return a;if(Array['isArray'](a))return a['map'](d=>resolveSchemaRefs(d,b));const c={};for(const [d,e]of Object['entries'](a)){if(d==='$ref'&&typeof e==='string'){if(e['startsWith']('#'))c[d]=e;else{const f=loadRefSchema(e,b);f&&Object['assign'](c,resolveSchemaRefs(f,b));}}else typeof e==='object'?c[d]=resolveSchemaRefs(e,b):c[d]=e;}return c;}function loadRefSchema(a,b){if(a['startsWith']('#'))return null;if(b['has'](a))return{'description':'Circular\x20reference\x20to\x20'+a};b['add'](a);try{const c=join(SCHEMAS_DIR,a);if(!existsSync(c))return null;const d=readFileSync(c,'utf-8');return JSON['parse'](d);}catch{return null;}}export function searchSchemas(a){const b=listSchemas(),c=a['toLowerCase']();return b['filter'](d=>{const e=d['name']['toLowerCase']()['includes'](c),f=d['title']?.['toLowerCase']()['includes'](c),g=d['description']?.['toLowerCase']()['includes'](c);return e||f||g;});}export function listOperations(){const a=getSchemaIndex();if(!a)return[];return(a['operations']||[])['filter'](b=>b['name']['startsWith']('onchain_operations_'));}function writeResponseToFile(a,b){try{let c;if(b)c=resolve(process['cwd'](),b);else{!existsSync(WORKSPACE_TMP_DIR)&&mkdirSync(WORKSPACE_TMP_DIR,{'recursive':!![]});const g=Date['now']();c=join(WORKSPACE_TMP_DIR,'schema-'+g+'.json');}const d=dirname(c);!existsSync(d)&&mkdirSync(d,{'recursive':!![]});const f=typeof a==='string'?a:JSON['stringify'](a,null,0x2);return writeFileSync(c,f,'utf-8'),c;}catch(h){return null;}}const INLINE_CHAR_LIMIT=0x20*0x400,AUTO_OVERFLOW_DIR='.wowok/tmp';function unionVariantLabel(a){if(!a||typeof a!=='object')return'variant';const b=a['properties']&&typeof a['properties']==='object'?a['properties']:undefined;if(b)for(const [c,d]of Object['entries'](b)){if(d&&typeof d==='object'&&d['const']!==undefined)return c+'='+String(d['const']);}return typeof a['title']==='string'?a['title']:'variant';}export function buildSchemaSummary(a){const b=[];a&&typeof a['title']==='string'&&b['push']('Title:\x20'+a['title']);const c=a&&typeof a==='object'?a['properties']:undefined;if(c&&typeof c==='object'&&!Array['isArray'](c)){const d=Array['isArray'](a['required'])?a['required']:[],e=Object['keys'](c);b['push']('Top-level\x20fields\x20('+e['length']+',\x20*\x20=\x20required):');for(const f of e['slice'](0x0,0x28)){const g=c[f]??{},h=Array['isArray'](g['type'])?g['type']['join']('|'):g['type']??(g['$ref']?'ref':g['anyOf']||g['oneOf']?'union':'any'),i=d['includes'](f)?'*':'',j=typeof g['description']==='string'&&g['description']['length']>0x0?'\x20—\x20'+g['description']['split']('\x0a')[0x0]['slice'](0x0,0x50):'';b['push']('\x20\x20-\x20'+f+i+':\x20'+h+j);}e['length']>0x28&&b['push']('\x20\x20-\x20...and\x20'+(e['length']-0x28)+'\x20more\x20—\x20use\x20action=\x27get_field\x27\x20with\x20field_path\x20to\x20inspect');}else{if(a&&(Array['isArray'](a['oneOf'])||Array['isArray'](a['anyOf']))){const k=a['oneOf']??a['anyOf'];b['push']('Union\x20of\x20'+k['length']+'\x20variants:');for(const m of k['slice'](0x0,0x28)){const o=m&&typeof m['description']==='string'&&m['description']['length']>0x0?'\x20—\x20'+m['description']['split']('\x0a')[0x0]['slice'](0x0,0x50):'';b['push']('\x20\x20-\x20'+unionVariantLabel(m)+o);}k['length']>0x28&&b['push']('\x20\x20-\x20...and\x20'+(k['length']-0x28)+'\x20more');const l=k['filter'](q=>q&&typeof q==='object'&&q['properties']&&typeof q['properties']==='object');if(l['length']===k['length']&&l['length']>0x0){const q=Object['keys'](l[0x0]['properties'])['filter'](r=>l['every'](s=>Object['prototype']['hasOwnProperty']['call'](s['properties'],r)));b['push'](q['length']>0x0?'Common\x20fields\x20(declared\x20by\x20ALL\x20'+l['length']+'\x20variants):\x20'+q['join'](',\x20')+'.':'No\x20field\x20is\x20declared\x20by\x20all\x20'+l['length']+'\x20variants\x20—\x20each\x20variant\x20takes\x20its\x20own\x20parameters.');}else b['push']('Field\x20names\x20differ\x20per\x20variant\x20—\x20read\x20the\x20variant\x27s\x20own\x20list\x20above.\x20'+'The\x20discriminator\x20(\x22operation\x22\x20and\x20friends)\x20is\x20the\x20only\x20shared\x20key.');for(const r of k['slice'](0x0,0x28)){const s=r&&typeof r==='object'&&r['properties']&&typeof r['properties']==='object'?Object['keys'](r['properties']):[];if(s['length']===0x0)continue;b['push']('\x20\x20\x20\x20'+unionVariantLabel(r)+'\x20fields:\x20'+s['join'](',\x20'));}b['push']('Drill\x20into\x20the\x20variant\x20you\x20need\x20with\x20action=\x27get_field\x27\x20(name\x20+\x20field_path)\x20—\x20the\x20lists\x20above\x20are\x20a\x20summary,\x20not\x20the\x20schema.');}else b['push']('No\x20top-level\x20properties\x20map\x20—\x20use\x20action=\x27get_field\x27\x20with\x20a\x20field_path\x20to\x20inspect\x20this\x20schema.');}return b['join']('\x0a');}export function autoOverflowToFile(a,b){try{const c=JSON['stringify'](a)['length'];if(c<=INLINE_CHAR_LIMIT)return null;const d=process['env']['WOWOK_SCHEMA_TMP_DIR'],e=d?resolve(d):resolve(process['cwd'](),AUTO_OVERFLOW_DIR);!existsSync(e)&&mkdirSync(e,{'recursive':!![]});const f=b['replace'](/[^a-zA-Z0-9_-]/g,'_'),g=f+'.schema.json',h=join(e,g);return writeFileSync(h,JSON['stringify'](a,null,0x2),'utf-8'),{'absolute_path':h,'relative_path':d?h:join(AUTO_OVERFLOW_DIR,g),'bytes':c,'summary':buildSchemaSummary(a)};}catch{return null;}}export function processSchemaQuery(a){const {action:b,name:c,query:d,field_path:f,template:g,output_file:h,object_type:i,params:j}=a;if(b==='get_guard_templates'){const k=getGuardTemplates(g);if(!k)return{'success':![],'action':b,'data':null,'message':g?'Guard\x20template\x20\x27'+g+'\x27\x20not\x20found.\x20Omit\x20\x27template\x27\x20to\x20list\x20all\x20available\x20templates.':'Guard\x20templates\x20file\x20not\x20found.\x20Ensure\x20scripts/guard-templates.json\x20exists.','suggestions':['Omit\x20\x27template\x27\x20to\x20list\x20all\x20available\x20templates.','Available\x20template\x20names:\x20signer_verification,\x20progress_node_check,\x20order_owner_verification,\x20service_belonging_check,\x20reward_not_claimed,\x20combined_reward_guard']};if(h){const l=writeResponseToFile(k,h);if(l)return{'success':!![],'action':b,'data':null,'message':'Guard\x20template'+(g?'\x20\x27'+g+'\x27':'s')+'\x20written\x20to\x20file:\x20'+l,'output_file_path':l,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+l]};}return{'success':!![],'action':b,'data':k,'message':g?'Retrieved\x20Guard\x20template:\x20'+g:'Retrieved\x20'+(Array['isArray'](k['templates'])?k['templates']['length']:0x0)+'\x20Guard\x20templates'};}if(b==='get_templates'){if(!g){const p=a425a(i),q=getTemplateCounts(),r={'total':p['length'],'filter':i??null,'counts_by_object_type':q,'templates':p};if(h){const s=writeResponseToFile(r,h);if(s)return{'success':!![],'action':b,'data':null,'message':p['length']+'\x20templates\x20written\x20to\x20file:\x20'+s,'output_file_path':s,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+s]};}return{'success':!![],'action':b,'data':r,'message':p['length']+'\x20template(s)'+(i?'\x20for\x20object_type=\x27'+i+'\x27':'')+'\x20'+('(total\x20registry:\x20'+Object['values'](q)['reduce']((t,u)=>t+u,0x0)+'\x20across\x20'+TEMPLATE_OBJECT_TYPES['length']+'\x20object\x20types).\x20')+'Provide\x20\x27template\x27\x20(id)\x20for\x20full\x20detail;\x20add\x20\x27params\x27\x20(JSON\x20string)\x20to\x20instantiate.'};}if(!j){const t=getTemplateDetail(g);if(!t)return{'success':![],'action':b,'data':null,'message':'Template\x20\x27'+g+'\x27\x20not\x20found\x20in\x20the\x20unified\x20registry.','suggestions':['Omit\x20\x27template\x27\x20to\x20list\x20all\x20template\x20metadata\x20(id\x20+\x20object_type\x20+\x20parameters).','Filter\x20by\x20object_type:\x20'+TEMPLATE_OBJECT_TYPES['join'](',\x20')]};if(h){const u=writeResponseToFile(t,h);if(u)return{'success':!![],'action':b,'data':null,'message':'Template\x20\x27'+g+'\x27\x20detail\x20written\x20to\x20file:\x20'+u,'output_file_path':u,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+u]};}return{'success':!![],'action':b,'data':t,'message':'Template\x20\x27'+g+'\x27\x20('+t['object_type']+',\x20'+(t['instantiable']?'instantiable':'guidance-only')+').\x20'+'To\x20instantiate,\x20call\x20again\x20with\x20\x27params\x27\x20=\x20JSON\x20object\x20of\x20the\x20declared\x20parameters.'};}let m;try{const v=JSON['parse'](j);if(!v||typeof v!=='object'||Array['isArray'](v))return{'success':![],'action':b,'data':null,'message':'\x27params\x27\x20must\x20be\x20a\x20JSON\x20object\x20(e.g.\x20\x27{\x22key\x22:\x22value\x22}\x27),\x20got\x20'+(Array['isArray'](v)?'array':typeof v)+'.'};m=v;}catch(w){return{'success':![],'action':b,'data':null,'message':'Failed\x20to\x20parse\x20\x27params\x27\x20as\x20JSON:\x20'+(w instanceof Error?w['message']:String(w)),'suggestions':['Example:\x20params=\x27{\x22whitelist\x22:[\x220xabc...\x22]}\x27']};}const n=instantiateTemplate(g,m);if(!n['ok'])return{'success':![],'action':b,'data':n['guidance']!==undefined?{'guidance':n['guidance']}:null,'message':'Instantiation\x20failed\x20for\x20\x27'+g+'\x27:\x20'+n['error'],'suggestions':n['missing_params']?['Missing\x20required\x20params:\x20'+n['missing_params']['join'](',\x20'),'Call\x20with\x20\x27template\x27\x20only\x20(no\x20\x27params\x27)\x20to\x20see\x20full\x20parameter\x20declarations.']:['Call\x20with\x20\x27template\x27\x20only\x20(no\x20\x27params\x27)\x20to\x20see\x20full\x20parameter\x20declarations.']};const o={'object_type':n['object_type'],'template_id':n['template_id'],'body':n['body'],...n['notes']?{'notes':n['notes']}:{}};if(h){const x=writeResponseToFile(o,h);if(x)return{'success':!![],'action':b,'data':null,'message':'Instantiated\x20template\x20\x27'+g+'\x27\x20written\x20to\x20file:\x20'+x,'output_file_path':x,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+x]};}return{'success':!![],'action':b,'data':o,'message':'Instantiated\x20\x27'+g+'\x27\x20('+n['object_type']+').\x20'+'Review\x20the\x20body\x20against\x20the\x20onchain_operations\x20schema\x20before\x20submitting.'};}if(b==='get_tool_reference'){if(c){const z=getToolReference(c);if(!z)return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20not\x20found\x20in\x20the\x20tool\x20reference.','suggestions':['Omit\x20\x27name\x27\x20to\x20list\x20all\x20tools.','Available\x20tools:\x20'+TOOLS_REFERENCE['map'](B=>B['name'])['join'](',\x20')]};const A=getToolSequence(c);return{'success':!![],'action':b,'data':{'tool':z,'call_sequence':A??null},'message':'Retrieved\x20tool\x20reference:\x20'+c};}if(d){const B=searchToolReference(d);return{'success':!![],'action':b,'data':{'tools':B,'count':B['length']},'message':'Found\x20'+B['length']+'\x20tool(s)\x20matching\x20\x27'+d+'\x27','suggestions':B['length']===0x0?['Try\x20a\x20broader\x20keyword\x20(e.g.\x20\x27onchain\x27,\x20\x27guard\x27,\x20\x27schema\x27),\x20or\x20omit\x20\x27query\x27\x20to\x20list\x20all\x20tools.']:undefined};}const y=TOOLS_REFERENCE['map'](C=>({'name':C['name'],'summary':C['summary'],'actions':C['actions']??[],'notes':C['notes']??[]}));return{'success':!![],'action':b,'data':{'tools':y,'count':y['length']},'message':'Retrieved\x20reference\x20for\x20'+y['length']+'\x20MCP\x20tools.\x20Pass\x20name=\x27<tool>\x27\x20for\x20full\x20detail\x20(params,\x20prerequisites,\x20follow-ups).'};}if(b==='get_guard_design_patterns'){if(c){const D=getGuardDesignPattern(c);if(!D)return{'success':![],'action':b,'data':null,'message':'Guard\x20design\x20pattern\x20\x27'+c+'\x27\x20not\x20found.','suggestions':['Omit\x20\x27name\x27\x20to\x20list\x20the\x20full\x20catalog.','Available\x20pattern\x20ids:\x20'+GUARD_DESIGN_PATTERNS['map'](E=>E['id'])['join'](',\x20')]};return{'success':!![],'action':b,'data':{'pattern':D},'message':'Retrieved\x20Guard\x20design\x20pattern:\x20'+c};}if(d){const E=GUARD_DESIGN_PATTERNS['filter'](G=>G['host']===d),F=E['length']>0x0?E:GUARD_DESIGN_PATTERNS['filter'](G=>G['business_requirement']['toLowerCase']()['includes'](d['toLowerCase']())||G['logic_summary']['toLowerCase']()['includes'](d['toLowerCase']()));return{'success':!![],'action':b,'data':{'patterns':F,'count':F['length'],'filtered_by':E['length']>0x0?'host':'keyword','schema_notes':GUARD_SCHEMA_NOTES},'message':'Found\x20'+F['length']+'\x20Guard\x20design\x20pattern(s)\x20matching\x20\x27'+d+'\x27','suggestions':F['length']===0x0?['Filter\x20by\x20host:\x20service_buy_guard,\x20service_allocator_guard,\x20machine_forward,\x20progress_submission,\x20reward_claim,\x20repository_write,\x20arbitration_usage,\x20arbitration_voting,\x20gen_passport']:undefined};}const C=GUARD_DESIGN_PATTERNS['map'](G=>({'id':G['id'],'business_requirement':G['business_requirement'],'host':G['host'],'data_source':G['data_source'],'verifier_level':G['verifier_level'],'logic_summary':G['logic_summary'],'key_queries':G['key_queries'],'notes':G['notes']??[]}));return{'success':!![],'action':b,'data':{'patterns':C,'count':C['length'],'version':GUARD_DESIGN_PATTERNS_VERSION,'schema_notes':GUARD_SCHEMA_NOTES},'message':'Retrieved\x20'+C['length']+'\x20Guard\x20design\x20patterns.\x20Pass\x20name=\x27<pattern_id>\x27\x20for\x20full\x20detail\x20(witness\x20types,\x20mitigated\x20risks,\x20industries).'};}if(b==='get_safety_rules')return{'success':!![],'action':b,'data':{'version':SAFETY_RULES_VERSION,'object_reuse_rules':OBJECT_REUSE_RULES,'create_vs_modify_pattern':CREATE_VS_MODIFY_PATTERN,'immutability_rules':IMMUTABILITY_RULES,'operation_type_classification':OPERATION_TYPE_CLASSIFICATION,'operation_class_meta':OPERATION_CLASS_META,'naming_conventions':NAMING_CONVENTIONS},'message':'Retrieved\x20safety\x20rule\x20tables\x20(reuse\x20/\x20immutability\x20/\x20operation\x20classification\x20/\x20naming).\x20'+'Key\x20points:\x20prefer\x20REUSING\x20existing\x20objects\x20(string\x20reference\x20=\x20reuse,\x20object\x20shape\x20=\x20create);\x20'+'Machine\x20publish\x20locks\x20nodes/pairs/forwards,\x20Service\x20publish\x20locks\x20machine/order_allocators/arbitrations\x20(sales\x20stays\x20mutable);\x20'+'Guard\x20is\x20CREATE-only\x20immutable;\x20on-chain\x20writes\x20require\x20explicit\x20user\x20confirmation.'};if(!areSchemasAvailable())return{'success':![],'action':b,'data':null,'message':'Schema\x20files\x20are\x20not\x20available.\x20Please\x20run\x20\x27npm\x20run\x20generate:schemas\x27\x20first.','suggestions':['Run\x20\x27npm\x20run\x20generate:schemas\x27\x20to\x20generate\x20schema\x20files','Ensure\x20the\x20dist/schemas\x20directory\x20exists']};switch(b){case'list':{const G=listSchemas();return{'success':!![],'action':b,'data':G,'message':'Found\x20'+G['length']+'\x20available\x20schemas'};}case'get':{if(!c)return{'success':![],'action':b,'data':null,'message':'Schema\x20name\x20is\x20required\x20for\x20\x27get\x27\x20action','suggestions':['Provide\x20a\x20schema\x20name','Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20schemas']};const H=getSchema(c);if(!H){const J=searchSchemas(c)['slice'](0x0,0x5);return{'success':![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20not\x20found','suggestions':J['length']>0x0?J['map'](K=>'Did\x20you\x20mean:\x20'+K['name']+'?'):['Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20schemas']};}if(h){const K=writeResponseToFile(H,h);if(K)return{'success':!![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20written\x20to\x20file:\x20'+K,'output_file_path':K,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+K]};}const I=autoOverflowToFile(H,c);if(I)return{'success':!![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20is\x20large\x20('+Math['round'](I['bytes']/0x400)+'\x20KB)\x20—\x20'+'written\x20to\x20file\x20instead\x20of\x20inlining\x20to\x20protect\x20your\x20context.','output_file_path':I['absolute_path'],'inline_summary':I['summary'],'suggestions':['Read\x20the\x20full\x20file\x20with\x20the\x20Read\x20tool:\x20'+I['absolute_path'],'If\x20the\x20sandbox\x20blocks\x20that\x20path,\x20resolve\x20the\x20relative\x20path\x20\x27'+I['relative_path']+'\x27\x20against\x20the\x20workspace\x20root\x20and\x20read\x20that.','Without\x20file\x20access,\x20query\x20specific\x20fields\x20via\x20action=\x27get_field\x27\x20with\x20name=\x27'+c+'\x27\x20and\x20a\x20field_path\x20from\x20the\x20summary\x20below.']};return{'success':!![],'action':b,'data':H,'message':'Retrieved\x20schema:\x20'+c};}case'get_field':{if(!c||!f)return{'success':![],'action':b,'data':null,'message':'Both\x20\x27name\x27\x20and\x20\x27field_path\x27\x20are\x20required\x20for\x20\x27get_field\x27\x20action','suggestions':['Example:\x20{action:\x20\x27get_field\x27,\x20name:\x20\x27onchain_operations_machine\x27,\x20field_path:\x20\x27data.node\x27}','Use\x20\x27get\x27\x20action\x20to\x20retrieve\x20the\x20full\x20schema']};const L=getSchemaField(c,f);if(!L)return{'success':![],'action':b,'data':null,'message':'Field\x20path\x20\x27'+f+'\x27\x20not\x20found\x20in\x20schema\x20\x27'+c+'\x27','suggestions':['Check\x20the\x20field\x20path\x20(dot-separated,\x20e.g.\x20\x27data.node\x27)','Use\x20\x27get\x27\x20action\x20to\x20see\x20the\x20full\x20schema\x20structure']};return{'success':!![],'action':b,'data':L,'message':'Retrieved\x20field\x20\x27'+f+'\x27\x20from\x20schema\x20\x27'+c+'\x27'};}case'search':{if(!d)return{'success':![],'action':b,'data':null,'message':'Search\x20query\x20is\x20required\x20for\x20\x27search\x27\x20action'};const M=searchSchemas(d);return{'success':!![],'action':b,'data':M,'message':'Found\x20'+M['length']+'\x20schemas\x20matching\x20\x27'+d+'\x27'};}case'list_operations':{const N=listOperations();return{'success':!![],'action':b,'data':N,'message':'Found\x20'+N['length']+'\x20on-chain\x20operations'};}case'get_output':{if(!c)return{'success':![],'action':b,'data':null,'message':'Tool\x20name\x20is\x20required\x20for\x20\x27get_output\x27\x20action','suggestions':['Provide\x20a\x20tool\x20name','Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20tools\x20and\x20their\x20outputPath']};const O=getOutputSchema(c);if(!O){const Q=listSchemas(),R=Q['find'](T=>T['name']===c);if(R)return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20exists\x20but\x20has\x20no\x20output\x20schema\x20file.\x20The\x20tool\x20may\x20not\x20declare\x20an\x20outputSchema,\x20or\x20the\x20schema\x20file\x20was\x20not\x20generated.','suggestions':['Use\x20\x27get\x27\x20action\x20with\x20name=\x27'+c+'\x27\x20to\x20retrieve\x20its\x20input\x20schema']};const S=searchSchemas(c)['slice'](0x0,0x5);return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20not\x20found','suggestions':S['length']>0x0?S['map'](T=>'Did\x20you\x20mean:\x20'+T['name']+'?'):['Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20tools']};}if(h){const T=writeResponseToFile(O,h);if(T)return{'success':!![],'action':b,'data':null,'message':'Output\x20schema\x20\x27'+c+'\x27\x20written\x20to\x20file:\x20'+T,'output_file_path':T,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+T]};}const P=autoOverflowToFile(O,c);if(P)return{'success':!![],'action':b,'data':null,'message':'Output\x20schema\x20\x27'+c+'\x27\x20is\x20large\x20('+Math['round'](P['bytes']/0x400)+'\x20KB)\x20—\x20'+'written\x20to\x20file\x20instead\x20of\x20inlining\x20to\x20protect\x20your\x20context.','output_file_path':P['absolute_path'],'inline_summary':P['summary'],'suggestions':['Read\x20the\x20full\x20file\x20with\x20the\x20Read\x20tool:\x20'+P['absolute_path'],'If\x20the\x20sandbox\x20blocks\x20that\x20path,\x20resolve\x20the\x20relative\x20path\x20\x27'+P['relative_path']+'\x27\x20against\x20the\x20workspace\x20root\x20and\x20read\x20that.','Without\x20file\x20access,\x20query\x20specific\x20fields\x20via\x20action=\x27get_field\x27\x20with\x20name=\x27'+c+'\x27\x20and\x20a\x20field_path\x20from\x20the\x20summary\x20below.']};return{'success':!![],'action':b,'data':O,'message':'Retrieved\x20output\x20schema:\x20'+c};}default:return{'success':![],'action':b,'data':null,'message':'Unknown\x20action:\x20'+b,'suggestions':['Use\x20\x27list\x27,\x20\x27get\x27,\x20\x27get_field\x27,\x20\x27get_output\x27,\x20\x27search\x27,\x20\x27list_operations\x27,\x20\x27get_guard_templates\x27,\x20\x27get_tool_reference\x27,\x20\x27get_guard_design_patterns\x27,\x20\x27get_safety_rules\x27,\x20\x27get_templates\x27,\x20or\x20\x27analyze_guard_semantics\x27']};}}const GUARD_SEMANTICS_READING_CHECKLIST=['WHO\x20can\x20satisfy\x20this\x20Guard\x20(identity:\x20Signer\x20bindings,\x20Entity\x20membership,\x20allowlists)?','WHEN\x20can\x20it\x20be\x20satisfied\x20(time:\x20Clock\x20comparisons,\x20deadlines,\x20windows)?','WHAT\x20evidence\x20must\x20the\x20caller\x20submit\x20(b_submission\x20table\x20entries\x20—\x20Payment/Order/Proof\x20objects)?','WHICH\x20on-chain\x20data\x20does\x20it\x20read,\x20and\x20can\x20that\x20data\x20change\x20(Repository\x20entries\x20are\x20MUTABLE\x20—\x20who\x20controls\x20the\x20writes)?','WHAT\x20does\x20the\x20counterparty\x20gain/lose\x20in\x20each\x20branch\x20of\x20the\x20logic\x20tree?','ARE\x20there\x20error-level\x20diagnostics\x20or\x20critical\x20risks\x20(they\x20block\x20or\x20endanger\x20execution)?'];export async function analyzeGuardSemantics(a){const b=await lintGuard(a,{'auto_fix':![]}),c={'root':a['root'],'table':(a['table']??[])['map'](k=>({'identifier':k['identifier'],'name':k['name'],'value_type':k['value_type']??'Address','b_submission':k['b_submission']??![],'value':k['value']})),'guardName':a['description']??null,'rely':a['rely']??null},d=renderGuardTreeIndented(c),e=renderGuardMermaid(a['root']),f=new Set(),g=[];let h=![],i=![];walkGuardTree(a['root'],k=>{if(k['type']==='context'){if(k['context']==='Clock')h=!![];if(k['context']==='Signer')i=!![];}if(k['type']==='query'&&k['query']!==undefined&&k['query']!==null){if(typeof k['query']==='number'){const l=getGuardQueryByIdOrName(k['query']);if(l)f['add'](l['id']);else g['push'](k['query']);}else{const m=getGuardQueryByIdOrName(k['query']);if(m)f['add'](m['id']);else g['push'](k['query']);}}});const j={'submission_requirements':(a['table']??[])['filter'](k=>k['b_submission']===!![])['map'](k=>({'identifier':k['identifier'],'value_type':k['value_type'],'object_type':k['object_type'],'name':k['name']})),'data_sources':(a['table']??[])['filter'](k=>k['b_submission']!==!![])['map'](k=>({'identifier':k['identifier'],'kind':k['is_system_address']?'system_address':k['object_type']?'object':'fixed_value','value_type':k['value_type'],'object_type':k['object_type'],'name':k['name'],'is_mutable_onchain':k['object_type']==='Repository'})),'query_dependencies':[...f]['sort']((k,l)=>k-l),'unresolved_queries':g,'has_time_conditions':h,'has_signer_constraints':i,'has_rely_composition':Array['isArray'](a['rely']?.['guards'])&&a['rely']['guards']['length']>0x0,'reading_checklist':GUARD_SEMANTICS_READING_CHECKLIST};return{'render':{'tree_indented':d,'mermaid':e},'lint':b,'party_evaluation':j};}export{formatLintResult};
|
|
1
|
+
import{readFileSync,existsSync,writeFileSync,mkdirSync}from'fs';import{resolve,join,dirname}from'path';import{fileURLToPath}from'url';import{TOOLS_REFERENCE,getToolReference,searchToolReference,getToolSequence}from'../knowledge/tools-reference.js';import{GUARD_DESIGN_PATTERNS,getGuardDesignPattern,GUARD_DESIGN_PATTERNS_VERSION,GUARD_SCHEMA_NOTES}from'../knowledge/guard-design-patterns.js';import{OBJECT_REUSE_RULES,CREATE_VS_MODIFY_PATTERN,IMMUTABILITY_RULES,OPERATION_TYPE_CLASSIFICATION,OPERATION_CLASS_META,NAMING_CONVENTIONS,SAFETY_RULES_VERSION}from'../knowledge/safety-rules.js';import{listTemplates as a427a,getTemplateDetail,instantiateTemplate,getTemplateCounts,TEMPLATE_OBJECT_TYPES}from'../knowledge/template-registry.js';import{lintGuard,formatLintResult}from'../knowledge/guard-lint.js';import{renderGuardTreeIndented,renderGuardMermaid,walkGuardTree}from'../knowledge/guard-render.js';import{getGuardQueryByIdOrName}from'../schema/utils/guard-query-utils.js';const __filename=fileURLToPath(import.meta.url),__dirname=fileURLToPath(new URL('.',import.meta.url)),SCHEMAS_DIR=resolve(__dirname,'../../dist/schemas'),GUARD_TEMPLATES_PATH_SCRIPTS=resolve(__dirname,'../../scripts/guard-templates.json'),GUARD_TEMPLATES_PATH_DIST=resolve(__dirname,'../../dist/schemas/guard-templates.json'),GUARD_TEMPLATES_PATH=existsSync(GUARD_TEMPLATES_PATH_SCRIPTS)?GUARD_TEMPLATES_PATH_SCRIPTS:GUARD_TEMPLATES_PATH_DIST,WORKSPACE_TMP_DIR=resolve(process['cwd'](),'.trae','tmp');export function areSchemasAvailable(){return existsSync(SCHEMAS_DIR)&&existsSync(join(SCHEMAS_DIR,'index.json'));}export function getSchemaIndex(){try{const a=join(SCHEMAS_DIR,'index.json');if(!existsSync(a))return null;const b=readFileSync(a,'utf-8');return JSON['parse'](b);}catch{return null;}}export function listSchemas(){const a=getSchemaIndex();if(!a)return[];return[...a['tools']||[],...a['operations']||[]];}export function getSchema(a){try{let b=join(SCHEMAS_DIR,a+'.schema.json');!existsSync(b)&&(b=join(SCHEMAS_DIR,a+'.json'));if(!existsSync(b))return null;const c=readFileSync(b,'utf-8'),d=JSON['parse'](c);return resolveSchemaRefs(d);}catch{return null;}}export function getOutputSchema(a){try{const b=join(SCHEMAS_DIR,a+'.output.json');if(!existsSync(b))return null;const c=readFileSync(b,'utf-8'),d=JSON['parse'](c);return resolveSchemaRefs(d);}catch{return null;}}export function getGuardTemplates(a){try{if(!existsSync(GUARD_TEMPLATES_PATH))return null;const b=readFileSync(GUARD_TEMPLATES_PATH,'utf-8'),c=JSON['parse'](b);if(!a)return{'version':c['version'],'description':c['description'],'templates':(c['templates']||[])['map'](e=>({'name':e['name'],'title':e['title'],'description':e['description'],'use_case':e['use_case']})),'query_reference':c['query_reference'],'node_return_types':c['node_return_types']};const d=(c['templates']||[])['find'](e=>e['name']===a);if(!d)return null;return d;}catch{return null;}}export function getSchemaField(a,b){const c=getSchema(a);if(!c)return null;const d=b['split']('.')['filter'](Boolean);let e=c;for(const f of d){if(!e||typeof e!=='object')return null;if(e['properties']&&f in e['properties']){e=e['properties'][f];continue;}if(e['items']&&typeof e['items']==='object'){if(/^\d+$/['test'](f)){e=e['items'];continue;}if(e['items']['properties']&&f in e['items']['properties']){e=e['items']['properties'][f];continue;}}if(Array['isArray'](e['oneOf'])||Array['isArray'](e['anyOf'])){const g=e['oneOf']??e['anyOf'];for(const h of g){if(h&&typeof h==='object'&&h['properties']&&f in h['properties']){e=h['properties'][f];break;}}continue;}if(f in e){e=e[f];continue;}return null;}return e;}function resolveSchemaRefs(a,b=new Set()){if(!a||typeof a!=='object')return a;if(Array['isArray'](a))return a['map'](d=>resolveSchemaRefs(d,b));const c={};for(const [d,e]of Object['entries'](a)){if(d==='$ref'&&typeof e==='string'){if(e['startsWith']('#'))c[d]=e;else{const f=loadRefSchema(e,b);f&&Object['assign'](c,resolveSchemaRefs(f,b));}}else typeof e==='object'?c[d]=resolveSchemaRefs(e,b):c[d]=e;}return c;}function loadRefSchema(a,b){if(a['startsWith']('#'))return null;if(b['has'](a))return{'description':'Circular\x20reference\x20to\x20'+a};b['add'](a);try{const c=join(SCHEMAS_DIR,a);if(!existsSync(c))return null;const d=readFileSync(c,'utf-8');return JSON['parse'](d);}catch{return null;}}export function searchSchemas(a){const b=listSchemas(),c=a['toLowerCase']();return b['filter'](d=>{const e=d['name']['toLowerCase']()['includes'](c),f=d['title']?.['toLowerCase']()['includes'](c),g=d['description']?.['toLowerCase']()['includes'](c);return e||f||g;});}export function listOperations(){const a=getSchemaIndex();if(!a)return[];return(a['operations']||[])['filter'](b=>b['name']['startsWith']('onchain_operations_'));}function writeResponseToFile(a,b){try{let c;if(b)c=resolve(process['cwd'](),b);else{!existsSync(WORKSPACE_TMP_DIR)&&mkdirSync(WORKSPACE_TMP_DIR,{'recursive':!![]});const g=Date['now']();c=join(WORKSPACE_TMP_DIR,'schema-'+g+'.json');}const d=dirname(c);!existsSync(d)&&mkdirSync(d,{'recursive':!![]});const f=typeof a==='string'?a:JSON['stringify'](a,null,0x2);return writeFileSync(c,f,'utf-8'),c;}catch(h){return null;}}const INLINE_CHAR_LIMIT=0x20*0x400,AUTO_OVERFLOW_DIR='.wowok/tmp';function unionVariantLabel(a){if(!a||typeof a!=='object')return'variant';const b=a['properties']&&typeof a['properties']==='object'?a['properties']:undefined;if(b)for(const [c,d]of Object['entries'](b)){if(d&&typeof d==='object'&&d['const']!==undefined)return c+'='+String(d['const']);}return typeof a['title']==='string'?a['title']:'variant';}export function buildSchemaSummary(a){const b=[];a&&typeof a['title']==='string'&&b['push']('Title:\x20'+a['title']);const c=a&&typeof a==='object'?a['properties']:undefined;if(c&&typeof c==='object'&&!Array['isArray'](c)){const d=Array['isArray'](a['required'])?a['required']:[],e=Object['keys'](c);b['push']('Top-level\x20fields\x20('+e['length']+',\x20*\x20=\x20required):');for(const f of e['slice'](0x0,0x28)){const g=c[f]??{},h=Array['isArray'](g['type'])?g['type']['join']('|'):g['type']??(g['$ref']?'ref':g['anyOf']||g['oneOf']?'union':'any'),i=d['includes'](f)?'*':'',j=typeof g['description']==='string'&&g['description']['length']>0x0?'\x20—\x20'+g['description']['split']('\x0a')[0x0]['slice'](0x0,0x50):'';b['push']('\x20\x20-\x20'+f+i+':\x20'+h+j);}e['length']>0x28&&b['push']('\x20\x20-\x20...and\x20'+(e['length']-0x28)+'\x20more\x20—\x20use\x20action=\x27get_field\x27\x20with\x20field_path\x20to\x20inspect');}else{if(a&&(Array['isArray'](a['oneOf'])||Array['isArray'](a['anyOf']))){const k=a['oneOf']??a['anyOf'];b['push']('Union\x20of\x20'+k['length']+'\x20variants:');for(const m of k['slice'](0x0,0x28)){const o=m&&typeof m['description']==='string'&&m['description']['length']>0x0?'\x20—\x20'+m['description']['split']('\x0a')[0x0]['slice'](0x0,0x50):'';b['push']('\x20\x20-\x20'+unionVariantLabel(m)+o);}k['length']>0x28&&b['push']('\x20\x20-\x20...and\x20'+(k['length']-0x28)+'\x20more');const l=k['filter'](q=>q&&typeof q==='object'&&q['properties']&&typeof q['properties']==='object');if(l['length']===k['length']&&l['length']>0x0){const q=Object['keys'](l[0x0]['properties'])['filter'](r=>l['every'](s=>Object['prototype']['hasOwnProperty']['call'](s['properties'],r)));b['push'](q['length']>0x0?'Common\x20fields\x20(declared\x20by\x20ALL\x20'+l['length']+'\x20variants):\x20'+q['join'](',\x20')+'.':'No\x20field\x20is\x20declared\x20by\x20all\x20'+l['length']+'\x20variants\x20—\x20each\x20variant\x20takes\x20its\x20own\x20parameters.');}else b['push']('Field\x20names\x20differ\x20per\x20variant\x20—\x20read\x20the\x20variant\x27s\x20own\x20list\x20above.\x20'+'The\x20discriminator\x20(\x22operation\x22\x20and\x20friends)\x20is\x20the\x20only\x20shared\x20key.');for(const r of k['slice'](0x0,0x28)){const s=r&&typeof r==='object'&&r['properties']&&typeof r['properties']==='object'?Object['keys'](r['properties']):[];if(s['length']===0x0)continue;b['push']('\x20\x20\x20\x20'+unionVariantLabel(r)+'\x20fields:\x20'+s['join'](',\x20'));}b['push']('Drill\x20into\x20the\x20variant\x20you\x20need\x20with\x20action=\x27get_field\x27\x20(name\x20+\x20field_path)\x20—\x20the\x20lists\x20above\x20are\x20a\x20summary,\x20not\x20the\x20schema.');}else b['push']('No\x20top-level\x20properties\x20map\x20—\x20use\x20action=\x27get_field\x27\x20with\x20a\x20field_path\x20to\x20inspect\x20this\x20schema.');}return b['join']('\x0a');}export function autoOverflowToFile(a,b){try{const c=JSON['stringify'](a)['length'];if(c<=INLINE_CHAR_LIMIT)return null;const d=process['env']['WOWOK_SCHEMA_TMP_DIR'],e=d?resolve(d):resolve(process['cwd'](),AUTO_OVERFLOW_DIR);!existsSync(e)&&mkdirSync(e,{'recursive':!![]});const f=b['replace'](/[^a-zA-Z0-9_-]/g,'_'),g=f+'.schema.json',h=join(e,g);return writeFileSync(h,JSON['stringify'](a,null,0x2),'utf-8'),{'absolute_path':h,'relative_path':d?h:join(AUTO_OVERFLOW_DIR,g),'bytes':c,'summary':buildSchemaSummary(a)};}catch{return null;}}export function processSchemaQuery(a){const {action:b,name:c,query:d,field_path:f,template:g,output_file:h,object_type:i,params:j}=a;if(b==='get_guard_templates'){const k=getGuardTemplates(g);if(!k)return{'success':![],'action':b,'data':null,'message':g?'Guard\x20template\x20\x27'+g+'\x27\x20not\x20found.\x20Omit\x20\x27template\x27\x20to\x20list\x20all\x20available\x20templates.':'Guard\x20templates\x20file\x20not\x20found.\x20Ensure\x20scripts/guard-templates.json\x20exists.','suggestions':['Omit\x20\x27template\x27\x20to\x20list\x20all\x20available\x20templates.','Available\x20template\x20names:\x20signer_verification,\x20progress_node_check,\x20order_owner_verification,\x20service_belonging_check,\x20reward_not_claimed,\x20combined_reward_guard']};if(h){const l=writeResponseToFile(k,h);if(l)return{'success':!![],'action':b,'data':null,'message':'Guard\x20template'+(g?'\x20\x27'+g+'\x27':'s')+'\x20written\x20to\x20file:\x20'+l,'output_file_path':l,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+l]};}return{'success':!![],'action':b,'data':k,'message':g?'Retrieved\x20Guard\x20template:\x20'+g:'Retrieved\x20'+(Array['isArray'](k['templates'])?k['templates']['length']:0x0)+'\x20Guard\x20templates'};}if(b==='get_templates'){if(!g){const p=a427a(i),q=getTemplateCounts(),r={'total':p['length'],'filter':i??null,'counts_by_object_type':q,'templates':p};if(h){const s=writeResponseToFile(r,h);if(s)return{'success':!![],'action':b,'data':null,'message':p['length']+'\x20templates\x20written\x20to\x20file:\x20'+s,'output_file_path':s,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+s]};}return{'success':!![],'action':b,'data':r,'message':p['length']+'\x20template(s)'+(i?'\x20for\x20object_type=\x27'+i+'\x27':'')+'\x20'+('(total\x20registry:\x20'+Object['values'](q)['reduce']((t,u)=>t+u,0x0)+'\x20across\x20'+TEMPLATE_OBJECT_TYPES['length']+'\x20object\x20types).\x20')+'Provide\x20\x27template\x27\x20(id)\x20for\x20full\x20detail;\x20add\x20\x27params\x27\x20(JSON\x20string)\x20to\x20instantiate.'};}if(!j){const t=getTemplateDetail(g);if(!t)return{'success':![],'action':b,'data':null,'message':'Template\x20\x27'+g+'\x27\x20not\x20found\x20in\x20the\x20unified\x20registry.','suggestions':['Omit\x20\x27template\x27\x20to\x20list\x20all\x20template\x20metadata\x20(id\x20+\x20object_type\x20+\x20parameters).','Filter\x20by\x20object_type:\x20'+TEMPLATE_OBJECT_TYPES['join'](',\x20')]};if(h){const u=writeResponseToFile(t,h);if(u)return{'success':!![],'action':b,'data':null,'message':'Template\x20\x27'+g+'\x27\x20detail\x20written\x20to\x20file:\x20'+u,'output_file_path':u,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+u]};}return{'success':!![],'action':b,'data':t,'message':'Template\x20\x27'+g+'\x27\x20('+t['object_type']+',\x20'+(t['instantiable']?'instantiable':'guidance-only')+').\x20'+'To\x20instantiate,\x20call\x20again\x20with\x20\x27params\x27\x20=\x20JSON\x20object\x20of\x20the\x20declared\x20parameters.'};}let m;try{const v=JSON['parse'](j);if(!v||typeof v!=='object'||Array['isArray'](v))return{'success':![],'action':b,'data':null,'message':'\x27params\x27\x20must\x20be\x20a\x20JSON\x20object\x20(e.g.\x20\x27{\x22key\x22:\x22value\x22}\x27),\x20got\x20'+(Array['isArray'](v)?'array':typeof v)+'.'};m=v;}catch(w){return{'success':![],'action':b,'data':null,'message':'Failed\x20to\x20parse\x20\x27params\x27\x20as\x20JSON:\x20'+(w instanceof Error?w['message']:String(w)),'suggestions':['Example:\x20params=\x27{\x22whitelist\x22:[\x220xabc...\x22]}\x27']};}const n=instantiateTemplate(g,m);if(!n['ok'])return{'success':![],'action':b,'data':n['guidance']!==undefined?{'guidance':n['guidance']}:null,'message':'Instantiation\x20failed\x20for\x20\x27'+g+'\x27:\x20'+n['error'],'suggestions':n['missing_params']?['Missing\x20required\x20params:\x20'+n['missing_params']['join'](',\x20'),'Call\x20with\x20\x27template\x27\x20only\x20(no\x20\x27params\x27)\x20to\x20see\x20full\x20parameter\x20declarations.']:['Call\x20with\x20\x27template\x27\x20only\x20(no\x20\x27params\x27)\x20to\x20see\x20full\x20parameter\x20declarations.']};const o={'object_type':n['object_type'],'template_id':n['template_id'],'body':n['body'],...n['notes']?{'notes':n['notes']}:{}};if(h){const x=writeResponseToFile(o,h);if(x)return{'success':!![],'action':b,'data':null,'message':'Instantiated\x20template\x20\x27'+g+'\x27\x20written\x20to\x20file:\x20'+x,'output_file_path':x,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+x]};}return{'success':!![],'action':b,'data':o,'message':'Instantiated\x20\x27'+g+'\x27\x20('+n['object_type']+').\x20'+'Review\x20the\x20body\x20against\x20the\x20onchain_operations\x20schema\x20before\x20submitting.'};}if(b==='get_tool_reference'){if(c){const z=getToolReference(c);if(!z)return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20not\x20found\x20in\x20the\x20tool\x20reference.','suggestions':['Omit\x20\x27name\x27\x20to\x20list\x20all\x20tools.','Available\x20tools:\x20'+TOOLS_REFERENCE['map'](B=>B['name'])['join'](',\x20')]};const A=getToolSequence(c);return{'success':!![],'action':b,'data':{'tool':z,'call_sequence':A??null},'message':'Retrieved\x20tool\x20reference:\x20'+c};}if(d){const B=searchToolReference(d);return{'success':!![],'action':b,'data':{'tools':B,'count':B['length']},'message':'Found\x20'+B['length']+'\x20tool(s)\x20matching\x20\x27'+d+'\x27','suggestions':B['length']===0x0?['Try\x20a\x20broader\x20keyword\x20(e.g.\x20\x27onchain\x27,\x20\x27guard\x27,\x20\x27schema\x27),\x20or\x20omit\x20\x27query\x27\x20to\x20list\x20all\x20tools.']:undefined};}const y=TOOLS_REFERENCE['map'](C=>({'name':C['name'],'summary':C['summary'],'actions':C['actions']??[],'notes':C['notes']??[]}));return{'success':!![],'action':b,'data':{'tools':y,'count':y['length']},'message':'Retrieved\x20reference\x20for\x20'+y['length']+'\x20MCP\x20tools.\x20Pass\x20name=\x27<tool>\x27\x20for\x20full\x20detail\x20(params,\x20prerequisites,\x20follow-ups).'};}if(b==='get_guard_design_patterns'){if(c){const D=getGuardDesignPattern(c);if(!D)return{'success':![],'action':b,'data':null,'message':'Guard\x20design\x20pattern\x20\x27'+c+'\x27\x20not\x20found.','suggestions':['Omit\x20\x27name\x27\x20to\x20list\x20the\x20full\x20catalog.','Available\x20pattern\x20ids:\x20'+GUARD_DESIGN_PATTERNS['map'](E=>E['id'])['join'](',\x20')]};return{'success':!![],'action':b,'data':{'pattern':D},'message':'Retrieved\x20Guard\x20design\x20pattern:\x20'+c};}if(d){const E=GUARD_DESIGN_PATTERNS['filter'](G=>G['host']===d),F=E['length']>0x0?E:GUARD_DESIGN_PATTERNS['filter'](G=>G['business_requirement']['toLowerCase']()['includes'](d['toLowerCase']())||G['logic_summary']['toLowerCase']()['includes'](d['toLowerCase']()));return{'success':!![],'action':b,'data':{'patterns':F,'count':F['length'],'filtered_by':E['length']>0x0?'host':'keyword','schema_notes':GUARD_SCHEMA_NOTES},'message':'Found\x20'+F['length']+'\x20Guard\x20design\x20pattern(s)\x20matching\x20\x27'+d+'\x27','suggestions':F['length']===0x0?['Filter\x20by\x20host:\x20service_buy_guard,\x20service_allocator_guard,\x20machine_forward,\x20progress_submission,\x20reward_claim,\x20repository_write,\x20arbitration_usage,\x20arbitration_voting,\x20gen_passport']:undefined};}const C=GUARD_DESIGN_PATTERNS['map'](G=>({'id':G['id'],'business_requirement':G['business_requirement'],'host':G['host'],'data_source':G['data_source'],'verifier_level':G['verifier_level'],'logic_summary':G['logic_summary'],'key_queries':G['key_queries'],'notes':G['notes']??[]}));return{'success':!![],'action':b,'data':{'patterns':C,'count':C['length'],'version':GUARD_DESIGN_PATTERNS_VERSION,'schema_notes':GUARD_SCHEMA_NOTES},'message':'Retrieved\x20'+C['length']+'\x20Guard\x20design\x20patterns.\x20Pass\x20name=\x27<pattern_id>\x27\x20for\x20full\x20detail\x20(witness\x20types,\x20mitigated\x20risks,\x20industries).'};}if(b==='get_safety_rules')return{'success':!![],'action':b,'data':{'version':SAFETY_RULES_VERSION,'object_reuse_rules':OBJECT_REUSE_RULES,'create_vs_modify_pattern':CREATE_VS_MODIFY_PATTERN,'immutability_rules':IMMUTABILITY_RULES,'operation_type_classification':OPERATION_TYPE_CLASSIFICATION,'operation_class_meta':OPERATION_CLASS_META,'naming_conventions':NAMING_CONVENTIONS},'message':'Retrieved\x20safety\x20rule\x20tables\x20(reuse\x20/\x20immutability\x20/\x20operation\x20classification\x20/\x20naming).\x20'+'Key\x20points:\x20prefer\x20REUSING\x20existing\x20objects\x20(string\x20reference\x20=\x20reuse,\x20object\x20shape\x20=\x20create);\x20'+'Machine\x20publish\x20locks\x20nodes/pairs/forwards,\x20Service\x20publish\x20locks\x20machine/order_allocators/arbitrations\x20(sales\x20stays\x20mutable);\x20'+'Guard\x20is\x20CREATE-only\x20immutable;\x20on-chain\x20writes\x20require\x20explicit\x20user\x20confirmation.'};if(!areSchemasAvailable())return{'success':![],'action':b,'data':null,'message':'Schema\x20files\x20are\x20not\x20available.\x20Please\x20run\x20\x27npm\x20run\x20generate:schemas\x27\x20first.','suggestions':['Run\x20\x27npm\x20run\x20generate:schemas\x27\x20to\x20generate\x20schema\x20files','Ensure\x20the\x20dist/schemas\x20directory\x20exists']};switch(b){case'list':{const G=listSchemas();return{'success':!![],'action':b,'data':G,'message':'Found\x20'+G['length']+'\x20available\x20schemas'};}case'get':{if(!c)return{'success':![],'action':b,'data':null,'message':'Schema\x20name\x20is\x20required\x20for\x20\x27get\x27\x20action','suggestions':['Provide\x20a\x20schema\x20name','Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20schemas']};const H=getSchema(c);if(!H){const J=searchSchemas(c)['slice'](0x0,0x5);return{'success':![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20not\x20found','suggestions':J['length']>0x0?J['map'](K=>'Did\x20you\x20mean:\x20'+K['name']+'?'):['Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20schemas']};}if(h){const K=writeResponseToFile(H,h);if(K)return{'success':!![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20written\x20to\x20file:\x20'+K,'output_file_path':K,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+K]};}const I=autoOverflowToFile(H,c);if(I)return{'success':!![],'action':b,'data':null,'message':'Schema\x20\x27'+c+'\x27\x20is\x20large\x20('+Math['round'](I['bytes']/0x400)+'\x20KB)\x20—\x20'+'written\x20to\x20file\x20instead\x20of\x20inlining\x20to\x20protect\x20your\x20context.','output_file_path':I['absolute_path'],'inline_summary':I['summary'],'suggestions':['Read\x20the\x20full\x20file\x20with\x20the\x20Read\x20tool:\x20'+I['absolute_path'],'If\x20the\x20sandbox\x20blocks\x20that\x20path,\x20resolve\x20the\x20relative\x20path\x20\x27'+I['relative_path']+'\x27\x20against\x20the\x20workspace\x20root\x20and\x20read\x20that.','Without\x20file\x20access,\x20query\x20specific\x20fields\x20via\x20action=\x27get_field\x27\x20with\x20name=\x27'+c+'\x27\x20and\x20a\x20field_path\x20from\x20the\x20summary\x20below.']};return{'success':!![],'action':b,'data':H,'message':'Retrieved\x20schema:\x20'+c};}case'get_field':{if(!c||!f)return{'success':![],'action':b,'data':null,'message':'Both\x20\x27name\x27\x20and\x20\x27field_path\x27\x20are\x20required\x20for\x20\x27get_field\x27\x20action','suggestions':['Example:\x20{action:\x20\x27get_field\x27,\x20name:\x20\x27onchain_operations_machine\x27,\x20field_path:\x20\x27data.node\x27}','Use\x20\x27get\x27\x20action\x20to\x20retrieve\x20the\x20full\x20schema']};const L=getSchemaField(c,f);if(!L)return{'success':![],'action':b,'data':null,'message':'Field\x20path\x20\x27'+f+'\x27\x20not\x20found\x20in\x20schema\x20\x27'+c+'\x27','suggestions':['Check\x20the\x20field\x20path\x20(dot-separated,\x20e.g.\x20\x27data.node\x27)','Use\x20\x27get\x27\x20action\x20to\x20see\x20the\x20full\x20schema\x20structure']};return{'success':!![],'action':b,'data':L,'message':'Retrieved\x20field\x20\x27'+f+'\x27\x20from\x20schema\x20\x27'+c+'\x27'};}case'search':{if(!d)return{'success':![],'action':b,'data':null,'message':'Search\x20query\x20is\x20required\x20for\x20\x27search\x27\x20action'};const M=searchSchemas(d);return{'success':!![],'action':b,'data':M,'message':'Found\x20'+M['length']+'\x20schemas\x20matching\x20\x27'+d+'\x27'};}case'list_operations':{const N=listOperations();return{'success':!![],'action':b,'data':N,'message':'Found\x20'+N['length']+'\x20on-chain\x20operations'};}case'get_output':{if(!c)return{'success':![],'action':b,'data':null,'message':'Tool\x20name\x20is\x20required\x20for\x20\x27get_output\x27\x20action','suggestions':['Provide\x20a\x20tool\x20name','Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20tools\x20and\x20their\x20outputPath']};const O=getOutputSchema(c);if(!O){const Q=listSchemas(),R=Q['find'](T=>T['name']===c);if(R)return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20exists\x20but\x20has\x20no\x20output\x20schema\x20file.\x20The\x20tool\x20may\x20not\x20declare\x20an\x20outputSchema,\x20or\x20the\x20schema\x20file\x20was\x20not\x20generated.','suggestions':['Use\x20\x27get\x27\x20action\x20with\x20name=\x27'+c+'\x27\x20to\x20retrieve\x20its\x20input\x20schema']};const S=searchSchemas(c)['slice'](0x0,0x5);return{'success':![],'action':b,'data':null,'message':'Tool\x20\x27'+c+'\x27\x20not\x20found','suggestions':S['length']>0x0?S['map'](T=>'Did\x20you\x20mean:\x20'+T['name']+'?'):['Use\x20\x27list\x27\x20action\x20to\x20see\x20available\x20tools']};}if(h){const T=writeResponseToFile(O,h);if(T)return{'success':!![],'action':b,'data':null,'message':'Output\x20schema\x20\x27'+c+'\x27\x20written\x20to\x20file:\x20'+T,'output_file_path':T,'suggestions':['Use\x20Read\x20tool\x20to\x20open\x20'+T]};}const P=autoOverflowToFile(O,c);if(P)return{'success':!![],'action':b,'data':null,'message':'Output\x20schema\x20\x27'+c+'\x27\x20is\x20large\x20('+Math['round'](P['bytes']/0x400)+'\x20KB)\x20—\x20'+'written\x20to\x20file\x20instead\x20of\x20inlining\x20to\x20protect\x20your\x20context.','output_file_path':P['absolute_path'],'inline_summary':P['summary'],'suggestions':['Read\x20the\x20full\x20file\x20with\x20the\x20Read\x20tool:\x20'+P['absolute_path'],'If\x20the\x20sandbox\x20blocks\x20that\x20path,\x20resolve\x20the\x20relative\x20path\x20\x27'+P['relative_path']+'\x27\x20against\x20the\x20workspace\x20root\x20and\x20read\x20that.','Without\x20file\x20access,\x20query\x20specific\x20fields\x20via\x20action=\x27get_field\x27\x20with\x20name=\x27'+c+'\x27\x20and\x20a\x20field_path\x20from\x20the\x20summary\x20below.']};return{'success':!![],'action':b,'data':O,'message':'Retrieved\x20output\x20schema:\x20'+c};}default:return{'success':![],'action':b,'data':null,'message':'Unknown\x20action:\x20'+b,'suggestions':['Use\x20\x27list\x27,\x20\x27get\x27,\x20\x27get_field\x27,\x20\x27get_output\x27,\x20\x27search\x27,\x20\x27list_operations\x27,\x20\x27get_guard_templates\x27,\x20\x27get_tool_reference\x27,\x20\x27get_guard_design_patterns\x27,\x20\x27get_safety_rules\x27,\x20\x27get_templates\x27,\x20or\x20\x27analyze_guard_semantics\x27']};}}const GUARD_SEMANTICS_READING_CHECKLIST=['WHO\x20can\x20satisfy\x20this\x20Guard\x20(identity:\x20Signer\x20bindings,\x20Entity\x20membership,\x20allowlists)?','WHEN\x20can\x20it\x20be\x20satisfied\x20(time:\x20Clock\x20comparisons,\x20deadlines,\x20windows)?','WHAT\x20evidence\x20must\x20the\x20caller\x20submit\x20(b_submission\x20table\x20entries\x20—\x20Payment/Order/Proof\x20objects)?','WHICH\x20on-chain\x20data\x20does\x20it\x20read,\x20and\x20can\x20that\x20data\x20change\x20(Repository\x20entries\x20are\x20MUTABLE\x20—\x20who\x20controls\x20the\x20writes)?','WHAT\x20does\x20the\x20counterparty\x20gain/lose\x20in\x20each\x20branch\x20of\x20the\x20logic\x20tree?','ARE\x20there\x20error-level\x20diagnostics\x20or\x20critical\x20risks\x20(they\x20block\x20or\x20endanger\x20execution)?'];export async function analyzeGuardSemantics(a){const b=await lintGuard(a,{'auto_fix':![]}),c={'root':a['root'],'table':(a['table']??[])['map'](k=>({'identifier':k['identifier'],'name':k['name'],'value_type':k['value_type']??'Address','b_submission':k['b_submission']??![],'value':k['value']})),'guardName':a['description']??null,'rely':a['rely']??null},d=renderGuardTreeIndented(c),e=renderGuardMermaid(a['root']),f=new Set(),g=[];let h=![],i=![];walkGuardTree(a['root'],k=>{if(k['type']==='context'){if(k['context']==='Clock')h=!![];if(k['context']==='Signer')i=!![];}if(k['type']==='query'&&k['query']!==undefined&&k['query']!==null){if(typeof k['query']==='number'){const l=getGuardQueryByIdOrName(k['query']);if(l)f['add'](l['id']);else g['push'](k['query']);}else{const m=getGuardQueryByIdOrName(k['query']);if(m)f['add'](m['id']);else g['push'](k['query']);}}});const j={'submission_requirements':(a['table']??[])['filter'](k=>k['b_submission']===!![])['map'](k=>({'identifier':k['identifier'],'value_type':k['value_type'],'object_type':k['object_type'],'name':k['name']})),'data_sources':(a['table']??[])['filter'](k=>k['b_submission']!==!![])['map'](k=>({'identifier':k['identifier'],'kind':k['is_system_address']?'system_address':k['object_type']?'object':'fixed_value','value_type':k['value_type'],'object_type':k['object_type'],'name':k['name'],'is_mutable_onchain':k['object_type']==='Repository'})),'query_dependencies':[...f]['sort']((k,l)=>k-l),'unresolved_queries':g,'has_time_conditions':h,'has_signer_constraints':i,'has_rely_composition':Array['isArray'](a['rely']?.['guards'])&&a['rely']['guards']['length']>0x0,'reading_checklist':GUARD_SEMANTICS_READING_CHECKLIST};return{'render':{'tree_indented':d,'mermaid':e},'lint':b,'party_evaluation':j};}export{formatLintResult};
|
|
@@ -1177,7 +1177,7 @@
|
|
|
1177
1177
|
"action"
|
|
1178
1178
|
],
|
|
1179
1179
|
"additionalProperties": false,
|
|
1180
|
-
"description": "10-step merchant onboarding wizard: intent text → BusinessIntent → industry confirmation → module adoption →
|
|
1180
|
+
"description": "10-step merchant onboarding wizard: intent text → BusinessIntent → industry confirmation → module adoption → Blueprint (L1 plan projection) → evaluation preview → harness check → creation plan. NEVER executes on-chain operations. Stateless: pass guide_state/guide_confirm to advance."
|
|
1181
1181
|
}
|
|
1182
1182
|
]
|
|
1183
1183
|
}
|
package/dist/schemas/index.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
3
|
"title": "WoWok MCP Schema Index",
|
|
4
4
|
"description": "Index of all available JSON schemas for WoWok MCP tools",
|
|
5
|
-
"generatedAt": "2026-10-
|
|
5
|
+
"generatedAt": "2026-10-09T11:29:18.016Z",
|
|
6
6
|
"tools": [
|
|
7
7
|
{
|
|
8
8
|
"name": "onchain_operations",
|
|
@@ -813,7 +813,7 @@
|
|
|
813
813
|
]
|
|
814
814
|
},
|
|
815
815
|
"arbitrations": {
|
|
816
|
-
"description": "Service Arbitration object list. FORMAT: same as repositories — use the `objects` field name inside the operation data. Example: {arbitrations: [{name: 'my_arb_1'}, {name: 'my_arb_2'}]}. Each item is a NameOrAddress (object ID or local mark name). ⚠️ PERMISSION RULE (contract-enforced): every Arbitration bound here MUST use a Permission object DIFFERENT from THIS Service's permission — binding an Arbitration that shares the Service's Permission aborts with E_ARBITRATION_PERMISSION_CONFLICT (error 33). Create a dedicated Permission for each Arbitration BEFORE binding. DESIGN RATIONALE (confirmed intentional): dispute resolution requires NEUTRALITY — an Arbitration controlled by the same Permission admins as the Service it judges would be a conflict of interest. ONLY Arbitration has this check: Reward and Treasury objects MAY share the Service's Permission (they are the provider's own tools).",
|
|
816
|
+
"description": "Service Arbitration object list. FORMAT: same as repositories — use the `objects` field name inside the operation data. Example: {arbitrations: {op: 'set', objects: [{name: 'my_arb_1'}, {name: 'my_arb_2'}]}}. NOTE: op:'add' is disabled on this surface (its success response can arrive unparseable and reads like a failure); ALWAYS pass the FULL list with op:'set'. Each item is a NameOrAddress (object ID or local mark name). ⚠️ PERMISSION RULE (contract-enforced): every Arbitration bound here MUST use a Permission object DIFFERENT from THIS Service's permission — binding an Arbitration that shares the Service's Permission aborts with E_ARBITRATION_PERMISSION_CONFLICT (error 33). Create a dedicated Permission for each Arbitration BEFORE binding. DESIGN RATIONALE (confirmed intentional): dispute resolution requires NEUTRALITY — an Arbitration controlled by the same Permission admins as the Service it judges would be a conflict of interest. ONLY Arbitration has this check: Reward and Treasury objects MAY share the Service's Permission (they are the provider's own tools).",
|
|
817
817
|
"anyOf": [
|
|
818
818
|
{
|
|
819
819
|
"type": "object",
|
|
@@ -1005,6 +1005,41 @@
|
|
|
1005
1005
|
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1006
1006
|
}
|
|
1007
1007
|
},
|
|
1008
|
+
"discount_send": {
|
|
1009
|
+
"description": "Transfer ALREADY-MINTED coupons you own to another address, instead of destroying them (discount_destroy) or minting new ones (discount). This is a pure ownership handover: the on-chain entry points are public funs with NO Service permission requirement — the only preconditions are that the sender owns each coupon and each was minted transferable:true. Typical use: hand out pre-minted campaign coupons, or move coupons between your own accounts.",
|
|
1010
|
+
"type": "object",
|
|
1011
|
+
"properties": {
|
|
1012
|
+
"discounts": {
|
|
1013
|
+
"minItems": 1,
|
|
1014
|
+
"type": "array",
|
|
1015
|
+
"items": {
|
|
1016
|
+
"type": "string",
|
|
1017
|
+
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1018
|
+
},
|
|
1019
|
+
"description": "Coupon object IDs or local names to transfer. You MUST own these Discount objects. Each coupon must have been minted with transferable:true — otherwise the chain aborts with E_DISCOUNT_NOT_TRANSFERABLE (semantic code service:10). Coupons stay single-use; the transfer does not change that. Max 1000 coupons per call (SDK limit MAX_DISCOUNT_COUNT_ONCE)."
|
|
1020
|
+
},
|
|
1021
|
+
"recipient": {
|
|
1022
|
+
"type": "object",
|
|
1023
|
+
"properties": {
|
|
1024
|
+
"name_or_address": {
|
|
1025
|
+
"type": "string",
|
|
1026
|
+
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1027
|
+
},
|
|
1028
|
+
"local_mark_first": {
|
|
1029
|
+
"description": "Whether to prioritize local marks, if true, prioritize local marks, otherwise prioritize global marks",
|
|
1030
|
+
"type": "boolean"
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
"additionalProperties": false,
|
|
1034
|
+
"description": "Destination address (or account/local mark resolvable to one). ALL listed coupons are moved to this single address in one call."
|
|
1035
|
+
}
|
|
1036
|
+
},
|
|
1037
|
+
"required": [
|
|
1038
|
+
"discounts",
|
|
1039
|
+
"recipient"
|
|
1040
|
+
],
|
|
1041
|
+
"additionalProperties": false
|
|
1042
|
+
},
|
|
1008
1043
|
"customer_required": {
|
|
1009
1044
|
"description": "Customer required information labels. Such as phone, email, shipping_address, etc. ⚠️ HARD LINKAGE (SDK-enforced): if customer_required is set (non-empty), the Service MUST also bind a Contact via `um` — otherwise the customer's private information cannot be delivered through end-to-end encrypted Messenger (which routes to the Contact bound as um). Set `um` together with customer_required.",
|
|
1010
1045
|
"type": "array",
|
|
@@ -1201,7 +1236,7 @@
|
|
|
1201
1236
|
]
|
|
1202
1237
|
},
|
|
1203
1238
|
"order_allocators_append": {
|
|
1204
|
-
"description": "Append-only correction window for order_allocators — the ONLY allocator mutation allowed AFTER publish (J1). REQUIREMENTS (chain-enforced, allocation abort code 20 EALLOCATORS_NOT_EXTENSION): the supplied Allocators must be a pure EXTENSION of the current on-chain plan — every existing allocator appears VERBATIM as a prefix (same guard, same sharing, same fix/max), threshold must be UNCHANGED; only description may change freely. New allocators are appended after the prefix. WHY: rewriting an existing allocator or changing the threshold would retroactively alter payout rules for orders already escrowed against the old plan. Clearing the plan (null) is NOT possible here — that would strand in-flight orders. Permission: same index 313 as order_allocators. USE CASE: you forgot one allocator guard (e.g. the refund exit for a review node) and the Service is already published — instead of abandoning the Service, append the missing allocator. ⚠️ Appended allocators are evaluated AFTER the existing ones against the shrinking pool (vector order), so they see the balance left by earlier allocators — design appended waterfall tails accordingly. ⚠️ Once appended, an allocator can NEVER be edited or removed — same permanence as the original plan.",
|
|
1239
|
+
"description": "Append-only correction window for order_allocators — the ONLY allocator mutation allowed AFTER publish (J1). REQUIREMENTS (chain-enforced, allocation abort code 20 EALLOCATORS_NOT_EXTENSION): the supplied Allocators must be a pure EXTENSION of the current on-chain plan — every existing allocator appears VERBATIM as a prefix (same guard, same sharing, same fix/max), threshold must be UNCHANGED; only description may change freely. New allocators are appended after the prefix. WHY: rewriting an existing allocator or changing the threshold would retroactively alter payout rules for orders already escrowed against the old plan. Clearing the plan (null) is NOT possible here — that would strand in-flight orders. Permission: same index 313 as order_allocators. USE CASE: you forgot one allocator guard (e.g. the refund exit for a review node) and the Service is already published — instead of abandoning the Service, append the missing allocator. ⚠️ SCOPE — NEW ORDERS ONLY: each order instantiates its own Allocation from this plan AT BUY TIME, so appending changes the template for FUTURE orders only. Orders already escrowed under the previous plan do NOT gain the appended allocator — their Allocation (and its fund exits) is frozen as originally instantiated; if in-flight orders are already stranded, this append does NOT rescue them. ⚠️ Appended allocators are evaluated AFTER the existing ones against the shrinking pool (vector order), so they see the balance left by earlier allocators — design appended waterfall tails accordingly. ⚠️ Once appended, an allocator can NEVER be edited or removed — same permanence as the original plan.",
|
|
1205
1240
|
"type": "object",
|
|
1206
1241
|
"properties": {
|
|
1207
1242
|
"description": {
|
|
@@ -811,7 +811,7 @@
|
|
|
811
811
|
]
|
|
812
812
|
},
|
|
813
813
|
"arbitrations": {
|
|
814
|
-
"description": "Service Arbitration object list. FORMAT: same as repositories — use the `objects` field name inside the operation data. Example: {arbitrations: [{name: 'my_arb_1'}, {name: 'my_arb_2'}]}. Each item is a NameOrAddress (object ID or local mark name). ⚠️ PERMISSION RULE (contract-enforced): every Arbitration bound here MUST use a Permission object DIFFERENT from THIS Service's permission — binding an Arbitration that shares the Service's Permission aborts with E_ARBITRATION_PERMISSION_CONFLICT (error 33). Create a dedicated Permission for each Arbitration BEFORE binding. DESIGN RATIONALE (confirmed intentional): dispute resolution requires NEUTRALITY — an Arbitration controlled by the same Permission admins as the Service it judges would be a conflict of interest. ONLY Arbitration has this check: Reward and Treasury objects MAY share the Service's Permission (they are the provider's own tools).",
|
|
814
|
+
"description": "Service Arbitration object list. FORMAT: same as repositories — use the `objects` field name inside the operation data. Example: {arbitrations: {op: 'set', objects: [{name: 'my_arb_1'}, {name: 'my_arb_2'}]}}. NOTE: op:'add' is disabled on this surface (its success response can arrive unparseable and reads like a failure); ALWAYS pass the FULL list with op:'set'. Each item is a NameOrAddress (object ID or local mark name). ⚠️ PERMISSION RULE (contract-enforced): every Arbitration bound here MUST use a Permission object DIFFERENT from THIS Service's permission — binding an Arbitration that shares the Service's Permission aborts with E_ARBITRATION_PERMISSION_CONFLICT (error 33). Create a dedicated Permission for each Arbitration BEFORE binding. DESIGN RATIONALE (confirmed intentional): dispute resolution requires NEUTRALITY — an Arbitration controlled by the same Permission admins as the Service it judges would be a conflict of interest. ONLY Arbitration has this check: Reward and Treasury objects MAY share the Service's Permission (they are the provider's own tools).",
|
|
815
815
|
"anyOf": [
|
|
816
816
|
{
|
|
817
817
|
"type": "object",
|
|
@@ -1003,6 +1003,41 @@
|
|
|
1003
1003
|
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1004
1004
|
}
|
|
1005
1005
|
},
|
|
1006
|
+
"discount_send": {
|
|
1007
|
+
"description": "Transfer ALREADY-MINTED coupons you own to another address, instead of destroying them (discount_destroy) or minting new ones (discount). This is a pure ownership handover: the on-chain entry points are public funs with NO Service permission requirement — the only preconditions are that the sender owns each coupon and each was minted transferable:true. Typical use: hand out pre-minted campaign coupons, or move coupons between your own accounts.",
|
|
1008
|
+
"type": "object",
|
|
1009
|
+
"properties": {
|
|
1010
|
+
"discounts": {
|
|
1011
|
+
"minItems": 1,
|
|
1012
|
+
"type": "array",
|
|
1013
|
+
"items": {
|
|
1014
|
+
"type": "string",
|
|
1015
|
+
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1016
|
+
},
|
|
1017
|
+
"description": "Coupon object IDs or local names to transfer. You MUST own these Discount objects. Each coupon must have been minted with transferable:true — otherwise the chain aborts with E_DISCOUNT_NOT_TRANSFERABLE (semantic code service:10). Coupons stay single-use; the transfer does not change that. Max 1000 coupons per call (SDK limit MAX_DISCOUNT_COUNT_ONCE)."
|
|
1018
|
+
},
|
|
1019
|
+
"recipient": {
|
|
1020
|
+
"type": "object",
|
|
1021
|
+
"properties": {
|
|
1022
|
+
"name_or_address": {
|
|
1023
|
+
"type": "string",
|
|
1024
|
+
"description": "Account/Object name or ID. If specifying an account, use empty string '' for the default account. If it starts with '0x', it will be treated as an ID. Otherwise, it will be treated as a name (max 64 bcs characters)."
|
|
1025
|
+
},
|
|
1026
|
+
"local_mark_first": {
|
|
1027
|
+
"description": "Whether to prioritize local marks, if true, prioritize local marks, otherwise prioritize global marks",
|
|
1028
|
+
"type": "boolean"
|
|
1029
|
+
}
|
|
1030
|
+
},
|
|
1031
|
+
"additionalProperties": false,
|
|
1032
|
+
"description": "Destination address (or account/local mark resolvable to one). ALL listed coupons are moved to this single address in one call."
|
|
1033
|
+
}
|
|
1034
|
+
},
|
|
1035
|
+
"required": [
|
|
1036
|
+
"discounts",
|
|
1037
|
+
"recipient"
|
|
1038
|
+
],
|
|
1039
|
+
"additionalProperties": false
|
|
1040
|
+
},
|
|
1006
1041
|
"customer_required": {
|
|
1007
1042
|
"description": "Customer required information labels. Such as phone, email, shipping_address, etc. ⚠️ HARD LINKAGE (SDK-enforced): if customer_required is set (non-empty), the Service MUST also bind a Contact via `um` — otherwise the customer's private information cannot be delivered through end-to-end encrypted Messenger (which routes to the Contact bound as um). Set `um` together with customer_required.",
|
|
1008
1043
|
"type": "array",
|
|
@@ -1199,7 +1234,7 @@
|
|
|
1199
1234
|
]
|
|
1200
1235
|
},
|
|
1201
1236
|
"order_allocators_append": {
|
|
1202
|
-
"description": "Append-only correction window for order_allocators — the ONLY allocator mutation allowed AFTER publish (J1). REQUIREMENTS (chain-enforced, allocation abort code 20 EALLOCATORS_NOT_EXTENSION): the supplied Allocators must be a pure EXTENSION of the current on-chain plan — every existing allocator appears VERBATIM as a prefix (same guard, same sharing, same fix/max), threshold must be UNCHANGED; only description may change freely. New allocators are appended after the prefix. WHY: rewriting an existing allocator or changing the threshold would retroactively alter payout rules for orders already escrowed against the old plan. Clearing the plan (null) is NOT possible here — that would strand in-flight orders. Permission: same index 313 as order_allocators. USE CASE: you forgot one allocator guard (e.g. the refund exit for a review node) and the Service is already published — instead of abandoning the Service, append the missing allocator. ⚠️ Appended allocators are evaluated AFTER the existing ones against the shrinking pool (vector order), so they see the balance left by earlier allocators — design appended waterfall tails accordingly. ⚠️ Once appended, an allocator can NEVER be edited or removed — same permanence as the original plan.",
|
|
1237
|
+
"description": "Append-only correction window for order_allocators — the ONLY allocator mutation allowed AFTER publish (J1). REQUIREMENTS (chain-enforced, allocation abort code 20 EALLOCATORS_NOT_EXTENSION): the supplied Allocators must be a pure EXTENSION of the current on-chain plan — every existing allocator appears VERBATIM as a prefix (same guard, same sharing, same fix/max), threshold must be UNCHANGED; only description may change freely. New allocators are appended after the prefix. WHY: rewriting an existing allocator or changing the threshold would retroactively alter payout rules for orders already escrowed against the old plan. Clearing the plan (null) is NOT possible here — that would strand in-flight orders. Permission: same index 313 as order_allocators. USE CASE: you forgot one allocator guard (e.g. the refund exit for a review node) and the Service is already published — instead of abandoning the Service, append the missing allocator. ⚠️ SCOPE — NEW ORDERS ONLY: each order instantiates its own Allocation from this plan AT BUY TIME, so appending changes the template for FUTURE orders only. Orders already escrowed under the previous plan do NOT gain the appended allocator — their Allocation (and its fund exits) is frozen as originally instantiated; if in-flight orders are already stranded, this append does NOT rescue them. ⚠️ Appended allocators are evaluated AFTER the existing ones against the shrinking pool (vector order), so they see the balance left by earlier allocators — design appended waterfall tails accordingly. ⚠️ Once appended, an allocator can NEVER be edited or removed — same permanence as the original plan.",
|
|
1203
1238
|
"type": "object",
|
|
1204
1239
|
"properties": {
|
|
1205
1240
|
"description": {
|
|
@@ -1,19 +1,8 @@
|
|
|
1
|
-
import { type IndustryTemplate } from "../../knowledge/template-loader.js";
|
|
1
|
+
import { validateAllocatorRows, type IndustryTemplate } from "../../knowledge/template-loader.js";
|
|
2
2
|
import type { DeliverableDefinition } from "../../playbooks/service-build/intent-analyzer.js";
|
|
3
3
|
import type { IndustryMode } from "../../extensions/index.js";
|
|
4
4
|
import type { ToolDispatchResult } from "../types.js";
|
|
5
|
-
export
|
|
6
|
-
interface PlanDivergence {
|
|
7
|
-
severity: "critical" | "warning";
|
|
8
|
-
item: string;
|
|
9
|
-
detail: string;
|
|
10
|
-
action: string;
|
|
11
|
-
}
|
|
12
|
-
export declare function planDivergences(t: IndustryTemplate, allocation: Array<{
|
|
13
|
-
recipient: string;
|
|
14
|
-
percentage: number;
|
|
15
|
-
}> | undefined): PlanDivergence[];
|
|
5
|
+
export { validateAllocatorRows };
|
|
16
6
|
export declare function variantPaymentModel(t: IndustryTemplate): "milestone" | "subscription" | "escrow";
|
|
17
7
|
export declare function variantDeliverables(t: IndustryTemplate, traits: IndustryMode["traits"] | undefined): DeliverableDefinition[];
|
|
18
8
|
export declare function handleBenchmarkMigrationOperation(args: unknown): Promise<ToolDispatchResult>;
|
|
19
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{inferArbitration}from'../../playbooks/service-build/intent-analyzer.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}export function validateAllocatorRows(a){const b=a['allocator']['rows'];if(b===undefined||b['length']===0x0)return[];const c=[],d=b['filter'](f=>f['track']==='settlement'),e=b['filter'](f=>f['track']==='refund');d['length']!==a['allocator']['count']&&c['push']('settlement\x20rows\x20'+d['length']+'\x20!=\x20allocator.count\x20'+a['allocator']['count']);e['length']>0x0&&!a['allocator']['refund_track']&&c['push']('refund\x20rows\x20declared\x20but\x20allocator.refund_track\x20is\x20missing');a['allocator']['refund_track']&&e['length']===0x0&&c['push']('refund_track\x20\x27'+a['allocator']['refund_track']+'\x27\x20declared\x20but\x20no\x20refund\x20row\x20carries\x20it');for(const [f,g]of[['settlement',d],['refund',e]]){const h=g['filter'](j=>j['mode']==='surplus')['length'];if(h>0x1)c['push'](f+'\x20track\x20has\x20'+h+'\x20Surplus\x20rows\x20(allocation.move\x20allows\x20at\x20most\x20one)');const i=g['filter'](j=>j['mode']==='rate');if(i['length']===g['length']&&i['length']>0x0&&h===0x0){const j=i['reduce']((k,l)=>k+(typeof l['value']==='number'?l['value']:Number(l['value']??NaN)),0x0);(!Number['isFinite'](j)||j!==0x2710)&&c['push'](f+'\x20track\x20is\x20all-Rate\x20but\x20sums\x20to\x20'+j+',\x20not\x2010000\x20bps');}for(const k of g){if(k['mode']==='surplus'&&k['value']!==undefined)c['push'](f+'/'+(k['recipient_key']??'?')+':\x20surplus\x20row\x20must\x20not\x20carry\x20a\x20value');k['mode']==='amount'&&k['value']===undefined&&k['value_from']===undefined&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20amount\x20row\x20needs\x20value\x20or\x20value_from'),k['value_from']!==undefined&&!(k['value_from']in a['fee_params'])&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20value_from\x20\x27'+k['value_from']+'\x27\x20is\x20not\x20a\x20fee_params\x20key'),k['recipient']==='guard_identifier'&&k['track']==='settlement'&&c['push']('settlement\x20row\x20uses\x20GuardIdentifier\x20—\x20order-anchored\x20recipients\x20belong\x20to\x20the\x20refund\x20track\x20(see\x20refund_track)');}}return c;}export function planDivergences(a,b){const c=[],d=b?.['length']??0x0,e=(a['allocator']['rows']?.['length']??0x0)>0x0;if(e){const i=validateAllocatorRows(a);i['length']>0x0&&c['push']({'severity':'critical','item':'allocator_rows_invalid','detail':'Template\x20allocator\x20rows\x20are\x20internally\x20inconsistent:\x20'+i['join'](';\x20')+'.','action':'Fix\x20the\x20template\x27s\x20allocator.rows\x20(they\x20are\x20the\x20authoritative\x20money\x20plan;\x20order_allocators\x20is\x20L1-frozen\x20at\x20publish).'});}else d!==a['allocator']['count']&&c['push']({'severity':'critical','item':'allocator_row_count','detail':'Template\x20declares\x20'+a['allocator']['count']+'\x20sharing\x20row(s);\x20the\x20generated\x20plan\x20carries\x20'+d+'\x20percentage\x20row(s).','action':'Build\x20the\x20Allocation\x20with\x20the\x20template\x27s\x20own\x20row\x20set\x20(order_allocators\x20is\x20L1\x20—\x20frozen\x20at\x20Service\x20publish),\x20or\x20declare\x20allocator.rows\x20in\x20the\x20template.'}),a['allocator']['mode']!=='rate'&&c['push']({'severity':'critical','item':'allocation_mode','detail':'Template\x20allocator\x20mode\x20is\x20\x27'+a['allocator']['mode']+'\x27,\x20which\x20a\x20percentage\x20pair\x20cannot\x20represent\x20—\x20no\x20percentage\x20hint\x20was\x20emitted.','action':'Declare\x20allocator.rows\x20in\x20the\x20template\x20(per-row\x20amount\x20/\x20rate\x20/\x20surplus);\x20the\x20pipeline\x20will\x20then\x20carry\x20the\x20real\x20split\x20instead\x20of\x20a\x20hint.'});const f=a['allocator']['refund_track']!==undefined||/refund/i['test'](a['allocator']['description']),g=(a['allocator']['rows']??[])['some'](j=>j['track']==='refund');a['allocator']['refund_track']&&!g&&c['push']({'severity':'critical','item':'refund_track_not_in_plan','detail':'Template\x20declares\x20a\x20\x27'+a['allocator']['refund_track']+'\x27\x20refund\x20track\x20but\x20declares\x20no\x20allocator\x20row\x20with\x20track=\x27refund\x27;\x20the\x20generated\x20plan\x20cannot\x20carry\x20the\x20promised\x20refund\x20rail.','action':'Declare\x20a\x20refund\x20row\x20in\x20allocator.rows\x20(recipient\x20guard_identifier,\x20recipient_key\x20\x270\x27,\x20mode\x20rate,\x20value\x2010000)\x20so\x20the\x20order-anchored\x20full-refund\x20rail\x20rides\x20with\x20the\x20plan.'});if(!f)c['push']({'severity':'critical','item':'refund_track','detail':'The\x20template\x27s\x20allocator\x20declares\x20no\x20refund\x20track\x20—\x20returns/refunds\x20have\x20no\x20funded\x20path\x20in\x20the\x20money\x20plan.','action':'Add\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer)\x20bound\x20to\x20the\x20refund\x20Guard,\x20or\x20confirm\x20with\x20the\x20merchant\x20that\x20refunds\x20are\x20out\x20of\x20scope.'});else!a['allocator']['refund_track']&&c['push']({'severity':'warning','item':'refund_track','detail':'A\x20refund\x20track\x20is\x20declared\x20but\x20not\x20order-anchored,\x20so\x20the\x20refund\x20recipient\x20is\x20resolved\x20from\x20the\x20signer/Entity\x20rather\x20than\x20the\x20paying\x20Order.','action':'Gate\x20the\x20refund\x20track\x20with\x20AND[signer\x20==\x20order.owner,\x20progress.node\x20==\x20X]\x20or\x20move\x20it\x20to\x20an\x20order-anchored\x20GuardIdentifier(0)\x20recipient.'});const h=Object['keys'](a['fee_params'])['filter'](j=>/_(?:days|hours)$/['test'](j));return h['length']>0x0&&!a['time_anchors']&&c['push']({'severity':'warning','item':'window_anchors','detail':'fee_params\x20declares\x20business\x20windows\x20('+h['join'](',\x20')+')\x20but\x20the\x20template\x20declares\x20no\x20time_anchors.','action':'Add\x20time_anchors\x20(or\x20name\x20the\x20window\x20in\x20the\x20Guard\x20set)\x20so\x20the\x20plan\x20emits\x20the\x20release/timeout\x20build\x20steps.'}),c;}function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}export function variantPaymentModel(a){if(a['payment_model'])return a['payment_model'];const b=a['machine_shape']['map'](c=>c['name']+'\x20'+c['role'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](b))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](b))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}export function variantDeliverables(a,b){const c=a['machine_shape']['filter'](g=>g['semantic_role']==='final'),d=c[c['length']-0x1]??[...a['machine_shape']]['reverse']()['find'](g=>!/refund|cancel|dispute|terminat/i['test'](g['name']+'\x20'+g['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],e=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session',f=(a['guards']??[])['filter'](h=>/repository_data_check|required_info_evidence_gate|allocator_order_anchor/['test'](h['template_id']));return[{'name':a['variant']+'\x20fulfillment','type':e,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+d['name']+'\x27\x20('+d['role']+')','proofOfDelivery':f['length']>0x0?'wip_hash':'manual_confirm'}];}function variantModePrior(a,b){if(!b)return undefined;return{...b,'name':a['industry']+'_'+a['variant'],'display_name':a['variant']+'\x20archetype\x20('+a['industry']+')','source':'custom','machine_shape':a['machine_shape']['map'](c=>({...c})),'guards':a['guards']['map'](c=>({...c})),'allocator':{...a['allocator']},'key_risk':a['key_risk'],'build_notes':[...a['build_notes']],...a['time_anchors']?{'time_anchors':{...a['time_anchors']}}:{}};}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[],i=(a['allocator']['rows']?.['length']??0x0)>0x0;if(f!==undefined&&f>0x0&&!i&&a['allocator']['mode']==='rate'){const n=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-n)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':n}),g['allocation']=h;}const j=variantRefundPolicy(a),k={'escrow':!![]};if(j)k['refundPolicy']=j;k['arbitration']=a['arbitration_mode']??k['arbitration']??inferArbitration(templateIntent(a,b));const l=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':k,'deliverables':variantDeliverables(a,e?.['traits'])},'mode_prior_override':variantModePrior(a,e),'name_base':a['id']}),m=planDivergences(a,h);if(a['allocator']['rows']?.['length'])l['template_allocator_rows']=a['allocator']['rows']['map'](o=>({...o}));if(m['length']>0x0){l['plan_divergence']={'template_allocator':{...a['allocator']},'template_guard_refs':a['guards']['length'],'plan_allocation':h,'divergences':m,'publish_ready':![]};const o=m['filter'](q=>q['severity']==='critical'),p=a['allocator']['refund_track']!==undefined;if(o['length']>0x0&&p&&!(a['allocator']['rows']?.['length']??0x0))throw new Error('action\x20blocked:\x20template\x20\x27'+a['id']+'\x27\x20declares\x20refund_track=\x27'+a['allocator']['refund_track']+'\x27\x20but\x20'+'carries\x20no\x20allocator.rows,\x20so\x20the\x20generated\x20plan\x20would\x20ship\x20WITHOUT\x20the\x20refund\x20rail\x20it\x20'+'promises.\x20Because\x20order_allocators\x20is\x20L1\x20and\x20one-way-frozen\x20at\x20Service\x20publish,\x20escrow\x20'+'locked\x20under\x20such\x20a\x20plan\x20can\x20never\x20be\x20returned.\x20Refusing\x20to\x20emit\x20an\x20unsafe\x20build\x20plan.\x20'+'Critical\x20divergences:\x20'+o['map'](q=>'['+q['item']+']\x20'+q['detail']+'\x20→\x20'+q['action'])['join']('\x20|\x20')+'.\x20Fix\x20the\x20template\x20by\x20declaring\x20allocator.rows\x20(one\x20row\x20per\x20sharing\x20entry,\x20including\x20the\x20'+'refund\x20track).\x20If\x20the\x20template\x20is\x20already\x20correct\x20on\x20disk\x20but\x20the\x20running\x20build\x20predates\x20'+'it,\x20run\x20industry_pack_operation\x20action=\x27repair_builtin_templates\x27\x20(and\x20'+'action=\x27template_drift\x27\x20to\x20diagnose)\x20first.');}l['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)l['template_fee_overrides']=c;return l;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
|
|
1
|
+
import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates,validateAllocatorRows,platformShareBps}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{inferArbitration}from'../../playbooks/service-build/intent-analyzer.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}export{validateAllocatorRows};export function variantPaymentModel(a){if(a['payment_model'])return a['payment_model'];const b=a['allocator']['rows']??[];if(b['some'](d=>d['track']==='refund'))return'escrow';const c=a['machine_shape']['map'](d=>d['name'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](c))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](c))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}export function variantDeliverables(a,b){const c=a['machine_shape']['filter'](g=>g['semantic_role']==='final'),d=c[c['length']-0x1]??[...a['machine_shape']]['reverse']()['find'](g=>!/refund|cancel|dispute|terminat/i['test'](g['name']+'\x20'+g['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],e=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session',f=(a['guards']??[])['filter'](h=>/repository_data_check|required_info_evidence_gate|allocator_order_anchor/['test'](h['template_id']));return[{'name':a['variant']+'\x20fulfillment','type':e,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+d['name']+'\x27\x20('+d['role']+')','proofOfDelivery':f['length']>0x0?'wip_hash':'manual_confirm'}];}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[],i=(a['allocator']['rows']?.['length']??0x0)>0x0;if(f!==undefined&&f>0x0&&!i&&a['allocator']['mode']==='rate'){const m=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-m)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':m}),g['allocation']=h;}const j=variantRefundPolicy(a),k={'escrow':!![]};if(j)k['refundPolicy']=j;k['arbitration']=a['arbitration_mode']??k['arbitration']??inferArbitration(templateIntent(a,b));const l=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':k,'deliverables':variantDeliverables(a,e?.['traits'])},'template_override':a,'name_base':a['id']});if(a['allocator']['rows']?.['length'])l['template_allocator_rows']=a['allocator']['rows']['map'](n=>({...n}));l['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)l['template_fee_overrides']=c;return l;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{listServices,getServiceInfo,toggle as
|
|
1
|
+
import{listServices,getServiceInfo,toggle as a442a,setEnabled as a442b,reset as a442c}from'../../config/index.js';import{judgmentStatus,setJudgmentOverride,clearJudgmentOverride,clearJudgmentOverrides,patchUserJudgmentDoc,readUserJudgmentDocView}from'../../config/judgment.js';import{strictParse}from'../../schema/index.js';import{ConfigOperationInputSchema}from'../../schema/config/index.js';export async function handleConfigOperation(a){const b=strictParse(ConfigOperationInputSchema,a,'config_operation\x20input'),{action:c,service:d,path:e,value:f}=b;let g;switch(c){case'list':g={'action':'list','services':listServices()};break;case'toggle':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20toggle');const h=d,i=getServiceInfo(h);if(!i)throw new Error('Unknown\x20service:\x20'+h+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(h==='confirm_gate'&&i['enabled'])throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');const j=a442a(h);g={'action':'toggle','service':h,'enabled':j,'reminder':i['reminder']};break;}case'disable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20disable');const k=d,l=getServiceInfo(k);if(!l)throw new Error('Unknown\x20service:\x20'+k+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(k==='confirm_gate')throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');a442b(k,![]),g={'action':'disable','service':k,'enabled':![],'reminder':l['reminder']};break;}case'enable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20enable');const m=d,n=getServiceInfo(m);if(!n)throw new Error('Unknown\x20service:\x20'+m+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a442b(m,!![]),g={'action':'enable','service':m,'enabled':!![],'reminder':n['reminder']};break;}case'reset':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20reset');const o=d,p=getServiceInfo(o);if(!p)throw new Error('Unknown\x20service:\x20'+o+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a442c(o),g={'action':'reset','service':o,'enabled':getServiceInfo(o)?.['enabled'],'reminder':p['reminder'],'reset':!![]};break;}case'info':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20info');const q=d,r=getServiceInfo(q);if(!r)throw new Error('Unknown\x20service:\x20'+q+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');g={'action':'info',...r};break;}case'judgment_list':g={'action':'judgment_list',...judgmentStatus()};break;case'judgment_set':{if(!e)throw new Error('\x27path\x27\x20param\x20is\x20required\x20for\x20judgment_set\x20(dotted,\x20e.g.\x20\x27evaluation.weights.trust_reviews\x27)');if(!('value'in b))throw new Error('\x27value\x27\x20param\x20is\x20required\x20for\x20judgment_set');const s=setJudgmentOverride(e,f);if(!s['ok'])throw new Error(s['error']);g={'action':'judgment_set','path':e,'value':f,'applied':!![]};break;}case'judgment_reset':{const t=e?clearJudgmentOverride(e)?0x1:0x0:clearJudgmentOverrides();g={'action':'judgment_reset',...e?{'path':e}:{},'cleared':t};break;}case'judgment_doc_read':{g={'action':'judgment_doc_read',...readUserJudgmentDocView()};break;}case'judgment_doc_patch':{if(!b['patch']||typeof b['patch']!=='object'||Array['isArray'](b['patch']))throw new Error('\x27patch\x27\x20param\x20is\x20required\x20for\x20judgment_doc_patch\x20(a\x20partial\x20judgment\x20document\x20object,\x20e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');g={'action':'judgment_doc_patch',...patchUserJudgmentDoc(b['patch'])};break;}default:throw new Error('Unknown\x20config_operation\x20action:\x20'+String(c));}return{'content':[{'type':'text','text':JSON['stringify']({'result':g})}],'structuredContent':{'result':g}};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdirSync,readFileSync,writeFileSync,existsSync,mkdirSync,statSync,cpSync,renameSync,rmSync}from'node:fs';import{join,relative,resolve,sep,dirname,basename}from'node:path';import{strictParse}from'../../schema/index.js';import{IndustryPackOperationInputSchema}from'../../schema/industry-pack/index.js';import{validateJudgmentFragment}from'../../config/judgment.js';import{scaffoldIndustryPack,listRegisteredPacks,scanDefaultIndustryPacks,seedBuiltinIndustryTemplates,seedBuiltinStrategyManuals,ensureIndustryReadme,resolveIndustryPackDir,rescanPack,resolveDisputeRules,resolveComplianceRules,resolveSupplyRules,resolveIndustryRules,resolveIndustryPlaybook,diffIndustryPack,resetIndustryPath}from'../../extensions/index.js';import{getIndustryModeRegistry}from'../../extensions/registry.js';import{handleRecommendIndustry,handleListModes,handleDeriveUserMode,handleEvolveUserMode,handleRegisterUserMode,handleUnregisterUserMode,handleRegisterCustomMetric,handleUnregisterCustomMetric,handleRegisterCustomConstraint,handleUnregisterCustomConstraint,handleListMetricsConstraints}from'../../playbooks/service-build/mode-actions.js';import{repairBuiltinTemplates,builtinTemplateDrift,resolveTemplatesDir}from'../../knowledge/template-loader.js';const INDUSTRY_ROOT=resolveIndustryPackDir(),resolveTemplatesDirSafe=resolveTemplatesDir;function resolveIndustryPath(a){const b=resolve(INDUSTRY_ROOT,a);if(b!==INDUSTRY_ROOT&&!b['startsWith'](INDUSTRY_ROOT+sep))throw new Error('path\x20\x27'+a+'\x27\x20escapes\x20the\x20industry\x20root');return b;}function isTemplateTreePath(a){const b=a['split'](/[\\/]+/)['filter'](c=>c['length']>0x0);return b['length']>=0x2&&b[0x1]==='templates';}function assertTemplateWriteAuthorized(a,b,c){if(c===!![])return;const d=b['find'](e=>e!==undefined&&isTemplateTreePath(e));if(!d)return;throw new Error('action=\x27'+a+'\x27\x20modifies\x20the\x20user-editable\x20template\x20file\x20\x27'+d+'\x27.\x20'+'Present\x20the\x20intended\x20change\x20to\x20the\x20user\x20first;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20'+'re-call\x20with\x20authorize=true\x20(C5).');}function rescanAffectedPack(a){const b=a['split'](/[\\/]+/)['find'](c=>c['length']>0x0);if(!b)return;rescanPack(b);}const BASELINES_FILENAME='baselines.json',PACK_FILENAME='pack.json';function assertBaselinesContentValid(a,b){const c=a['split'](/[\\/]+/)['pop']()??'';if(c!==BASELINES_FILENAME&&c!==PACK_FILENAME)return;let d;try{d=JSON['parse'](b);}catch{return;}if(!d||typeof d!=='object'||Array['isArray'](d))return;const e=d,f=c===BASELINES_FILENAME?d:e['baselines'];if(f===undefined||f===null)return;const g=validateJudgmentFragment(f,a+'\x20baselines');if(g)throw new Error('write\x20rejected\x20—\x20the\x20baselines\x20fragment\x20in\x20\x27'+a+'\x27\x20is\x20not\x20a\x20valid\x20judgment\x20fragment:\x20'+g);}function listRecursive(a,b,c,d=0x0){if(d>0x8)return;let f;try{f=readdirSync(a,{'withFileTypes':!![]});}catch{return;}for(const g of f){const h=join(a,g['name']),i=relative(b,h)['split'](sep)['join']('/');let j=0x0,k=0x0;try{const l=statSync(h);k=l['size'],j=l['mtimeMs'];}catch{}g['isDirectory']()?(c['push']({'path':i,'is_dir':!![],'size':0x0,'mtime':j}),listRecursive(h,b,c,d+0x1)):c['push']({'path':i,'is_dir':![],'size':k,'mtime':j});}}export async function handleIndustryPackOperation(a){const b=strictParse(IndustryPackOperationInputSchema,a,'industry_pack_operation\x20input');mkdirSync(INDUSTRY_ROOT,{'recursive':!![]}),seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme();let c;switch(b['action']){case'scaffold':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27scaffold\x27');const d=scaffoldIndustryPack(b['name']);c={'action':'scaffold','ok':d['ok'],'dir':d['dir'],'files':d['files'],'errors':d['errors']};if(d['ok'])rescanPack(b['name']);break;}case'list':{c={'action':'list','packs':listRegisteredPacks()};break;}case'scan':{c={'action':'scan','results':scanDefaultIndustryPacks()};break;}case'repair_builtin_templates':{if(b['authorize']!==!![]){const g=repairBuiltinTemplates({'backup':!![],'dryRun':!![]}),h=g['filter'](i=>i['status']==='would_update');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':0x0,'requires_authorization':!![],'results':g,'note':h['length']?'PLAN\x20ONLY\x20(no\x20writes)\x20—\x20'+h['length']+'\x20legacy\x20sentinel-less\x20builtin\x20file(s)\x20would\x20be\x20reseeded\x20from\x20the\x20in-code\x20catalog,\x20each\x20previous\x20body\x20preserved\x20as\x20<file>.bak.\x20Present\x20this\x20plan\x20to\x20the\x20user;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20re-call\x20with\x20authorize=true\x20to\x20execute.':'No\x20legacy\x20sentinel-less\x20builtin\x20files\x20found\x20—\x20every\x20builtin\x20template\x20already\x20carries\x20a\x20release\x20sentinel.'};break;}const e=repairBuiltinTemplates({'backup':!![]}),f=e['filter'](i=>i['status']==='updated');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':f['length'],'results':e,'note':f['length']?'Legacy\x20sentinel-less\x20builtin\x20files\x20were\x20reseeded\x20from\x20the\x20in-code\x20catalog.\x20Each\x20previous\x20body\x20is\x20preserved\x20as\x20<file>.bak.':'No\x20legacy\x20sentinel-less\x20builtin\x20files\x20found\x20—\x20every\x20builtin\x20template\x20already\x20carries\x20a\x20release\x20sentinel.'};break;}case'template_drift':{const i=builtinTemplateDrift();c={'action':'template_drift','dir':resolveTemplatesDirSafe(),'drift_count':i['length'],'drift':i,'note':i['length']?'On-disk\x20builtin\x20templates\x20differ\x20from\x20the\x20in-code\x20catalog.\x20Run\x20action=\x27repair_builtin_templates\x27\x20to\x20reseed.':'Every\x20builtin\x20template\x20on\x20disk\x20matches\x20the\x20in-code\x20catalog.'};break;}case'resolve':{c={'action':'resolve','dir':INDUSTRY_ROOT};break;}case'list_files':{const j=[];listRecursive(INDUSTRY_ROOT,INDUSTRY_ROOT,j),c={'action':'list_files','dir':INDUSTRY_ROOT,'files':j};break;}case'read_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27read_file\x27');const k=resolveIndustryPath(b['path']);if(!existsSync(k))throw new Error('file\x20not\x20found:\x20'+b['path']);c={'action':'read_file','path':k,'content':readFileSync(k,'utf-8')};break;}case'write_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');if(b['content']===undefined)throw new Error('\x27content\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');assertTemplateWriteAuthorized('write_file',[b['path']],b['authorize']);const l=resolveIndustryPath(b['path']);assertBaselinesContentValid(b['path'],b['content']),mkdirSync(dirname(l),{'recursive':!![]}),writeFileSync(l,b['content'],'utf-8'),c={'action':'write_file','path':l,'ok':!![]},rescanAffectedPack(b['path']);break;}case'get':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27get\x27');const m=b['name'],n=getIndustryModeRegistry()['getMode'](m),o=n?{'name':n['name'],'display_name':n['display_name'],'key_risk':n['key_risk'],'needs':n['needs']['map'](p=>p['description']),...n['analyze']?.['key_questions']?.['length']?{'analyze_questions':n['analyze']['key_questions']['slice'](0x0,0x2)}:{}}:undefined;c={'action':'get','category':m,...o?{'mode':o}:{},...resolveDisputeRules(m)?{'dispute':resolveDisputeRules(m)}:{},...resolveComplianceRules(m)?{'compliance':resolveComplianceRules(m)}:{},...resolveSupplyRules(m)?{'supply':resolveSupplyRules(m)}:{},...resolveIndustryRules(m)?{'rules':resolveIndustryRules(m)}:{},...resolveIndustryPlaybook(m)?{'playbook':resolveIndustryPlaybook(m)}:{}};break;}case'diff':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27diff\x27');c={'action':'diff',...diffIndustryPack(b['name'])};break;}case'reset':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27reset\x27');assertTemplateWriteAuthorized('reset',[b['path']],b['authorize']);const p=resetIndustryPath(b['path']);c={'action':'reset','ok':p['ok'],'layout':p['layout'],'target':p['target'],'restored_files':p['restored_files'],'errors':p['errors']},rescanAffectedPack(b['path']);break;}case'delete_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27delete_file\x27');assertTemplateWriteAuthorized('delete_file',[b['path']],b['authorize']);const q=resolveIndustryPath(b['path']);if(!existsSync(q))throw new Error('file\x20not\x20found:\x20'+b['path']);rmSync(q,{'recursive':!![],'force':!![]}),c={'action':'delete_file','path':q,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_file\x27');const t=resolveIndustryPath(b['path']);if(existsSync(t))throw new Error('file\x20already\x20exists:\x20'+b['path']);if(b['content']!==undefined)assertBaselinesContentValid(b['path'],b['content']);mkdirSync(dirname(t),{'recursive':!![]}),writeFileSync(t,b['content']??'','utf-8'),c={'action':'create_file','path':t,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_dir':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_dir\x27');const u=resolveIndustryPath(b['path']);mkdirSync(u,{'recursive':!![]}),c={'action':'create_dir','path':u,'ok':!![]},rescanAffectedPack(b['path']);break;}case'copy':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27copy\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27copy\x27');const v=resolveIndustryPath(b['from']);let w=resolveIndustryPath(b['to']);if(!existsSync(v))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(w)&&statSync(w)['isDirectory']()&&(w=join(w,basename(v)));}catch{}if(w===v)throw new Error('\x27copy\x27\x20cannot\x20copy\x20a\x20file\x20onto\x20itself');existsSync(w)&&isTemplateTreePath(b['to'])&&assertTemplateWriteAuthorized('copy',[b['to']],b['authorize']);mkdirSync(dirname(w),{'recursive':!![]}),cpSync(v,w,{'recursive':!![],'force':!![]}),c={'action':'copy','from':v,'to':w,'ok':!![]},rescanAffectedPack(b['to']);break;}case'move':case'rename':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');assertTemplateWriteAuthorized(b['action'],[b['from'],b['to']],b['authorize']);const x=resolveIndustryPath(b['from']);let y=resolveIndustryPath(b['to']);if(!existsSync(x))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(y)&&statSync(y)['isDirectory']()&&(y=join(y,basename(x)));}catch{}if(y===x)throw new Error('\x27'+b['action']+'\x27\x20cannot\x20move\x20onto\x20itself');mkdirSync(dirname(y),{'recursive':!![]}),renameSync(x,y),c={'action':b['action'],'from':x,'to':y,'ok':!![]},rescanAffectedPack(b['from']),rescanAffectedPack(b['to']);break;}case'recommend_industry':c=await handleRecommendIndustry(b);break;case'list_modes':c=await handleListModes();break;case'derive_user_mode':c=await handleDeriveUserMode(b);break;case'evolve_user_mode':c=await handleEvolveUserMode(b);break;case'register_user_mode':c=await handleRegisterUserMode(b);break;case'unregister_user_mode':c=await handleUnregisterUserMode(b);break;case'register_custom_metric':c=await handleRegisterCustomMetric(b);break;case'unregister_custom_metric':c=await handleUnregisterCustomMetric(b);break;case'register_custom_constraint':c=await handleRegisterCustomConstraint(b);break;case'unregister_custom_constraint':c=await handleUnregisterCustomConstraint(b);break;case'list_metrics_constraints':c=await handleListMetricsConstraints(b);break;default:throw new Error('Unknown\x20industry_pack_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}
|
|
1
|
+
import{readdirSync,readFileSync,writeFileSync,existsSync,mkdirSync,statSync,cpSync,renameSync,rmSync}from'node:fs';import{join,relative,resolve,sep,dirname,basename}from'node:path';import{strictParse}from'../../schema/index.js';import{IndustryPackOperationInputSchema}from'../../schema/industry-pack/index.js';import{validateJudgmentFragment}from'../../config/judgment.js';import{scaffoldIndustryPack,listRegisteredPacks,scanDefaultIndustryPacks,seedBuiltinIndustryTemplates,seedBuiltinStrategyManuals,ensureIndustryReadme,resolveIndustryPackDir,rescanPack,resolveDisputeRules,resolveComplianceRules,resolveSupplyRules,resolveIndustryRules,resolveIndustryPlaybook,diffIndustryPack,resetIndustryPath}from'../../extensions/index.js';import{getIndustryModeRegistry}from'../../extensions/registry.js';import{handleRecommendIndustry,handleListModes,handleDeriveUserMode,handleEvolveUserMode,handleRegisterUserMode,handleUnregisterUserMode,handleRegisterCustomMetric,handleUnregisterCustomMetric,handleRegisterCustomConstraint,handleUnregisterCustomConstraint,handleListMetricsConstraints}from'../../playbooks/service-build/mode-actions.js';import{repairBuiltinTemplates,builtinTemplateDrift,resolveTemplatesDir,parseTemplateFile,TemplateFrontmatterSchema}from'../../knowledge/template-loader.js';const INDUSTRY_ROOT=resolveIndustryPackDir(),resolveTemplatesDirSafe=resolveTemplatesDir;function resolveIndustryPath(a){const b=resolve(INDUSTRY_ROOT,a);if(b!==INDUSTRY_ROOT&&!b['startsWith'](INDUSTRY_ROOT+sep))throw new Error('path\x20\x27'+a+'\x27\x20escapes\x20the\x20industry\x20root');return b;}function isTemplateTreePath(a){const b=a['split'](/[\\/]+/)['filter'](c=>c['length']>0x0);return b['length']>=0x2&&b[0x1]==='templates';}function assertTemplateWriteAuthorized(a,b,c){if(c===!![])return;const d=b['find'](e=>e!==undefined&&isTemplateTreePath(e));if(!d)return;throw new Error('action=\x27'+a+'\x27\x20modifies\x20the\x20user-editable\x20template\x20file\x20\x27'+d+'\x27.\x20'+'Present\x20the\x20intended\x20change\x20to\x20the\x20user\x20first;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20'+'re-call\x20with\x20authorize=true\x20(C5).');}function rescanAffectedPack(a){const b=a['split'](/[\\/]+/)['find'](c=>c['length']>0x0);if(!b)return;rescanPack(b);}const BASELINES_FILENAME='baselines.json',PACK_FILENAME='pack.json';function assertBaselinesContentValid(a,b){const c=a['split'](/[\\/]+/)['pop']()??'';if(c!==BASELINES_FILENAME&&c!==PACK_FILENAME)return;let d;try{d=JSON['parse'](b);}catch{return;}if(!d||typeof d!=='object'||Array['isArray'](d))return;const e=d,f=c===BASELINES_FILENAME?d:e['baselines'];if(f===undefined||f===null)return;const g=validateJudgmentFragment(f,a+'\x20baselines');if(g)throw new Error('write\x20rejected\x20—\x20the\x20baselines\x20fragment\x20in\x20\x27'+a+'\x27\x20is\x20not\x20a\x20valid\x20judgment\x20fragment:\x20'+g);}function assertTemplateContentValid(a,b){if(!isTemplateTreePath(a)||!a['endsWith']('.md'))return;let c;try{({frontmatter:c}=parseTemplateFile(b));}catch(e){throw new Error('write\x20rejected\x20—\x20\x27'+a+'\x27\x20is\x20a\x20template\x20file\x20but\x20the\x20frontmatter\x20block\x20is\x20malformed:\x20'+e['message']);}const d=TemplateFrontmatterSchema['safeParse'](c);if(!d['success']){const f=d['error']['issues']['map'](g=>'\x20\x20'+g['path']['join']('.')+':\x20'+g['message'])['join']('\x0a');throw new Error('write\x20rejected\x20—\x20the\x20template\x20frontmatter\x20in\x20\x27'+a+'\x27\x20violates\x20the\x20schema\x20(the\x20editor\x20whitelist\x20IS\x20the\x20zod\x20schema):\x0a'+f);}}function listRecursive(a,b,c,d=0x0){if(d>0x8)return;let f;try{f=readdirSync(a,{'withFileTypes':!![]});}catch{return;}for(const g of f){const h=join(a,g['name']),i=relative(b,h)['split'](sep)['join']('/');let j=0x0,k=0x0;try{const l=statSync(h);k=l['size'],j=l['mtimeMs'];}catch{}g['isDirectory']()?(c['push']({'path':i,'is_dir':!![],'size':0x0,'mtime':j}),listRecursive(h,b,c,d+0x1)):c['push']({'path':i,'is_dir':![],'size':k,'mtime':j});}}export async function handleIndustryPackOperation(a){const b=strictParse(IndustryPackOperationInputSchema,a,'industry_pack_operation\x20input');mkdirSync(INDUSTRY_ROOT,{'recursive':!![]}),seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme();let c;switch(b['action']){case'scaffold':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27scaffold\x27');const d=scaffoldIndustryPack(b['name']);c={'action':'scaffold','ok':d['ok'],'dir':d['dir'],'files':d['files'],'errors':d['errors']};if(d['ok'])rescanPack(b['name']);break;}case'list':{c={'action':'list','packs':listRegisteredPacks()};break;}case'scan':{c={'action':'scan','results':scanDefaultIndustryPacks()};break;}case'repair_builtin_templates':{if(b['authorize']!==!![]){const g=repairBuiltinTemplates({'backup':!![],'dryRun':!![]}),h=g['filter'](i=>i['status']==='would_update');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':0x0,'requires_authorization':!![],'results':g,'note':h['length']?'PLAN\x20ONLY\x20(no\x20writes)\x20—\x20'+h['length']+'\x20builtin\x20file(s)\x20differ\x20from\x20the\x20in-code\x20catalog\x20and\x20would\x20be\x20reseeded\x20(each\x20result\x20carries\x20a\x20field-level\x20diff;\x20previous\x20bodies\x20preserved\x20as\x20<file>.bak).\x20Present\x20this\x20plan\x20to\x20the\x20user;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20re-call\x20with\x20authorize=true\x20to\x20execute.':'Nothing\x20to\x20repair\x20—\x20every\x20on-disk\x20builtin\x20template\x20either\x20matches\x20the\x20in-code\x20catalog\x20or\x20carries\x20user\x20edits\x20(which\x20are\x20never\x20overwritten).'};break;}const e=repairBuiltinTemplates({'backup':!![]}),f=e['filter'](i=>i['status']==='updated');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':f['length'],'results':e,'note':f['length']?'Diverging\x20builtin\x20files\x20were\x20reseeded\x20from\x20the\x20in-code\x20catalog.\x20Each\x20previous\x20body\x20is\x20preserved\x20as\x20<file>.bak.':'Nothing\x20repaired\x20—\x20every\x20on-disk\x20builtin\x20template\x20either\x20matches\x20the\x20in-code\x20catalog\x20or\x20carries\x20user\x20edits\x20(which\x20are\x20never\x20overwritten).'};break;}case'template_drift':{const i=builtinTemplateDrift(),j=i['filter'](k=>k['repairable'])['length'];c={'action':'template_drift','dir':resolveTemplatesDirSafe(),'drift_count':i['length'],'repairable_count':j,'drift':i,'note':i['length']?j>0x0?j+'\x20of\x20'+i['length']+'\x20diverging\x20builtin\x20template(s)\x20can\x20be\x20reseeded\x20without\x20losing\x20user\x20work\x20—\x20run\x20action=\x27repair_builtin_templates\x27\x20(plan-only\x20preview\x20first,\x20then\x20authorize=true\x20after\x20the\x20user\x20confirms).\x20The\x20rest\x20carry\x20user\x20edits\x20and\x20are\x20never\x20overwritten.':'All\x20diverging\x20builtin\x20templates\x20carry\x20user\x20edits\x20—\x20never\x20overwritten\x20automatically;\x20resolve\x20by\x20hand\x20or\x20via\x20an\x20authorized\x20write.':'Every\x20builtin\x20template\x20on\x20disk\x20matches\x20the\x20in-code\x20catalog.'};break;}case'resolve':{c={'action':'resolve','dir':INDUSTRY_ROOT};break;}case'list_files':{const k=[];listRecursive(INDUSTRY_ROOT,INDUSTRY_ROOT,k),c={'action':'list_files','dir':INDUSTRY_ROOT,'files':k};break;}case'read_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27read_file\x27');const l=resolveIndustryPath(b['path']);if(!existsSync(l))throw new Error('file\x20not\x20found:\x20'+b['path']);c={'action':'read_file','path':l,'content':readFileSync(l,'utf-8')};break;}case'write_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');if(b['content']===undefined)throw new Error('\x27content\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');assertTemplateWriteAuthorized('write_file',[b['path']],b['authorize']);const m=resolveIndustryPath(b['path']);assertBaselinesContentValid(b['path'],b['content']),assertTemplateContentValid(b['path'],b['content']),mkdirSync(dirname(m),{'recursive':!![]}),writeFileSync(m,b['content'],'utf-8'),c={'action':'write_file','path':m,'ok':!![]},rescanAffectedPack(b['path']);break;}case'get':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27get\x27');const n=b['name'],o=getIndustryModeRegistry()['getMode'](n),p=o?{'name':o['name'],'display_name':o['display_name'],'key_risk':o['key_risk'],'needs':o['needs']['map'](q=>q['description']),...o['analyze']?.['key_questions']?.['length']?{'analyze_questions':o['analyze']['key_questions']['slice'](0x0,0x2)}:{}}:undefined;c={'action':'get','category':n,...p?{'mode':p}:{},...resolveDisputeRules(n)?{'dispute':resolveDisputeRules(n)}:{},...resolveComplianceRules(n)?{'compliance':resolveComplianceRules(n)}:{},...resolveSupplyRules(n)?{'supply':resolveSupplyRules(n)}:{},...resolveIndustryRules(n)?{'rules':resolveIndustryRules(n)}:{},...resolveIndustryPlaybook(n)?{'playbook':resolveIndustryPlaybook(n)}:{}};break;}case'diff':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27diff\x27');c={'action':'diff',...diffIndustryPack(b['name'])};break;}case'reset':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27reset\x27');assertTemplateWriteAuthorized('reset',[b['path']],b['authorize']);const q=resetIndustryPath(b['path']);c={'action':'reset','ok':q['ok'],'layout':q['layout'],'target':q['target'],'restored_files':q['restored_files'],'errors':q['errors']},rescanAffectedPack(b['path']);break;}case'delete_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27delete_file\x27');assertTemplateWriteAuthorized('delete_file',[b['path']],b['authorize']);const t=resolveIndustryPath(b['path']);if(!existsSync(t))throw new Error('file\x20not\x20found:\x20'+b['path']);rmSync(t,{'recursive':!![],'force':!![]}),c={'action':'delete_file','path':t,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_file\x27');const u=resolveIndustryPath(b['path']);if(existsSync(u))throw new Error('file\x20already\x20exists:\x20'+b['path']);if(b['content']!==undefined)assertBaselinesContentValid(b['path'],b['content']);mkdirSync(dirname(u),{'recursive':!![]}),writeFileSync(u,b['content']??'','utf-8'),c={'action':'create_file','path':u,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_dir':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_dir\x27');const v=resolveIndustryPath(b['path']);mkdirSync(v,{'recursive':!![]}),c={'action':'create_dir','path':v,'ok':!![]},rescanAffectedPack(b['path']);break;}case'copy':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27copy\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27copy\x27');const w=resolveIndustryPath(b['from']);let x=resolveIndustryPath(b['to']);if(!existsSync(w))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(x)&&statSync(x)['isDirectory']()&&(x=join(x,basename(w)));}catch{}if(x===w)throw new Error('\x27copy\x27\x20cannot\x20copy\x20a\x20file\x20onto\x20itself');existsSync(x)&&isTemplateTreePath(b['to'])&&assertTemplateWriteAuthorized('copy',[b['to']],b['authorize']);mkdirSync(dirname(x),{'recursive':!![]}),cpSync(w,x,{'recursive':!![],'force':!![]}),c={'action':'copy','from':w,'to':x,'ok':!![]},rescanAffectedPack(b['to']);break;}case'move':case'rename':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');assertTemplateWriteAuthorized(b['action'],[b['from'],b['to']],b['authorize']);const y=resolveIndustryPath(b['from']);let z=resolveIndustryPath(b['to']);if(!existsSync(y))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(z)&&statSync(z)['isDirectory']()&&(z=join(z,basename(y)));}catch{}if(z===y)throw new Error('\x27'+b['action']+'\x27\x20cannot\x20move\x20onto\x20itself');mkdirSync(dirname(z),{'recursive':!![]}),renameSync(y,z),c={'action':b['action'],'from':y,'to':z,'ok':!![]},rescanAffectedPack(b['from']),rescanAffectedPack(b['to']);break;}case'recommend_industry':c=await handleRecommendIndustry(b);break;case'list_modes':c=await handleListModes();break;case'derive_user_mode':c=await handleDeriveUserMode(b);break;case'evolve_user_mode':c=await handleEvolveUserMode(b);break;case'register_user_mode':c=await handleRegisterUserMode(b);break;case'unregister_user_mode':c=await handleUnregisterUserMode(b);break;case'register_custom_metric':c=await handleRegisterCustomMetric(b);break;case'unregister_custom_metric':c=await handleUnregisterCustomMetric(b);break;case'register_custom_constraint':c=await handleRegisterCustomConstraint(b);break;case'unregister_custom_constraint':c=await handleUnregisterCustomConstraint(b);break;case'list_metrics_constraints':c=await handleListMetricsConstraints(b);break;default:throw new Error('Unknown\x20industry_pack_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}
|