@wowok/agent-mcp 3.3.6 → 3.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chain-semantics/eval-order.js +1 -1
- package/dist/chain-semantics/field-capability.js +1 -1
- package/dist/chain-semantics/fund-flow.js +1 -1
- package/dist/chain-semantics/guard-verbs.js +1 -1
- package/dist/chain-semantics/object-graph.js +1 -1
- package/dist/communication/message-cursors.d.ts +35 -0
- package/dist/communication/message-cursors.js +1 -0
- package/dist/communication/wts-attestation.d.ts +5 -0
- package/dist/communication/wts-attestation.js +1 -1
- package/dist/composition/audit.js +1 -1
- package/dist/composition/compile.d.ts +3 -2
- package/dist/composition/compile.js +1 -1
- package/dist/composition/inflight.d.ts +7 -0
- package/dist/composition/inflight.js +1 -1
- package/dist/composition/materialize.d.ts +4 -1
- package/dist/composition/materialize.js +1 -1
- package/dist/config/index.d.ts +1 -0
- package/dist/config/index.js +1 -1
- package/dist/config/store-policy.d.ts +14 -0
- package/dist/config/store-policy.js +1 -0
- package/dist/config/store-policy.spec.d.ts +1 -0
- package/dist/config/store-policy.spec.js +1 -0
- package/dist/customer/industry-risks.js +1 -1
- package/dist/customer/user-preferences.js +1 -1
- package/dist/data/projection/facets.spec.js +1 -1
- package/dist/evaluation/builtins/graph-service.spec.js +1 -1
- package/dist/evaluation/engine.js +1 -1
- package/dist/evaluation/match-policy.d.ts +30 -6
- package/dist/evaluation/match-policy.js +1 -1
- package/dist/evaluation/match-policy.spec.js +1 -1
- package/dist/experience/realtime-feedback.js +1 -1
- package/dist/extensions/business-modules.d.ts +1 -1
- package/dist/extensions/business-modules.js +1 -1
- package/dist/extensions/industry-pack.js +1 -1
- package/dist/extensions/modes.js +1 -1
- package/dist/graph/onchain/analyze.js +1 -1
- package/dist/graph/onchain/expand.js +1 -1
- package/dist/graph/onchain/exposure.js +1 -1
- package/dist/graph/onchain/facts.d.ts +1 -0
- package/dist/graph/onchain/facts.js +1 -1
- package/dist/graph/onchain/facts.spec.js +1 -1
- package/dist/harness/recover.js +1 -1
- package/dist/intent/types.d.ts +1 -1
- package/dist/intent/types.js +1 -1
- package/dist/keeper/detectors.d.ts +3 -0
- package/dist/keeper/detectors.js +1 -1
- package/dist/keeper/keeper.spec.js +1 -1
- package/dist/knowledge/acquisition-flywheel.js +1 -1
- package/dist/knowledge/allocation-ledger.d.ts +1 -0
- package/dist/knowledge/allocation-ledger.js +1 -1
- package/dist/knowledge/allocator-rail-verifier.d.ts +6 -2
- package/dist/knowledge/allocator-rail-verifier.js +1 -1
- package/dist/knowledge/arbitration-ledger.js +1 -1
- package/dist/knowledge/audit-rules.d.ts +37 -0
- package/dist/knowledge/audit-rules.js +1 -1
- package/dist/knowledge/baselines/rules/plan.json +128 -3
- package/dist/knowledge/builtin-templates.d.ts +18 -1
- package/dist/knowledge/builtin-templates.js +1 -1
- package/dist/knowledge/commission-landing.d.ts +26 -0
- package/dist/knowledge/commission-landing.js +1 -0
- package/dist/knowledge/discount-threshold.js +1 -1
- package/dist/knowledge/event-semantics.js +1 -1
- package/dist/knowledge/fund-layer.d.ts +7 -0
- package/dist/knowledge/fund-layer.js +1 -1
- package/dist/knowledge/getting-started.js +1 -1
- package/dist/knowledge/guard-design-patterns.d.ts +1 -1
- package/dist/knowledge/guard-design-patterns.js +1 -1
- package/dist/knowledge/guard-puzzle.js +1 -1
- package/dist/knowledge/guard-render.d.ts +7 -0
- package/dist/knowledge/guard-render.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/guard-translation.js +1 -1
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/industry-generalizer.d.ts +4 -0
- package/dist/knowledge/industry-generalizer.js +1 -1
- package/dist/knowledge/industry-registry.d.ts +1 -1
- package/dist/knowledge/industry-registry.js +1 -1
- package/dist/knowledge/industry-strategy.js +1 -1
- package/dist/knowledge/jsonrpc-enum.js +1 -1
- package/dist/knowledge/machine-fork-watch.d.ts +9 -0
- package/dist/knowledge/machine-fork-watch.js +1 -0
- package/dist/knowledge/migration-preflight.js +1 -1
- package/dist/knowledge/projection.spec.js +1 -1
- package/dist/knowledge/scenario-modes.d.ts +8 -2
- package/dist/knowledge/scenario-modes.js +1 -1
- package/dist/knowledge/semantic-ir.d.ts +132 -0
- package/dist/knowledge/semantic-ir.js +1 -0
- package/dist/knowledge/service-ledger.js +1 -1
- package/dist/knowledge/strategy-manuals.js +1 -1
- package/dist/knowledge/template-index.js +1 -1
- package/dist/knowledge/template-loader.d.ts +45 -0
- package/dist/knowledge/template-loader.js +1 -1
- package/dist/knowledge/template-prose.d.ts +50 -0
- package/dist/knowledge/template-prose.js +1 -0
- package/dist/knowledge/template-registry.js +1 -1
- package/dist/knowledge/template-scanner.d.ts +5 -3
- package/dist/knowledge/template-scanner.js +1 -1
- package/dist/knowledge/template-validation.js +1 -1
- package/dist/knowledge/tools-reference.js +1 -1
- package/dist/monitor/MonitorLoop.js +1 -1
- package/dist/monitor/normalize.d.ts +1 -1
- package/dist/monitor/normalize.js +1 -1
- package/dist/monitor/types.js +1 -1
- package/dist/playbooks/service-build/business-puzzle.js +1 -1
- package/dist/playbooks/service-build/machine-panorama.js +1 -1
- package/dist/playbooks/service-build/merchant-guide.d.ts +16 -6
- package/dist/playbooks/service-build/merchant-guide.js +1 -1
- package/dist/playbooks/service-build/migration-planner.d.ts +11 -2
- package/dist/playbooks/service-build/migration-planner.js +1 -1
- package/dist/playbooks/service-build/mode-actions.d.ts +8 -0
- package/dist/playbooks/service-build/mode-actions.js +1 -1
- package/dist/playbooks/service-build/object-panorama.d.ts +22 -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.js +1 -1
- package/dist/playbooks/service-build/reverse-mapping.d.ts +1 -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/service-quote.spec.js +1 -1
- package/dist/review/index.js +1 -1
- package/dist/safety/confirm-gate.js +1 -1
- package/dist/schema/benchmark-migration/index.d.ts +135 -10
- package/dist/schema/benchmark-migration/index.js +1 -1
- package/dist/schema/call/allocation.d.ts +3 -0
- package/dist/schema/call/allocation.js +1 -1
- package/dist/schema/call/arbitration.js +1 -1
- package/dist/schema/call/base.d.ts +32 -0
- package/dist/schema/call/bridge.d.ts +8 -0
- package/dist/schema/call/error-codes.d.ts +1 -1
- package/dist/schema/call/error-codes.js +1 -1
- package/dist/schema/call/order.js +1 -1
- package/dist/schema/call/reward.d.ts +10 -0
- package/dist/schema/call/reward.js +1 -1
- package/dist/schema/call/semantic.js +1 -1
- package/dist/schema/call/service.js +1 -1
- package/dist/schema/common/index.js +1 -1
- package/dist/schema/config/index.d.ts +24 -0
- package/dist/schema/config/index.js +1 -1
- package/dist/schema/evaluation/index.d.ts +152 -0
- package/dist/schema/evaluation/index.js +1 -1
- package/dist/schema/goal/index.d.ts +16 -0
- package/dist/schema/goal/planning.d.ts +29 -0
- package/dist/schema/goal/planning.js +1 -1
- package/dist/schema/industry-pack/index.d.ts +70 -0
- package/dist/schema/industry-pack/modes.d.ts +70 -0
- package/dist/schema/industry-pack/modes.js +1 -1
- package/dist/schema/intent-radar/index.d.ts +3 -0
- package/dist/schema/intent-radar/index.js +1 -1
- package/dist/schema/local/index.d.ts +80 -0
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/messenger/index.d.ts +278 -1
- package/dist/schema/messenger/index.js +1 -1
- package/dist/schema/operations.d.ts +6 -0
- package/dist/schema/query/bi.d.ts +38 -0
- package/dist/schema/query/bi.js +1 -1
- package/dist/schema/query/index.d.ts +148 -47
- package/dist/schema/query/index.js +1 -1
- package/dist/schema/schema-version.js +1 -1
- package/dist/schema/service-clone/index.d.ts +17 -0
- package/dist/schema/service-clone/index.js +1 -1
- package/dist/schema-query-impl/index.js +1 -1
- package/dist/schemas/account_operation.output.json +8 -0
- package/dist/schemas/benchmark_migration_operation.output.json +296 -2
- package/dist/schemas/benchmark_migration_operation.schema.json +292 -7
- package/dist/schemas/bridge_operation.output.json +8 -0
- package/dist/schemas/config_operation.output.json +95 -0
- package/dist/schemas/config_operation.schema.json +16 -1
- package/dist/schemas/evaluation_operation.output.json +240 -0
- package/dist/schemas/evaluation_operation.schema.json +397 -1
- package/dist/schemas/goal_operation.schema.json +40 -10
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/industry_pack_operation.output.json +90 -2
- package/dist/schemas/industry_pack_operation.schema.json +236 -0
- package/dist/schemas/intent_radar.output.json +2 -0
- package/dist/schemas/intent_radar.schema.json +1 -0
- package/dist/schemas/local_cache_operation.output.json +8 -0
- package/dist/schemas/local_history_operation.output.json +8 -0
- package/dist/schemas/local_info_operation.output.json +8 -0
- package/dist/schemas/local_mark_operation.output.json +8 -0
- package/dist/schemas/messenger_operation.output.json +609 -1
- package/dist/schemas/messenger_operation.schema.json +96 -1
- package/dist/schemas/onchain_events.output.json +281 -11
- package/dist/schemas/onchain_events.schema.json +5 -1
- package/dist/schemas/onchain_operations.output.json +8 -0
- package/dist/schemas/onchain_operations.schema.json +371 -10
- package/dist/schemas/onchain_operations_allocation.schema.json +10 -1
- package/dist/schemas/onchain_operations_arbitration.schema.json +1 -1
- package/dist/schemas/onchain_operations_guard.schema.json +318 -0
- package/dist/schemas/onchain_operations_order.schema.json +1 -1
- package/dist/schemas/onchain_operations_reward.schema.json +35 -1
- package/dist/schemas/onchain_operations_service.schema.json +6 -6
- package/dist/schemas/query_toolkit.output.json +305 -8
- package/dist/schemas/service_clone_operation.output.json +79 -0
- package/dist/tools/handlers/benchmark-migration.d.ts +15 -0
- package/dist/tools/handlers/benchmark-migration.js +1 -1
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/evaluation.js +1 -1
- package/dist/tools/handlers/evaluation.spec.js +1 -1
- package/dist/tools/handlers/intent-radar.js +1 -1
- package/dist/tools/handlers/messenger.d.ts +1 -0
- package/dist/tools/handlers/messenger.js +1 -1
- package/dist/tools/handlers/onchain.d.ts +20 -1
- package/dist/tools/handlers/onchain.js +1 -1
- package/dist/tools/handlers/query.d.ts +1 -0
- package/dist/tools/handlers/query.js +1 -1
- package/dist/tools/handlers/service-clone.d.ts +18 -0
- package/dist/tools/handlers/service-clone.js +1 -1
- package/dist/tools/handlers/wip.js +1 -1
- package/dist/tools/registry/agent.js +1 -1
- package/dist/tools/registry/business.js +1 -1
- package/dist/tools/registry/query.js +1 -1
- package/dist/tools/wip-verify-ledger.d.ts +14 -0
- package/dist/tools/wip-verify-ledger.js +1 -0
- package/dist/tools/wrap.d.ts +4 -0
- package/dist/tools/wrap.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,renameSync,rmdirSync,statSync,writeFileSync}from'node:fs';import{join,relative,sep}from'node:path';import{z}from'zod';import{getWowokDataDir,getWowokIndustryDir}from'@wowok/wowok';import{SUPPORTED_INDUSTRIES}from'../customer/user-preferences.js';import{isRegisteredIndustry}from'./industry-registry.js';import{BUILTIN_TEMPLATES,BUILTIN_TEMPLATES_VERSION}from'./builtin-templates.js';import{releaseBodyHash,releaseSentinelLine,stripReleaseSentinel}from'./release-sentinel.js';export const TEMPLATES_SUBDIR='templates';export function resolveTemplatesDir(){return process['env']['WOWOK_TEMPLATES_DIR']||getWowokIndustryDir();}function resolveLegacyTemplatesDir(){return process['env']['WOWOK_LEGACY_TEMPLATES_DIR']||join(getWowokDataDir(),'templates');}const MachineEdgeSchema=z['object']({'prev':z['string'](),'forward':z['string']()['min'](0x1)['optional'](),'operator':z['enum'](['merchant','order_payer'])['optional'](),'permission_index':z['number']()['int']()['min'](0x3e8)['optional'](),'guard_key':z['string']()['min'](0x1)['optional']()}),MachineNodeSchema=z['object']({'name':z['string']()['min'](0x1),'role':z['string']()['min'](0x1),'operator':z['enum'](['merchant','order_payer'])['optional'](),'semantic_role':z['enum'](['draft','active','delivered','final','cancelled'])['optional'](),'optional':z['boolean']()['optional'](),'threshold':z['number']()['int']()['min'](0x0)['optional'](),'from':z['array'](z['union']([z['string'](),MachineEdgeSchema]))['optional']()}),GuardRefSchema=z['object']({'template_id':z['string']()['regex'](/^(pattern\.[a-z0-9_]+|tpl_[a-z0-9_]+)$/,'guard\x20template_id\x20must\x20be\x20a\x20\x27pattern.*\x27\x20design\x20pattern\x20or\x20\x27tpl_*\x27\x20guard\x20template'),'host':z['enum'](['service','machine','reward','repository','arbitration']),'purpose':z['string']()['min'](0x1),'key':z['string']()['min'](0x1)['optional'](),'policy':z['object']({'name':z['string']()['min'](0x1)['optional'](),'description':z['string']()['min'](0x1)['optional'](),'id_from':z['string']()['min'](0x1)['optional'](),'value_type':z['string']()['min'](0x1)['optional']()})['optional'](),'params':z['record'](z['string'](),z['unknown']())['optional']()}),ConditionalGuardEmissionSchema=z['object']({'guard_key':z['string']()['min'](0x1),'param':z['string']()['min'](0x1),'values':z['array'](z['string']()['min'](0x1))['min'](0x2),'emit_value':z['string']()['min'](0x1),'question':z['string']()['min'](0x1)})['strict'](),AllocatorRowSchema=z['object']({'track':z['enum'](['settlement','refund']),'recipient':z['enum'](['entity','guard_identifier','signer']),'recipient_key':z['string']()['min'](0x1)['optional'](),'mode':z['enum'](['amount','rate','surplus']),'value':z['union']([z['string'](),z['number']()])['optional'](),'value_from':z['string']()['optional'](),'fix':z['union']([z['string'](),z['number']()])['optional'](),'fix_from':z['string']()['optional'](),'guard_key':z['string']()['min'](0x1)['optional'](),'note':z['string']()['optional']()})['strict'](),AllocatorSchema=z['object']({'recipient':z['enum'](['signer','entity','fixed']),'recipient_key':z['string']()['min'](0x1)['optional'](),'refund_track':z['enum'](['order_anchored'])['optional'](),'count':z['number']()['int']()['positive'](),'mode':z['enum'](['amount','rate','surplus']),'once_per_order':z['boolean']()['optional'](),'rows':z['array'](AllocatorRowSchema)['optional'](),'description':z['string']()['min'](0x1)})['strict'](),IndustryNameSchema=z['string']()['regex'](/^[a-z][a-z0-9_]*$/,'industry\x20must\x20be\x20lowercase\x20snake_case\x20(a-z,\x200-9,\x20_)')['refine'](a=>isRegisteredIndustry(a),{'message':'unknown\x20industry\x20—\x20register\x20it\x20first\x20via\x20an\x20industry\x20pack\x20'+'(industry_pack_operation\x20action=\x27scaffold\x27)\x20or\x20the\x20industry\x20generalizer;\x20'+('builtin\x20industries:\x20'+SUPPORTED_INDUSTRIES['join'](',\x20'))});export const TemplateFrontmatterSchema=z['object']({'id':z['string']()['regex'](/^[a-z][a-z0-9_-]*\/[a-z][a-z0-9_-]*$/,'id\x20must\x20be\x20\x27<industry>/<variant>\x27'),'industry':IndustryNameSchema,'variant':z['string']()['regex'](/^[a-z][a-z0-9_-]*$/),'product_ref':z['string']()['regex'](/^[a-z][a-z0-9._-]*$/,'product_ref\x20must\x20be\x20a\x20lowercase\x20product\x20slug')['optional'](),'archetype':z['enum'](['leader','challenger']),'phase':z['number']()['int']()['min'](0x1)['max'](0x3),'machine_shape':z['array'](MachineNodeSchema)['min'](0x1),'guards':z['array'](GuardRefSchema),'allocator':AllocatorSchema,'fee_params':z['record'](z['string'](),z['union']([z['number'](),z['string']()])),'trust_mechanisms':z['array'](z['string']()),'keeper_dependencies':z['array'](z['string']()),'recommended_role':z['enum'](['merchant','supplier','both']),'role_rationale':z['string']()['min'](0x1),'differences':z['array'](z['string']()),'user_inputs':z['array'](z['string']()),'key_risk':z['string']()['min'](0x1)['max'](0x12c,'key_risk\x20must\x20be\x20a\x20one-line\x20risk\x20statement\x20(<=\x20300\x20chars)\x20—\x20rules\x20and\x20doctrine\x20do\x20not\x20belong\x20in\x20this\x20field')['refine'](a=>!/STANDING RULE|TECHNOLOGY PROVIDER|NOT A PARTY TO THE DEAL|Full text:/i['test'](a),{'message':'key_risk\x20carries\x20an\x20instruction-block\x20fragment\x20(STANDING\x20RULE\x20/\x20provider\x20doctrine\x20/\x20\x27Full\x20text:\x27\x20reference)\x20—\x20keep\x20doctrine\x20in\x20body\x20prose\x20or\x20playbooks,\x20not\x20in\x20this\x20field'}),'build_notes':z['array'](z['string']()),'evidence_refs':z['array'](z['string']())['optional'](),'conditional_guards':z['array'](ConditionalGuardEmissionSchema)['optional'](),'time_anchors':z['record'](z['string'](),z['string']())['optional'](),'payment_model':z['enum'](['milestone','subscription','escrow'])['optional'](),'arbitration_mode':z['enum'](['none','merchant_pick','mutual_pick','third_party'])['optional'](),'reward_claim_policy':z['object']({'kind':z['enum'](['once','periodic','capped']),'min_claim_interval_ms':z['number']()['optional'](),'max_total_per_recipient':z['string']()['optional']()})['optional'](),'review_mode':z['enum'](['none','review','review_reward'])['optional'](),'after_sales_mode':z['enum'](['none','return','exchange','warranty'])['optional'](),'acceptance_mode':z['enum'](['none','milestone','contest','bounty','agent'])['optional'](),'installment_mode':z['enum'](['none','deposit_balance','milestone_n'])['optional'](),'affiliate_mode':z['enum'](['none','commission'])['optional'](),'crowdfunding_mode':z['enum'](['none','threshold','flexible'])['optional'](),'compensation_fund_policy':z['enum'](['allowed','forbidden'])['optional'](),'reentry_kind':z['enum'](['none','review-loop','paid-cycle'])['optional']()})['strict']();import{validateAllocatorRows}from'./template-validation.js';export{validateAllocatorRows};export 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 parseTemplateFile(a){const b=a['replace'](/^\uFEFF/,'')['replace'](/^<!-- builtin:[a-z0-9-]+:v\d+:[0-9a-f]+ -->\r?\n/,''),c=b['split'](/\r?\n/);if(c[0x0]?.['trim']()!=='---')throw new Error('template\x20must\x20start\x20with\x20a\x20\x27---\x27\x20frontmatter\x20block');let d=-0x1;for(let f=0x1;f<c['length'];f++){if(c[f]['trim']()==='---'){d=f;break;}}if(d===-0x1)throw new Error('unterminated\x20frontmatter\x20block\x20(missing\x20closing\x20\x27---\x27)');const e={};for(let g=0x1;g<d;g++){const h=c[g];if(!h['trim']()||h['trim']()['startsWith']('#'))continue;const j=h['indexOf'](':');if(j===-0x1)throw new Error('invalid\x20frontmatter\x20line\x20'+(g+0x1)+':\x20\x27'+h['trim']()+'\x27\x20(expected\x20\x27key:\x20value\x27)');const k=h['slice'](0x0,j)['trim'](),l=h['slice'](j+0x1)['trim']();if(!k)throw new Error('invalid\x20frontmatter\x20line\x20'+(g+0x1)+':\x20empty\x20key');if(l['startsWith']('[')||l['startsWith']('{'))try{e[k]=JSON['parse'](l);}catch(m){throw new Error('frontmatter\x20key\x20\x27'+k+'\x27\x20is\x20not\x20valid\x20JSON:\x20'+m['message']);}else{if(/^-?\d+(\.\d+)?$/['test'](l))e[k]=Number(l);else{if(l['startsWith']('\x22')&&l['endsWith']('\x22')&&l['length']>=0x2||l['startsWith']('\x27')&&l['endsWith']('\x27')&&l['length']>=0x2){if(l[0x0]==='\x22')try{e[k]=JSON['parse'](l);}catch(n){throw new Error('frontmatter\x20key\x20\x27'+k+'\x27\x20is\x20not\x20valid\x20JSON:\x20'+n['message']);}else e[k]=l['slice'](0x1,-0x1);}else e[k]=l;}}}return{'frontmatter':e,'body':c['slice'](d+0x1)['join']('\x0a')['trim']()};}function frontmatterLine(a,b){if(typeof b==='number')return a+':\x20'+b;if(typeof b==='string')return a+':\x20'+b;return a+':\x20'+JSON['stringify'](b);}export const TEMPLATE_SENTINEL_KIND='industry-template';export function canonicalTemplateContent(a){const b=[['id',a['id']],['industry',a['industry']],['variant',a['variant']],['product_ref',a['product_ref']],['archetype',a['archetype']],['phase',a['phase']],['recommended_role',a['recommended_role']],['role_rationale',a['role_rationale']],['key_risk',a['key_risk']],['machine_shape',a['machine_shape']],['guards',a['guards']],['allocator',a['allocator']],['fee_params',a['fee_params']],['trust_mechanisms',a['trust_mechanisms']],['keeper_dependencies',a['keeper_dependencies']],['differences',a['differences']],['user_inputs',a['user_inputs']],['build_notes',a['build_notes']],...a['evidence_refs']?[['evidence_refs',a['evidence_refs']]]:[],...a['conditional_guards']?[['conditional_guards',a['conditional_guards']]]:[],...a['time_anchors']?[['time_anchors',a['time_anchors']]]:[],...a['payment_model']?[['payment_model',a['payment_model']]]:[],...a['arbitration_mode']?[['arbitration_mode',a['arbitration_mode']]]:[],...a['review_mode']?[['review_mode',a['review_mode']]]:[],...a['after_sales_mode']?[['after_sales_mode',a['after_sales_mode']]]:[],...a['acceptance_mode']?[['acceptance_mode',a['acceptance_mode']]]:[],...a['installment_mode']?[['installment_mode',a['installment_mode']]]:[],...a['affiliate_mode']?[['affiliate_mode',a['affiliate_mode']]]:[],...a['crowdfunding_mode']?[['crowdfunding_mode',a['crowdfunding_mode']]]:[],...a['reward_claim_policy']?[['reward_claim_policy',a['reward_claim_policy']]]:[],...a['compensation_fund_policy']?[['compensation_fund_policy',a['compensation_fund_policy']]]:[],...a['reentry_kind']&&a['reentry_kind']!=='none'?[['reentry_kind',a['reentry_kind']]]:[]],c=['---',...b['map'](([e,f])=>frontmatterLine(e,f)),'---'],d=['','#\x20'+a['industry']+'\x20/\x20'+a['variant']+'\x20('+a['archetype']+')','','>\x20Industry\x20archetype\x20template.\x20Editable\x20and\x20migratable:\x20the\x20frontmatter\x20is','>\x20zod-validated\x20on\x20every\x20load;\x20the\x20body\x20is\x20free-form\x20guidance\x20for\x20the\x20AI.','','##\x20Key\x20risk','',a['key_risk'],'','##\x20Differences\x20vs\x20the\x20sibling\x20variant','',...a['differences']['map'](e=>'-\x20'+e),'','##\x20User\x20inputs\x20(inject\x20at\x20build\x20time)','',...a['user_inputs']['map'](e=>'-\x20'+e),'','##\x20Risk-avoidance\x20checklist\x20(R1-R10)','',...a['trust_mechanisms']['map'](e=>'-\x20'+e),'','##\x20Build\x20notes','',...a['build_notes']['map'](e=>'-\x20'+e),''];return[...c,...d]['join']('\x0a');}export function renderTemplateFile(a){const b=canonicalTemplateContent(a);return releaseSentinelLine(TEMPLATE_SENTINEL_KIND,BUILTIN_TEMPLATES_VERSION,releaseBodyHash(b))+'\x0a'+b;}export function matchBuiltinTemplateFile(a){const b=relative(resolveTemplatesDir(),a);if(!b||b['startsWith']('..'))return null;const c=b['split'](sep);if(c['length']!==0x3||c[0x1]!==TEMPLATES_SUBDIR||!c[0x2]['endsWith']('.md'))return null;const d=c[0x2]['slice'](0x0,-'.md'['length']);return BUILTIN_TEMPLATES['find'](e=>e['industry']===c[0x0]&&e['variant']===d)??null;}let seeded=![];function migrateLegacyTemplates(a){const b=resolveLegacyTemplatesDir();if(b===a)return;if(!existsSync(b))return;try{for(const c of readdirSync(b,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(b,c['name']),e=join(a,c['name'],TEMPLATES_SUBDIR);for(const g of readdirSync(d,{'withFileTypes':!![]})){if(!g['isFile']()||!g['name']['endsWith']('.md'))continue;const h=join(e,g['name']);if(existsSync(h))continue;mkdirSync(e,{'recursive':!![]}),renameSync(join(d,g['name']),h);}try{rmdirSync(d);}catch{}}try{rmdirSync(b);}catch{}}catch{}}export function seedBuiltinTemplates(){const a=[],b=resolveTemplatesDir();migrateLegacyTemplates(b);for(const c of BUILTIN_TEMPLATES){const d=join(b,c['industry'],TEMPLATES_SUBDIR),e=join(d,c['variant']+'.md'),f=canonicalTemplateContent(c),g={'template':c['id'],'status':'written','path':e};try{if(!existsSync(e))mkdirSync(d,{'recursive':!![]}),writeFileSync(e,renderTemplateFile(c),'utf-8');else{const h=readFileSync(e,'utf-8'),{sentinel:i,content:j}=stripReleaseSentinel(h,TEMPLATE_SENTINEL_KIND);!i?j===f?(writeFileSync(e,renderTemplateFile(c),'utf-8'),g['status']='restamped',g['detail']='body\x20matches\x20canonical\x20but\x20no\x20sentinel\x20present;\x20sentinel\x20header\x20added,\x20body\x20untouched'):(g['status']='skipped_user_file',g['detail']='template\x20file\x20exists\x20without\x20builtin\x20sentinel\x20and\x20body\x20differs\x20from\x20canonical;\x20leaving\x20user\x20file\x20untouched'):j===f?i['version']!==BUILTIN_TEMPLATES_VERSION||releaseBodyHash(j)!==i['hash']?(writeFileSync(e,renderTemplateFile(c),'utf-8'),g['status']='restamped',g['detail']='body\x20matches\x20canonical\x20but\x20sentinel\x20stale/wrong;\x20header\x20refreshed,\x20body\x20untouched'):g['status']='current':(g['status']='skipped_modified',g['detail']='body\x20differs\x20from\x20canonical;\x20not\x20overwritten\x20by\x20seeding\x20—\x20use\x20repair_builtin_templates\x20(preview→confirm)\x20to\x20reseed');}}catch(k){g['status']='error',g['detail']=k['message'];}a['push'](g);}return a;}export function summarizeTemplateDiff(a,b){let c,d;try{c=parseTemplateFile(a);}catch(g){return'on-disk\x20file\x20is\x20not\x20parseable\x20('+g['message']+');\x20full\x20content\x20will\x20be\x20replaced';}try{d=parseTemplateFile(b);}catch{return'canonical\x20render\x20is\x20not\x20parseable\x20(code\x20defect);\x20full\x20content\x20will\x20be\x20replaced';}const e=[],f=new Set([...Object['keys'](c['frontmatter']),...Object['keys'](d['frontmatter'])]);for(const h of[...f]['sort']()){const i=h in c['frontmatter'],j=h in d['frontmatter'];if(i&&!j)e['push']('-'+h);else{if(!i&&j)e['push']('+'+h);else{if(JSON['stringify'](c['frontmatter'][h])!==JSON['stringify'](d['frontmatter'][h]))e['push']('~'+h);}}}return c['body']!==d['body']&&e['push']('~body\x20('+c['body']['split']('\x0a')['length']+'\x20->\x20'+d['body']['split']('\x0a')['length']+'\x20lines)'),e['length']>0x0?e['join'](',\x20'):'whitespace/ordering\x20only';}export function repairBuiltinTemplates(a){const b=[],c=resolveTemplatesDir(),d=a?.['backup']!==![],e=a?.['dryRun']===!![],f=new Set(a?.['includeUserEdited']??[]);for(const g of BUILTIN_TEMPLATES){const h=join(c,g['industry'],TEMPLATES_SUBDIR),i=join(h,g['variant']+'.md');if(!existsSync(i))continue;const j=canonicalTemplateContent(g);let k=null,l='';const m={'template':g['id'],'status':'would_update','path':i};try{const p=stripReleaseSentinel(readFileSync(i,'utf-8'),TEMPLATE_SENTINEL_KIND);k=p['sentinel'],l=p['content'];}catch(q){m['status']='error',m['detail']=q['message'],b['push'](m);continue;}if(l===j)continue;let n;if(k){if(k['version']>BUILTIN_TEMPLATES_VERSION){m['status']='error',m['detail']='newer\x20release\x20on\x20disk\x20(sentinel\x20v'+k['version']+'\x20>\x20running\x20catalog\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20'+'repair\x20would\x20DOWNGRADE\x20and\x20lose\x20the\x20newer\x20release\x27s\x20content;\x20refused.\x20Upgrade\x20the\x20MCP\x20server\x20instead',b['push'](m);continue;}if(releaseBodyHash(l)!==k['hash']){if(!f['has'](g['id']))continue;n='sentinel-body\x20hash\x20mismatch\x20(sentinel\x20v'+k['version']+'\x20no\x20longer\x20binds\x20the\x20body)\x20'+'reseeded\x20under\x20EXPLICIT\x20include_user_edited\x20authorization';}else n='untouched\x20older\x20release\x20(sentinel\x20v'+k['version']+',\x20current\x20v'+BUILTIN_TEMPLATES_VERSION+')';}else{let r;try{r=String(parseTemplateFile(l)['frontmatter']['id']??'');}catch{continue;}if(r!==g['id'])continue;n='legacy\x20sentinel-less\x20builtin\x20file';}const o=summarizeTemplateDiff(l,j);if(e){m['status']='would_update',m['detail']=n+'\x20would\x20be\x20reseeded\x20from\x20BUILTIN_TEMPLATES\x20('+g['id']+')\x20—\x20diff\x20vs\x20canonical:\x20'+o+(d?';\x20previous\x20body\x20would\x20be\x20saved\x20as\x20<file>.bak':'')+'\x20—\x20execute\x20with\x20authorize=true\x20after\x20the\x20user\x20explicitly\x20confirms',b['push'](m);continue;}try{if(d)copyFileSync(i,i+'.bak');writeFileSync(i,renderTemplateFile(g),'utf-8'),cache['delete'](i),m['status']='updated',m['detail']=n+'\x20reseeded\x20from\x20BUILTIN_TEMPLATES\x20('+g['id']+')\x20—\x20diff\x20was:\x20'+o+(d?';\x20previous\x20body\x20saved\x20as\x20<file>.bak':'');}catch(s){m['status']='error',m['detail']=s['message'];}b['push'](m);}return b;}export function builtinTemplateDrift(a){const b=new Set(a?.['includeUserEdited']??[]),c=[],d=resolveTemplatesDir();for(const e of BUILTIN_TEMPLATES){const f=join(d,e['industry'],TEMPLATES_SUBDIR,e['variant']+'.md');if(!existsSync(f)){c['push']({'template':e['id'],'path':f,'state':'missing','repairable':!![],'detail':'no\x20file\x20on\x20disk;\x20seeding\x20will\x20create\x20it'});continue;}const g=canonicalTemplateContent(e);let h=null,i='';try{const k=stripReleaseSentinel(readFileSync(f,'utf-8'),TEMPLATE_SENTINEL_KIND);h=k['sentinel'],i=k['content'];}catch(l){c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'unreadable:\x20'+l['message']});continue;}if(i===g)continue;const j=summarizeTemplateDiff(i,g);if(!h){let m;try{m=String(parseTemplateFile(i)['frontmatter']['id']??'');}catch{m=undefined;}m===e['id']?c['push']({'template':e['id'],'path':f,'state':'modified','repairable':!![],'detail':'legacy\x20sentinel-less\x20builtin\x20file\x20—\x20seeding\x20never\x20rewrites\x20it\x20and\x20no\x20sentinel\x20proves\x20provenance;\x20repair\x20can\x20reseed\x20—\x20diff\x20vs\x20canonical:\x20'+j}):c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'no\x20release\x20sentinel\x20and\x20id\x20\x27'+(m??'<unparseable>')+'\x27\x20does\x20not\x20match\x20the\x20builtin\x20id\x20—\x20a\x20user\x20file\x20occupies\x20this\x20path;\x20never\x20touched\x20(rename\x20it\x20to\x20free\x20the\x20slot)'});continue;}if(releaseBodyHash(i)===h['hash'])h['version']>BUILTIN_TEMPLATES_VERSION?c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'newer\x20release\x20(sentinel\x20v'+h['version']+'\x20>\x20running\x20catalog\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20'+'repair\x20would\x20DOWNGRADE\x20and\x20lose\x20the\x20newer\x20release\x27s\x20content;\x20repairable:\x20false.\x20'+'Upgrade\x20the\x20MCP\x20server\x20to\x20match\x20—\x20diff\x20vs\x20canonical:\x20'+j}):c['push']({'template':e['id'],'path':f,'state':'modified','repairable':!![],'detail':'untouched\x20older\x20release\x20(sentinel\x20v'+h['version']+',\x20current\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20repair\x20can\x20upgrade\x20—\x20diff\x20vs\x20canonical:\x20'+j});else{const n=b['has'](e['id']);c['push']({'template':e['id'],'path':f,'state':'modified','repairable':n,'detail':n?'sentinel-body\x20hash\x20mismatch\x20(sentinel\x20v'+h['version']+'\x20no\x20longer\x20binds\x20the\x20body)\x20—\x20reseedable\x20under\x20the\x20explicit\x20include_user_edited\x20authorization\x20for\x20this\x20id\x20—\x20diff\x20vs\x20canonical:\x20'+j:'user-edited\x20body\x20—\x20kept\x20by\x20design;\x20repair\x20never\x20overwrites\x20user\x20edits\x20—\x20diff\x20vs\x20canonical:\x20'+j});}}return c;}const cache=new Map();export function reloadTemplates(){cache['clear'](),seeded=![];}export function loadAndValidate(a){const b=readFileSync(a,'utf-8');let c;try{c=parseTemplateFile(b);}catch(f){throw new Error('template\x20\x27'+a+'\x27\x20failed\x20to\x20parse:\x20'+f['message']);}const d=TemplateFrontmatterSchema['safeParse'](c['frontmatter']);if(!d['success']){const g=d['error']['issues']['map'](h=>(h['path']['join']('.')||'<root>')+':\x20'+h['message'])['join'](';\x20');throw new Error('template\x20\x27'+a+'\x27\x20failed\x20validation:\x20'+g);}const e=validateAllocatorRows(d['data']);if(e['length']>0x0)throw new Error('template\x20\x27'+a+'\x27\x20failed\x20allocator-row\x20validation:\x20'+e['join'](';\x20'));return{...d['data'],'body':c['body'],'source_path':a};}function templateFilesOnDisk(a){const b=[];if(!existsSync(a))return b;for(const c of readdirSync(a,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(a,c['name'],TEMPLATES_SUBDIR);if(!existsSync(d))continue;for(const e of readdirSync(d,{'withFileTypes':!![]})){if(e['isFile']()&&e['name']['endsWith']('.md'))b['push'](join(d,e['name']));}}return b['sort']();}export function listTemplates(){!seeded&&(seedBuiltinTemplates(),seeded=!![]);const a=resolveTemplatesDir(),b=[],c=[],d=new Set();for(const e of templateFilesOnDisk(a)){d['add'](e);try{const f=statSync(e)['mtimeMs'],g=cache['get'](e);if(g&&g['mtimeMs']===f){b['push'](g['template']);continue;}const h=loadAndValidate(e);cache['set'](e,{'mtimeMs':f,'template':h}),b['push'](h);}catch(i){cache['delete'](e),c['push'](i['message']);}}for(const j of[...cache['keys']()]){if(!d['has'](j))cache['delete'](j);}return b['sort']((k,l)=>k['id']['localeCompare'](l['id'])),{'templates':b,'errors':c};}export function getTemplate(a){return listTemplates()['templates']['find'](b=>b['id']===a);}export function getTemplatesByIndustry(a){return listTemplates()['templates']['filter'](b=>b['industry']===a);}
|
|
1
|
+
import{copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,renameSync,rmdirSync,statSync,writeFileSync}from'node:fs';import{join,relative,sep}from'node:path';import{z}from'zod';import{getWowokDataDir,getWowokIndustryDir}from'@wowok/wowok';import{SUPPORTED_INDUSTRIES}from'../customer/user-preferences.js';import{isRegisteredIndustry}from'./industry-registry.js';import{BUILTIN_TEMPLATES,BUILTIN_TEMPLATES_VERSION}from'./builtin-templates.js';import{MachineProseEnvelopeSchema}from'./template-prose.js';import{releaseBodyHash,releaseSentinelLine,stripReleaseSentinel}from'./release-sentinel.js';export const TEMPLATES_SUBDIR='templates';export function resolveTemplatesDir(){return process['env']['WOWOK_TEMPLATES_DIR']||getWowokIndustryDir();}function resolveLegacyTemplatesDir(){return process['env']['WOWOK_LEGACY_TEMPLATES_DIR']||join(getWowokDataDir(),'templates');}const MachineEdgeSchema=z['object']({'prev':z['string'](),'forward':z['string']()['min'](0x1)['optional'](),'operator':z['enum'](['merchant','order_payer'])['optional'](),'named_operator':z['string']()['min'](0x1)['optional'](),'permission_index':z['number']()['int']()['min'](0x3e8)['optional'](),'guard_key':z['string']()['min'](0x1)['optional']()}),MachineNodeSchema=z['object']({'name':z['string']()['min'](0x1),'role':z['string']()['min'](0x1),'operator':z['enum'](['merchant','order_payer'])['optional'](),'named_operator':z['string']()['min'](0x1)['optional'](),'semantic_role':z['enum'](['draft','active','delivered','final','cancelled'])['optional'](),'optional':z['boolean']()['optional'](),'threshold':z['number']()['int']()['min'](0x0)['optional'](),'from':z['array'](z['union']([z['string'](),MachineEdgeSchema]))['optional']()}),GuardRefSchema=z['object']({'template_id':z['string']()['regex'](/^(pattern\.[a-z0-9_]+|tpl_[a-z0-9_]+)$/,'guard\x20template_id\x20must\x20be\x20a\x20\x27pattern.*\x27\x20design\x20pattern\x20or\x20\x27tpl_*\x27\x20guard\x20template'),'host':z['enum'](['service','machine','reward','repository','arbitration']),'purpose':z['string']()['min'](0x1),'key':z['string']()['min'](0x1)['optional'](),'policy':z['object']({'name':z['string']()['min'](0x1)['optional'](),'description':z['string']()['min'](0x1)['optional'](),'id_from':z['string']()['min'](0x1)['optional'](),'value_type':z['string']()['min'](0x1)['optional']()})['optional'](),'params':z['record'](z['string'](),z['unknown']())['optional']()}),ConditionalGuardEmissionSchema=z['object']({'guard_key':z['string']()['min'](0x1),'param':z['string']()['min'](0x1),'values':z['array'](z['string']()['min'](0x1))['min'](0x2),'emit_value':z['string']()['min'](0x1),'question':z['string']()['min'](0x1)})['strict'](),AllocatorRowSchema=z['object']({'track':z['enum'](['settlement','refund']),'recipient':z['enum'](['entity','guard_identifier','signer']),'recipient_key':z['string']()['min'](0x1)['optional'](),'mode':z['enum'](['amount','rate','surplus']),'value':z['union']([z['string'](),z['number']()])['optional'](),'value_from':z['string']()['optional'](),'value_from_complement':z['string']()['min'](0x1)['optional'](),'fix':z['union']([z['string'](),z['number']()])['optional'](),'fix_from':z['string']()['optional'](),'guard_key':z['string']()['min'](0x1)['optional'](),'note':z['string']()['optional']()})['strict'](),AllocatorSchema=z['object']({'recipient':z['enum'](['signer','entity','fixed']),'recipient_key':z['string']()['min'](0x1)['optional'](),'refund_track':z['enum'](['order_anchored'])['optional'](),'count':z['number']()['int']()['positive'](),'mode':z['enum'](['amount','rate','surplus']),'once_per_order':z['boolean']()['optional'](),'rows':z['array'](AllocatorRowSchema)['optional'](),'description':z['string']()['min'](0x1)})['strict'](),IndustryNameSchema=z['string']()['regex'](/^[a-z][a-z0-9_]*$/,'industry\x20must\x20be\x20lowercase\x20snake_case\x20(a-z,\x200-9,\x20_)')['refine'](a=>isRegisteredIndustry(a),{'message':'unknown\x20industry\x20—\x20register\x20it\x20first\x20via\x20an\x20industry\x20pack\x20'+'(industry_pack_operation\x20action=\x27scaffold\x27)\x20or\x20the\x20industry\x20generalizer;\x20'+('builtin\x20industries:\x20'+SUPPORTED_INDUSTRIES['join'](',\x20'))});export const TemplateFrontmatterSchema=z['object']({'id':z['string']()['regex'](/^[a-z][a-z0-9_-]*\/[a-z][a-z0-9_-]*$/,'id\x20must\x20be\x20\x27<industry>/<variant>\x27'),'industry':IndustryNameSchema,'variant':z['string']()['regex'](/^[a-z][a-z0-9_-]*$/),'product_ref':z['string']()['regex'](/^[a-z][a-z0-9._-]*$/,'product_ref\x20must\x20be\x20a\x20lowercase\x20product\x20slug')['optional'](),'archetype':z['enum'](['leader','challenger']),'phase':z['number']()['int']()['min'](0x1)['max'](0x3),'machine_shape':z['array'](MachineNodeSchema)['min'](0x1),'guards':z['array'](GuardRefSchema),'allocator':AllocatorSchema,'fee_params':z['record'](z['string'](),z['union']([z['number'](),z['string']()])),'trust_mechanisms':z['array'](z['string']()),'keeper_dependencies':z['array'](z['string']()),'keeper_duty':z['array'](z['object']({'when':z['string']()['min'](0x1),'action':z['string']()['min'](0x1),'miss_consequence':z['string']()['min'](0x1)})['strict']())['optional'](),'recommended_role':z['enum'](['merchant','supplier','both']),'role_rationale':z['string']()['min'](0x1),'differences':z['array'](z['string']()),'user_inputs':z['array'](z['string']()),'key_risk':z['string']()['min'](0x1)['max'](0x12c,'key_risk\x20must\x20be\x20a\x20one-line\x20risk\x20statement\x20(<=\x20300\x20chars)\x20—\x20rules\x20and\x20doctrine\x20do\x20not\x20belong\x20in\x20this\x20field')['refine'](a=>!/STANDING RULE|TECHNOLOGY PROVIDER|NOT A PARTY TO THE DEAL|Full text:/i['test'](a),{'message':'key_risk\x20carries\x20an\x20instruction-block\x20fragment\x20(STANDING\x20RULE\x20/\x20provider\x20doctrine\x20/\x20\x27Full\x20text:\x27\x20reference)\x20—\x20keep\x20doctrine\x20in\x20body\x20prose\x20or\x20playbooks,\x20not\x20in\x20this\x20field'}),'build_notes':z['array'](z['string']()),'prose_language':z['enum'](['en','other'])['optional'](),'machine_prose':z['record'](z['string'](),MachineProseEnvelopeSchema)['optional'](),'evidence_refs':z['array'](z['string']())['optional'](),'conditional_guards':z['array'](ConditionalGuardEmissionSchema)['optional'](),'time_anchors':z['record'](z['string'](),z['string']())['optional'](),'payment_model':z['enum'](['milestone','subscription','escrow'])['optional'](),'arbitration_mode':z['enum'](['none','merchant_pick','mutual_pick','third_party'])['optional'](),'reward_claim_policy':z['object']({'kind':z['enum'](['once','periodic','capped']),'min_claim_interval_ms':z['number']()['optional'](),'max_total_per_recipient':z['string']()['optional']()})['optional'](),'review_mode':z['enum'](['none','review','review_reward'])['optional'](),'after_sales_mode':z['enum'](['none','return','exchange','warranty'])['optional'](),'acceptance_mode':z['enum'](['none','milestone','contest','bounty','agent'])['optional'](),'installment_mode':z['enum'](['none','deposit_balance','milestone_n'])['optional'](),'affiliate_mode':z['enum'](['none','commission'])['optional'](),'crowdfunding_mode':z['enum'](['none','threshold','flexible'])['optional'](),'logistics_mode':z['enum'](['none','carrier','merchant_managed','courier','pickup_point'])['optional'](),'compensation_fund_policy':z['enum'](['allowed','forbidden'])['optional'](),'reentry_kind':z['enum'](['none','review-loop','paid-cycle'])['optional']()})['strict']();import{validateAllocatorRows}from'./template-validation.js';export{validateAllocatorRows};export function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&!/_cap_bps$/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}export const PLATFORM_TAKE_KEY=/^(?:platform_(?:share|commission|take|tool_fee)_bps|platform_fee_rate_bps|commission_rate_bps|(?:base_)?commission_rate_bps|offsite_ads_rate_bps|service_fee_rate_bps|payment_fee_bps)$/;export function parseTemplateFile(a){const b=a['replace'](/^\uFEFF/,'')['replace'](/^<!-- builtin:[a-z0-9-]+:v\d+:[0-9a-f]+ -->\r?\n/,''),c=b['split'](/\r?\n/);if(c[0x0]?.['trim']()!=='---')throw new Error('template\x20must\x20start\x20with\x20a\x20\x27---\x27\x20frontmatter\x20block');let d=-0x1;for(let f=0x1;f<c['length'];f++){if(c[f]['trim']()==='---'){d=f;break;}}if(d===-0x1)throw new Error('unterminated\x20frontmatter\x20block\x20(missing\x20closing\x20\x27---\x27)');const e={};for(let g=0x1;g<d;g++){const h=c[g];if(!h['trim']()||h['trim']()['startsWith']('#'))continue;const j=h['indexOf'](':');if(j===-0x1)throw new Error('invalid\x20frontmatter\x20line\x20'+(g+0x1)+':\x20\x27'+h['trim']()+'\x27\x20(expected\x20\x27key:\x20value\x27)');const k=h['slice'](0x0,j)['trim'](),l=h['slice'](j+0x1)['trim']();if(!k)throw new Error('invalid\x20frontmatter\x20line\x20'+(g+0x1)+':\x20empty\x20key');if(l['startsWith']('[')||l['startsWith']('{'))try{e[k]=JSON['parse'](l);}catch(m){throw new Error('frontmatter\x20key\x20\x27'+k+'\x27\x20is\x20not\x20valid\x20JSON:\x20'+m['message']);}else{if(/^-?\d+(\.\d+)?$/['test'](l))e[k]=Number(l);else{if(l['startsWith']('\x22')&&l['endsWith']('\x22')&&l['length']>=0x2||l['startsWith']('\x27')&&l['endsWith']('\x27')&&l['length']>=0x2){if(l[0x0]==='\x22')try{e[k]=JSON['parse'](l);}catch(n){throw new Error('frontmatter\x20key\x20\x27'+k+'\x27\x20is\x20not\x20valid\x20JSON:\x20'+n['message']);}else e[k]=l['slice'](0x1,-0x1);}else e[k]=l;}}}return{'frontmatter':e,'body':c['slice'](d+0x1)['join']('\x0a')['trim']()};}function frontmatterLine(a,b){if(typeof b==='number')return a+':\x20'+b;if(typeof b==='string')return a+':\x20'+b;return a+':\x20'+JSON['stringify'](b);}export const TEMPLATE_SENTINEL_KIND='industry-template';export function canonicalTemplateContent(a){const b=a,c=[['id',a['id']],['industry',a['industry']],['variant',a['variant']],['product_ref',a['product_ref']],['archetype',a['archetype']],['phase',a['phase']],['recommended_role',a['recommended_role']],['role_rationale',a['role_rationale']],['key_risk',a['key_risk']],['machine_shape',a['machine_shape']],['guards',a['guards']],['allocator',a['allocator']],['fee_params',a['fee_params']],['trust_mechanisms',a['trust_mechanisms']],['keeper_dependencies',a['keeper_dependencies']],...a['keeper_duty']?[['keeper_duty',a['keeper_duty']]]:[],['differences',a['differences']],['user_inputs',a['user_inputs']],['build_notes',a['build_notes']],...b['prose_language']?[['prose_language',b['prose_language']]]:[],...b['machine_prose']?[['machine_prose',b['machine_prose']]]:[],...a['evidence_refs']?[['evidence_refs',a['evidence_refs']]]:[],...a['conditional_guards']?[['conditional_guards',a['conditional_guards']]]:[],...a['time_anchors']?[['time_anchors',a['time_anchors']]]:[],...a['payment_model']?[['payment_model',a['payment_model']]]:[],...a['arbitration_mode']?[['arbitration_mode',a['arbitration_mode']]]:[],...a['review_mode']?[['review_mode',a['review_mode']]]:[],...a['after_sales_mode']?[['after_sales_mode',a['after_sales_mode']]]:[],...a['acceptance_mode']?[['acceptance_mode',a['acceptance_mode']]]:[],...a['installment_mode']?[['installment_mode',a['installment_mode']]]:[],...a['affiliate_mode']?[['affiliate_mode',a['affiliate_mode']]]:[],...a['crowdfunding_mode']?[['crowdfunding_mode',a['crowdfunding_mode']]]:[],...a['logistics_mode']?[['logistics_mode',a['logistics_mode']]]:[],...a['reward_claim_policy']?[['reward_claim_policy',a['reward_claim_policy']]]:[],...a['compensation_fund_policy']?[['compensation_fund_policy',a['compensation_fund_policy']]]:[],...a['reentry_kind']&&a['reentry_kind']!=='none'?[['reentry_kind',a['reentry_kind']]]:[]],d=['---',...c['map'](([f,g])=>frontmatterLine(f,g)),'---'],e=['','#\x20'+a['industry']+'\x20/\x20'+a['variant']+'\x20('+a['archetype']+')','','>\x20Industry\x20archetype\x20template.\x20Editable\x20and\x20migratable:\x20the\x20frontmatter\x20is','>\x20zod-validated\x20on\x20every\x20load;\x20the\x20body\x20is\x20free-form\x20guidance\x20for\x20the\x20AI.','','##\x20Key\x20risk','',a['key_risk'],'','##\x20Differences\x20vs\x20the\x20sibling\x20variant','',...a['differences']['map'](f=>'-\x20'+f),'','##\x20User\x20inputs\x20(inject\x20at\x20build\x20time)','',...a['user_inputs']['map'](f=>'-\x20'+f),'','##\x20Risk-avoidance\x20checklist\x20(R1-R10)','',...a['trust_mechanisms']['map'](f=>'-\x20'+f),'','##\x20Build\x20notes','',...a['build_notes']['map'](f=>'-\x20'+f),''];return[...d,...e]['join']('\x0a');}export function renderTemplateFile(a){const b=canonicalTemplateContent(a);return releaseSentinelLine(TEMPLATE_SENTINEL_KIND,BUILTIN_TEMPLATES_VERSION,releaseBodyHash(b))+'\x0a'+b;}export function matchBuiltinTemplateFile(a){const b=relative(resolveTemplatesDir(),a);if(!b||b['startsWith']('..'))return null;const c=b['split'](sep);if(c['length']!==0x3||c[0x1]!==TEMPLATES_SUBDIR||!c[0x2]['endsWith']('.md'))return null;const d=c[0x2]['slice'](0x0,-'.md'['length']);return BUILTIN_TEMPLATES['find'](e=>e['industry']===c[0x0]&&e['variant']===d)??null;}let seeded=![];function migrateLegacyTemplates(a){const b=resolveLegacyTemplatesDir();if(b===a)return;if(!existsSync(b))return;try{for(const c of readdirSync(b,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(b,c['name']),e=join(a,c['name'],TEMPLATES_SUBDIR);for(const g of readdirSync(d,{'withFileTypes':!![]})){if(!g['isFile']()||!g['name']['endsWith']('.md'))continue;const h=join(e,g['name']);if(existsSync(h))continue;mkdirSync(e,{'recursive':!![]}),renameSync(join(d,g['name']),h);}try{rmdirSync(d);}catch{}}try{rmdirSync(b);}catch{}}catch{}}export function seedBuiltinTemplates(){const a=[],b=resolveTemplatesDir();migrateLegacyTemplates(b);for(const c of BUILTIN_TEMPLATES){const d=join(b,c['industry'],TEMPLATES_SUBDIR),e=join(d,c['variant']+'.md'),f=canonicalTemplateContent(c),g={'template':c['id'],'status':'written','path':e};try{if(!existsSync(e))mkdirSync(d,{'recursive':!![]}),writeFileSync(e,renderTemplateFile(c),'utf-8');else{const h=readFileSync(e,'utf-8'),{sentinel:i,content:j}=stripReleaseSentinel(h,TEMPLATE_SENTINEL_KIND);!i?j===f?(writeFileSync(e,renderTemplateFile(c),'utf-8'),g['status']='restamped',g['detail']='body\x20matches\x20canonical\x20but\x20no\x20sentinel\x20present;\x20sentinel\x20header\x20added,\x20body\x20untouched'):(g['status']='skipped_user_file',g['detail']='template\x20file\x20exists\x20without\x20builtin\x20sentinel\x20and\x20body\x20differs\x20from\x20canonical;\x20leaving\x20user\x20file\x20untouched'):j===f?i['version']!==BUILTIN_TEMPLATES_VERSION||releaseBodyHash(j)!==i['hash']?(writeFileSync(e,renderTemplateFile(c),'utf-8'),g['status']='restamped',g['detail']='body\x20matches\x20canonical\x20but\x20sentinel\x20stale/wrong;\x20header\x20refreshed,\x20body\x20untouched'):g['status']='current':(g['status']='skipped_modified',g['detail']='body\x20differs\x20from\x20canonical;\x20not\x20overwritten\x20by\x20seeding\x20—\x20use\x20repair_builtin_templates\x20(preview→confirm)\x20to\x20reseed');}}catch(k){g['status']='error',g['detail']=k['message'];}a['push'](g);}return a;}export function summarizeTemplateDiff(a,b){let c,d;try{c=parseTemplateFile(a);}catch(g){return'on-disk\x20file\x20is\x20not\x20parseable\x20('+g['message']+');\x20full\x20content\x20will\x20be\x20replaced';}try{d=parseTemplateFile(b);}catch{return'canonical\x20render\x20is\x20not\x20parseable\x20(code\x20defect);\x20full\x20content\x20will\x20be\x20replaced';}const e=[],f=new Set([...Object['keys'](c['frontmatter']),...Object['keys'](d['frontmatter'])]);for(const h of[...f]['sort']()){const i=h in c['frontmatter'],j=h in d['frontmatter'];if(i&&!j)e['push']('-'+h);else{if(!i&&j)e['push']('+'+h);else{if(JSON['stringify'](c['frontmatter'][h])!==JSON['stringify'](d['frontmatter'][h]))e['push']('~'+h);}}}return c['body']!==d['body']&&e['push']('~body\x20('+c['body']['split']('\x0a')['length']+'\x20->\x20'+d['body']['split']('\x0a')['length']+'\x20lines)'),e['length']>0x0?e['join'](',\x20'):'whitespace/ordering\x20only';}export function repairBuiltinTemplates(a){const b=[],c=resolveTemplatesDir(),d=a?.['backup']!==![],e=a?.['dryRun']===!![],f=new Set(a?.['includeUserEdited']??[]);for(const g of BUILTIN_TEMPLATES){const h=join(c,g['industry'],TEMPLATES_SUBDIR),i=join(h,g['variant']+'.md');if(!existsSync(i))continue;const j=canonicalTemplateContent(g);let k=null,l='';const m={'template':g['id'],'status':'would_update','path':i};try{const p=stripReleaseSentinel(readFileSync(i,'utf-8'),TEMPLATE_SENTINEL_KIND);k=p['sentinel'],l=p['content'];}catch(q){m['status']='error',m['detail']=q['message'],b['push'](m);continue;}if(l===j)continue;let n;if(k){if(k['version']>BUILTIN_TEMPLATES_VERSION){m['status']='error',m['detail']='newer\x20release\x20on\x20disk\x20(sentinel\x20v'+k['version']+'\x20>\x20running\x20catalog\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20'+'repair\x20would\x20DOWNGRADE\x20and\x20lose\x20the\x20newer\x20release\x27s\x20content;\x20refused.\x20Upgrade\x20the\x20MCP\x20server\x20instead',b['push'](m);continue;}if(releaseBodyHash(l)!==k['hash']){if(!f['has'](g['id']))continue;n='sentinel-body\x20hash\x20mismatch\x20(sentinel\x20v'+k['version']+'\x20no\x20longer\x20binds\x20the\x20body)\x20'+'reseeded\x20under\x20EXPLICIT\x20include_user_edited\x20authorization';}else n='untouched\x20older\x20release\x20(sentinel\x20v'+k['version']+',\x20current\x20v'+BUILTIN_TEMPLATES_VERSION+')';}else{let r;try{r=String(parseTemplateFile(l)['frontmatter']['id']??'');}catch{continue;}if(r!==g['id'])continue;n='legacy\x20sentinel-less\x20builtin\x20file';}const o=summarizeTemplateDiff(l,j);if(e){m['status']='would_update',m['detail']=n+'\x20would\x20be\x20reseeded\x20from\x20BUILTIN_TEMPLATES\x20('+g['id']+')\x20—\x20diff\x20vs\x20canonical:\x20'+o+(d?';\x20previous\x20body\x20would\x20be\x20saved\x20as\x20<file>.bak':'')+'\x20—\x20execute\x20with\x20authorize=true\x20after\x20the\x20user\x20explicitly\x20confirms',b['push'](m);continue;}try{if(d)copyFileSync(i,i+'.bak');writeFileSync(i,renderTemplateFile(g),'utf-8'),cache['delete'](i),m['status']='updated',m['detail']=n+'\x20reseeded\x20from\x20BUILTIN_TEMPLATES\x20('+g['id']+')\x20—\x20diff\x20was:\x20'+o+(d?';\x20previous\x20body\x20saved\x20as\x20<file>.bak':'');}catch(s){m['status']='error',m['detail']=s['message'];}b['push'](m);}return b;}export function builtinTemplateDrift(a){const b=new Set(a?.['includeUserEdited']??[]),c=[],d=resolveTemplatesDir();for(const e of BUILTIN_TEMPLATES){const f=join(d,e['industry'],TEMPLATES_SUBDIR,e['variant']+'.md');if(!existsSync(f)){c['push']({'template':e['id'],'path':f,'state':'missing','repairable':!![],'detail':'no\x20file\x20on\x20disk;\x20seeding\x20will\x20create\x20it'});continue;}const g=canonicalTemplateContent(e);let h=null,i='';try{const k=stripReleaseSentinel(readFileSync(f,'utf-8'),TEMPLATE_SENTINEL_KIND);h=k['sentinel'],i=k['content'];}catch(l){c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'unreadable:\x20'+l['message']});continue;}if(i===g)continue;const j=summarizeTemplateDiff(i,g);if(!h){let m;try{m=String(parseTemplateFile(i)['frontmatter']['id']??'');}catch{m=undefined;}m===e['id']?c['push']({'template':e['id'],'path':f,'state':'modified','repairable':!![],'detail':'legacy\x20sentinel-less\x20builtin\x20file\x20—\x20seeding\x20never\x20rewrites\x20it\x20and\x20no\x20sentinel\x20proves\x20provenance;\x20repair\x20can\x20reseed\x20—\x20diff\x20vs\x20canonical:\x20'+j}):c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'no\x20release\x20sentinel\x20and\x20id\x20\x27'+(m??'<unparseable>')+'\x27\x20does\x20not\x20match\x20the\x20builtin\x20id\x20—\x20a\x20user\x20file\x20occupies\x20this\x20path;\x20never\x20touched\x20(rename\x20it\x20to\x20free\x20the\x20slot)'});continue;}if(releaseBodyHash(i)===h['hash'])h['version']>BUILTIN_TEMPLATES_VERSION?c['push']({'template':e['id'],'path':f,'state':'modified','repairable':![],'detail':'newer\x20release\x20(sentinel\x20v'+h['version']+'\x20>\x20running\x20catalog\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20'+'repair\x20would\x20DOWNGRADE\x20and\x20lose\x20the\x20newer\x20release\x27s\x20content;\x20repairable:\x20false.\x20'+'Upgrade\x20the\x20MCP\x20server\x20to\x20match\x20—\x20diff\x20vs\x20canonical:\x20'+j}):c['push']({'template':e['id'],'path':f,'state':'modified','repairable':!![],'detail':'untouched\x20older\x20release\x20(sentinel\x20v'+h['version']+',\x20current\x20v'+BUILTIN_TEMPLATES_VERSION+')\x20—\x20repair\x20can\x20upgrade\x20—\x20diff\x20vs\x20canonical:\x20'+j});else{const n=b['has'](e['id']);c['push']({'template':e['id'],'path':f,'state':'modified','repairable':n,'detail':n?'sentinel-body\x20hash\x20mismatch\x20(sentinel\x20v'+h['version']+'\x20no\x20longer\x20binds\x20the\x20body)\x20—\x20reseedable\x20under\x20the\x20explicit\x20include_user_edited\x20authorization\x20for\x20this\x20id\x20—\x20diff\x20vs\x20canonical:\x20'+j:'user-edited\x20body\x20—\x20kept\x20by\x20design;\x20repair\x20never\x20overwrites\x20user\x20edits\x20—\x20diff\x20vs\x20canonical:\x20'+j});}}return c;}const cache=new Map();export function reloadTemplates(){cache['clear'](),seeded=![];}export function loadAndValidate(a){const b=readFileSync(a,'utf-8');let c;try{c=parseTemplateFile(b);}catch(f){throw new Error('template\x20\x27'+a+'\x27\x20failed\x20to\x20parse:\x20'+f['message']);}const d=TemplateFrontmatterSchema['safeParse'](c['frontmatter']);if(!d['success']){const g=d['error']['issues']['map'](h=>(h['path']['join']('.')||'<root>')+':\x20'+h['message'])['join'](';\x20');throw new Error('template\x20\x27'+a+'\x27\x20failed\x20validation:\x20'+g);}const e=validateAllocatorRows(d['data']);if(e['length']>0x0)throw new Error('template\x20\x27'+a+'\x27\x20failed\x20allocator-row\x20validation:\x20'+e['join'](';\x20'));return{...d['data'],'body':c['body'],'source_path':a};}function templateFilesOnDisk(a){const b=[];if(!existsSync(a))return b;for(const c of readdirSync(a,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(a,c['name'],TEMPLATES_SUBDIR);if(!existsSync(d))continue;for(const e of readdirSync(d,{'withFileTypes':!![]})){if(e['isFile']()&&e['name']['endsWith']('.md'))b['push'](join(d,e['name']));}}return b['sort']();}export function listTemplates(){!seeded&&(seedBuiltinTemplates(),seeded=!![]);const a=resolveTemplatesDir(),b=[],c=[],d=new Set();for(const e of templateFilesOnDisk(a)){d['add'](e);try{const f=statSync(e)['mtimeMs'],g=cache['get'](e);if(g&&g['mtimeMs']===f){b['push'](g['template']);continue;}const h=loadAndValidate(e);cache['set'](e,{'mtimeMs':f,'template':h}),b['push'](h);}catch(i){cache['delete'](e),c['push'](i['message']);}}for(const j of[...cache['keys']()]){if(!d['has'](j))cache['delete'](j);}return b['sort']((k,l)=>k['id']['localeCompare'](l['id'])),{'templates':b,'errors':c};}export function getTemplate(a){return listTemplates()['templates']['find'](b=>b['id']===a);}export function getTemplatesByIndustry(a){return listTemplates()['templates']['filter'](b=>b['industry']===a);}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { IndustryTemplate } from "./template-loader.js";
|
|
3
|
+
export declare const PROSE_LANGUAGES: readonly ["en", "other"];
|
|
4
|
+
export type ProseLanguage = (typeof PROSE_LANGUAGES)[number];
|
|
5
|
+
export declare const PROSE_CLAIM_KEYS: readonly ["review_mode", "refund_rail", "reward_pool", "escrow_release", "independent_arbitration"];
|
|
6
|
+
export type ProseClaimKey = (typeof PROSE_CLAIM_KEYS)[number];
|
|
7
|
+
export declare const REVIEW_MODE_VALUES: readonly ["none", "review", "review_reward"];
|
|
8
|
+
export declare const MachineProseEnvelopeSchema: z.ZodObject<{
|
|
9
|
+
text_en: z.ZodString;
|
|
10
|
+
source_sha256: z.ZodString;
|
|
11
|
+
method: z.ZodEnum<{
|
|
12
|
+
human: "human";
|
|
13
|
+
llm: "llm";
|
|
14
|
+
}>;
|
|
15
|
+
model: z.ZodOptional<z.ZodString>;
|
|
16
|
+
prompt_version: z.ZodOptional<z.ZodString>;
|
|
17
|
+
claims: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
18
|
+
key: z.ZodEnum<{
|
|
19
|
+
review_mode: "review_mode";
|
|
20
|
+
refund_rail: "refund_rail";
|
|
21
|
+
reward_pool: "reward_pool";
|
|
22
|
+
escrow_release: "escrow_release";
|
|
23
|
+
independent_arbitration: "independent_arbitration";
|
|
24
|
+
}>;
|
|
25
|
+
value: z.ZodUnion<readonly [z.ZodBoolean, z.ZodEnum<{
|
|
26
|
+
review: "review";
|
|
27
|
+
none: "none";
|
|
28
|
+
review_reward: "review_reward";
|
|
29
|
+
}>]>;
|
|
30
|
+
evidence: z.ZodOptional<z.ZodString>;
|
|
31
|
+
}, z.core.$strict>>>;
|
|
32
|
+
}, z.core.$strict>;
|
|
33
|
+
export type MachineProseEnvelope = z.infer<typeof MachineProseEnvelopeSchema>;
|
|
34
|
+
export interface MachineProseField {
|
|
35
|
+
address: string;
|
|
36
|
+
text: string;
|
|
37
|
+
}
|
|
38
|
+
export interface MachineProseFinding {
|
|
39
|
+
rule_id: "R-PROSE-VERIFIABLE-01" | "R-PROSE-CANONICAL-01";
|
|
40
|
+
severity: "high";
|
|
41
|
+
title: string;
|
|
42
|
+
detail: string;
|
|
43
|
+
suggestion: string;
|
|
44
|
+
}
|
|
45
|
+
export declare function proseSourceDigest(text: string): string;
|
|
46
|
+
export declare function machineProseFields(t: IndustryTemplate): MachineProseField[];
|
|
47
|
+
export declare function trustedEnvelopes(t: IndustryTemplate): Map<string, MachineProseEnvelope>;
|
|
48
|
+
export declare function proseClaim(t: IndustryTemplate, address: string, key: ProseClaimKey): boolean | string | undefined;
|
|
49
|
+
export declare function canonicalizeMachineProse(t: IndustryTemplate): IndustryTemplate;
|
|
50
|
+
export declare function machineProseFindings(t: IndustryTemplate): MachineProseFinding[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from'node:crypto';import{z}from'zod';export const PROSE_LANGUAGES=['en','other'];export const PROSE_CLAIM_KEYS=['review_mode','refund_rail','reward_pool','escrow_release','independent_arbitration'];export const REVIEW_MODE_VALUES=['none','review','review_reward'];const ProseClaimSchema=z['object']({'key':z['enum'](PROSE_CLAIM_KEYS),'value':z['union']([z['boolean'](),z['enum'](REVIEW_MODE_VALUES)]),'evidence':z['string']()['max'](0x190)['optional']()})['strict']();export const MachineProseEnvelopeSchema=z['object']({'text_en':z['string']()['min'](0x1),'source_sha256':z['string']()['regex'](/^[0-9a-f]{64}$/,'source_sha256\x20must\x20be\x20lowercase\x20hex\x20sha256'),'method':z['enum'](['human','llm']),'model':z['string']()['max'](0x78)['optional'](),'prompt_version':z['string']()['max'](0x3c)['optional'](),'claims':z['array'](ProseClaimSchema)['max'](0x8)['optional']()})['strict']();function normalizeText(a){return a['replace'](/\s+/g,'\x20')['trim']();}export function proseSourceDigest(a){return createHash('sha256')['update'](normalizeText(a))['digest']('hex');}export function machineProseFields(a){const b=[];return a['build_notes']['forEach']((c,d)=>b['push']({'address':'build_notes['+d+']','text':c})),b['push']({'address':'allocator.description','text':a['allocator']['description']}),a['trust_mechanisms']['forEach']((c,d)=>b['push']({'address':'trust_mechanisms['+d+']','text':c})),a['guards']['forEach']((c,d)=>b['push']({'address':'guards['+d+'].purpose','text':c['purpose']})),a['machine_shape']['forEach']((c,d)=>b['push']({'address':'machine_shape['+d+'].role','text':c['role']})),b['filter'](c=>typeof c['text']==='string'&&normalizeText(c['text'])['length']>0x0);}const NON_LATIN_SCRIPT_PROBES=[['Han',/\p{Script=Han}/u],['Hiragana',/\p{Script=Hiragana}/u],['Katakana',/\p{Script=Katakana}/u],['Hangul',/\p{Script=Hangul}/u],['Cyrillic',/\p{Script=Cyrillic}/u],['Arabic',/\p{Script=Arabic}/u],['Hebrew',/\p{Script=Hebrew}/u],['Thai',/\p{Script=Thai}/u],['Devanagari',/\p{Script=Devanagari}/u]],ACCENTED_LATIN=/[\u00c0-\u024f\u1e00-\u1e0f\u1e20-\u1e7f]/g,NON_ENGLISH_FUNCTION_WORDS=new Set(['le','les','des','du','une','et','est','pour','avec','sur','dans','par','aux','peut','doit','sont','être','sera','cette','ces','nous','vous','mais','plus','der','die','das','und','ist','nicht','wird','mit','für','von','auf','dem','den','ein','eine','einen','auch','oder','bei','nach','zum','zur','keine','kann','muss']);function nonLatinScripts(a){const b=[];for(const [c,d]of NON_LATIN_SCRIPT_PROBES){if(d['test'](a))b['push'](c);}return b;}function nonEnglishSignals(a){const b=[],c=a['match'](ACCENTED_LATIN)??[];if(c['length']>=0x2)b['push'](c['length']+'\x20accented\x20Latin\x20letters');const d=a['toLowerCase']()['match'](/[a-zà-öø-ÿß]+/g)??[],e=new Set(d['filter'](f=>NON_ENGLISH_FUNCTION_WORDS['has'](f)));return e['size']>=0x2&&b['push']('non-English\x20function\x20words:\x20'+[...e]['slice'](0x0,0x4)['join'](',\x20')),b;}export function trustedEnvelopes(a){const b=new Map(machineProseFields(a)['map'](d=>[d['address'],d['text']])),c=new Map();for(const [d,e]of Object['entries'](a['machine_prose']??{})){const f=MachineProseEnvelopeSchema['safeParse'](e);if(!f['success'])continue;const g=b['get'](d);if(g===undefined)continue;if(proseSourceDigest(g)!==f['data']['source_sha256'])continue;c['set'](d,f['data']);}return c;}export function proseClaim(a,b,c){const d=trustedEnvelopes(a)['get'](b);if(!d)return undefined;const e=(d['claims']??[])['find'](f=>f['key']===c);return e?.['value'];}export function canonicalizeMachineProse(a){const b=trustedEnvelopes(a);if(b['size']===0x0)return a;const c=(d,e)=>b['get'](d)?.['text_en']??e;return{...a,'allocator':{...a['allocator'],'description':c('allocator.description',a['allocator']['description'])},'build_notes':a['build_notes']['map']((d,e)=>c('build_notes['+e+']',d)),'trust_mechanisms':a['trust_mechanisms']['map']((d,e)=>c('trust_mechanisms['+e+']',d)),'guards':a['guards']['map']((d,e)=>({...d,'purpose':c('guards['+e+'].purpose',d['purpose'])})),'machine_shape':a['machine_shape']['map']((d,e)=>({...d,'role':c('machine_shape['+e+'].role',d['role'])}))};}const CLAIM_KEYWORDS={'refund_rail':['refund','money-back','money\x20back'],'reward_pool':['reward','bonus'],'escrow_release':['escrow'],'independent_arbitration':['arbitration','third-party','third\x20party']};function affirmativeClauses(a){return a['split'](/[.;]/)['filter'](b=>!/\b(?:never|no|not|don'?t|cannot|must not|avoid|prohibit\w*|forbid\w*|instead of|rather than|previously|without)\b/i['test'](b))['join']('\x20.\x20');}function mentions(a,b){return b['some'](c=>{const d=c['replace'](/[-/\\^$*+?.()|[\]{}]/g,'\x5c$&')['replace'](/ /g,'\x5cs+');return new RegExp('\x5cb'+d+'(?:s|es|ed|ing)?\x5cb','i')['test'](a);});}const NUMERIC_TOKEN=/-?\d+(?:[.,]\d+)?%?/g,IDENTIFIER_TOKEN=/[a-z][a-z0-9]*(?:[._][a-z0-9]+)+/g;function numericTokens(a){return new Set((a['match'](NUMERIC_TOKEN)??[])['map'](b=>b['replace'](/[,_]/g,'')));}function identifierTokens(a){return new Set((a['match'](IDENTIFIER_TOKEN)??[])['map'](b=>b['toLowerCase']()));}function envelopeIntegrityIssues(a,b){const c=[],d=normalizeText(a['text']),e=normalizeText(b['text_en']),f=d['toLowerCase'](),g=affirmativeClauses(e),h=nonLatinScripts(e);if(h['length']>0x0)c['push'](a['address']+':\x20text_en\x20is\x20not\x20English\x20(non-Latin\x20script:\x20'+h['join'](',\x20')+')');else{const m=nonEnglishSignals(e);m['length']>0x0&&c['push'](a['address']+':\x20text_en\x20is\x20not\x20English\x20('+m['join'](';\x20')+')');}for(const o of b['claims']??[]){const p=o['value']===!![]||o['key']==='review_mode'&&o['value']!=='none';if(!p)continue;const q=o['evidence']?normalizeText(o['evidence']):'';(q['length']===0x0||!f['includes'](q['toLowerCase']()))&&c['push'](a['address']+':\x20claim\x20\x27'+o['key']+'\x27\x20asserts\x20a\x20capability\x20without\x20a\x20verbatim\x20source\x20quote');}const i=numericTokens(d),j=numericTokens(e);for(const r of i){!j['has'](r)&&c['push'](a['address']+':\x20numeric\x20token\x20\x27'+r+'\x27\x20from\x20the\x20source\x20is\x20missing\x20in\x20text_en');}const k=identifierTokens(d),l=identifierTokens(e);for(const s of k){!l['has'](s)&&c['push'](a['address']+':\x20identifier\x20\x27'+s+'\x27\x20from\x20the\x20source\x20is\x20missing\x20in\x20text_en');}for(const [t,u]of Object['entries'](CLAIM_KEYWORDS)){if(!mentions(g,u))continue;const v=(b['claims']??[])['find'](w=>w['key']===t);if(v?.['value']===!![])continue;c['push'](a['address']+':\x20text_en\x20names\x20a\x20\x27'+t+'\x27\x20capability\x20that\x20no\x20claim\x20asserts\x20(over-claim)');}return c;}export function machineProseFindings(a){const b=[],c=machineProseFields(a),d=a['prose_language']??'en',e=a['machine_prose']??{},f=[];for(const i of c){const j=e[i['address']],k=j?'present\x20but\x20not\x20trusted\x20(stale\x20or\x20malformed)':'missing';if(j){const n=MachineProseEnvelopeSchema['safeParse'](j);if(n['success']&&proseSourceDigest(i['text'])===n['data']['source_sha256'])continue;}if(d==='other'){f['push'](i['address']+'\x20(declared\x20non-English;\x20canonical\x20envelope\x20'+k+';\x20'+('expected\x20source_sha256='+proseSourceDigest(i['text'])+')'));continue;}const l=nonLatinScripts(i['text']);if(l['length']>0x0){f['push'](i['address']+'\x20(non-Latin\x20script:\x20'+l['join'](',\x20')+';\x20'+('expected\x20source_sha256='+proseSourceDigest(i['text'])+')'));continue;}const m=nonEnglishSignals(i['text']);m['length']>0x0&&f['push'](i['address']+'\x20('+m['join'](';\x20')+';\x20expected\x20source_sha256='+proseSourceDigest(i['text'])+')');}f['length']>0x0&&b['push']({'rule_id':'R-PROSE-VERIFIABLE-01','severity':'high','title':'Machine-read\x20prose\x20is\x20not\x20verifiable\x20('+f['length']+'\x20field'+(f['length']===0x1?'':'s')+')','detail':'The\x20pre-deploy\x20prose\x20rules\x20are\x20an\x20English\x20lexical\x20canon.\x20These\x20machine-read\x20fields\x20are\x20'+'neither\x20verifiably\x20English\x20nor\x20backed\x20by\x20a\x20frozen\x20canonical\x20English\x20envelope:\x20'+(f['join'](';\x20')+'.\x20Prose\x20the\x20scanner\x20cannot\x20read\x20matches\x20no\x20pattern\x20and\x20would\x20pass\x20')+'as\x20compliant\x20purely\x20by\x20silence.','suggestion':'Either\x20write\x20the\x20machine-read\x20prose\x20in\x20English,\x20or\x20author\x20it\x20in\x20any\x20language\x20and\x20declare\x20'+'prose_language:\x20\x27other\x27\x20with\x20one\x20machine_prose\x20envelope\x20per\x20field\x20'+'({text_en,\x20source_sha256,\x20method,\x20claims})\x20so\x20the\x20scanner\x20reads\x20a\x20frozen\x20English\x20rendering.\x20'+'Each\x20listed\x20field\x20prints\x20its\x20expected\x20source_sha256\x20(sha256\x20of\x20the\x20whitespace-collapsed\x20'+'source)\x20—\x20copy\x20it\x20verbatim\x20into\x20the\x20envelope.\x20'+'This\x20finding\x20blocks\x20template_generate\x20(fail-closed)\x20until\x20the\x20prose\x20is\x20verifiable.'});const g=[],h=new Set(c['map'](o=>o['address']));for(const [o,p]of Object['entries'](e)){const q=MachineProseEnvelopeSchema['safeParse'](p);if(!q['success']){g['push'](o+':\x20envelope\x20does\x20not\x20match\x20the\x20contract\x20('+(q['error']['issues'][0x0]?.['message']??'invalid')+')');continue;}if(!h['has'](o)){g['push'](o+':\x20envelope\x20targets\x20a\x20prose\x20field\x20that\x20does\x20not\x20exist');continue;}const r=c['find'](s=>s['address']===o);if(proseSourceDigest(r['text'])!==q['data']['source_sha256']){g['push'](o+':\x20envelope\x20is\x20stale\x20(source_sha256\x20does\x20not\x20match\x20the\x20current\x20prose;\x20'+('expected\x20source_sha256='+proseSourceDigest(r['text'])+')'));continue;}q['data']['method']==='llm'&&!q['data']['model']&&!q['data']['prompt_version']&&g['push'](o+':\x20llm-normalized\x20envelope\x20carries\x20no\x20model\x20/\x20prompt_version\x20provenance'),g['push'](...envelopeIntegrityIssues(r,q['data']));}if(d==='other')for(const s of c){!e[s['address']]&&g['push'](s['address']+':\x20missing\x20envelope\x20(prose_language=\x27other\x27\x20requires\x20one\x20per\x20non-empty\x20'+('machine-read\x20field;\x20expected\x20source_sha256='+proseSourceDigest(s['text'])+')'));}return g['length']>0x0&&b['push']({'rule_id':'R-PROSE-CANONICAL-01','severity':'high','title':'Canonical\x20prose\x20envelope\x20integrity\x20failure\x20('+g['length']+')','detail':'A\x20canonical\x20envelope\x20must\x20be\x20FROZEN\x20(source_sha256\x20binds\x20the\x20exact\x20prose),\x20must\x20not\x20invent\x20'+'capabilities\x20(asserted\x20claims\x20need\x20a\x20verbatim\x20source\x20quote),\x20must\x20carry\x20numbers\x20and\x20code\x20'+('identifiers\x20verbatim,\x20and\x20must\x20not\x20name\x20a\x20capability\x20its\x20claims\x20deny:\x20'+g['join'](';\x20')+'.'),'suggestion':'Re-normalize\x20the\x20affected\x20field\x20from\x20the\x20CURRENT\x20prose,\x20copy\x20the\x20source\x20quote\x20verbatim\x20into\x20'+'the\x20claim\x20evidence,\x20keep\x20numbers\x20and\x20fee/param\x20identifiers\x20untranslated,\x20and\x20either\x20assert\x20the\x20'+'capability\x20in\x20a\x20claim\x20or\x20remove\x20it\x20from\x20text_en.\x20A\x20stale\x20binding\x20prints\x20the\x20expected\x20'+'source_sha256\x20—\x20copy\x20it\x20verbatim.\x20This\x20finding\x20blocks\x20template_generate\x20(fail-closed).'}),b;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GUARD_TEMPLATES,fillGuardTemplate}from'./guard-templates.js';import{MACHINE_TEMPLATES,fillTemplate as
|
|
1
|
+
import{GUARD_TEMPLATES,fillGuardTemplate}from'./guard-templates.js';import{MACHINE_TEMPLATES,fillTemplate as a317a}from'./machine-templates.js';import{SERVICE_TEMPLATES,fillServiceTemplate}from'./service-templates.js';import{ORDER_TEMPLATES,fillTemplate as a317b}from'./order-templates.js';import{PROGRESS_TEMPLATES,fillProgressTemplate}from'./progress-templates.js';import{ARBITRATION_TEMPLATES,fillTemplate as a317c}from'./arbitration-templates.js';import{TREASURY_TEMPLATES,fillTemplate as a317d}from'./treasury-templates.js';import{PERMISSION_TEMPLATES,fillTemplate as a317e}from'./permission-templates.js';import{PASSPORT_TEMPLATES,fillTemplate as a317f}from'./passport-templates.js';import{ALLOCATION_TEMPLATES,fillTemplate as a317g}from'./allocation-templates.js';import{CONTACT_TEMPLATES,fillTemplate as a317h}from'./contact-templates.js';import{REWARD_TEMPLATES}from'./reward-templates.js';export const TEMPLATE_REGISTRY_VERSION=0x1;export const TEMPLATE_OBJECT_TYPES=['guard','machine','service','order','progress','arbitration','treasury','permission','passport','allocation','reward','contact'];function normalizeParam(a){return{'name':a['name'],'type':a['type'],'description':a['description']??'','required':a['required'],...a['default']!==undefined?{'default':a['default']}:{},...a['constraint']!==undefined?{'constraint':a['constraint']}:{}};}function guardMeta(a){return{'id':a['id'],'object_type':'guard','name':a['name'],'description':a['description'],'scenes':[a['scene_id']],'industries':a['applicable_industries'],'instantiable':!![],'parameters':a['parameters']['map'](b=>normalizeParam(b))};}function machineMeta(a){return{'id':a['id'],'object_type':'machine','name':a['name'],'description':a['description'],'scenes':[a['scene_id']],'industries':a['applicable_industries'],'instantiable':!![],'parameters':a['parameters']['map'](b=>normalizeParam(b))};}function bodyMeta(a,b,c,d){return{'id':a['id'],'object_type':b,'name':a['name'],'description':a['description'],'scenes':c,'industries':d,'instantiable':!![],'parameters':a['params']['map'](e=>normalizeParam(e))};}function rewardMeta(a){return{'id':a['type'],'object_type':'reward','name':a['name'],'description':a['description'],'scenes':[],'industries':[],'instantiable':![],'parameters':a['parameters']['map'](b=>normalizeParam(b))};}let REGISTRY=null,ID_COLLISIONS=[];function buildRegistry(){const a=new Map(),b=[],c=d=>{if(a['has'](d['meta']['id'])){b['push'](d['meta']['id']);return;}a['set'](d['meta']['id'],d);};for(const d of GUARD_TEMPLATES){c({'meta':guardMeta(d),'raw':d,'notes':d['creation_notes']});}for(const e of MACHINE_TEMPLATES){c({'meta':machineMeta(e),'raw':e,'notes':e['creation_notes']});}for(const f of SERVICE_TEMPLATES){c({'meta':bodyMeta(f,'service',f['applicable_scenes'],f['industry_tags']),'raw':f,'notes':f['notes']});}for(const g of ORDER_TEMPLATES){c({'meta':bodyMeta(g,'order',g['applicable_scenes'],g['industry_tags']),'raw':g,'notes':g['notes']});}for(const h of PROGRESS_TEMPLATES){c({'meta':bodyMeta(h,'progress',h['applicable_scenes'],h['industry_tags']),'raw':h,'notes':h['notes']});}for(const i of ARBITRATION_TEMPLATES){c({'meta':bodyMeta(i,'arbitration',i['applicable_scenes'],i['industry_tags']),'raw':i,'notes':i['notes']});}for(const j of TREASURY_TEMPLATES){c({'meta':bodyMeta(j,'treasury',j['applicable_scenes'],j['industry_tags']),'raw':j,'notes':j['notes']});}for(const k of PERMISSION_TEMPLATES){c({'meta':bodyMeta(k,'permission',k['applicable_scenes'],k['industry_tags']),'raw':k,'notes':k['notes']});}for(const l of PASSPORT_TEMPLATES){c({'meta':bodyMeta(l,'passport',l['applicable_scenarios'],l['industry_tags']),'raw':l,'notes':l['notes']});}for(const m of ALLOCATION_TEMPLATES){c({'meta':bodyMeta(m,'allocation',m['applicable_scenes'],m['industry_tags']),'raw':m,'notes':m['notes']});}for(const n of REWARD_TEMPLATES){c({'meta':rewardMeta(n),'raw':n,'guidance':{'guardCondition':n['guardCondition'],'amountRange':n['amountRange'],'allocationStrategy':n['allocationStrategy'],'example':n['example'],'relevantGuardOps':n['relevantGuardOps']}});}for(const o of CONTACT_TEMPLATES){c({'meta':bodyMeta(o,'contact',o['applicable_scenes'],o['industry_tags']),'raw':o,'notes':o['notes']});}return ID_COLLISIONS=b,a;}function registry(){return!REGISTRY&&(REGISTRY=buildRegistry()),REGISTRY;}export function getTemplateIdCollisions(){return registry(),ID_COLLISIONS;}export function getTemplateCounts(){const a=Object['fromEntries'](TEMPLATE_OBJECT_TYPES['map'](b=>[b,0x0]));for(const b of registry()['values']()){a[b['meta']['object_type']]+=0x1;}return a;}export function listTemplates(a){const b=[...registry()['values']()]['map'](c=>c['meta']);return a?b['filter'](c=>c['object_type']===a):b;}export function getTemplateDetail(a){const b=registry()['get'](a);if(!b)return null;return{...b['meta'],'raw':b['raw'],...b['notes']?{'notes':b['notes']}:{},...b['guidance']?{'guidance':b['guidance']}:{}};}export function findTemplateObjectType(a){return registry()['get'](a)?.['meta']['object_type']??null;}export function instantiateTemplate(a,b){const c=registry()['get'](a);if(!c)return{'ok':![],'object_type':null,'template_id':a,'error':'Template\x20not\x20found:\x20'+a+'.\x20Use\x20get_templates\x20without\x20\x27template\x27\x20to\x20list\x20all\x20template\x20ids.'};const d=c['meta']['object_type'];if(!c['meta']['instantiable'])return{'ok':![],'object_type':d,'template_id':a,'error':'Reward\x20templates\x20are\x20guidance-only\x20(prose\x20guard\x20conditions)\x20and\x20cannot\x20be\x20'+'instantiated\x20into\x20executable\x20JSON.\x20Use\x20the\x20guidance\x20payload\x20to\x20design\x20the\x20'+'Reward\x20+\x20Guard\x20manually.','guidance':c['guidance']};switch(d){case'guard':{const e=fillGuardTemplate(a,b);if(!e['ok'])return{'ok':![],'object_type':d,'template_id':a,'error':e['error'],...e['missing']?{'missing_params':e['missing']}:{}};return{'ok':!![],'object_type':d,'template_id':a,'body':{'table':e['table'],'root':e['root']},...c['notes']?{'notes':c['notes']}:{}};}case'machine':{const f=a317a(a,b);if(!f['success'])return{'ok':![],'object_type':d,'template_id':a,'error':f['validation_errors']?.['join'](';\x20')??'Machine\x20template\x20fill\x20failed',...f['missing_params']?{'missing_params':f['missing_params']}:{}};return{'ok':!![],'object_type':d,'template_id':a,'body':{'nodes':f['filled_nodes'],'pairs':f['filled_pairs']},...c['notes']?{'notes':c['notes']}:{}};}case'service':{const g=fillServiceTemplate(a,b);if(!g['ok'])return{'ok':![],'object_type':d,'template_id':a,'error':g['error']??'Service\x20template\x20fill\x20failed',...g['missing_required']?{'missing_params':g['missing_required']}:{}};return{'ok':!![],'object_type':d,'template_id':a,'body':g['body'],...c['notes']?{'notes':c['notes']}:{}};}case'order':case'arbitration':case'treasury':case'permission':case'passport':case'allocation':case'progress':case'contact':{const h=fillBodyTemplate(d,a,b);if(!h['ok'])return{'ok':![],'object_type':d,'template_id':a,'error':h['error']};return{'ok':!![],'object_type':d,'template_id':a,'body':h['body'],...c['notes']?{'notes':c['notes']}:{}};}default:return{'ok':![],'object_type':d,'template_id':a,'error':'Instantiation\x20not\x20supported\x20for\x20object_type\x20\x27'+d+'\x27'};}}function fillBodyTemplate(a,b,c){switch(a){case'order':return a317b(b,c);case'arbitration':return a317c(b,c);case'treasury':return a317d(b,c);case'permission':return a317e(b,c);case'passport':return a317f(b,c);case'allocation':return a317g(b,c);case'progress':return fillProgressTemplate(b,c);case'contact':return a317h(b,c);default:return{'ok':![],'error':'No\x20body-template\x20fill\x20for\x20\x27'+a+'\x27'};}}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PLATFORM_TAKE_KEY } from "./template-loader.js";
|
|
1
2
|
import type { IndustryTemplate } from "./template-loader.js";
|
|
2
3
|
export type TemplateRiskLevel = "low" | "medium" | "high" | "critical";
|
|
3
4
|
export interface TemplateScanFinding {
|
|
@@ -14,6 +15,7 @@ export interface TemplateScanResult {
|
|
|
14
15
|
findings: TemplateScanFinding[];
|
|
15
16
|
red_flags: string[];
|
|
16
17
|
}
|
|
18
|
+
export { PLATFORM_TAKE_KEY };
|
|
17
19
|
export type AfterSalesModeRail = Exclude<IndustryTemplate["after_sales_mode"], undefined | "none">;
|
|
18
20
|
export declare function afterSalesRailRegex(mode: AfterSalesModeRail): RegExp;
|
|
19
21
|
export declare function afterSalesRailNodeMatches(mode: AfterSalesModeRail, name: string): boolean;
|
|
@@ -27,12 +29,13 @@ interface RatingKeyRow {
|
|
|
27
29
|
export declare function auditRewardRootRatingKey(root: unknown, table: RatingKeyRow[]): string[];
|
|
28
30
|
export declare function rootNegatesRepoDataHasTemplateRoot(node: unknown): boolean;
|
|
29
31
|
export interface FeeParamLanding {
|
|
30
|
-
surface: "guard" | "allocator_row" | "time_anchor" | "directive";
|
|
32
|
+
surface: "guard" | "allocator_row" | "time_anchor" | "directive" | "kernel";
|
|
31
33
|
site: string;
|
|
32
34
|
excerpt: string;
|
|
33
35
|
recipient_blank?: boolean;
|
|
34
36
|
}
|
|
35
37
|
export declare function isSplitFamilyFeeParam(key: string): boolean;
|
|
38
|
+
export declare function isKernelConsumedFeeParam(key: string): boolean;
|
|
36
39
|
export declare function collectFeeParamLandings(t: IndustryTemplate): Map<string, FeeParamLanding[]>;
|
|
37
40
|
export declare function buildFeeParamLandingTable(t: IndustryTemplate, fee: Record<string, number | string>): Array<{
|
|
38
41
|
param: string;
|
|
@@ -40,5 +43,4 @@ export declare function buildFeeParamLandingTable(t: IndustryTemplate, fee: Reco
|
|
|
40
43
|
split_family: boolean;
|
|
41
44
|
landings: FeeParamLanding[];
|
|
42
45
|
}>;
|
|
43
|
-
export declare function scanTemplate(
|
|
44
|
-
export {};
|
|
46
|
+
export declare function scanTemplate(raw: IndustryTemplate): TemplateScanResult;
|