@wowok/agent-mcp 2.7.10 → 3.0.1
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/communication/evidence.d.ts +6 -0
- package/dist/communication/evidence.js +1 -0
- package/dist/evaluation/acceptance.d.ts +24 -0
- package/dist/evaluation/acceptance.js +1 -0
- package/dist/evaluation/builtins/demand-match.d.ts +3 -2
- package/dist/evaluation/builtins/demand-match.js +1 -1
- package/dist/evaluation/builtins/service-risk.d.ts +2 -1
- package/dist/evaluation/builtins/service-risk.js +1 -1
- package/dist/evaluation/index.d.ts +1 -0
- package/dist/evaluation/index.js +1 -1
- package/dist/evaluation/match-operation.d.ts +14 -0
- package/dist/evaluation/match-operation.js +1 -0
- package/dist/experience/realtime-feedback.js +1 -1
- package/dist/extensions/capability-manifest.d.ts +1 -82
- package/dist/extensions/capability-manifest.js +1 -1
- package/dist/extensions/constraint-registry.d.ts +6 -4
- package/dist/extensions/constraint-registry.js +1 -1
- package/dist/extensions/index.d.ts +4 -5
- package/dist/extensions/index.js +1 -1
- package/dist/extensions/industry-pack.js +1 -1
- package/dist/extensions/metric-registry.d.ts +6 -4
- package/dist/extensions/metric-registry.js +1 -1
- package/dist/extensions/mode-evaluator.d.ts +2 -3
- package/dist/extensions/mode-evaluator.js +1 -1
- package/dist/extensions/modes.js +1 -1
- package/dist/extensions/registry.d.ts +3 -25
- package/dist/extensions/registry.js +1 -1
- package/dist/extensions/types.d.ts +0 -68
- package/dist/goal/GoalClassifier.js +1 -1
- package/dist/goal/GoalEngine.d.ts +44 -1
- package/dist/goal/GoalEngine.js +1 -1
- package/dist/goal/types.d.ts +5 -1
- package/dist/harness/auto-escalation.d.ts +0 -12
- package/dist/harness/auto-escalation.js +1 -1
- package/dist/harness/index.d.ts +1 -14
- package/dist/harness/index.js +1 -1
- package/dist/harness/types.d.ts +0 -38
- package/dist/keeper/KeeperScan.d.ts +39 -0
- package/dist/keeper/KeeperScan.js +1 -0
- package/dist/keeper/KeeperStore.d.ts +43 -0
- package/dist/keeper/KeeperStore.js +1 -0
- package/dist/keeper/detectors.d.ts +23 -0
- package/dist/keeper/detectors.js +1 -0
- package/dist/keeper/keeper.spec.d.ts +1 -0
- package/dist/keeper/keeper.spec.js +1 -0
- package/dist/keeper/types.d.ts +65 -0
- package/dist/keeper/types.js +1 -0
- package/dist/knowledge/account-marks.d.ts +1 -0
- package/dist/knowledge/account-marks.js +1 -1
- package/dist/knowledge/demand-risk.js +1 -1
- package/dist/knowledge/event-semantics.d.ts +3 -0
- package/dist/knowledge/event-semantics.js +1 -1
- package/dist/knowledge/event-semantics.spec.d.ts +1 -0
- package/dist/knowledge/event-semantics.spec.js +1 -0
- package/dist/knowledge/evidence-review.d.ts +23 -0
- package/dist/knowledge/evidence-review.js +1 -1
- package/dist/knowledge/examples-scanner-cli.js +1 -1
- package/dist/knowledge/examples-scanner.js +1 -1
- package/dist/knowledge/fund-layer.d.ts +13 -9
- package/dist/knowledge/fund-layer.js +1 -1
- package/dist/knowledge/goal-completion.js +1 -1
- package/dist/knowledge/guard-bindings.d.ts +21 -0
- package/dist/knowledge/guard-bindings.js +1 -0
- package/dist/knowledge/guard-bytecode-spec.d.ts +82 -0
- package/dist/knowledge/guard-bytecode-spec.js +1 -0
- package/dist/knowledge/guard-design-patterns.d.ts +1 -1
- package/dist/knowledge/guard-design-patterns.js +1 -1
- package/dist/knowledge/index.d.ts +13 -7
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/industry-registry.js +1 -1
- package/dist/knowledge/mcp-schema-audit-cli.js +1 -1
- package/dist/knowledge/mcp-schema-audit.js +1 -1
- package/dist/knowledge/reward-risk.d.ts +1 -1
- package/dist/knowledge/reward-risk.js +1 -1
- package/dist/knowledge/safety-rules.d.ts +2 -1
- package/dist/knowledge/safety-rules.js +1 -1
- package/dist/knowledge/scenario-modes.d.ts +1 -1
- package/dist/knowledge/scenario-modes.js +1 -1
- package/dist/knowledge/scenario-topology.d.ts +43 -0
- package/dist/knowledge/scenario-topology.js +1 -0
- package/dist/knowledge/supply-chain.js +1 -1
- package/dist/knowledge/template-registry.js +1 -1
- package/dist/knowledge/tools-reference.js +1 -1
- package/dist/knowledge/workflow-guidance.d.ts +55 -0
- package/dist/knowledge/workflow-guidance.js +1 -1
- package/dist/knowledge/workspace-lists.d.ts +1 -0
- package/dist/knowledge/workspace-lists.js +1 -1
- package/dist/monitor/MonitorLoop.d.ts +3 -0
- package/dist/monitor/MonitorLoop.js +1 -1
- package/dist/monitor/ScopeResolver.js +1 -1
- package/dist/monitor/SuggestionBridge.d.ts +38 -0
- package/dist/monitor/SuggestionBridge.js +1 -0
- package/dist/monitor/SuggestionBridge.spec.d.ts +1 -0
- package/dist/monitor/SuggestionBridge.spec.js +1 -0
- package/dist/monitor/types.d.ts +0 -1
- package/dist/monitor/types.js +1 -1
- package/dist/participation/arbitrator-interest.d.ts +20 -0
- package/dist/participation/arbitrator-interest.js +1 -0
- package/dist/participation/demander-interest.d.ts +23 -0
- package/dist/participation/demander-interest.js +1 -0
- package/dist/participation/employee-kpi.d.ts +12 -0
- package/dist/participation/employee-kpi.js +1 -1
- package/dist/participation/employee-kpi.spec.d.ts +1 -0
- package/dist/participation/employee-kpi.spec.js +1 -0
- package/dist/playbooks/service-build/business-puzzle.js +1 -1
- package/dist/playbooks/service-build/context-assembly.js +1 -1
- package/dist/playbooks/service-build/machine-nodes.js +1 -1
- package/dist/playbooks/service-build/machine-panorama.js +1 -1
- package/dist/playbooks/service-build/merchant-guide.d.ts +20 -0
- package/dist/playbooks/service-build/merchant-guide.js +1 -1
- package/dist/playbooks/service-build/mode-actions.d.ts +30 -12
- 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.d.ts +2 -0
- package/dist/playbooks/service-build/relationship-profile.js +1 -0
- package/dist/playbooks/service-build/semantic-graph.d.ts +5 -1
- package/dist/playbooks/service-build/semantic-graph.js +1 -1
- package/dist/playbooks/service-build/service-panorama.js +1 -1
- package/dist/relationship/derivation.d.ts +94 -0
- package/dist/relationship/derivation.js +1 -0
- package/dist/relationship/derivation.spec.d.ts +1 -0
- package/dist/relationship/derivation.spec.js +1 -0
- package/dist/relationship/incentive.d.ts +38 -0
- package/dist/relationship/incentive.js +1 -0
- package/dist/relationship/index.d.ts +4 -0
- package/dist/relationship/index.js +1 -0
- package/dist/relationship/registry.d.ts +13 -0
- package/dist/relationship/registry.js +1 -0
- package/dist/relationship/types.d.ts +45 -0
- package/dist/relationship/types.js +1 -0
- package/dist/review/progress.js +1 -1
- package/dist/role/index.d.ts +2 -2
- package/dist/role/index.js +1 -1
- package/dist/role/model.d.ts +2 -1
- package/dist/role/model.js +1 -1
- package/dist/role/types.d.ts +5 -0
- package/dist/rules.d.ts +1 -1
- package/dist/safety/confirm-gate.js +1 -1
- package/dist/safety/preview.js +1 -1
- package/dist/schema/call/bridge.d.ts +25 -3
- package/dist/schema/call/bridge.js +1 -1
- package/dist/schema/call/semantic.js +1 -1
- package/dist/schema/common/index.js +1 -1
- package/dist/schema/employee/index.d.ts +61 -1
- package/dist/schema/employee/index.js +1 -1
- package/dist/schema/evaluation/index.d.ts +70 -5
- package/dist/schema/evaluation/index.js +1 -1
- package/dist/schema/goal/index.d.ts +40 -14
- package/dist/schema/goal/index.js +1 -1
- package/dist/schema/goal/planning.d.ts +6 -6
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/index.js +1 -1
- package/dist/schema/industry-pack/index.d.ts +59 -7
- package/dist/schema/industry-pack/index.js +1 -1
- package/dist/schema/industry-pack/modes.d.ts +59 -7
- package/dist/schema/industry-pack/modes.js +1 -1
- package/dist/schema/intent-radar/index.d.ts +19 -19
- package/dist/schema/keeper/index.d.ts +475 -0
- package/dist/schema/keeper/index.js +1 -0
- package/dist/schema/local/index.d.ts +11 -0
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/messenger/index.d.ts +2 -0
- package/dist/schema/messenger/index.js +1 -1
- package/dist/schema/operations.d.ts +64 -16
- package/dist/schema/persona/index.d.ts +1 -1
- package/dist/schema/query/bi.d.ts +244 -16
- package/dist/schema/query/bi.js +1 -1
- package/dist/schema/query/index.d.ts +2 -2
- package/dist/schema/schema-query/index.d.ts +2 -11
- package/dist/schema/schema-query/index.js +1 -1
- package/dist/schema/schema-version.js +1 -1
- package/dist/schema/utils/skills-recommendation.js +1 -1
- package/dist/schema/watch/index.d.ts +4 -0
- package/dist/schema/watch/index.js +1 -1
- package/dist/schema-query-impl/index.d.ts +33 -14
- package/dist/schema-query-impl/index.js +1 -1
- package/dist/schemas/account_operation.output.json +29 -0
- package/dist/schemas/account_operation.schema.json +6 -2
- package/dist/schemas/bridge_operation.output.json +24 -1
- package/dist/schemas/bridge_operation.schema.json +73 -1
- package/dist/schemas/employee_operation.output.json +100 -0
- package/dist/schemas/employee_operation.schema.json +148 -5
- package/dist/schemas/evaluation_operation.output.json +135 -9
- package/dist/schemas/evaluation_operation.schema.json +176 -7
- package/dist/schemas/goal_operation.schema.json +76 -0
- package/dist/schemas/index.json +7 -1
- package/dist/schemas/industry_pack_operation.output.json +172 -27
- package/dist/schemas/industry_pack_operation.schema.json +19 -0
- package/dist/schemas/keeper_operation.output.json +1274 -0
- package/dist/schemas/keeper_operation.schema.json +359 -0
- package/dist/schemas/messenger_operation.schema.json +8 -0
- package/dist/schemas/onchain_events.output.json +1 -1
- package/dist/schemas/onchain_operations.schema.json +41 -41
- package/dist/schemas/onchain_operations_allocation.schema.json +4 -4
- package/dist/schemas/onchain_operations_arbitration.schema.json +3 -3
- package/dist/schemas/onchain_operations_contact.schema.json +2 -2
- package/dist/schemas/onchain_operations_demand.schema.json +2 -2
- package/dist/schemas/onchain_operations_machine.schema.json +2 -2
- package/dist/schemas/onchain_operations_order.schema.json +2 -2
- package/dist/schemas/onchain_operations_payment.schema.json +1 -1
- package/dist/schemas/onchain_operations_permission.schema.json +2 -2
- package/dist/schemas/onchain_operations_progress.schema.json +2 -2
- package/dist/schemas/onchain_operations_repository.schema.json +2 -2
- package/dist/schemas/onchain_operations_reward.schema.json +6 -6
- package/dist/schemas/onchain_operations_service.schema.json +7 -7
- package/dist/schemas/onchain_operations_treasury.schema.json +6 -6
- package/dist/schemas/onchain_table_data.output.json +71 -0
- package/dist/schemas/query_toolkit.output.json +485 -7
- package/dist/schemas/query_toolkit.schema.json +71 -0
- package/dist/schemas/schema_query.output.json +1 -64
- package/dist/schemas/schema_query.schema.json +18 -3
- package/dist/schemas/watch_operation.output.json +21 -1
- package/dist/task/ProcessStore.d.ts +18 -1
- package/dist/task/ProcessStore.js +1 -1
- package/dist/task/playbook.js +1 -1
- package/dist/task/types.d.ts +24 -0
- package/dist/tools/handlers/bridge.js +1 -1
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/employee.d.ts +6 -0
- package/dist/tools/handlers/employee.js +1 -1
- package/dist/tools/handlers/employee.spec.d.ts +1 -0
- package/dist/tools/handlers/employee.spec.js +1 -0
- package/dist/tools/handlers/evaluation.js +1 -1
- package/dist/tools/handlers/evaluation.spec.d.ts +1 -0
- package/dist/tools/handlers/evaluation.spec.js +1 -0
- package/dist/tools/handlers/goal.js +1 -1
- package/dist/tools/handlers/industry-pack.js +1 -1
- package/dist/tools/handlers/keeper.d.ts +12 -0
- package/dist/tools/handlers/keeper.js +1 -0
- package/dist/tools/handlers/local.d.ts +4 -3
- package/dist/tools/handlers/local.js +1 -1
- package/dist/tools/handlers/messenger.js +1 -1
- package/dist/tools/handlers/onchain.js +1 -1
- package/dist/tools/handlers/permission.js +1 -1
- package/dist/tools/handlers/query.js +1 -1
- package/dist/tools/handlers/schema-query.js +1 -1
- package/dist/tools/handlers/watch.js +1 -1
- package/dist/tools/handlers/workflow.js +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/registry/agent.d.ts +2 -0
- package/dist/tools/registry/agent.js +1 -0
- package/dist/tools/registry/bridge.d.ts +2 -0
- package/dist/tools/registry/bridge.js +1 -0
- package/dist/tools/registry/business.d.ts +2 -0
- package/dist/tools/registry/business.js +1 -0
- package/dist/tools/registry/config.d.ts +2 -0
- package/dist/tools/registry/config.js +1 -0
- package/dist/tools/registry/files.d.ts +2 -0
- package/dist/tools/registry/files.js +1 -0
- package/dist/tools/registry/identity.d.ts +2 -0
- package/dist/tools/registry/identity.js +1 -0
- package/dist/tools/registry/local.d.ts +2 -0
- package/dist/tools/registry/local.js +1 -0
- package/dist/tools/registry/messenger.d.ts +2 -0
- package/dist/tools/registry/messenger.js +1 -0
- package/dist/tools/registry/monitor.d.ts +2 -0
- package/dist/tools/registry/monitor.js +1 -0
- package/dist/tools/registry/onchain.d.ts +2 -0
- package/dist/tools/registry/onchain.js +1 -0
- package/dist/tools/registry/query.d.ts +2 -0
- package/dist/tools/registry/query.js +1 -0
- package/dist/tools/registry/trust.d.ts +2 -0
- package/dist/tools/registry/trust.js +1 -0
- package/dist/tools/rules-hook.d.ts +1 -0
- package/dist/tools/rules-hook.js +1 -1
- package/dist/tools/shared.js +1 -1
- package/dist/tools/wrap.js +1 -1
- package/package.json +2 -2
- package/dist/examples/arbitration-dispute-create.json +0 -41
- package/dist/examples/arbitration-vote-weighted.json +0 -35
- package/dist/examples/arbitration-voting-guard-add.json +0 -38
- package/dist/examples/demand-present-service.json +0 -33
- package/dist/examples/education-contact-create.json +0 -40
- package/dist/examples/freelance-contact-create.json +0 -40
- package/dist/examples/gen-passport-verify-guard.json +0 -48
- package/dist/examples/guard-template-balance-check.json +0 -59
- package/dist/examples/guard-template-time-lock.json +0 -60
- package/dist/examples/insurance-guard-claim-timelock.json +0 -75
- package/dist/examples/insurance-guard-withdraw-allocation.json +0 -96
- package/dist/examples/insurance-machine-create.json +0 -75
- package/dist/examples/insurance-service-allocators.json +0 -55
- package/dist/examples/machine-multisig-threshold.json +0 -87
- package/dist/examples/machine-publish.json +0 -30
- package/dist/examples/machine-template-7node-rental.json +0 -119
- package/dist/examples/payment-scenario-bound.json +0 -45
- package/dist/examples/rental-ziroom-machine-create.json +0 -148
- package/dist/examples/rental-ziroom-permission-create.json +0 -41
- package/dist/examples/rental-ziroom-service-create.json +0 -36
- package/dist/examples/retail-adv-guard-customer-win-create.json +0 -80
- package/dist/examples/retail-adv-guard-messenger-proof-create.json +0 -65
- package/dist/examples/retail-adv-guard-reward-timeout-create.json +0 -92
- package/dist/examples/retail-adv-reward-guard-add.json +0 -51
- package/dist/examples/retail-myshop-allocation-activate.json +0 -55
- package/dist/examples/retail-myshop-arbitration-create.json +0 -40
- package/dist/examples/retail-myshop-contact-create.json +0 -43
- package/dist/examples/retail-myshop-order-create.json +0 -56
- package/dist/examples/retail-myshop-progress-operate.json +0 -38
- package/dist/examples/retail-myshop-reward-create.json +0 -35
- package/dist/examples/retail-myshop-service-create.json +0 -38
- package/dist/examples/retail-myshop-service-customer-required.json +0 -31
- package/dist/examples/service-discount-issue.json +0 -46
- package/dist/examples/subscription-contact-create.json +0 -40
- package/dist/examples/threebody-guard-create.json +0 -56
- package/dist/examples/threebody-machine-create.json +0 -71
- package/dist/examples/threebody-permission-create.json +0 -38
- package/dist/examples/threebody-service-allocators.json +0 -48
- package/dist/examples/travel-guard-time-lock.json +0 -69
- package/dist/examples/travel-guard-weather-oracle.json +0 -70
- package/dist/examples/travel-machine-create.json +0 -135
- package/dist/examples/travel-repository-create.json +0 -47
- package/dist/examples/travel-service-create.json +0 -34
- package/dist/examples/travel-treasury-create.json +0 -34
- package/dist/examples/treasury-deposit.json +0 -37
- package/dist/examples/treasury-withdraw.json +0 -38
- package/dist/harness/plan.d.ts +0 -33
- package/dist/harness/plan.js +0 -1
- package/dist/knowledge/demand-matching.d.ts +0 -29
- package/dist/knowledge/demand-matching.js +0 -1
- package/dist/knowledge/guard-context.d.ts +0 -56
- package/dist/knowledge/guard-context.js +0 -1
- package/dist/knowledge/guard-migration.d.ts +0 -48
- package/dist/knowledge/guard-migration.js +0 -1
- package/dist/mode-market/index.d.ts +0 -3
- package/dist/mode-market/index.js +0 -1
- package/dist/mode-market/registry.d.ts +0 -53
- package/dist/mode-market/registry.js +0 -1
- package/dist/mode-market/review.d.ts +0 -27
- package/dist/mode-market/review.js +0 -1
- package/dist/mode-market/submission.d.ts +0 -25
- package/dist/mode-market/submission.js +0 -1
- package/dist/schemas/guard-node-schema.json +0 -1000
- package/dist/task/stage-gate.d.ts +0 -22
- package/dist/task/stage-gate.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{UserModeStorage}from'@wowok/wowok';import{CapabilityRegistry}from'./capability-manifest.js';import{ModeEvaluator}from'./mode-evaluator.js';import{MetricRegistry}from'./metric-registry.js';import{ConstraintRegistry}from'./constraint-registry.js';import{BUILTIN_MODES}from'./modes.js';export class IndustryModeRegistry{static ['instance'];['registrations']=new Map();['userModes']=new Map();['aliases']=new Map();['evaluator'];['initialized']=![];['persistence']=new UserModeStorage();['userModesLoaded']=![];static['Instance'](){return!IndustryModeRegistry['instance']&&(IndustryModeRegistry['instance']=new IndustryModeRegistry()),IndustryModeRegistry['instance'];}constructor(){this['evaluator']=new ModeEvaluator(CapabilityRegistry['Instance'](),MetricRegistry['Instance'](),ConstraintRegistry['Instance']()),this['registerBuiltinModes'](),this['initialized']=!![];}['registerMode'](a,b){if(!a['name']||!a['traits']||!a['machine_shape'])return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20invalid\x20mode\x20'+('(name='+(a['name']||'<missing>')+',\x20traits='+(a['traits']?'ok':'<missing>')+',\x20')+('machine_shape='+(a['machine_shape']?'ok':'<missing>')+').')),![];if(this['registrations']['has'](a['name'])){const c=this['registrations']['get'](a['name']);return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20mode\x20\x27'+a['name']+'\x27\x20already\x20registered\x20'+('(registered_at='+new Date(c?.['registered_at']??0x0)['toISOString']()+').\x20')+'Use\x20evolveMode/deriveMode\x20for\x20user\x20modifications,\x20or\x20unregister\x20first.'),![];}this['registrations']['set'](a['name'],{'mode':a,'aliases':b,'enabled':!![],'registered_at':Date['now']()});if(b)for(const d of b){this['aliases']['set'](d,a['name']);}return!![];}['getMode'](a){const b=this['resolveAlias'](a);return this['registrations']['get'](b)?.['mode'];}['listModes'](){return Array['from'](this['registrations']['values']())['filter'](a=>a['enabled'])['map'](a=>a['mode']);}['resolveAlias'](a){return this['aliases']['get'](a)??a;}['hasMode'](a){const b=this['resolveAlias'](a);return this['registrations']['has'](b);}['unregisterMode'](a){const b=this['resolveAlias'](a);if(!this['registrations']['has'](b))return![];this['registrations']['delete'](b);for(const [c,d]of this['aliases']){if(d===b)this['aliases']['delete'](c);}return!![];}['evaluateMode'](a,b,c){const d=this['getMode'](a);if(!d)return{'applicable':![],'risk_score':0x64,'benefit_score':0x0,'risk_benefit_ratio':0x0,'capability_conflicts':[],'violated_constraints':[],'unmet_conditions':['Mode\x20\x27'+a+'\x27\x20not\x20found'],'recommendations':['Mode\x20\x27'+a+'\x27\x20not\x20registered,\x20falling\x20back\x20to\x20\x27general\x27']};return this['evaluator']['evaluateMode'](d,b,c);}['evaluateMigration'](a,b){const c=this['getMode'](a),d=this['getMode'](b);if(!c||!d)return{'feasibility_score':0x0,'source_risk_score':0x0,'target_risk_score':0x0,'source_benefit_score':0x0,'target_benefit_score':0x0,'risk_delta':0x0,'benefit_delta':0x0,'added_capabilities':[],'removed_capabilities':[],'conflicting_capabilities':[],'recommendations':['Mode\x20\x27'+a+'\x27\x20or\x20\x27'+b+'\x27\x20not\x20found']};return this['evaluator']['evaluateMigration'](c,d);}async['registerUserMode'](a,b){await this['ensureUserModesLoaded']();if(!a['name']||!a['owner']||!a['machine_shape'])return![];if(a['source']!=='custom')return![];if(a['owner']!==b)return![];const c=this['userModeKey'](a['owner'],a['name']);if(this['registrations']['has'](a['name']))return![];if(this['userModes']['has'](c))return![];return(!a['evolution_history']||a['evolution_history']['length']===0x0)&&(a['evolution_history']=[{'version':a['version']||'v1','changed_at':Date['now'](),'changes':['Initial\x20registration\x20(registerUserMode)']}]),this['userModes']['set'](c,a),await this['persistUserMode'](a),!![];}async['deriveMode'](a,b,c,d,e){await this['ensureUserModesLoaded']();const f=this['getMode'](a);if(!f)return undefined;if(!d||this['registrations']['has'](d))return undefined;const g=this['userModeKey'](c,d);if(this['userModes']['has'](g))return undefined;const h={'name':d,'display_name':e??d,'version':'v1','source':'custom','traits':b['traits']??f['traits'],'machine_shape':b['machine_shape']??f['machine_shape'],'guards':b['guards']??f['guards'],'allocator':b['allocator']??f['allocator'],'risk_checks':b['risk_checks']??f['risk_checks'],'needs':b['needs']??f['needs'],'flywheel':b['flywheel']??f['flywheel'],'key_risk':b['key_risk']??f['key_risk'],'build_notes':b['build_notes']??f['build_notes'],'capabilities_used':b['capabilities_used']??f['capabilities_used'],'config_overrides':b['config_overrides']??f['config_overrides'],'config_override_rules':b['config_override_rules']??f['config_override_rules'],'expected_benefits':b['expected_benefits']??f['expected_benefits'],'risk_appetite':b['risk_appetite']??f['risk_appetite'],'risk_constraints':b['risk_constraints']??f['risk_constraints'],'applicable_conditions':b['applicable_conditions']??f['applicable_conditions'],'similar_industries':b['similar_industries']??f['similar_industries'],'novel_capabilities':b['novel_capabilities']??f['novel_capabilities'],'owner':c,'derived_from':a,'custom_metrics':b['custom_metrics']??f['custom_metrics'],'custom_constraints':b['custom_constraints']??f['custom_constraints'],'evolution_history':[{'version':'v1','changed_at':Date['now'](),'changes':['Derived\x20from\x20builtin\x20\x27'+a+'\x27']}]};return this['userModes']['set'](g,h),await this['persistUserMode'](h),h;}async['evolveMode'](a,b,c,d,e=!![]){await this['ensureUserModesLoaded']();const f=this['userModeKey'](c,a),g=this['userModes']['get'](f);if(!g)return undefined;const h=e?this['bumpPatchVersion'](g['version']):g['version'],i={...g,...b,'name':g['name'],'owner':g['owner'],'source':'custom','derived_from':g['derived_from'],'evolution_history':[...g['evolution_history']??[],{'version':h,'changed_at':Date['now'](),'changes':[d]}],'version':h};return this['userModes']['set'](f,i),await this['persistUserMode'](i),i;}async['listUserModes'](a){await this['ensureUserModesLoaded']();const b=[];for(const c of this['userModes']['values']()){c['owner']===a&&b['push'](c);}return b;}async['getUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a);return this['userModes']['get'](c);}async['unregisterUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a),d=this['userModes']['delete'](c);return d&&await this['unpersistUserMode'](b,a),d;}['userModeKey'](a,b){return a+':'+b;}async['ensureUserModesLoaded'](){if(this['userModesLoaded'])return;this['userModesLoaded']=!![];try{const a=await this['persistence']['list']();for(const b of a){try{const c=JSON['parse'](b['data']);c?.['name']&&c?.['owner']&&c?.['machine_shape']&&this['userModes']['set'](this['userModeKey'](b['owner'],b['name']),c);}catch{console['warn']('[IndustryModeRegistry]\x20Skipping\x20corrupt\x20user_modes\x20row\x20\x27'+b['owner']+':'+b['name']+'\x27.');}}}catch(d){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20load\x20persisted\x20user\x20modes:',d['message']);}}async['persistUserMode'](a){try{await this['persistence']['save'](a['owner'],a['name'],JSON['stringify'](a));}catch(b){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20persist\x20user\x20mode\x20\x27'+a['owner']+':'+a['name']+'\x27:',b['message']);}}async['unpersistUserMode'](a,b){try{await this['persistence']['delete'](a,b);}catch(c){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20delete\x20persisted\x20user\x20mode\x20\x27'+a+':'+b+'\x27:',c['message']);}}['bumpPatchVersion'](a){const b=a['replace'](/^v/,''),c=b['split']('.');if(c['length']<0x2)return'v'+b+'.1';const d=parseInt(c[0x1]??'0',0xa);return c[0x1]=String(d+0x1),'v'+c['join']('.');}async['applyTemplate'](a,b,c){const d=this['getMode'](a);if(d){const g=this['doApplyTemplate'](d,b,c);return this['recordCapabilitiesUsed'](d),g;}if(a['includes'](':')){const [h,i]=a['split'](':',0x2),j=await this['getUserMode'](i,h);if(j){const k=this['doApplyTemplate'](j,b,c);return this['recordCapabilitiesUsed'](j),k;}}const e=this['getMode']('general');if(!e)throw new Error('IndustryMode\x20\x27general\x27\x20not\x20registered\x20—\x20cannot\x20fallback');const f=this['doApplyTemplate'](e,b,c);return this['recordCapabilitiesUsed'](e),f;}async['applyUserMode'](a,b,c,d){const e=await this['getUserMode'](a,b);if(!e)throw new Error('User\x20mode\x20\x27'+a+'\x27\x20not\x20found\x20for\x20user\x20\x27'+b+'\x27');const f=this['doApplyTemplate'](e,c,d);return this['recordCapabilitiesUsed'](e),f;}['doApplyTemplate'](a,b,c){let d=this['buildObjects'](a,b,c);d=this['applyConfigOverrides'](a,d),d=this['applyConfigOverrideRules'](a,d,b,c);const e=this['buildEdges'](d,c),f=this['buildSteps'](d,e,c['network']),g=this['defaultScenarios'](a,b,d),h=this['validateBlueprint'](d,e,a);if(h['errors']['length']>0x0)throw new Error('Blueprint\x20validation\x20for\x20mode\x20\x27'+a['name']+'\x27\x20failed\x20with\x20'+h['errors']['length']+'\x20CRITICAL\x20error(s):\x0a'+h['errors']['map']((j,k)=>'\x20\x20'+(k+0x1)+'.\x20'+j)['join']('\x0a'));return h['warnings']['length']>0x0&&console['warn']('[IndustryModeRegistry]\x20Blueprint\x20validation\x20for\x20\x27'+a['name']+'\x27\x20produced\x20'+h['warnings']['length']+'\x20warning(s):',h['warnings']),{'context':c,'objects':d,'edges':e,'steps':f,'scenarios':g,'industry_source':a['name'],'applied_template':a['name']+'@'+a['version'],'validation':h};}['validateBlueprint'](a,b,c){const d=[],e=[],f=a['find'](j=>j['object_type']==='machine'),g=a['find'](j=>j['object_type']==='service');if(f){const j=f['config']['entry_node_forward_hint'];if(!j)e['push']('Machine\x20blueprint\x20missing\x20entry_node_forward_hint.\x20'+'The\x20AI\x20must\x20ensure\x20the\x20entry\x20node\x20(prev_node=\x27\x27)\x20has\x20≥1\x20forward\x20when\x20constructing\x20the\x20Machine\x20creation\x20call\x20(P0-2).');else j['required']===!![]&&!j['example_forward']&&e['push']('Machine\x20entry_node_forward_hint\x20marked\x20required\x20but\x20example_forward\x20is\x20missing.');const k=f['config']['nodes'];(!k||k['length']===0x0)&&d['push']('Machine\x20blueprint\x20has\x20no\x20nodes\x20—\x20mode\x20\x27'+c['name']+'\x27\x20machine_shape\x20is\x20empty.\x20'+'Add\x20nodes\x20to\x20the\x20mode\x27s\x20machine_shape\x20before\x20applying\x20template.');}if(g){const l=g['config']['compensation_fund'];l&&d['push']('Service\x20blueprint\x20has\x20compensation_fund=\x27'+l+'\x27\x20(string\x20reference).\x20'+'BUG:\x20compensation_fund\x20is\x20Balance<T>\x20(numeric),\x20NOT\x20a\x20Treasury\x20object\x20reference.\x20'+'Remove\x20compensation_fund\x20field\x20and\x20use\x20compensation_fund_balance\x20+\x20compensation_fund_add_hint\x20instead.\x20'+'Smart\x20contract\x20(service.move:179):\x20compensation_fund:\x20Balance<T>.');const m=g['config']['compensation_fund_balance'];m===undefined&&e['push']('Service\x20blueprint\x20missing\x20compensation_fund_balance.\x20'+'Should\x20be\x200\x20(initial\x20Balance<T>\x20state)\x20—\x20filled\x20via\x20service.compensation_fund_add(coin).');}const h=new Set(a['map'](n=>n['entry_id'])),i=new Set(a['map'](n=>n['name']));for(const n of b){const o=h['has'](n['from'])||i['has'](n['from']),p=h['has'](n['to'])||i['has'](n['to']);(!o||!p)&&d['push']('Edge\x20\x27'+n['from']+'\x27\x20→\x20\x27'+n['to']+'\x27\x20(kind=\x27'+n['edge_kind']+'\x27)\x20references\x20undefined\x20object.\x20'+('from_exists='+o+',\x20to_exists='+p+'.'));}return{'errors':d,'warnings':e};}['buildObjects'](a,b,c){const d=c['prefix'],e=[];e['push'](this['makeObject']('permission',d+'_permission',{'name':d+'_permission','description':'Permission:\x20role\x20permission\x20index\x20('+a['display_name']+')','permission_indexes':this['buildPermissionIndexes'](a),'tags':['industry:'+a['name']]}));const f=this['getFirstServiceGuardName'](a,d);for(const g of a['guards']){const h=this['deriveGuardShortName'](g['template_id']),i=d+'_guard_'+h;e['push'](this['makeObject']('guard',i,{'name':i,'description':'Guard:\x20'+g['purpose']+'\x20('+a['display_name']+')','host':g['host'],'template_id':g['template_id'],'tags':['industry:'+a['name'],'host:'+g['host']]}));}return e['push'](this['makeObject']('machine',d+'_machine',{'name':d+'_machine','description':'Machine:\x20workflow\x20topology\x20('+a['display_name']+')\x20—\x20'+a['machine_shape']['length']+'\x20nodes','nodes':a['machine_shape']['map'](j=>({'name':j['name'],'role':j['role']})),'guard_objects':a['guards']['filter'](j=>j['host']==='machine')['map'](j=>({'template_id':j['template_id'],'object_name':d+'_guard_'+this['deriveGuardShortName'](j['template_id']),'purpose':j['purpose']})),'permission':d+'_permission','entry_node_forward_hint':{'entry_node_name':a['machine_shape'][0x0]?.['name']??'paid','required':!![],'example_forward':{'next_node':a['machine_shape'][0x0]?.['name']??'paid','namedOperator':'','weight':0x1},'reason':'Progress\x20starts\x20at\x20current=\x27\x27\x20and\x20follows\x20the\x20entry\x20node\x27s\x20forwards.\x20'+'Without\x20a\x20forward,\x20Progress\x20is\x20permanently\x20stuck\x20(P0-2).\x20'+'Schema\x20refinement\x20in\x20MachineNodePairSchema\x20enforces\x20this\x20at\x20publish\x20time.'},'tags':['industry:'+a['name']]},!![])),e['push'](this['makeObject']('treasury',d+'_treasury',{'name':d+'_treasury','description':'Treasury:\x20fund\x20escrow\x20('+a['display_name']+')','owner_receive':!![],'tags':['industry:'+a['name']]})),e['push'](this['makeObject']('allocation',d+'_allocation',{'name':d+'_allocation','description':'Allocation:\x20allocation\x20strategy\x20('+a['display_name']+')\x20—\x20'+a['allocator']['description'],'strategy':a['allocator'],'treasury':d+'_treasury','guard':f,'tags':['industry:'+a['name']]})),e['push'](this['makeObject']('service',d+'_service',{'name':d+'_service','description':'Service:\x20business\x20service\x20('+a['display_name']+')\x20—\x20'+b['slice'](0x0,0x64),'machine':d+'_machine','buy_guard':f,'permission':d+'_permission','order_allocators':[d+'_allocation'],'compensation_fund_balance':0x0,'compensation_fund_required':a['risk_constraints']?.['require_compensation_fund']??![],'compensation_fund_coverage_ratio':a['risk_constraints']?.['compensation_fund_coverage_ratio']??0x5,'compensation_fund_add_hint':'Call\x20service.compensation_fund_add\x20with\x20a\x20Coin<T>\x20to\x20deposit.\x20'+'The\x20compensation_fund\x20is\x20a\x20Balance<T>\x20(numeric),\x20not\x20a\x20Treasury\x20object\x20reference.\x20'+'Without\x20deposit,\x20arbitration\x20rulings\x20that\x20award\x20refunds\x20to\x20buyers\x20cannot\x20be\x20paid\x20out.\x20'+('Recommend\x20'+(a['risk_constraints']?.['compensation_fund_coverage_ratio']??0x5)+'×\x20the\x20max\x20single-order\x20amount\x20(P1-1\x20evaluation\x20rule,\x20industry:\x20'+a['name']+').'),'arbitrations':[d+'_arb'],'rewards':[d+'_reward'],'business_intent':b,'industry':a['name'],'tags':['industry:'+a['name']]},!![])),e['push'](this['makeObject']('progress',d+'_progress',{'name':d+'_progress','description':'Progress:\x20order\x20fulfillment\x20progress\x20('+a['display_name']+')','parent':d+'_machine','tags':['industry:'+a['name']]})),e['push'](this['makeObject']('arb',d+'_arb',{'name':d+'_arb','description':'Arbitration:\x20arbitration\x20rules\x20('+a['display_name']+')\x20—\x20'+a['key_risk'],'guard':d+'_guard_buy','tags':['industry:'+a['name']]})),e['push'](this['makeObject']('reward',d+'_reward',{'name':d+'_reward','description':'Reward:\x20incentive\x20rules\x20('+a['display_name']+')','claim_guard':d+'_guard_buy','tags':['industry:'+a['name']]})),e['push'](this['makeObject']('contact',d+'_contact',{'name':d+'_contact','description':'Contact:\x20customer\x20service\x20contact\x20('+a['display_name']+')','tags':['industry:'+a['name']]})),e;}['buildPermissionIndexes'](a){const b=a['config_overrides']?.['permission'];if(b?.['permission_indexes'])return b['permission_indexes'];return[{'name':'merchant','description':'Service\x20owner\x20/\x20provider'},{'name':'customer','description':'Service\x20buyer\x20/\x20customer'},{'name':'arbiter','description':'Arbitration\x20arbiter'}];}['applyConfigOverrides'](a,b){if(!a['config_overrides'])return b;for(const c of b){const d=a['config_overrides'][c['object_type']];if(d)for(const [e,f]of Object['entries'](d)){c['config'][e]=f;}}return b;}['applyConfigOverrideRules'](a,b,c,d){if(!a['config_override_rules'])return b;for(const e of a['config_override_rules']){const f=b['find'](h=>h['object_type']===e['object_type']);if(!f)continue;let g;if(e['condition']){const h=this['evaluateCondition'](e,c,d);g=h?e['condition']['then_value']:e['condition']['else_value']??e['value'];}else g=e['value'];g!==undefined&&this['setNestedField'](f['config'],e['field_path'],g);}return b;}['evaluateCondition'](a,b,c){if(!a['condition'])return![];if(a['condition']['intent_contains'])return b['toLowerCase']()['includes'](a['condition']['intent_contains']['toLowerCase']());if(a['condition']['context_field']&&a['condition']['matches']!==undefined){const d=c[a['condition']['context_field']];return d===a['condition']['matches'];}return![];}['setNestedField'](a,b,c){const d=b['split']('.');let e=a;for(let f=0x0;f<d['length']-0x1;f++){const g=d[f];(e[g]===undefined||e[g]===null)&&(e[g]={}),e=e[g];}e[d[d['length']-0x1]]=c;}['buildEdges'](a,b){const c=[],d=r=>a['find'](s=>s['name']===r),e=a[0x0]?.['config']?.['prefix'],f=b?.['prefix']??(typeof e==='string'?e:undefined)??a[0x0]?.['name']['split']('_')[0x0]??'',g=d(f+'_service'),h=d(f+'_machine'),i=d(f+'_permission'),j=d(f+'_allocation'),k=d(f+'_treasury'),l=d(f+'_arb'),m=d(f+'_reward'),n=d(f+'_progress'),o=a['filter'](r=>r['object_type']==='guard'),p=o['find'](r=>r['config']?.['host']==='service'),q=o['filter'](r=>r['config']?.['host']==='machine');if(!g||!h||!i){const r=[];if(!g)r['push']('service');if(!h)r['push']('machine');if(!i)r['push']('permission');return console['warn']('[buildEdges]\x20Missing\x20core\x20objects:\x20'+r['join'](',\x20')+'.\x20'+('Edges\x20will\x20be\x20empty\x20(prefix=\x27'+f+'\x27).\x20')+'Check\x20buildObjects\x20output\x20or\x20context.prefix.'),c;}c['push'](this['makeEdge'](g,h,'machine','service.machine',!![]));p&&c['push'](this['makeEdge'](g,p,'buy_guard','service.buy_guard',!![]));c['push'](this['makeEdge'](g,i,'permission','service.permission',!![]));if(j)c['push'](this['makeEdge'](g,j,'order_allocators','service.order_allocators',!![]));if(l)c['push'](this['makeEdge'](g,l,'arbitrations','service.arbitrations',![]));if(m)c['push'](this['makeEdge'](g,m,'rewards','service.rewards',![]));c['push'](this['makeEdge'](h,i,'permission','machine.permission',![]));for(const s of q){c['push'](this['makeEdge'](h,s,'guard','machine.forwards.guard',![]));}if(n)c['push'](this['makeEdge'](n,h,'parent','progress.parent',![]));if(j&&k)c['push'](this['makeEdge'](j,k,'treasury','allocation.treasury',![]));if(j&&p)c['push'](this['makeEdge'](j,p,'buy_guard','allocation.guard',![]));return c;}['makeEdge'](a,b,c,d,e){return{'from':a['entry_id'],'to':b['entry_id'],'edge_kind':c,'field_path':d,'required_at_publish':e};}['buildSteps'](a,b,c){const d=['permission','guard','machine','treasury','allocation','arb','reward','contact','service','progress'],e=[],f=new Map();let g=0x1;for(const h of d){const i=a['find'](l=>l['object_type']===h);if(!i)continue;const j=[];for(const l of b){if(l['to']===i['entry_id']){const m=f['get'](l['from']);m!==undefined&&j['push'](m);}}const k=i['publish_required']?'publish':'create';e['push']({'step':g,'object_type':i['object_type'],'operation':k,'substep_count':0x1,'depends_on':j,'entry_id':i['entry_id'],'network_phase':c}),f['set'](i['entry_id'],g),g++;}return e;}['defaultScenarios'](a,b,c){const d=c['find'](e=>e['object_type']==='service');return[{'scenario_id':a['name']+'_primary','description':a['display_name']+'\x20main\x20flow:\x20'+b['slice'](0x0,0x50),'primary_object':d?.['entry_id']??'','supporting_objects':c['filter'](e=>e['object_type']!=='service')['map'](e=>e['entry_id'])}];}['recordCapabilitiesUsed'](a){if(!a['capabilities_used'])return;try{const b=CapabilityRegistry['Instance']();for(const c of a['capabilities_used']){b['recordUsage'](c,a['name']);}}catch{}}['deriveGuardShortName'](a){if(a['startsWith']('tpl_')){const c=a['split']('_');return c[c['length']-0x1]||a;}const b=a['match'](/^([a-z]+)_guard_/);if(b)return b[0x1];return a['split']('_')[0x0]||a;}['getFirstServiceGuardName'](a,b){const c=a['guards']['find'](d=>d['host']==='service');if(!c)return'';return b+'_guard_'+this['deriveGuardShortName'](c['template_id']);}['makeObject'](a,b,c,d=![]){return{'entry_id':a+':'+b,'object_type':a,'name':b,'config':c,'publish_required':d,'status':'draft'};}['registerBuiltinModes'](){for(const a of BUILTIN_MODES){this['registerMode'](a);}}}export function getIndustryModeRegistry(){return IndustryModeRegistry['Instance']();}export const INDUSTRY_MODE_REGISTRY_VERSION=2.2;
|
|
1
|
+
import{OwnedRecordStorage}from'@wowok/wowok';import{CapabilityRegistry}from'./capability-manifest.js';import{ModeEvaluator}from'./mode-evaluator.js';import{MetricRegistry}from'./metric-registry.js';import{ConstraintRegistry}from'./constraint-registry.js';import{BUILTIN_MODES}from'./modes.js';export class IndustryModeRegistry{static ['instance'];['registrations']=new Map();['userModes']=new Map();['aliases']=new Map();['evaluator'];['initialized']=![];['persistence']=new OwnedRecordStorage('user_modes');['userModesLoaded']=![];static['Instance'](){return!IndustryModeRegistry['instance']&&(IndustryModeRegistry['instance']=new IndustryModeRegistry()),IndustryModeRegistry['instance'];}constructor(){this['evaluator']=new ModeEvaluator(CapabilityRegistry['Instance'](),MetricRegistry['Instance'](),ConstraintRegistry['Instance']()),this['registerBuiltinModes'](),this['initialized']=!![];}['registerMode'](a,b){if(!a['name']||!a['traits']||!a['machine_shape'])return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20invalid\x20mode\x20'+('(name='+(a['name']||'<missing>')+',\x20traits='+(a['traits']?'ok':'<missing>')+',\x20')+('machine_shape='+(a['machine_shape']?'ok':'<missing>')+').')),![];if(this['registrations']['has'](a['name'])){const c=this['registrations']['get'](a['name']);return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20mode\x20\x27'+a['name']+'\x27\x20already\x20registered\x20'+('(registered_at='+new Date(c?.['registered_at']??0x0)['toISOString']()+').\x20')+'Use\x20evolveMode/deriveMode\x20for\x20user\x20modifications,\x20or\x20unregister\x20first.'),![];}this['registrations']['set'](a['name'],{'mode':a,'aliases':b,'enabled':!![],'registered_at':Date['now']()});if(b)for(const d of b){this['aliases']['set'](d,a['name']);}return!![];}['getMode'](a){const b=this['resolveAlias'](a);return this['registrations']['get'](b)?.['mode'];}['listModes'](){return Array['from'](this['registrations']['values']())['filter'](a=>a['enabled'])['map'](a=>a['mode']);}['resolveAlias'](a){return this['aliases']['get'](a)??a;}['hasMode'](a){const b=this['resolveAlias'](a);return this['registrations']['has'](b);}['unregisterMode'](a){const b=this['resolveAlias'](a);if(!this['registrations']['has'](b))return![];this['registrations']['delete'](b);for(const [c,d]of this['aliases']){if(d===b)this['aliases']['delete'](c);}return!![];}async['evaluateModeObject'](a){return await Promise['all']([MetricRegistry['Instance']()['ensureLoaded'](),ConstraintRegistry['Instance']()['ensureLoaded']()]),this['evaluator']['evaluateMode'](a);}async['registerUserMode'](a,b){await this['ensureUserModesLoaded']();if(!a['name']||!a['owner']||!a['machine_shape'])return![];if(a['source']!=='custom')return![];if(a['owner']!==b)return![];const c=this['userModeKey'](a['owner'],a['name']);if(this['registrations']['has'](a['name']))return![];if(this['userModes']['has'](c))return![];return(!a['evolution_history']||a['evolution_history']['length']===0x0)&&(a['evolution_history']=[{'version':a['version']||'v1','changed_at':Date['now'](),'changes':['Initial\x20registration\x20(registerUserMode)']}]),this['userModes']['set'](c,a),await this['persistUserMode'](a),!![];}async['deriveMode'](a,b,c,d,e){await this['ensureUserModesLoaded']();const f=this['getMode'](a);if(!f)return undefined;if(!d||this['registrations']['has'](d))return undefined;const g=this['userModeKey'](c,d);if(this['userModes']['has'](g))return undefined;const h={'name':d,'display_name':e??d,'version':'v1','source':'custom','traits':b['traits']??f['traits'],'machine_shape':b['machine_shape']??f['machine_shape'],'guards':b['guards']??f['guards'],'allocator':b['allocator']??f['allocator'],'risk_checks':b['risk_checks']??f['risk_checks'],'needs':b['needs']??f['needs'],'flywheel':b['flywheel']??f['flywheel'],'key_risk':b['key_risk']??f['key_risk'],'build_notes':b['build_notes']??f['build_notes'],'capabilities_used':b['capabilities_used']??f['capabilities_used'],'config_overrides':b['config_overrides']??f['config_overrides'],'config_override_rules':b['config_override_rules']??f['config_override_rules'],'expected_benefits':b['expected_benefits']??f['expected_benefits'],'risk_appetite':b['risk_appetite']??f['risk_appetite'],'risk_constraints':b['risk_constraints']??f['risk_constraints'],'applicable_conditions':b['applicable_conditions']??f['applicable_conditions'],'similar_industries':b['similar_industries']??f['similar_industries'],'novel_capabilities':b['novel_capabilities']??f['novel_capabilities'],'owner':c,'derived_from':a,'custom_metrics':b['custom_metrics']??f['custom_metrics'],'custom_constraints':b['custom_constraints']??f['custom_constraints'],'evolution_history':[{'version':'v1','changed_at':Date['now'](),'changes':['Derived\x20from\x20builtin\x20\x27'+a+'\x27']}]};return this['userModes']['set'](g,h),await this['persistUserMode'](h),h;}async['evolveMode'](a,b,c,d,e=!![]){await this['ensureUserModesLoaded']();const f=this['userModeKey'](c,a),g=this['userModes']['get'](f);if(!g)return undefined;const h=e?this['bumpPatchVersion'](g['version']):g['version'],i={...g,...b,'name':g['name'],'owner':g['owner'],'source':'custom','derived_from':g['derived_from'],'evolution_history':[...g['evolution_history']??[],{'version':h,'changed_at':Date['now'](),'changes':[d]}],'version':h};return this['userModes']['set'](f,i),await this['persistUserMode'](i),i;}async['listUserModes'](a){await this['ensureUserModesLoaded']();const b=[];for(const c of this['userModes']['values']()){c['owner']===a&&b['push'](c);}return b;}async['getUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a);return this['userModes']['get'](c);}async['unregisterUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a),d=this['userModes']['delete'](c);return d&&await this['unpersistUserMode'](b,a),d;}['userModeKey'](a,b){return a+':'+b;}async['ensureUserModesLoaded'](){if(this['userModesLoaded'])return;this['userModesLoaded']=!![];try{const a=await this['persistence']['list']();for(const b of a){try{const c=JSON['parse'](b['data']);c?.['name']&&c?.['owner']&&c?.['machine_shape']&&this['userModes']['set'](this['userModeKey'](b['owner'],b['name']),c);}catch{console['warn']('[IndustryModeRegistry]\x20Skipping\x20corrupt\x20user_modes\x20row\x20\x27'+b['owner']+':'+b['name']+'\x27.');}}}catch(d){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20load\x20persisted\x20user\x20modes:',d['message']);}}async['persistUserMode'](a){try{await this['persistence']['save'](a['owner'],a['name'],JSON['stringify'](a));}catch(b){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20persist\x20user\x20mode\x20\x27'+a['owner']+':'+a['name']+'\x27:',b['message']);}}async['unpersistUserMode'](a,b){try{await this['persistence']['delete'](a,b);}catch(c){console['warn']('[IndustryModeRegistry]\x20Failed\x20to\x20delete\x20persisted\x20user\x20mode\x20\x27'+a+':'+b+'\x27:',c['message']);}}['bumpPatchVersion'](a){const b=a['replace'](/^v/,''),c=b['split']('.');if(c['length']<0x2)return'v'+b+'.1';const d=parseInt(c[0x1]??'0',0xa);return c[0x1]=String(d+0x1),'v'+c['join']('.');}['registerBuiltinModes'](){for(const a of BUILTIN_MODES){this['registerMode'](a);}}}export function getIndustryModeRegistry(){return IndustryModeRegistry['Instance']();}export const INDUSTRY_MODE_REGISTRY_VERSION=2.3;
|
|
@@ -4,59 +4,6 @@ import type { AcquisitionFlywheel } from "../knowledge/acquisition-flywheel.js";
|
|
|
4
4
|
import type { IndustryRiskCheck, IndustryNeed } from "../customer/industry-risks.js";
|
|
5
5
|
import type { ModeMachineNode, ModeGuardRef, ModeAllocatorStrategy } from "../knowledge/scenario-modes.js";
|
|
6
6
|
export type { ProjectObjectType, IndustryTraits, IndustrySource, AcquisitionFlywheel, IndustryRiskCheck, IndustryNeed, ModeMachineNode, ModeGuardRef, ModeAllocatorStrategy, };
|
|
7
|
-
export interface ProjectContext {
|
|
8
|
-
project_id?: string;
|
|
9
|
-
prefix: string;
|
|
10
|
-
network: "testnet" | "mainnet" | "both";
|
|
11
|
-
business_intent?: string;
|
|
12
|
-
version?: string;
|
|
13
|
-
testnet_test_passed?: boolean;
|
|
14
|
-
industry?: string;
|
|
15
|
-
}
|
|
16
|
-
export interface Blueprint {
|
|
17
|
-
context: ProjectContext;
|
|
18
|
-
objects: BlueprintObject[];
|
|
19
|
-
edges: BlueprintEdge[];
|
|
20
|
-
steps: BlueprintStep[];
|
|
21
|
-
scenarios?: BlueprintScenario[];
|
|
22
|
-
industry_source: string;
|
|
23
|
-
applied_template: string;
|
|
24
|
-
validation?: {
|
|
25
|
-
errors: string[];
|
|
26
|
-
warnings: string[];
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
export interface BlueprintObject {
|
|
30
|
-
entry_id: string;
|
|
31
|
-
object_type: ProjectObjectType;
|
|
32
|
-
name: string;
|
|
33
|
-
config: Record<string, unknown>;
|
|
34
|
-
publish_required: boolean;
|
|
35
|
-
status: "draft" | "deployed";
|
|
36
|
-
description?: string;
|
|
37
|
-
}
|
|
38
|
-
export interface BlueprintEdge {
|
|
39
|
-
from: string;
|
|
40
|
-
to: string;
|
|
41
|
-
edge_kind: string;
|
|
42
|
-
field_path: string;
|
|
43
|
-
required_at_publish: boolean;
|
|
44
|
-
}
|
|
45
|
-
export interface BlueprintStep {
|
|
46
|
-
step: number;
|
|
47
|
-
object_type: ProjectObjectType;
|
|
48
|
-
operation: "create" | "publish";
|
|
49
|
-
substep_count: number;
|
|
50
|
-
depends_on: number[];
|
|
51
|
-
entry_id: string;
|
|
52
|
-
network_phase: "testnet" | "mainnet" | "both";
|
|
53
|
-
}
|
|
54
|
-
export interface BlueprintScenario {
|
|
55
|
-
scenario_id: string;
|
|
56
|
-
description: string;
|
|
57
|
-
primary_object: string;
|
|
58
|
-
supporting_objects: string[];
|
|
59
|
-
}
|
|
60
7
|
export type RiskAppetite = "conservative" | "balanced" | "aggressive";
|
|
61
8
|
export interface ExpectedBenefit {
|
|
62
9
|
metric: string;
|
|
@@ -131,8 +78,6 @@ export interface IndustryModeRegistration {
|
|
|
131
78
|
enabled: boolean;
|
|
132
79
|
registered_at: number;
|
|
133
80
|
}
|
|
134
|
-
export type DeriveModeOptions = Partial<UserDefinedMode>;
|
|
135
|
-
export type EvolveModeOptions = Partial<UserDefinedMode>;
|
|
136
81
|
export type MetricType = "risk" | "benefit";
|
|
137
82
|
export type MetricScale = "level" | "numeric" | "percentage";
|
|
138
83
|
export type MetricValue = string | number;
|
|
@@ -205,16 +150,3 @@ export interface ModeEvaluation {
|
|
|
205
150
|
unmet_conditions: string[];
|
|
206
151
|
recommendations: string[];
|
|
207
152
|
}
|
|
208
|
-
export interface ModeMigrationEvaluation {
|
|
209
|
-
feasibility_score: number;
|
|
210
|
-
source_risk_score: number;
|
|
211
|
-
target_risk_score: number;
|
|
212
|
-
source_benefit_score: number;
|
|
213
|
-
target_benefit_score: number;
|
|
214
|
-
risk_delta: number;
|
|
215
|
-
benefit_delta: number;
|
|
216
|
-
added_capabilities: string[];
|
|
217
|
-
removed_capabilities: string[];
|
|
218
|
-
conflicting_capabilities: string[];
|
|
219
|
-
recommendations: string[];
|
|
220
|
-
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GOAL_TYPES}from'./types.js';export const GOAL_KEYWORD_RULES=[{'goal_type':'publish_service','keywords':['发布服务','开店','上线服务','开个店','开个点','出售服务','上架','publish\x20service','launch\x20service','open\x20store','open\x20a\x20store','open\x20shop','sell\x20service']},{'goal_type':'fulfill_order','keywords':['履约','交付订单','新订单','推进订单','处理订单','订单交付','fulfill','fulfil','deliver\x20order','new\x20order','process\x20order']},{'goal_type':'capture_demand','keywords':['需求机会','接单','有什么需求','找需求','需求匹配','capture\x20demand','opportunities','opportunity','demands\x20available','what\x20demands']},{'goal_type':'purchase_service','keywords':['购买服务','帮我买','帮我找','定制','下单','买个','buy','purchase','order\x20a\x20service','customize','custom-made']},{'goal_type':'collaborate_flow','keywords':['待办','我的节点','协作','员工','工作任务','my\x20tasks','pending\x20nodes','collaborate','my\x20node','todo']},{'goal_type':'supply_suborder','keywords':['子订单','应征','供应商','供货','sub-order','suborder','supplier','present']},{'goal_type':'publish_demand','keywords':['发布需求','找人做','悬赏','求人','publish\x20demand','post\x20demand','bounty','looking\x20for\x20someone']},{'goal_type':'run_arbitration','keywords':['仲裁业务','仲裁服务','经营仲裁','仲裁经营','arbitration\x20business','arbitrator','arbitration\x20service']},{'goal_type':'dispute_resolution','keywords':['争议','纠纷','投诉','申诉','维权','dispute','complaint','appeal']},{'goal_type':'manage_assets','keywords':['资产','资金','数据管理','盘点','权限盘点','treasury','assets','manage\x20funds','asset','inventory']}];const ASCII_RE=/^[\x20-\x7e]+$/;function keywordWeight(a){return a['length']>=0x4?0x2:0x1;}function escapeRe(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}const boundaryCache=new Map();function keywordMatches(a,b){if(ASCII_RE['test'](a)){let c=boundaryCache['get'](a);return!c&&(c=new RegExp('\x5cb'+escapeRe(a)+'\x5cb','i'),boundaryCache['set'](a,c)),c['test'](b);}return b['includes'](a);}export function classifyGoal(a){const b=(a??'')['trim']()['toLowerCase'](),c={'goal_type':null,'confidence':0x0,'matched':[],'alternatives':[]};if(!b)return c;const d=[];for(const k of GOAL_KEYWORD_RULES){const l=[];let m=0x0;for(const n of k['keywords']){keywordMatches(n,b)&&(l['push'](n),m+=keywordWeight(n));}if(m>0x0)d['push']({'goal_type':k['goal_type'],'score':m,'matched':l});}if(d['length']===0x0)return c;let e=d[0x0];for(const o of d){if(o['score']>e['score'])e=o;}const f=d['reduce']((p,q)=>p+q['score'],0x0),g=e['score']/f,h=Math['min'](0x1,e['score']/0x3),i=Math['round'](g*h*0x3e8)/0x3e8,j=d['filter'](p=>p['goal_type']!==e['goal_type'])['sort']((p,q)=>q['score']-p['score'])['map'](({goal_type:p,score:q})=>({'goal_type':p,'score':q}));return{'goal_type':e['goal_type'],'confidence':i,'matched':e['matched'],'alternatives':j};}export{GOAL_TYPES};
|
|
1
|
+
import{GOAL_TYPES}from'./types.js';export const GOAL_KEYWORD_RULES=[{'goal_type':'publish_service','keywords':['发布服务','开店','上线服务','开个店','开个点','出售服务','上架','publish\x20service','launch\x20service','open\x20store','open\x20a\x20store','open\x20shop','sell\x20service']},{'goal_type':'fulfill_order','keywords':['履约','交付订单','新订单','推进订单','处理订单','订单交付','fulfill','fulfil','deliver\x20order','new\x20order','process\x20order']},{'goal_type':'capture_demand','keywords':['需求机会','接单','有什么需求','找需求','需求匹配','capture\x20demand','opportunities','opportunity','demands\x20available','what\x20demands']},{'goal_type':'purchase_service','keywords':['购买服务','帮我买','帮我找','定制','下单','买个','buy','purchase','order\x20a\x20service','customize','custom-made']},{'goal_type':'collaborate_flow','keywords':['待办','我的节点','协作','员工','工作任务','my\x20tasks','pending\x20nodes','collaborate','my\x20node','todo']},{'goal_type':'supply_suborder','keywords':['子订单','应征','供应商','供货','sub-order','suborder','supplier','present']},{'goal_type':'publish_demand','keywords':['发布需求','找人做','悬赏','求人','publish\x20demand','post\x20demand','bounty','looking\x20for\x20someone']},{'goal_type':'run_arbitration','keywords':['仲裁业务','仲裁服务','经营仲裁','仲裁经营','arbitration\x20business','arbitrator','arbitration\x20service']},{'goal_type':'dispute_resolution','keywords':['争议','纠纷','投诉','申诉','维权','dispute','complaint','appeal']},{'goal_type':'manage_assets','keywords':['资产','资金','数据管理','盘点','权限盘点','权限管理','财务','治理','金库','treasury','assets','manage\x20funds','asset','inventory','permission\x20management','governance','fund\x20audit','withdraw']}];const ASCII_RE=/^[\x20-\x7e]+$/;function keywordWeight(a){return a['length']>=0x4?0x2:0x1;}function escapeRe(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}const boundaryCache=new Map();function keywordMatches(a,b){if(ASCII_RE['test'](a)){let c=boundaryCache['get'](a);return!c&&(c=new RegExp('\x5cb'+escapeRe(a)+'\x5cb','i'),boundaryCache['set'](a,c)),c['test'](b);}return b['includes'](a);}export function classifyGoal(a){const b=(a??'')['trim']()['toLowerCase'](),c={'goal_type':null,'confidence':0x0,'matched':[],'alternatives':[]};if(!b)return c;const d=[];for(const k of GOAL_KEYWORD_RULES){const l=[];let m=0x0;for(const n of k['keywords']){keywordMatches(n,b)&&(l['push'](n),m+=keywordWeight(n));}if(m>0x0)d['push']({'goal_type':k['goal_type'],'score':m,'matched':l});}if(d['length']===0x0)return c;let e=d[0x0];for(const o of d){if(o['score']>e['score'])e=o;}const f=d['reduce']((p,q)=>p+q['score'],0x0),g=e['score']/f,h=Math['min'](0x1,e['score']/0x3),i=Math['round'](g*h*0x3e8)/0x3e8,j=d['filter'](p=>p['goal_type']!==e['goal_type'])['sort']((p,q)=>q['score']-p['score'])['map'](({goal_type:p,score:q})=>({'goal_type':p,'score':q}));return{'goal_type':e['goal_type'],'confidence':i,'matched':e['matched'],'alternatives':j};}export{GOAL_TYPES};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { type GoalClassification } from "./GoalClassifier.js";
|
|
2
2
|
import { GoalStore } from "./GoalStore.js";
|
|
3
3
|
import { type GoalProcessSummary, type GoalRecord, type GoalStage, type GoalType, type ObjectRef } from "./types.js";
|
|
4
|
-
import { type FeedbackRecord, type ProblemRecord, type ProcessEvent, type ProcessManifest, type ProcessStageState } from "../task/types.js";
|
|
4
|
+
import { type FeedbackRecord, type ProblemRecord, type ProcessEvent, type ProcessManifest, type ProcessStageState, type SuggestionRecord } from "../task/types.js";
|
|
5
5
|
import type { UserIntentSignature } from "../experience/types.js";
|
|
6
6
|
import { type SubscriptionStore } from "../monitor/SubscriptionStore.js";
|
|
7
7
|
import type { CreateIntentInput } from "../intent/index.js";
|
|
8
8
|
import type { IntentRecord } from "../intent/types.js";
|
|
9
9
|
import { type LocalAccountInfo } from "../knowledge/workflow-guidance.js";
|
|
10
10
|
import { type GoalCompletionVerdict } from "../knowledge/goal-completion.js";
|
|
11
|
+
import type { CommunicationEvidenceKind } from "../communication/evidence.js";
|
|
11
12
|
export declare const GOAL_PLAYBOOKS: Record<GoalType, string | undefined>;
|
|
12
13
|
export declare const PLAN_APPROVAL_COVERS_LEVELS: readonly ["standard", "none"];
|
|
13
14
|
export interface GoalProcessDeps {
|
|
@@ -28,6 +29,22 @@ export interface GoalProcessDeps {
|
|
|
28
29
|
}): ProblemRecord[];
|
|
29
30
|
listFeedback(dir: string): FeedbackRecord[];
|
|
30
31
|
readEvents(dir: string): ProcessEvent[];
|
|
32
|
+
addSuggestion(dir: string, input: {
|
|
33
|
+
object?: string;
|
|
34
|
+
kind: SuggestionRecord["kind"];
|
|
35
|
+
stage?: string;
|
|
36
|
+
objects?: {
|
|
37
|
+
type: string;
|
|
38
|
+
object: string;
|
|
39
|
+
}[];
|
|
40
|
+
title: string;
|
|
41
|
+
detail?: string;
|
|
42
|
+
origin?: SuggestionRecord["origin"];
|
|
43
|
+
}): SuggestionRecord;
|
|
44
|
+
updateSuggestion(dir: string, id: string, patch: Partial<Pick<SuggestionRecord, "status" | "resolution_note" | "applied" | "stage" | "object">>): SuggestionRecord;
|
|
45
|
+
listSuggestions(dir: string, filter?: {
|
|
46
|
+
status?: SuggestionRecord["status"];
|
|
47
|
+
}): SuggestionRecord[];
|
|
31
48
|
removeDir(dir: string): void;
|
|
32
49
|
}
|
|
33
50
|
export interface GoalEngineDeps {
|
|
@@ -79,6 +96,13 @@ export declare class GoalEngine {
|
|
|
79
96
|
bind(network: string, id: string, account: string, persona?: string): Promise<GoalRecord>;
|
|
80
97
|
advance(network: string, id: string, input?: AdvanceInput): Promise<GoalRecord>;
|
|
81
98
|
registerActObjects(goalId: string, objects: ObjectRef[], network?: string): Promise<number>;
|
|
99
|
+
recordCommunicationEvidence(goalId: string, evidence: {
|
|
100
|
+
operation: string;
|
|
101
|
+
kind: CommunicationEvidenceKind;
|
|
102
|
+
title: string;
|
|
103
|
+
detail?: string;
|
|
104
|
+
data?: Record<string, unknown>;
|
|
105
|
+
}, network?: string): Promise<boolean>;
|
|
82
106
|
private registerProcessObjects;
|
|
83
107
|
private emitProcessEvent;
|
|
84
108
|
private distillOutcome;
|
|
@@ -108,6 +132,25 @@ export declare class GoalEngine {
|
|
|
108
132
|
process_summary?: GoalProcessSummary;
|
|
109
133
|
}>;
|
|
110
134
|
private summarizeProcess;
|
|
135
|
+
listSuggestions(network: string, id: string, opts?: {
|
|
136
|
+
include_resolved?: boolean;
|
|
137
|
+
}): Promise<{
|
|
138
|
+
goal: GoalRecord;
|
|
139
|
+
suggestions: SuggestionRecord[];
|
|
140
|
+
open_problems: ProblemRecord[];
|
|
141
|
+
}>;
|
|
142
|
+
resolveSuggestion(network: string, id: string, suggestionId: string, opts: {
|
|
143
|
+
decision: "confirm" | "dismiss";
|
|
144
|
+
note?: string;
|
|
145
|
+
apply?: boolean;
|
|
146
|
+
}): Promise<{
|
|
147
|
+
goal: GoalRecord;
|
|
148
|
+
suggestion: SuggestionRecord;
|
|
149
|
+
applied: boolean;
|
|
150
|
+
apply_error?: string;
|
|
151
|
+
complete_report?: GoalCompletionVerdict;
|
|
152
|
+
}>;
|
|
153
|
+
private emitSuggestionEvent;
|
|
111
154
|
list(network: string, filter?: {
|
|
112
155
|
stage?: GoalStage;
|
|
113
156
|
account?: string;
|
package/dist/goal/GoalEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{classifyGoal}from'./GoalClassifier.js';import{goalStore}from'./GoalStore.js';import{isTerminalStage,newGoalId,stageIndex}from'./types.js';import{GENERIC_PLAYBOOK,playbookForGoalType}from'../task/playbook.js';import{PROCESS_SCHEMA_VERSION,newProcessId}from'../task/types.js';import{addFeedback,appendEvent,deleteProcessDir,initProcess,listFeedback,listProblems,loadManifest,loadStageState,processesRootDir,readEvents,saveManifest}from'../task/ProcessStore.js';import{recordSignature}from'../experience/index.js';import{join}from'path';import{registerPlanApproval,revokePlanApproval}from'./plan-approval.js';import{subscriptionStore}from'../monitor/SubscriptionStore.js';import{createIntent,removeIntent}from'../intent/index.js';import{listLocalAccounts}from'../knowledge/workflow-guidance.js';import{evaluateGoalCompletion}from'../knowledge/goal-completion.js';export const GOAL_PLAYBOOKS={'publish_service':'wowok-provider','fulfill_order':'wowok-provider','capture_demand':'wowok-market','purchase_service':'wowok-order','collaborate_flow':'wowok-collaborator','supply_suborder':'wowok-supplier','publish_demand':'wowok-order','run_arbitration':'wowok-arbitrator','dispute_resolution':'wowok-order','manage_assets':undefined};export const PLAN_APPROVAL_COVERS_LEVELS=['standard','none'];export const ADOPT_JACCARD_THRESHOLD=0.6;export function tokenizeIntent(a){const b=new Set(),c=(a??'')['toLowerCase']();for(const d of c['matchAll'](/[a-z0-9]+/g))b['add'](d[0x0]);for(const e of c['matchAll'](/[\u3400-\u9fff\uf900-\ufaff]/g))b['add'](e[0x0]);return b;}export function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const f of c)if(d['has'](f))e++;return e/(c['size']+d['size']-e);}function deriveTitle(a){const b=(intent_text_first_line(a)||'Untitled\x20goal')['trim']();return b['length']>0x3c?b['slice'](0x0,0x39)+'…':b;}function intent_text_first_line(a){return(a??'')['split'](/\r?\n/,0x1)[0x0]??'';}function newApprovalId(){return'appr_'+Date['now']()['toString'](0x24)+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export class GoalEngine{['deps'];constructor(a){this['deps']=a;}async['createOrAdopt'](a){const b=a['network']??'default',c=(a['intent_text']??'')['trim']();if(!c)throw new Error('create_or_adopt\x20requires\x20non-empty\x20intent_text');let d=a['goal_type'],f;if(!d){f=classifyGoal(c),d=f['goal_type']??undefined;if(!d)return{'adopted':![],'classification':f,'needs_type':!![]};}const h=await this['deps']['store']['list'](b),i=a['account']??'',j=tokenizeIntent(c);let k;for(const r of h){if(isTerminalStage(r['stage']))continue;if(r['goal_type']!==d)continue;if((r['binding']?.['account']??'')!==i)continue;const s=jaccard(j,tokenizeIntent(r['intent_text']));s>=ADOPT_JACCARD_THRESHOLD&&(!k||s>k['sim'])&&(k={'goal':r,'sim':s});}if(k)return{'goal':k['goal'],'adopted':!![],'classification':f};const l=Date['now']();let m,n='recognized';if(a['account']){const t=await this['preflightAccount'](a['account']);m={'account':a['account'],'persona':a['persona'],'preflight':t},n='bound';}const o={'id':newGoalId(),'goal_type':d,'title':a['title']?.['trim']()||deriveTitle(c),'intent_text':c,...a['conversation_id']?{'conversation_id':a['conversation_id']}:{},'binding':m,'objects':[],'monitor':{'focus_ids':[],'intent_ids':[]},'stage':n,'playbook':GOAL_PLAYBOOKS[d],'approvals':[],'created_at':l,'updated_at':l};await this['deps']['store']['create'](b,o);const p=[],q=playbookForGoalType(d);if(q['name']!==GENERIC_PLAYBOOK||a['create_process']===!![])try{const u=newProcessId(),v=join(this['deps']['processes']['rootDir'](),u),w=new Date(l)['toISOString']();this['deps']['processes']['initProcess'](v,{'schema_version':PROCESS_SCHEMA_VERSION,'mcp_version':'unknown','process_id':u,'playbook':q['name'],'goal_id':o['id'],'title':o['title'],'network':b,'objects':[],'created_at':w,'updated_at':w,'archived':![]},q['stages']),o['process']={'id':u,'playbook':q['name'],'dir':v},o['plan_ref']=u,await this['deps']['store']['save'](b,o);}catch(x){p['push']('process\x20creation\x20failed\x20(goal\x20kept\x20without\x20process):\x20'+(x instanceof Error?x['message']:String(x)));}return{'goal':o,'adopted':![],'classification':f,...p['length']?{'warnings':p}:{}};}async['preflightAccount'](a){const b=[];let c;try{const d=await this['deps']['listLocalAccounts']();c=d['find'](f=>f['address']===a||f['name']===a);}catch(f){b['push']('local\x20account\x20lookup\x20failed:\x20'+(f instanceof Error?f['message']:String(f)));}if(c){if(c['address']!==a)b['push']('resolved\x20\x27'+a+'\x27\x20to\x20'+c['address']);}else b['push']('account\x20\x27'+a+'\x27\x20not\x20found\x20among\x20local\x20accounts');return{'account_found':Boolean(c),'notes':b};}async['approve'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={'id':newApprovalId(),'approved_at':Date['now'](),'scope':'plan','covers_levels':[...PLAN_APPROVAL_COVERS_LEVELS],...c?{'note':c}:{}};d['approvals']['push'](e),registerPlanApproval(d['id']);const f=stageIndex(d['stage']);if(f>=0x0&&f<stageIndex('approved'))d['stage']='approved';return d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['bind'](a,b,c,d){const e=await this['mustGet'](a,b);if(isTerminalStage(e['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+e['stage']+')');if(!c?.['trim']())throw new Error('bind\x20requires\x20a\x20non-empty\x20account');const f=await this['preflightAccount'](c['trim']());e['binding']={'account':c['trim'](),...d?.['trim']()?{'persona':d['trim']()}:{},'preflight':f};const g=stageIndex(e['stage']);if(g>=0x0&&g<stageIndex('bound'))e['stage']='bound';return e['updated_at']=Date['now'](),this['deps']['store']['save'](a,e);}async['advance'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=[];for(const g of c['objects']??[]){const h=d['objects']['some'](i=>i['type']===g['type']&&i['object']['toLowerCase']()===g['object']['toLowerCase']());!h&&(d['objects']['push']({'type':g['type'],'object':g['object']}),e['push']({'type':g['type'],'object':g['object']}));}const f=c['stage'];if(f){this['assertTransition'](d['stage'],f);const i=f==='monitoring'&&d['stage']!=='monitoring';d['stage']=f,d['updated_at']=Date['now']();if(i)await this['autoBindMonitor'](a,d);if(i)this['emitProcessEvent'](d,'goal_monitoring','goal\x20entered\x20monitoring');}else{if((c['objects']??[])['length']===0x0)throw new Error('advance\x20requires\x20a\x20target\x20stage\x20and/or\x20objects');}return e['length']>0x0&&d['process']&&this['registerProcessObjects'](d,e),d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['registerActObjects'](a,b,c='default'){if(b['length']===0x0)return 0x0;try{let d=c,e=await this['deps']['store']['get'](d,a);if(!e&&d!=='default'){e=await this['deps']['store']['get']('default',a);if(e)d='default';}if(!e||isTerminalStage(e['stage']))return 0x0;const f=e['objects']['length'],g=await this['advance'](d,a,{'objects':b});return g['objects']['length']-f;}catch{return 0x0;}}['registerProcessObjects'](a,b){try{const c=a['process']['dir'],d=this['deps']['processes']['loadManifest'](c);for(const e of b){const f=d['objects']['some'](g=>g['type']===e['type']&&g['object']['toLowerCase']()===e['object']['toLowerCase']());if(!f)d['objects']['push']({'type':e['type'],'object':e['object']});}this['deps']['processes']['saveManifest'](c,d),this['deps']['processes']['appendEvent'](c,{'timestamp':new Date()['toISOString'](),'event':'objects_registered','reason':b['length']+'\x20object(s)\x20registered\x20by\x20goal\x20'+a['id'],'data':{'added':b['map'](g=>g['type']+':'+g['object'])}});}catch{}}['emitProcessEvent'](a,b,c){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c});}catch{}}['distillOutcome'](a,b){try{const c={'playbook':a['process']?.['playbook'],'objects_count':a['objects']['length']};if(a['process']){const d=this['deps']['processes']['loadStageState'](a['process']['dir']),e=d?.['stages']['filter'](h=>d['stage_meta'][h]?.['committed'])['length'];if(e!==undefined)c['stages_completed']=e;const f=this['deps']['processes']['listProblems'](a['process']['dir']),g=this['deps']['processes']['listFeedback'](a['process']['dir']);c['problems_open']=f['filter'](h=>h['status']==='open')['length'],c['problems_resolved']=f['filter'](h=>h['status']==='resolved')['length'],c['feedback_positive']=g['filter'](h=>h['sentiment']==='positive')['length'],c['feedback_negative']=g['filter'](h=>h['sentiment']==='negative')['length'];}this['deps']['recordSignature']({'intent':a['goal_type'],'signals':c,'timestamp':Date['now'](),'outcome':b});}catch{}}['assertTransition'](a,b){if(isTerminalStage(a))throw new Error('goal\x20is\x20terminal\x20('+a+')');if(b==='abandoned')throw new Error('use\x20the\x20abandon\x20action\x20to\x20abandon\x20a\x20goal');if(b==='paused')return;if(a==='paused')return;if(b===a)return;const c=stageIndex(a),d=stageIndex(b);if(d<0x0||c<0x0||d<c)throw new Error('invalid\x20stage\x20transition:\x20'+a+'\x20→\x20'+b+'\x20(forward-only\x20along\x20'+'recognized→confirmed→bound→planned→approved→acting→monitoring→completed'+')');}async['pause'](a,b){return this['advance'](a,b,{'stage':'paused'});}async['autoBindMonitor'](a,b){const c=await this['deps']['subscriptionStore']['getConfig'](a),d=c['scope']['focus_objects']['map'](g=>({...g})),e=Date['now']();for(const f of b['objects']){const g=d['some'](h=>h['object']===f['object']&&h['goal_id']===b['id']);if(g)continue;d['push']({'object':f['object'],'added_at':e,'reason':'goal','closure':!![],'goal_id':b['id'],'note':b['title']});if(!b['monitor']['focus_ids']['includes'](f['object']))b['monitor']['focus_ids']['push'](f['object']);}await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...c['scope'],'focus_objects':d}});if((b['goal_type']==='capture_demand'||b['goal_type']==='publish_demand')&&b['monitor']['intent_ids']['length']===0x0){const h=await this['deps']['createIntent']({'intent':b['intent_text'],'account':b['binding']?.['account']});b['monitor']['intent_ids']['push'](h['id']);}}async['complete'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=await this['deps']['evaluateCompletion'](d,a),f=c['force']===!![];if(!e['complete']&&!f)return{'goal':d,'completed':![],'verify_report':e};const g=await this['teardown'](a,d);d['stage']='completed',d['outcome']={'success':e['complete']||f,'completed_at':Date['now'](),'verify_report':e,...!e['complete']&&f?{'forced':!![]}:{}},d['updated_at']=Date['now']();if(d['process']){if(c['feedback'])try{this['deps']['processes']['addFeedback'](d['process']['dir'],{'source':'user','sentiment':c['feedback']['sentiment'],'comment':c['feedback']['comment']});}catch{g['push']('feedback\x20recording\x20failed');}this['emitProcessEvent'](d,'goal_completed','goal\x20completed\x20('+d['title']+')');}this['distillOutcome'](d,'success');const h=await this['deps']['store']['save'](a,d);return{'goal':h,'completed':!![],'verify_report':e,'teardown_notes':g['length']?g:undefined};}async['abandon'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20already\x20terminal\x20('+d['stage']+')');const e=await this['teardown'](a,d);d['stage']='abandoned',d['outcome']={'success':![],'completed_at':Date['now'](),...c?{'verify_report':{'reason':c}}:{}},d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'goal_abandoned',c??'goal\x20abandoned'),this['distillOutcome'](d,'failed');const f=await this['deps']['store']['save'](a,d);return{'goal':f,'teardown_notes':e['length']?e:undefined};}async['remove'](a,b,c={}){const d=await this['mustGet'](a,b);let e;if(!isTerminalStage(d['stage'])){if(c['force']!==!![])throw new Error('goal\x20'+b+'\x20is\x20not\x20terminal\x20('+d['stage']+')\x20—\x20complete/abandon\x20it\x20first,\x20or\x20pass\x20force=true');await this['teardown'](a,d),e=!![];}let f;if(d['process'])try{this['deps']['processes']['removeDir'](d['process']['dir']),f=!![];}catch{f=![];}const g=await this['deps']['store']['remove'](a,b);return{'deleted':g,...e!==undefined?{'tore_down_active':e}:{},...f!==undefined?{'process_removed':f}:{}};}async['teardown'](a,b){const c=[];try{const d=await this['deps']['subscriptionStore']['getConfig'](a),f=d['scope']['focus_objects']['filter'](g=>g['goal_id']!==b['id']);f['length']!==d['scope']['focus_objects']['length']&&await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...d['scope'],'focus_objects':f}});}catch(g){c['push']('focus\x20teardown\x20failed:\x20'+(g instanceof Error?g['message']:String(g)));}revokePlanApproval(b['id']);for(const h of b['monitor']['intent_ids']){try{await this['deps']['removeIntent'](h);}catch(i){c['push']('intent\x20teardown\x20failed\x20('+h+'):\x20'+(i instanceof Error?i['message']:String(i)));}}return c;}async['get'](a,b){const c=await this['mustGet'](a,b);if(!c['process'])return c;try{return{...c,'process_summary':this['summarizeProcess'](c['process']['dir'],c['process']['id'],c['process']['playbook'])};}catch{return c;}}['summarizeProcess'](a,b,c){const d=this['deps']['processes']['loadStageState'](a),e=this['deps']['processes']['listProblems'](a,{'status':'open'}),f={'critical':0x0,'high':0x1,'medium':0x2,'low':0x3},g=[...e]['sort']((h,i)=>f[h['severity']]-f[i['severity']])['slice'](0x0,0x3)['map'](h=>h['title']);return{'id':b,'playbook':c,'current_stage':d?.['current_stage']??'unknown','stages':(d?.['stages']??[])['map'](h=>({'name':h,'committed':d?.['stage_meta'][h]?.['committed']??![],'completion':d?.['stage_meta'][h]?.['completion']??0x0})),'open_problems':{'count':e['length'],'top':g},'last_events':this['deps']['processes']['readEvents'](a)['slice'](-0x5),'feedback_count':this['deps']['processes']['listFeedback'](a)['length']};}async['list'](a,b={}){const [c,d]=await Promise['all']([this['deps']['store']['list'](a,b),this['deps']['store']['counts'](a)]);return{'goals':c,'counts':d};}async['mustGet'](a,b){const c=await this['deps']['store']['get'](a,b);if(!c)throw new Error('goal\x20not\x20found:\x20'+b);return c;}}export const goalEngine=new GoalEngine({'store':goalStore,'subscriptionStore':subscriptionStore,'createIntent':createIntent,'removeIntent':removeIntent,'listLocalAccounts':listLocalAccounts,'evaluateCompletion':(a,b)=>evaluateGoalCompletion(a,b),'processes':{'rootDir':processesRootDir,'initProcess':initProcess,'loadManifest':loadManifest,'saveManifest':saveManifest,'loadStageState':loadStageState,'appendEvent':appendEvent,'addFeedback':addFeedback,'listProblems':listProblems,'listFeedback':listFeedback,'readEvents':readEvents,'removeDir':deleteProcessDir},'recordSignature':recordSignature});
|
|
1
|
+
import{classifyGoal}from'./GoalClassifier.js';import{goalStore}from'./GoalStore.js';import{isTerminalStage,newGoalId,stageIndex}from'./types.js';import{GENERIC_PLAYBOOK,playbookForGoalType}from'../task/playbook.js';import{PROCESS_SCHEMA_VERSION,newProcessId}from'../task/types.js';import{addFeedback,addSuggestion,appendEvent,deleteProcessDir,initProcess,listFeedback,listProblems,listSuggestions,loadManifest,loadStageState,processesRootDir,readEvents,saveManifest,updateSuggestion}from'../task/ProcessStore.js';import{recordSignature}from'../experience/index.js';import{join}from'path';import{registerPlanApproval,revokePlanApproval}from'./plan-approval.js';import{subscriptionStore}from'../monitor/SubscriptionStore.js';import{createIntent,removeIntent}from'../intent/index.js';import{listLocalAccounts}from'../knowledge/workflow-guidance.js';import{evaluateGoalCompletion}from'../knowledge/goal-completion.js';export const GOAL_PLAYBOOKS={'publish_service':'wowok-provider','fulfill_order':'wowok-provider','capture_demand':'wowok-market','purchase_service':'wowok-order','collaborate_flow':'wowok-collaborator','supply_suborder':'wowok-supplier','publish_demand':'wowok-order','run_arbitration':'wowok-arbitrator','dispute_resolution':'wowok-order','manage_assets':'wowok-governance'};export const PLAN_APPROVAL_COVERS_LEVELS=['standard','none'];export const ADOPT_JACCARD_THRESHOLD=0.6;export function tokenizeIntent(a){const b=new Set(),c=(a??'')['toLowerCase']();for(const d of c['matchAll'](/[a-z0-9]+/g))b['add'](d[0x0]);for(const e of c['matchAll'](/[\u3400-\u9fff\uf900-\ufaff]/g))b['add'](e[0x0]);return b;}export function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const f of c)if(d['has'](f))e++;return e/(c['size']+d['size']-e);}function deriveTitle(a){const b=(intent_text_first_line(a)||'Untitled\x20goal')['trim']();return b['length']>0x3c?b['slice'](0x0,0x39)+'…':b;}function intent_text_first_line(a){return(a??'')['split'](/\r?\n/,0x1)[0x0]??'';}function newApprovalId(){return'appr_'+Date['now']()['toString'](0x24)+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export class GoalEngine{['deps'];constructor(a){this['deps']=a;}async['createOrAdopt'](a){const b=a['network']??'default',c=(a['intent_text']??'')['trim']();if(!c)throw new Error('create_or_adopt\x20requires\x20non-empty\x20intent_text');let d=a['goal_type'],f;if(!d){f=classifyGoal(c),d=f['goal_type']??undefined;if(!d)return{'adopted':![],'classification':f,'needs_type':!![]};}const h=await this['deps']['store']['list'](b),i=a['account']??'',j=tokenizeIntent(c);let k;for(const r of h){if(isTerminalStage(r['stage']))continue;if(r['goal_type']!==d)continue;if((r['binding']?.['account']??'')!==i)continue;const s=jaccard(j,tokenizeIntent(r['intent_text']));s>=ADOPT_JACCARD_THRESHOLD&&(!k||s>k['sim'])&&(k={'goal':r,'sim':s});}if(k)return{'goal':k['goal'],'adopted':!![],'classification':f};const l=Date['now']();let m,n='recognized';if(a['account']){const t=await this['preflightAccount'](a['account']);m={'account':a['account'],'persona':a['persona'],'preflight':t},n='bound';}const o={'id':newGoalId(),'goal_type':d,'title':a['title']?.['trim']()||deriveTitle(c),'intent_text':c,...a['conversation_id']?{'conversation_id':a['conversation_id']}:{},'binding':m,'objects':[],'monitor':{'focus_ids':[],'intent_ids':[]},'stage':n,'playbook':GOAL_PLAYBOOKS[d],'approvals':[],'created_at':l,'updated_at':l};await this['deps']['store']['create'](b,o);const p=[],q=playbookForGoalType(d);if(q['name']!==GENERIC_PLAYBOOK||a['create_process']===!![])try{const u=newProcessId(),v=join(this['deps']['processes']['rootDir'](),u),w=new Date(l)['toISOString']();this['deps']['processes']['initProcess'](v,{'schema_version':PROCESS_SCHEMA_VERSION,'mcp_version':'unknown','process_id':u,'playbook':q['name'],'goal_id':o['id'],'title':o['title'],'network':b,'objects':[],'created_at':w,'updated_at':w,'archived':![]},q['stages']),o['process']={'id':u,'playbook':q['name'],'dir':v},o['process_ref']=u,await this['deps']['store']['save'](b,o);}catch(x){p['push']('process\x20creation\x20failed\x20(goal\x20kept\x20without\x20process):\x20'+(x instanceof Error?x['message']:String(x)));}return{'goal':o,'adopted':![],'classification':f,...p['length']?{'warnings':p}:{}};}async['preflightAccount'](a){const b=[];let c;try{const d=await this['deps']['listLocalAccounts']();c=d['find'](f=>f['address']===a||f['name']===a);}catch(f){b['push']('local\x20account\x20lookup\x20failed:\x20'+(f instanceof Error?f['message']:String(f)));}if(c){if(c['address']!==a)b['push']('resolved\x20\x27'+a+'\x27\x20to\x20'+c['address']);}else b['push']('account\x20\x27'+a+'\x27\x20not\x20found\x20among\x20local\x20accounts');return{'account_found':Boolean(c),'notes':b};}async['approve'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={'id':newApprovalId(),'approved_at':Date['now'](),'scope':'plan','covers_levels':[...PLAN_APPROVAL_COVERS_LEVELS],...c?{'note':c}:{}};d['approvals']['push'](e),registerPlanApproval(d['id']);const f=stageIndex(d['stage']);if(f>=0x0&&f<stageIndex('approved'))d['stage']='approved';return d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['bind'](a,b,c,d){const e=await this['mustGet'](a,b);if(isTerminalStage(e['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+e['stage']+')');if(!c?.['trim']())throw new Error('bind\x20requires\x20a\x20non-empty\x20account');const f=await this['preflightAccount'](c['trim']());e['binding']={'account':c['trim'](),...d?.['trim']()?{'persona':d['trim']()}:{},'preflight':f};const g=stageIndex(e['stage']);if(g>=0x0&&g<stageIndex('bound'))e['stage']='bound';return e['updated_at']=Date['now'](),this['deps']['store']['save'](a,e);}async['advance'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=[];for(const g of c['objects']??[]){const h=d['objects']['some'](i=>i['type']===g['type']&&i['object']['toLowerCase']()===g['object']['toLowerCase']());!h&&(d['objects']['push']({'type':g['type'],'object':g['object']}),e['push']({'type':g['type'],'object':g['object']}));}const f=c['stage'];if(f){this['assertTransition'](d['stage'],f);const i=f==='monitoring'&&d['stage']!=='monitoring';d['stage']=f,d['updated_at']=Date['now']();if(i)await this['autoBindMonitor'](a,d);if(i)this['emitProcessEvent'](d,'goal_monitoring','goal\x20entered\x20monitoring');}else{if((c['objects']??[])['length']===0x0)throw new Error('advance\x20requires\x20a\x20target\x20stage\x20and/or\x20objects');}return e['length']>0x0&&d['process']&&this['registerProcessObjects'](d,e),d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['registerActObjects'](a,b,c='default'){if(b['length']===0x0)return 0x0;try{let d=c,e=await this['deps']['store']['get'](d,a);if(!e&&d!=='default'){e=await this['deps']['store']['get']('default',a);if(e)d='default';}if(!e||isTerminalStage(e['stage']))return 0x0;const f=e['objects']['length'],g=await this['advance'](d,a,{'objects':b});return g['objects']['length']-f;}catch{return 0x0;}}async['recordCommunicationEvidence'](a,b,c='default'){try{let d=await this['deps']['store']['get'](c,a);!d&&c!=='default'&&(d=await this['deps']['store']['get']('default',a));if(!d||isTerminalStage(d['stage'])||!d['process'])return![];return this['deps']['processes']['appendEvent'](d['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':'communication_evidence','reason':''+b['title'],'data':{'operation':b['operation'],'kind':b['kind'],...b['detail']?{'detail':b['detail']}:{},...b['data']??{}}}),!![];}catch{return![];}}['registerProcessObjects'](a,b){try{const c=a['process']['dir'],d=this['deps']['processes']['loadManifest'](c);for(const e of b){const f=d['objects']['some'](g=>g['type']===e['type']&&g['object']['toLowerCase']()===e['object']['toLowerCase']());if(!f)d['objects']['push']({'type':e['type'],'object':e['object']});}this['deps']['processes']['saveManifest'](c,d),this['deps']['processes']['appendEvent'](c,{'timestamp':new Date()['toISOString'](),'event':'objects_registered','reason':b['length']+'\x20object(s)\x20registered\x20by\x20goal\x20'+a['id'],'data':{'added':b['map'](g=>g['type']+':'+g['object'])}});}catch{}}['emitProcessEvent'](a,b,c){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c});}catch{}}['distillOutcome'](a,b){try{const c={'playbook':a['process']?.['playbook'],'objects_count':a['objects']['length']};if(a['process']){const d=this['deps']['processes']['loadStageState'](a['process']['dir']),e=d?.['stages']['filter'](h=>d['stage_meta'][h]?.['committed'])['length'];if(e!==undefined)c['stages_completed']=e;const f=this['deps']['processes']['listProblems'](a['process']['dir']),g=this['deps']['processes']['listFeedback'](a['process']['dir']);c['problems_open']=f['filter'](h=>h['status']==='open')['length'],c['problems_resolved']=f['filter'](h=>h['status']==='resolved')['length'],c['feedback_positive']=g['filter'](h=>h['sentiment']==='positive')['length'],c['feedback_negative']=g['filter'](h=>h['sentiment']==='negative')['length'];}this['deps']['recordSignature']({'intent':a['goal_type'],'signals':c,'timestamp':Date['now'](),'outcome':b});}catch{}}['assertTransition'](a,b){if(isTerminalStage(a))throw new Error('goal\x20is\x20terminal\x20('+a+')');if(b==='abandoned')throw new Error('use\x20the\x20abandon\x20action\x20to\x20abandon\x20a\x20goal');if(b==='paused')return;if(a==='paused')return;if(b===a)return;const c=stageIndex(a),d=stageIndex(b);if(d<0x0||c<0x0||d<c)throw new Error('invalid\x20stage\x20transition:\x20'+a+'\x20→\x20'+b+'\x20(forward-only\x20along\x20'+'recognized→confirmed→bound→planned→approved→acting→monitoring→completed'+')');}async['pause'](a,b){return this['advance'](a,b,{'stage':'paused'});}async['autoBindMonitor'](a,b){const c=await this['deps']['subscriptionStore']['getConfig'](a),d=c['scope']['focus_objects']['map'](g=>({...g})),e=Date['now']();for(const f of b['objects']){const g=d['some'](h=>h['object']===f['object']&&h['goal_id']===b['id']);if(g)continue;d['push']({'object':f['object'],'added_at':e,'reason':'goal','closure':!![],'goal_id':b['id'],'note':b['title']});if(!b['monitor']['focus_ids']['includes'](f['object']))b['monitor']['focus_ids']['push'](f['object']);}await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...c['scope'],'focus_objects':d}});if((b['goal_type']==='capture_demand'||b['goal_type']==='publish_demand')&&b['monitor']['intent_ids']['length']===0x0){const h=await this['deps']['createIntent']({'intent':b['intent_text'],'account':b['binding']?.['account']});b['monitor']['intent_ids']['push'](h['id']);}}async['complete'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=await this['deps']['evaluateCompletion'](d,a),f=c['force']===!![];if(!e['complete']&&!f)return{'goal':d,'completed':![],'verify_report':e};const g=await this['teardown'](a,d);d['stage']='completed',d['outcome']={'success':e['complete']||f,'completed_at':Date['now'](),'verify_report':e,...!e['complete']&&f?{'forced':!![]}:{}},d['updated_at']=Date['now']();if(d['process']){if(c['feedback'])try{this['deps']['processes']['addFeedback'](d['process']['dir'],{'source':'user','sentiment':c['feedback']['sentiment'],'comment':c['feedback']['comment']});}catch{g['push']('feedback\x20recording\x20failed');}this['emitProcessEvent'](d,'goal_completed','goal\x20completed\x20('+d['title']+')');}this['distillOutcome'](d,'success');const h=await this['deps']['store']['save'](a,d);return{'goal':h,'completed':!![],'verify_report':e,'teardown_notes':g['length']?g:undefined};}async['abandon'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20already\x20terminal\x20('+d['stage']+')');const e=await this['teardown'](a,d);d['stage']='abandoned',d['outcome']={'success':![],'completed_at':Date['now'](),...c?{'verify_report':{'reason':c}}:{}},d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'goal_abandoned',c??'goal\x20abandoned'),this['distillOutcome'](d,'failed');const f=await this['deps']['store']['save'](a,d);return{'goal':f,'teardown_notes':e['length']?e:undefined};}async['remove'](a,b,c={}){const d=await this['mustGet'](a,b);let e;if(!isTerminalStage(d['stage'])){if(c['force']!==!![])throw new Error('goal\x20'+b+'\x20is\x20not\x20terminal\x20('+d['stage']+')\x20—\x20complete/abandon\x20it\x20first,\x20or\x20pass\x20force=true');await this['teardown'](a,d),e=!![];}let f;if(d['process'])try{this['deps']['processes']['removeDir'](d['process']['dir']),f=!![];}catch{f=![];}const g=await this['deps']['store']['remove'](a,b);return{'deleted':g,...e!==undefined?{'tore_down_active':e}:{},...f!==undefined?{'process_removed':f}:{}};}async['teardown'](a,b){const c=[];try{const d=await this['deps']['subscriptionStore']['getConfig'](a),f=d['scope']['focus_objects']['filter'](g=>g['goal_id']!==b['id']);f['length']!==d['scope']['focus_objects']['length']&&await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...d['scope'],'focus_objects':f}});}catch(g){c['push']('focus\x20teardown\x20failed:\x20'+(g instanceof Error?g['message']:String(g)));}revokePlanApproval(b['id']);for(const h of b['monitor']['intent_ids']){try{await this['deps']['removeIntent'](h);}catch(i){c['push']('intent\x20teardown\x20failed\x20('+h+'):\x20'+(i instanceof Error?i['message']:String(i)));}}return c;}async['get'](a,b){const c=await this['mustGet'](a,b);if(!c['process'])return c;try{return{...c,'process_summary':this['summarizeProcess'](c['process']['dir'],c['process']['id'],c['process']['playbook'])};}catch{return c;}}['summarizeProcess'](a,b,c){const d=this['deps']['processes']['loadStageState'](a),e=this['deps']['processes']['listProblems'](a,{'status':'open'}),f={'critical':0x0,'high':0x1,'medium':0x2,'low':0x3},g=[...e]['sort']((i,j)=>f[i['severity']]-f[j['severity']])['slice'](0x0,0x3)['map'](i=>i['title']),h=this['deps']['processes']['listSuggestions'](a,{'status':'pending'});return{'id':b,'playbook':c,'current_stage':d?.['current_stage']??'unknown','stages':(d?.['stages']??[])['map'](i=>({'name':i,'committed':d?.['stage_meta'][i]?.['committed']??![],'completion':d?.['stage_meta'][i]?.['completion']??0x0})),'open_problems':{'count':e['length'],'top':g},'pending_suggestions':{'count':h['length'],'top':h['slice'](0x0,0x3)['map'](i=>i['title'])},'last_events':this['deps']['processes']['readEvents'](a)['slice'](-0x5),'feedback_count':this['deps']['processes']['listFeedback'](a)['length']};}async['listSuggestions'](a,b,c={}){const d=await this['mustGet'](a,b);if(!d['process'])return{'goal':d,'suggestions':[],'open_problems':[]};const e=this['deps']['processes']['listSuggestions'](d['process']['dir']),f=c['include_resolved']?e:e['filter'](h=>h['status']==='pending'),g=this['deps']['processes']['listProblems'](d['process']['dir'],{'status':'open'});return{'goal':d,'suggestions':f,'open_problems':g};}async['resolveSuggestion'](a,b,c,d){const f=await this['mustGet'](a,b);if(!f['process'])throw new Error('goal\x20'+b+'\x20has\x20no\x20TaskProcess\x20(no\x20suggestion\x20stream)');const g=f['process']['dir'],h=this['deps']['processes']['listSuggestions'](g)['find'](n=>n['id']===c);if(!h)throw new Error('suggestion\x20not\x20found:\x20'+c);if(h['status']!=='pending')throw new Error('suggestion\x20'+c+'\x20already\x20resolved\x20('+h['status']+')');if(d['decision']==='dismiss'){const n=this['deps']['processes']['updateSuggestion'](g,c,{'status':'dismissed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_dismissed',h,d['note']),{'goal':f,'suggestion':n,'applied':![]};}if(d['apply']!==!![]){const o=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_confirmed',h,d['note']),{'goal':f,'suggestion':o,'applied':![]};}let i,j,k=![];if(h['kind']==='advance_stage'&&h['stage'])try{await this['advance'](a,b,{'stage':h['stage']}),k=!![];}catch(p){i=p instanceof Error?p['message']:String(p);}else{if(h['kind']==='complete_goal')try{const q=await this['complete'](a,b,{});j=q['verify_report'],q['completed']?k=!![]:i='completion\x20conditions\x20unmet:\x20'+(q['verify_report']['missing']['join'](';\x20')||'no\x20evidence');}catch(r){i=r instanceof Error?r['message']:String(r);}else{if(h['kind']==='register_object'&&h['objects']?.['length'])try{await this['advance'](a,b,{'objects':h['objects']}),k=!![];}catch(s){i=s instanceof Error?s['message']:String(s);}else k=!![];}}if(i){const t=await this['mustGet'](a,b);return{'goal':t,'suggestion':h,'applied':![],'apply_error':i};}const l=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed','applied':!![],...d['note']?{'resolution_note':d['note']}:{}});this['emitSuggestionEvent'](f,'suggestion_applied',h,d['note']);const m=await this['mustGet'](a,b);return{'goal':m,'suggestion':l,'applied':!![],...j?{'complete_report':j}:{}};}['emitSuggestionEvent'](a,b,c,d){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c['kind']+'\x20\x27'+c['title']+'\x27\x20('+c['id']+')','data':{'suggestion_id':c['id'],'kind':c['kind'],...c['stage']?{'stage':c['stage']}:{},...d?{'note':d}:{}}});}catch{}}async['list'](a,b={}){const [c,d]=await Promise['all']([this['deps']['store']['list'](a,b),this['deps']['store']['counts'](a)]);return{'goals':c,'counts':d};}async['mustGet'](a,b){const c=await this['deps']['store']['get'](a,b);if(!c)throw new Error('goal\x20not\x20found:\x20'+b);return c;}}export const goalEngine=new GoalEngine({'store':goalStore,'subscriptionStore':subscriptionStore,'createIntent':createIntent,'removeIntent':removeIntent,'listLocalAccounts':listLocalAccounts,'evaluateCompletion':(a,b)=>evaluateGoalCompletion(a,b),'processes':{'rootDir':processesRootDir,'initProcess':initProcess,'loadManifest':loadManifest,'saveManifest':saveManifest,'loadStageState':loadStageState,'appendEvent':appendEvent,'addFeedback':addFeedback,'listProblems':listProblems,'listFeedback':listFeedback,'readEvents':readEvents,'addSuggestion':addSuggestion,'updateSuggestion':updateSuggestion,'listSuggestions':listSuggestions,'removeDir':deleteProcessDir},'recordSignature':recordSignature});
|
package/dist/goal/types.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export interface GoalRecord {
|
|
|
32
32
|
intent_text: string;
|
|
33
33
|
conversation_id?: string;
|
|
34
34
|
binding?: BindingRecord;
|
|
35
|
-
|
|
35
|
+
process_ref?: string;
|
|
36
36
|
process?: {
|
|
37
37
|
id: string;
|
|
38
38
|
playbook: string;
|
|
@@ -70,6 +70,10 @@ export interface GoalProcessSummary {
|
|
|
70
70
|
count: number;
|
|
71
71
|
top: string[];
|
|
72
72
|
};
|
|
73
|
+
pending_suggestions: {
|
|
74
|
+
count: number;
|
|
75
|
+
top: string[];
|
|
76
|
+
};
|
|
73
77
|
last_events: ProcessEvent[];
|
|
74
78
|
feedback_count: number;
|
|
75
79
|
}
|
|
@@ -7,21 +7,9 @@ export interface EscalationEvent {
|
|
|
7
7
|
from_tier: HarnessTier;
|
|
8
8
|
to_tier: HarnessTier;
|
|
9
9
|
}
|
|
10
|
-
export interface EscalationState {
|
|
11
|
-
current_tier: HarnessTier;
|
|
12
|
-
history: EscalationEvent[];
|
|
13
|
-
recent_failures: Array<{
|
|
14
|
-
timestamp: number;
|
|
15
|
-
operation: string;
|
|
16
|
-
error_code: string;
|
|
17
|
-
}>;
|
|
18
|
-
}
|
|
19
|
-
export declare function isFullTier(tier: HarnessTier): boolean;
|
|
20
10
|
export declare function shouldRunHeavyHooks(): boolean;
|
|
21
11
|
export declare function shouldRunLightHooks(): boolean;
|
|
22
12
|
export declare function recordCriticalRisk(description: string): EscalationEvent | null;
|
|
23
13
|
export declare function recordCriticalOperation(operation: string, errorCode: string): EscalationEvent | null;
|
|
24
14
|
export declare function recordSubstepFailure(detail: string): EscalationEvent | null;
|
|
25
15
|
export declare function recordOperationFailure(operation: string, errorCode: string): EscalationEvent | null;
|
|
26
|
-
export declare function getEscalationState(): Readonly<EscalationState>;
|
|
27
|
-
export declare function resetEscalation(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getHarnessTier,setHarnessTier}from'../config/runtime.js';
|
|
1
|
+
import{getHarnessTier,setHarnessTier}from'../config/runtime.js';let recent_failures=[];const REPEATED_FAILURE_WINDOW_MS=0xea60,REPEATED_FAILURE_THRESHOLD=0x3;function isFullTier(a){return a==='full';}export function shouldRunHeavyHooks(){return isFullTier(getHarnessTier());}export function shouldRunLightHooks(){const a=getHarnessTier();return a==='lightweight'||a==='full';}export function recordCriticalRisk(a){return escalate('E1_CRITICAL_RISK','CRITICAL\x20risk\x20detected:\x20'+a);}export function recordCriticalOperation(a,b){return escalate('E2_OPERATION_CRITICAL','Operation\x20\x27'+a+'\x27\x20returned\x20CRITICAL\x20error:\x20'+b);}export function recordSubstepFailure(a){return escalate('E3_SUBSTEP_FAILURE','Substep\x20trace\x20reported\x20failure:\x20'+a);}export function recordOperationFailure(a,b){const c=Date['now']();recent_failures['push']({'timestamp':c,'operation':a,'error_code':b}),recent_failures=recent_failures['filter'](d=>c-d['timestamp']<=REPEATED_FAILURE_WINDOW_MS);if(recent_failures['length']>=REPEATED_FAILURE_THRESHOLD){const d=recent_failures['map'](e=>e['operation']+':'+e['error_code'])['join'](',\x20');return escalate('E4_REPEATED_FAILURE','Repeated\x20failures\x20('+recent_failures['length']+'\x20in\x20'+REPEATED_FAILURE_WINDOW_MS/0x3e8+'s):\x20'+d);}return null;}function escalate(a,b){const c=getHarnessTier();if(c!=='lightweight')return null;const d={'trigger':a,'timestamp':new Date()['toISOString'](),'reason':b,'from_tier':c,'to_tier':'full'};return setHarnessTier('full'),d;}
|
package/dist/harness/index.d.ts
CHANGED
|
@@ -1,23 +1,10 @@
|
|
|
1
1
|
export * from "./types.js";
|
|
2
|
-
export * from "./plan.js";
|
|
3
2
|
export * from "./verify.js";
|
|
4
3
|
export * from "./recover.js";
|
|
5
|
-
import type { DecisionPoint, MigrationDecision } from "./plan.js";
|
|
6
4
|
import type { VerifyInput } from "./verify.js";
|
|
7
|
-
import type {
|
|
5
|
+
import type { ExpectedResult, VerifyReport, RecoveryAction } from "./types.js";
|
|
8
6
|
export declare class Harness {
|
|
9
7
|
private context;
|
|
10
|
-
plan(userInput: string, taskId?: string): ODG;
|
|
11
|
-
planFromSemanticGraph(graph: import("../playbooks/service-build/semantic-graph.js").SemanticObjectGraph, taskId?: string): ODG;
|
|
12
|
-
classifyIntent(userInput: string): import("./plan.js").IntentClassification;
|
|
13
|
-
getDecisions(odg: ODG): DecisionPoint[];
|
|
14
|
-
getMigrationDecisions(options?: {
|
|
15
|
-
from_network?: "testnet";
|
|
16
|
-
to_network?: "mainnet";
|
|
17
|
-
current_payment_token?: string;
|
|
18
|
-
}): MigrationDecision[];
|
|
19
|
-
detectCycles(odg: ODG): string[] | null;
|
|
20
|
-
getScenarioRegistry(): import("./types.js").ScenarioTemplate[];
|
|
21
8
|
expect(operation: string, intent: string, operationType: string, data?: Record<string, unknown>): ExpectedResult;
|
|
22
9
|
verify(input: VerifyInput): VerifyReport;
|
|
23
10
|
recover(errorCode: string, operationId: string, context?: {
|
package/dist/harness/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from'./types.js';export*from'./
|
|
1
|
+
export*from'./types.js';export*from'./verify.js';export*from'./recover.js';import{verify,generateExpected}from'./verify.js';import{recover,resetAttempts,getBackoffDelay,RECOVERY_RULES}from'./recover.js';export class Harness{['context']=new Map();['expect'](a,b,c,d){return generateExpected(a,b,c,d);}['verify'](a){return verify(a);}['recover'](a,b,c){return recover(a,b,c);}['resetRecovery'](a){resetAttempts(a);}['getBackoffDelay'](a){return getBackoffDelay(a);}['getRecoveryRules'](){return RECOVERY_RULES;}['setContext'](a,b){this['context']['set'](a,b);}['getContext'](a){return this['context']['get'](a);}}let singleton=null;export function getHarness(){return!singleton&&(singleton=new Harness()),singleton;}export function setHarness(a){singleton=a;}
|
package/dist/harness/types.d.ts
CHANGED
|
@@ -1,26 +1,3 @@
|
|
|
1
|
-
import type { GraphNodeBase } from "../graph/base.js";
|
|
2
|
-
export type ObjectType = "Permission" | "Service" | "Machine" | "Guard" | "Allocation" | "Progress" | "Repository" | "Treasury" | "Reward" | "Demand" | "Order" | "Arbitration" | "Contact" | "Personal" | "Payment";
|
|
3
|
-
export type ObjectStatus = "not_created" | "created_unpublished" | "published" | "failed";
|
|
4
|
-
export interface ODGNode extends GraphNodeBase {
|
|
5
|
-
type: ObjectType;
|
|
6
|
-
status: ObjectStatus;
|
|
7
|
-
reversible: boolean;
|
|
8
|
-
dependencies: string[];
|
|
9
|
-
user_decisions?: string[];
|
|
10
|
-
risk_flags?: string[];
|
|
11
|
-
estimated_time?: string;
|
|
12
|
-
}
|
|
13
|
-
export interface ODGPhase {
|
|
14
|
-
name: string;
|
|
15
|
-
objects: string[];
|
|
16
|
-
description?: string;
|
|
17
|
-
}
|
|
18
|
-
export interface ODG {
|
|
19
|
-
task_id: string;
|
|
20
|
-
scenario: string;
|
|
21
|
-
objects: ODGNode[];
|
|
22
|
-
phases: ODGPhase[];
|
|
23
|
-
}
|
|
24
1
|
export interface ExpectedObject {
|
|
25
2
|
role: string;
|
|
26
3
|
expect_fields?: Record<string, unknown>;
|
|
@@ -84,18 +61,3 @@ export interface RecoveryAction {
|
|
|
84
61
|
current_attempt: number;
|
|
85
62
|
detail: string;
|
|
86
63
|
}
|
|
87
|
-
export interface ScenarioTemplate {
|
|
88
|
-
name: string;
|
|
89
|
-
keywords: string[];
|
|
90
|
-
objects: Array<Omit<ODGNode, "id" | "status" | "address">>;
|
|
91
|
-
phases: Array<{
|
|
92
|
-
name: string;
|
|
93
|
-
object_types: ObjectType[];
|
|
94
|
-
}>;
|
|
95
|
-
default_permissions: {
|
|
96
|
-
provider?: number;
|
|
97
|
-
customer?: "namedOperator";
|
|
98
|
-
arbiter?: number;
|
|
99
|
-
};
|
|
100
|
-
description: string;
|
|
101
|
-
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ScopeSnapshot } from "../monitor/types.js";
|
|
2
|
+
import { type PaymentDetectorDeps, type ProgressDetectorDeps } from "./detectors.js";
|
|
3
|
+
import { type KeeperStore } from "./KeeperStore.js";
|
|
4
|
+
import { type KeeperTask } from "./types.js";
|
|
5
|
+
export interface KeeperExecutionOutcome {
|
|
6
|
+
ok: boolean;
|
|
7
|
+
digest?: string;
|
|
8
|
+
error?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface KeeperScanDeps {
|
|
11
|
+
store: KeeperStore;
|
|
12
|
+
payment: PaymentDetectorDeps;
|
|
13
|
+
progress: ProgressDetectorDeps;
|
|
14
|
+
execute(input: {
|
|
15
|
+
operation_type: string;
|
|
16
|
+
data: Record<string, unknown>;
|
|
17
|
+
account: string;
|
|
18
|
+
network: string;
|
|
19
|
+
via: string;
|
|
20
|
+
}): Promise<KeeperExecutionOutcome>;
|
|
21
|
+
now(): number;
|
|
22
|
+
logger(message: string): void;
|
|
23
|
+
}
|
|
24
|
+
export interface KeeperScanSummary {
|
|
25
|
+
scanned: boolean;
|
|
26
|
+
reason?: string;
|
|
27
|
+
opened: number;
|
|
28
|
+
refreshed: number;
|
|
29
|
+
revived: number;
|
|
30
|
+
superseded: number;
|
|
31
|
+
auto_executed: number;
|
|
32
|
+
auto_failed: number;
|
|
33
|
+
duration_ms: number;
|
|
34
|
+
}
|
|
35
|
+
export declare function realKeeperScanDeps(): KeeperScanDeps;
|
|
36
|
+
export declare function runKeeperScan(network: string, scope: ScopeSnapshot, deps: KeeperScanDeps, opts?: {
|
|
37
|
+
force?: boolean;
|
|
38
|
+
}): Promise<KeeperScanSummary>;
|
|
39
|
+
export declare function executeKeeperTask(network: string, task: KeeperTask, deps: KeeperScanDeps): Promise<KeeperExecutionOutcome>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{handleOnchainOperations}from'../tools/handlers/onchain.js';import{detectPaymentUnclaimed,detectProgressActionable,realPaymentDetectorDeps,realProgressDetectorDeps}from'./detectors.js';import{keeperStore}from'./KeeperStore.js';import{AUTO_EXECUTABLE_DETECTORS}from'./types.js';async function defaultExecute(a){try{const b=await handleOnchainOperations({'operation_type':a['operation_type'],'data':a['data'],'env':{'account':a['account'],'network':a['network'],'confirmed':!![],'user_intent_phrases':['keeper\x20auto-execute\x20via\x20'+a['via']]}}),c=b?.['structuredContent']?.['result'];if(c?.['type']==='transaction'&&typeof c?.['digest']==='string')return{'ok':!![],'digest':c['digest']};const d=c?.['type']==='error'&&typeof c?.['error']==='string'?c['error']:typeof b?.['structuredContent']?.['message']==='string'?b['structuredContent']['message']:'execution\x20did\x20not\x20produce\x20a\x20transaction';return{'ok':![],'error':String(d)['slice'](0x0,0x1f4)};}catch(f){return{'ok':![],'error':String(f?.['message']??f)['slice'](0x0,0x1f4)};}}export function realKeeperScanDeps(){return{'store':keeperStore,'payment':realPaymentDetectorDeps(),'progress':realProgressDetectorDeps(),'execute':defaultExecute,'now':()=>Date['now'](),'logger':a=>console['error']('[keeper]\x20'+a)};}export async function runKeeperScan(a,b,c,d){const f=c['now'](),g={'scanned':![],'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0,'auto_executed':0x0,'auto_failed':0x0,'duration_ms':0x0};try{const h=await c['store']['getConfig'](a);if(!h['enabled'])return g['reason']='disabled',g;const i=await c['store']['getLastScanAt'](a);if(!d?.['force']&&c['now']()-i<h['scan_interval_ms'])return g['reason']='interval',g;await c['store']['setLastScanAt'](a,c['now']()),g['scanned']=!![];if(h['detectors']['payment_unclaimed'])try{const l=await detectPaymentUnclaimed((b['accounts']??[])['slice'](0x0,h['max_scan_objects']),a,c['payment']),m=await c['store']['upsertDesired'](a,'payment_unclaimed',l,c['now']());g['opened']+=m['opened'],g['refreshed']+=m['refreshed'],g['revived']+=m['revived'],g['superseded']+=m['superseded'];}catch(n){c['logger']('scan\x20'+a+':\x20payment_unclaimed\x20detector\x20failed:\x20'+String(n?.['message']??n));}if(h['detectors']['progress_actionable'])try{const o=await detectProgressActionable(b,a,c['progress'],h['max_scan_objects']),p=await c['store']['upsertDesired'](a,'progress_actionable',o,c['now']());g['opened']+=p['opened'],g['refreshed']+=p['refreshed'],g['revived']+=p['revived'],g['superseded']+=p['superseded'];}catch(q){c['logger']('scan\x20'+a+':\x20progress_actionable\x20detector\x20failed:\x20'+String(q?.['message']??q));}const j=await c['store']['listTasks'](a,{'status':'pending'});let k=h['max_auto_execute_per_scan'];for(const s of j){if(k<=0x0)break;if(!s['operation'])continue;if(!AUTO_EXECUTABLE_DETECTORS['includes'](s['detector']))continue;if(s['last_auto_attempt_at']&&c['now']()-s['last_auto_attempt_at']<h['auto_retry_cooldown_ms'])continue;const t=await c['store']['matchingAutoRules'](a,s['detector'],s['beneficiary']),u=t[0x0];if(!u)continue;k--,await c['store']['markAutoAttempt'](a,s['id'],c['now']());const v=await c['execute']({'operation_type':s['operation']['operation_type'],'data':s['operation']['data'],'account':s['beneficiary'],'network':a,'via':'rule\x20'+u['id']});v['ok']?(await c['store']['resolveTask'](a,s['id'],'auto_executed',c['now'](),v['digest']?'tx\x20'+v['digest']:'executed',u['id']),g['auto_executed']++,c['logger']('auto-executed\x20'+s['dedupe_key']+'\x20via\x20rule\x20'+u['id']+'\x20('+(v['digest']??'no\x20digest')+')')):(await c['store']['resolveTask'](a,s['id'],'execute_failed',c['now'](),v['error']??'unknown\x20execution\x20error',u['id']),g['auto_failed']++,c['logger']('auto-execute\x20failed\x20for\x20'+s['dedupe_key']+':\x20'+(v['error']??'unknown')));}return g;}catch(w){return c['logger']('scan\x20'+a+'\x20failed:\x20'+String(w?.['message']??w)),g['reason']='error',g;}finally{g['duration_ms']=c['now']()-f;}}export async function executeKeeperTask(a,b,c){if(!b['operation'])return{'ok':![],'error':'This\x20task\x20is\x20reminder-only\x20(no\x20keeper-executable\x20operation).\x20'+'Follow\x20its\x20detail\x20text\x20—\x20progress\x20forwards\x20are\x20advanced\x20via\x20workflow_operation.'};const d=await c['execute']({'operation_type':b['operation']['operation_type'],'data':b['operation']['data'],'account':b['beneficiary'],'network':a,'via':'manual'});return d['ok']?await c['store']['resolveTask'](a,b['id'],'manual_executed',c['now'](),d['digest']?'tx\x20'+d['digest']:'executed'):await c['store']['resolveTask'](a,b['id'],'execute_failed',c['now'](),d['error']),d;}
|