@wowok/agent-mcp 2.7.10 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/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/registry.d.ts +3 -25
- package/dist/extensions/registry.js +1 -1
- package/dist/extensions/types.d.ts +0 -68
- package/dist/goal/GoalEngine.d.ts +36 -1
- package/dist/goal/GoalEngine.js +1 -1
- package/dist/goal/types.d.ts +4 -0
- package/dist/knowledge/account-marks.d.ts +1 -0
- package/dist/knowledge/account-marks.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/index.d.ts +5 -3
- 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-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/workflow-guidance.d.ts +35 -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 +2 -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/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/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 -6
- 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 +88 -0
- package/dist/relationship/derivation.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/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/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/industry-pack/index.d.ts +58 -0
- package/dist/schema/industry-pack/index.js +1 -1
- package/dist/schema/industry-pack/modes.d.ts +59 -1
- package/dist/schema/industry-pack/modes.js +1 -1
- package/dist/schema/intent-radar/index.d.ts +19 -19
- package/dist/schema/local/index.d.ts +11 -0
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/operations.d.ts +58 -16
- package/dist/schema/persona/index.d.ts +1 -1
- package/dist/schema/query/bi.d.ts +145 -16
- package/dist/schema/query/bi.js +1 -1
- package/dist/schema/query/index.d.ts +2 -2
- package/dist/schema/schema-version.js +1 -1
- 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/goal_operation.schema.json +76 -0
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/industry_pack_operation.output.json +176 -1
- package/dist/schemas/industry_pack_operation.schema.json +19 -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 +53 -0
- package/dist/schemas/query_toolkit.output.json +240 -7
- package/dist/schemas/query_toolkit.schema.json +53 -0
- package/dist/task/ProcessStore.d.ts +18 -1
- package/dist/task/ProcessStore.js +1 -1
- package/dist/task/types.d.ts +24 -0
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/evaluation.js +1 -1
- package/dist/tools/handlers/goal.js +1 -1
- package/dist/tools/handlers/industry-pack.js +1 -1
- package/dist/tools/handlers/local.d.ts +4 -3
- package/dist/tools/handlers/local.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/workflow.js +1 -1
- package/dist/tools/index.js +1 -1
- 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/package.json +2 -2
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
const BUILTIN_RISK_METRICS=[{'metric_id':'funds_risk','display_name':'Funds\x20Risk','description':'Directly\x20operates\x20funds\x20/\x20affects\x20fund\x20flow\x20/\x20no\x20fund\x20risk','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'trust_risk','display_name':'Trust\x20Risk','description':'Degree\x20of\x20impact\x20on\x20trust\x20mechanism','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'delivery_risk','display_name':'Delivery\x20Risk','description':'Degree\x20of\x20impact\x20on\x20order\x20fulfillment','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'compliance_risk','display_name':'Compliance\x20Risk','description':'Degree\x20of\x20regulatory\x20involvement','type':'risk','scale':'level','weight':0x1,'scope':'builtin'}],BUILTIN_BENEFIT_METRICS=[{'metric_id':'automation_level','display_name':'Automation\x20Level','description':'Fully\x20automated\x20/\x20semi-automated\x20/\x20manual','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'trust_boost','display_name':'Trust\x20Boost','description':'Degree\x20of\x20enhancement\x20to\x20trust\x20mechanism','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'efficiency_gain','display_name':'Efficiency\x20Gain','description':'Degree\x20of\x20efficiency\x20improvement','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'}];export class MetricRegistry{static ['instance'];['metrics']=new Map();['
|
|
1
|
+
import{OwnedRecordStorage}from'@wowok/wowok';const BUILTIN_RISK_METRICS=[{'metric_id':'funds_risk','display_name':'Funds\x20Risk','description':'Directly\x20operates\x20funds\x20/\x20affects\x20fund\x20flow\x20/\x20no\x20fund\x20risk','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'trust_risk','display_name':'Trust\x20Risk','description':'Degree\x20of\x20impact\x20on\x20trust\x20mechanism','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'delivery_risk','display_name':'Delivery\x20Risk','description':'Degree\x20of\x20impact\x20on\x20order\x20fulfillment','type':'risk','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'compliance_risk','display_name':'Compliance\x20Risk','description':'Degree\x20of\x20regulatory\x20involvement','type':'risk','scale':'level','weight':0x1,'scope':'builtin'}],BUILTIN_BENEFIT_METRICS=[{'metric_id':'automation_level','display_name':'Automation\x20Level','description':'Fully\x20automated\x20/\x20semi-automated\x20/\x20manual','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'trust_boost','display_name':'Trust\x20Boost','description':'Degree\x20of\x20enhancement\x20to\x20trust\x20mechanism','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'},{'metric_id':'efficiency_gain','display_name':'Efficiency\x20Gain','description':'Degree\x20of\x20efficiency\x20improvement','type':'benefit','scale':'level','weight':0x1,'scope':'builtin'}];export class MetricRegistry{static ['instance'];['metrics']=new Map();['persistence']=new OwnedRecordStorage('custom_metrics');['customMetricsLoaded']=![];static['Instance'](){return!MetricRegistry['instance']&&(MetricRegistry['instance']=new MetricRegistry()),MetricRegistry['instance'];}constructor(){this['registerBuiltinMetrics']();}async['ensureLoaded'](){if(this['customMetricsLoaded'])return;this['customMetricsLoaded']=!![];try{const a=await this['persistence']['list']();for(const b of a){try{const c=JSON['parse'](b['data']);c?.['metric_id']&&c['scope']==='custom'&&this['metrics']['set'](c['metric_id'],c);}catch{console['warn']('[MetricRegistry]\x20Skipping\x20corrupt\x20custom_metrics\x20row\x20\x27'+b['owner']+':'+b['name']+'\x27.');}}}catch(d){console['warn']('[MetricRegistry]\x20Failed\x20to\x20load\x20persisted\x20custom\x20metrics:',d['message']);}}['registerMetric'](a){if(!a['metric_id']||!a['type']||!a['scale'])return![];if(this['metrics']['has'](a['metric_id']))return![];return this['metrics']['set'](a['metric_id'],a),!![];}async['registerCustomMetric'](a,b,c,d,e,f,g){await this['ensureLoaded']();const h={'metric_id':a,'display_name':b,'description':c,'type':d,'scale':e,'weight':g??0x1,'scope':'custom','owner':f},i=this['registerMetric'](h);if(i)try{await this['persistence']['save'](f,a,JSON['stringify'](h));}catch(j){console['warn']('[MetricRegistry]\x20Failed\x20to\x20persist\x20custom\x20metric\x20\x27'+a+'\x27:',j['message']);}return i;}['getMetric'](a){return this['metrics']['get'](a);}async['listMetrics'](a){await this['ensureLoaded']();let b=Array['from'](this['metrics']['values']());if(!a)return b;if(a['type'])b=b['filter'](c=>c['type']===a['type']);if(a['scope'])b=b['filter'](c=>c['scope']===a['scope']);if(a['owner'])b=b['filter'](c=>c['owner']===a['owner']);return b;}async['unregisterMetric'](a,b){await this['ensureLoaded']();const c=this['metrics']['get'](a);if(!c||c['scope']!=='custom'||c['owner']!==b)return![];const d=this['metrics']['delete'](a);if(d)try{await this['persistence']['delete'](b,a);}catch(e){console['warn']('[MetricRegistry]\x20Failed\x20to\x20delete\x20persisted\x20custom\x20metric\x20\x27'+a+'\x27:',e['message']);}return d;}['evaluateMode'](a,b,c){const d=[...this['metrics']['values']()];if(c)for(const l of c){!d['some'](n=>n['metric_id']===l['metric_id'])&&d['push'](l);}const e=d['filter'](n=>n['type']==='risk'),f=d['filter'](n=>n['type']==='benefit'),g=[];for(const n of a['capabilities_used']){const o=b['getCard'](n);if(o)g['push'](o);}const h=this['evaluateMetricGroup'](g,e,'risk'),i=this['evaluateMetricGroup'](g,f,'benefit'),j=this['aggregateScore'](h),k=this['aggregateScore'](i);return{'risk_score':j,'benefit_score':k,'metric_details':[...h,...i]};}['evaluateMetricGroup'](a,b,c){const d=[];for(const e of b){const f=[];for(const h of a){const i=c==='risk'?h['risk_profile']:h['benefit_profile'];if(!i)continue;const j=i[e['metric_id']];j!==undefined&&f['push']({'value':j,'weight':0x1});}if(f['length']===0x0)continue;const g=this['computeAverageScore'](f,e['scale']);d['push']({'metric_id':e['metric_id'],'display_name':e['display_name'],'value':this['aggregateValue'](f,e['scale']),'normalized_score':g,'weight':e['weight']??0x1});}return d;}['computeAverageScore'](a,b){if(a['length']===0x0)return 0x0;if(b==='level'){const c={'high':0x64,'medium':0x3c,'low':0x1e};let d=0x0,e=0x0;for(const f of a){const g=c[String(f['value'])]??0x32;d+=g*f['weight'],e+=f['weight'];}return Math['round'](d/Math['max'](e,0x1));}if(b==='numeric'){let h=0x0,i=0x0;for(const j of a){const k=typeof j['value']==='number'?j['value']:0x32;h+=k*j['weight'],i+=j['weight'];}return Math['round'](h/Math['max'](i,0x1));}if(b==='percentage'){let l=0x0,m=0x0;for(const n of a){const o=typeof n['value']==='number'?n['value']:0x32;l+=o*n['weight'],m+=n['weight'];}return Math['round'](l/Math['max'](m,0x1));}return 0x0;}['aggregateValue'](a,b){if(b==='level'){const d={'high':0x0,'medium':0x0,'low':0x0};for(const f of a){const g=String(f['value']);if(d[g]!==undefined)d[g]++;}const e=Object['entries'](d)['sort']((h,i)=>i[0x1]-h[0x1])[0x0]?.[0x0];return e??'medium';}const c=a['reduce']((h,i)=>h+(typeof i['value']==='number'?i['value']:0x0),0x0);return Math['round'](c/a['length']);}['aggregateScore'](a){if(a['length']===0x0)return 0x0;let b=0x0,c=0x0;for(const e of a){b+=e['normalized_score']*e['weight'],c+=e['weight'];}return Math['round'](b/Math['max'](c,0x1));}['registerBuiltinMetrics'](){for(const a of BUILTIN_RISK_METRICS){this['registerMetric'](a);}for(const b of BUILTIN_BENEFIT_METRICS){this['registerMetric'](b);}}}export function getMetricRegistry(){return MetricRegistry['Instance']();}export const BUILTIN_METRICS_COUNT=BUILTIN_RISK_METRICS['length']+BUILTIN_BENEFIT_METRICS['length'];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { IndustryMode, ModeEvaluation
|
|
1
|
+
import type { IndustryMode, ModeEvaluation } from "./types.js";
|
|
2
2
|
import type { CapabilityRegistry } from "./capability-manifest.js";
|
|
3
3
|
import { MetricRegistry } from "./metric-registry.js";
|
|
4
4
|
import { ConstraintRegistry } from "./constraint-registry.js";
|
|
@@ -7,8 +7,7 @@ export declare class ModeEvaluator {
|
|
|
7
7
|
private metricRegistry;
|
|
8
8
|
private constraintRegistry;
|
|
9
9
|
constructor(capabilityRegistry: CapabilityRegistry, metricRegistry?: MetricRegistry, constraintRegistry?: ConstraintRegistry);
|
|
10
|
-
evaluateMode(mode: IndustryMode
|
|
11
|
-
evaluateMigration(source: IndustryMode, target: IndustryMode): ModeMigrationEvaluation;
|
|
10
|
+
evaluateMode(mode: IndustryMode): ModeEvaluation;
|
|
12
11
|
private isCustomMode;
|
|
13
12
|
private checkCapabilityConflicts;
|
|
14
13
|
private generateRecommendations;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MetricRegistry}from'./metric-registry.js';import{ConstraintRegistry}from'./constraint-registry.js';export class ModeEvaluator{['capabilityRegistry'];['metricRegistry'];['constraintRegistry'];constructor(a,b,c){this['capabilityRegistry']=a,this['metricRegistry']=b??MetricRegistry['Instance'](),this['constraintRegistry']=c??ConstraintRegistry['Instance']();}['evaluateMode'](a
|
|
1
|
+
import{MetricRegistry}from'./metric-registry.js';import{ConstraintRegistry}from'./constraint-registry.js';export class ModeEvaluator{['capabilityRegistry'];['metricRegistry'];['constraintRegistry'];constructor(a,b,c){this['capabilityRegistry']=a,this['metricRegistry']=b??MetricRegistry['Instance'](),this['constraintRegistry']=c??ConstraintRegistry['Instance']();}['evaluateMode'](a){const b=this['checkCapabilityConflicts'](a),c=this['isCustomMode'](a)?a['custom_constraints']:undefined,d=this['constraintRegistry']['checkConstraints'](a,this['capabilityRegistry'],c),e=d['filter'](n=>n['severity']==='hard')['map'](n=>n['display_name']+':\x20'+n['violation']),f=d['filter'](n=>n['severity']==='soft')['map'](n=>n['display_name']+':\x20'+n['violation']),g=this['isCustomMode'](a)?a['custom_metrics']:undefined,h=this['metricRegistry']['evaluateMode'](a,this['capabilityRegistry'],g),i=h['risk_score'],j=h['benefit_score'],k=j/Math['max'](i,0x1),l=b['length']===0x0&&e['length']===0x0,m=this['generateRecommendations'](a,i,j,b,e,f);return{'applicable':l,'risk_score':i,'benefit_score':j,'risk_benefit_ratio':k,'capability_conflicts':b,'violated_constraints':e,'unmet_conditions':f,'recommendations':m};}['isCustomMode'](a){return a['owner']!==undefined&&a['source']==='custom';}['checkCapabilityConflicts'](a){const b=[],c=a['capabilities_used'];for(const d of c){const e=this['capabilityRegistry']['getCard'](d);if(!e?.['constraints']?.['conflicts_with'])continue;for(const f of e['constraints']['conflicts_with']){c['includes'](f)&&b['push'](d+'\x20conflicts\x20with\x20'+f);}if(e['constraints']['must_pair_with'])for(const g of e['constraints']['must_pair_with']){!c['includes'](g)&&b['push'](d+'\x20requires\x20'+g+'\x20(must_pair_with\x20not\x20satisfied)');}}return b;}['generateRecommendations'](a,b,c,d,e,f){const g=[];d['length']>0x0&&g['push']('Detected\x20'+d['length']+'\x20capability\x20conflicts,\x20must\x20be\x20resolved\x20before\x20applying\x20the\x20mode');e['length']>0x0&&g['push']('Detected\x20'+e['length']+'\x20hard\x20constraint\x20violations,\x20need\x20to\x20supplement\x20missing\x20capabilities\x20or\x20adjust\x20mode\x20configuration');f['length']>0x0&&g['push']('Detected\x20'+f['length']+'\x20soft\x20constraints\x20not\x20met,\x20recommend\x20adjusting\x20to\x20improve\x20mode\x20quality');const h={'conservative':{'max_risk':0x1e,'min_benefit':0x32},'balanced':{'max_risk':0x3c,'min_benefit':0x3c},'aggressive':{'max_risk':0x64,'min_benefit':0x50}},i=h[a['risk_appetite']];return b>i['max_risk']&&g['push']('Risk\x20score\x20'+b+'\x20exceeds\x20'+a['risk_appetite']+'\x20mode\x20threshold\x20'+i['max_risk']+',\x20recommend\x20reducing\x20risk\x20or\x20adjusting\x20risk\x20appetite'),c<i['min_benefit']&&g['push']('Benefit\x20score\x20'+c+'\x20below\x20'+a['risk_appetite']+'\x20mode\x20threshold\x20'+i['min_benefit']+',\x20recommend\x20adding\x20benefit\x20capabilities\x20or\x20adjusting\x20risk\x20appetite'),g['length']===0x0&&g['push']('Mode\x20evaluation\x20passed:\x20risk\x20'+b+'\x20/\x20benefit\x20'+c+'\x20/\x20risk-benefit\x20ratio\x20'+(c/Math['max'](b,0x1))['toFixed'](0x2)),g;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { IndustryMode, UserDefinedMode,
|
|
1
|
+
import type { IndustryMode, UserDefinedMode, ModeEvaluation } from "./types.js";
|
|
2
2
|
export declare class IndustryModeRegistry {
|
|
3
3
|
private static instance;
|
|
4
4
|
private registrations;
|
|
@@ -16,8 +16,7 @@ export declare class IndustryModeRegistry {
|
|
|
16
16
|
resolveAlias(name: string): string;
|
|
17
17
|
hasMode(name: string): boolean;
|
|
18
18
|
unregisterMode(name: string): boolean;
|
|
19
|
-
|
|
20
|
-
evaluateMigration(sourceName: string, targetName: string): ModeMigrationEvaluation;
|
|
19
|
+
evaluateModeObject(mode: IndustryMode): Promise<ModeEvaluation>;
|
|
21
20
|
registerUserMode(mode: UserDefinedMode, userId: string): Promise<boolean>;
|
|
22
21
|
deriveMode(sourceMode: string, modifications: Partial<UserDefinedMode>, userId: string, newName: string, newDisplayName?: string): Promise<UserDefinedMode | undefined>;
|
|
23
22
|
evolveMode(modeName: string, updates: Partial<UserDefinedMode>, userId: string, changeDescription: string, bumpVersion?: boolean): Promise<UserDefinedMode | undefined>;
|
|
@@ -29,28 +28,7 @@ export declare class IndustryModeRegistry {
|
|
|
29
28
|
private persistUserMode;
|
|
30
29
|
private unpersistUserMode;
|
|
31
30
|
private bumpPatchVersion;
|
|
32
|
-
applyTemplate(name: string, intent: string, context: ProjectContext): Promise<Blueprint>;
|
|
33
|
-
applyUserMode(modeName: string, userId: string, intent: string, context: ProjectContext): Promise<Blueprint>;
|
|
34
|
-
private doApplyTemplate;
|
|
35
|
-
validateBlueprint(objects: BlueprintObject[], edges: BlueprintEdge[], mode: IndustryMode): {
|
|
36
|
-
errors: string[];
|
|
37
|
-
warnings: string[];
|
|
38
|
-
};
|
|
39
|
-
private buildObjects;
|
|
40
|
-
private buildPermissionIndexes;
|
|
41
|
-
private applyConfigOverrides;
|
|
42
|
-
private applyConfigOverrideRules;
|
|
43
|
-
private evaluateCondition;
|
|
44
|
-
private setNestedField;
|
|
45
|
-
private buildEdges;
|
|
46
|
-
private makeEdge;
|
|
47
|
-
private buildSteps;
|
|
48
|
-
private defaultScenarios;
|
|
49
|
-
private recordCapabilitiesUsed;
|
|
50
|
-
private deriveGuardShortName;
|
|
51
|
-
private getFirstServiceGuardName;
|
|
52
|
-
private makeObject;
|
|
53
31
|
private registerBuiltinModes;
|
|
54
32
|
}
|
|
55
33
|
export declare function getIndustryModeRegistry(): IndustryModeRegistry;
|
|
56
|
-
export declare const INDUSTRY_MODE_REGISTRY_VERSION = 2.
|
|
34
|
+
export declare const INDUSTRY_MODE_REGISTRY_VERSION = 2.3;
|
|
@@ -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,7 +1,7 @@
|
|
|
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";
|
|
@@ -28,6 +28,22 @@ export interface GoalProcessDeps {
|
|
|
28
28
|
}): ProblemRecord[];
|
|
29
29
|
listFeedback(dir: string): FeedbackRecord[];
|
|
30
30
|
readEvents(dir: string): ProcessEvent[];
|
|
31
|
+
addSuggestion(dir: string, input: {
|
|
32
|
+
object?: string;
|
|
33
|
+
kind: SuggestionRecord["kind"];
|
|
34
|
+
stage?: string;
|
|
35
|
+
objects?: {
|
|
36
|
+
type: string;
|
|
37
|
+
object: string;
|
|
38
|
+
}[];
|
|
39
|
+
title: string;
|
|
40
|
+
detail?: string;
|
|
41
|
+
origin?: SuggestionRecord["origin"];
|
|
42
|
+
}): SuggestionRecord;
|
|
43
|
+
updateSuggestion(dir: string, id: string, patch: Partial<Pick<SuggestionRecord, "status" | "resolution_note" | "applied" | "stage" | "object">>): SuggestionRecord;
|
|
44
|
+
listSuggestions(dir: string, filter?: {
|
|
45
|
+
status?: SuggestionRecord["status"];
|
|
46
|
+
}): SuggestionRecord[];
|
|
31
47
|
removeDir(dir: string): void;
|
|
32
48
|
}
|
|
33
49
|
export interface GoalEngineDeps {
|
|
@@ -108,6 +124,25 @@ export declare class GoalEngine {
|
|
|
108
124
|
process_summary?: GoalProcessSummary;
|
|
109
125
|
}>;
|
|
110
126
|
private summarizeProcess;
|
|
127
|
+
listSuggestions(network: string, id: string, opts?: {
|
|
128
|
+
include_resolved?: boolean;
|
|
129
|
+
}): Promise<{
|
|
130
|
+
goal: GoalRecord;
|
|
131
|
+
suggestions: SuggestionRecord[];
|
|
132
|
+
open_problems: ProblemRecord[];
|
|
133
|
+
}>;
|
|
134
|
+
resolveSuggestion(network: string, id: string, suggestionId: string, opts: {
|
|
135
|
+
decision: "confirm" | "dismiss";
|
|
136
|
+
note?: string;
|
|
137
|
+
apply?: boolean;
|
|
138
|
+
}): Promise<{
|
|
139
|
+
goal: GoalRecord;
|
|
140
|
+
suggestion: SuggestionRecord;
|
|
141
|
+
applied: boolean;
|
|
142
|
+
apply_error?: string;
|
|
143
|
+
complete_report?: GoalCompletionVerdict;
|
|
144
|
+
}>;
|
|
145
|
+
private emitSuggestionEvent;
|
|
111
146
|
list(network: string, filter?: {
|
|
112
147
|
stage?: GoalStage;
|
|
113
148
|
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':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']((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
|
@@ -1 +1 @@
|
|
|
1
|
-
import{objectTypeFromAddress,query_local_mark_list
|
|
1
|
+
import{objectTypeFromAddress,query_local_mark_list}from'@wowok/wowok';import{batchFetchEntityLinker,batchFetchEntityRegistrar,batchQueryObjectsByIds,batchQueryTableItems,fetchTableEntries,listLocalAccounts,resolveLocalNamesFor}from'./workflow-guidance.js';const AGG_TTL_MS=0x1d4c0,AGG_CACHE_MAX=0x8,aggCache=new Map(),aggInflight=new Map(),MAX_TARGETS=0xc8;export async function buildAccountMarks(a){const b=a['network'],c=a['account']?.['trim']()['toLowerCase']()||undefined,d=a['no_cache']===!![],e=(b??'')+'|'+(c??'');if(!d){const g=aggCache['get'](e);if(g&&Date['now']()-g['at']<AGG_TTL_MS)return{...g['value'],'cached':!![]};const h=aggInflight['get'](e);if(h)return h;}const f=((async()=>{const i=c?[{'address':c}]:(await listLocalAccounts())['map'](B=>({'address':B['address']})),j={'action':'account_marks','network':b,'updated_at_ms':Date['now'](),'cached':![],'marks':[],'count':0x0,'note':i['length']===0x0?'No\x20local\x20accounts\x20found\x20—\x20create\x20or\x20import\x20an\x20account\x20first.':undefined};if(i['length']===0x0)return aggCache['set'](e,{'at':Date['now'](),'value':j}),j;const l=await batchFetchEntityRegistrar(i['map'](B=>B['address']),b,d),n=i['map'](B=>l['get'](String(B['address'])['toLowerCase']())?.['mark_object']??null),p=new Map(),q=new Set();let r=![];for(const B of n){if(!B)continue;try{if(a['light']){const {entries:C}=await fetchTableEntries(B,{'network':b,'noCache':d,'limit':MAX_TARGETS,'maxItems':MAX_TARGETS});for(const D of C)q['add'](D['key']['toLowerCase']());}else{const {items:E,truncated:F}=await batchQueryTableItems(B,{'network':b,'noCache':d,'limit':MAX_TARGETS,'maxItems':MAX_TARGETS});r=r||F;for(const G of E){const H=G['object'];if(!H)continue;const I=G['key']['toLowerCase'](),J=(H?.['tags']??[])['map'](L=>String(L)['toLowerCase']())['filter'](L=>L==='like'||L==='dislike'||L==='favor');if(J['length']===0x0)continue;let K=p['get'](I);!K&&(K={'address':I,'tags':new Set()},p['set'](I,K));for(const L of J)K['tags']['add'](L);}}}catch{continue;}}if(a['light']){const M=[...q]['sort']((N,O)=>N['localeCompare'](O))['map'](N=>({'object':N,'vote_kinds':[],'object_type':objectTypeFromAddress(N)??null,'type_raw':undefined,'name':undefined,'description':undefined,'tags':undefined,'rep':undefined,'time':undefined}));return{'action':'account_marks','network':b,'updated_at_ms':Date['now'](),'cached':![],'marks':M,'count':M['length'],'note':i['length']===0x0?'No\x20local\x20accounts\x20found\x20—\x20create\x20or\x20import\x20an\x20account\x20first.':undefined};}const s=[...p['keys']()],u=await batchFetchEntityLinker(s,b,d);for(const N of s){const O=p['get'](N),P=u['get'](N);if(!P)continue;const Q=Array['isArray'](P?.['votes'])?P['votes']:[];for(const R of i){const S=Q['find'](T=>String(T?.['who']??'')['toLowerCase']()===R['address']['toLowerCase']());if(S?.['time']){const T=Number(S['time']);if(Number['isFinite'](T)&&(!O['time']||T>O['time']))O['time']=T;}}Q['length']>0x0&&(O['rep']={'like':Q['filter'](U=>U&&U['like'])['length'],'dislike':Q['filter'](U=>U&&U['dislike'])['length'],'favor':Q['filter'](U=>U&&U['favor'])['length'],'votes':Q['map'](U=>({'who':U?.['who']??null,'like':!!U?.['like'],'dislike':!!U?.['dislike'],'favor':!!U?.['favor']}))});}const v=await resolveLocalNamesFor(s),w=new Map(),x=new Map(),y=new Map();try{const [U,V]=await Promise['all']([s['length']>0x0?batchQueryObjectsByIds(s,b,d)['then'](X=>({'objects':X})):Promise['resolve']({'objects':[]}),query_local_mark_list(undefined)]);for(const X of U?.['objects']??[]){const Y=String(X?.['object']??X?.['address']??'')['toLowerCase'](),Z=X?.['description']??X?.['data']?.['description'];Y&&typeof Z==='string'&&Z['trim']()&&w['set'](Y,Z['trim']());const a0=X?.['type_raw']??X?.['data']?.['type_raw'];Y&&typeof a0==='string'&&a0['trim']()&&y['set'](Y,a0['trim']());}const W=new Set((U?.['objects']??[])['map'](a1=>String(a1?.['object']??a1?.['address']??'')['toLowerCase']())['filter'](Boolean));for(const a1 of[...p['keys']()]){if(!W['has'](a1)&&objectTypeFromAddress(a1))p['delete'](a1);}for(const a2 of V??[]){const a3=String(a2?.['address']??'')['toLowerCase']();a3&&Array['isArray'](a2?.['tags'])&&a2['tags']['length']>0x0&&x['set'](a3,a2['tags']['map'](String));}}catch{}const z=[...p['values']()]['map'](a4=>{const a5=objectTypeFromAddress(a4['address'])??null;return{'object':a4['address'],'vote_kinds':[...a4['tags']]['sort'](),'time':a4['time'],'object_type':a5,'type_raw':a5?undefined:y['get'](a4['address']),'name':v['byAddress']['get'](a4['address']),'description':w['get'](a4['address']),'tags':x['get'](a4['address']),'rep':a4['rep']};})['sort']((a4,a5)=>(a5['time']??0x0)-(a4['time']??0x0)||a4['object']['localeCompare'](a5['object'])),A={'action':'account_marks','network':b,'updated_at_ms':Date['now'](),'cached':![],'marks':z,'count':z['length'],'note':r?'Result\x20truncated\x20at\x20'+MAX_TARGETS+'\x20targets\x20per\x20account.':undefined};aggCache['set'](e,{'at':Date['now'](),'value':A});if(aggCache['size']>AGG_CACHE_MAX){const a4=aggCache['keys']()['next']()['value'];if(a4!==undefined)aggCache['delete'](a4);}return A;})());if(!d)aggInflight['set'](e,f);try{return await f;}finally{if(!d)aggInflight['delete'](e);}}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { extractGenericTypeArg } from "@wowok/wowok";
|
|
1
2
|
import type { ENTRYPOINT } from "@wowok/wowok";
|
|
2
3
|
export interface OfficialTokenEntry {
|
|
3
4
|
type: string;
|
|
@@ -36,26 +37,29 @@ export interface ParsedAmount {
|
|
|
36
37
|
}
|
|
37
38
|
export declare function isAmountWithSymbol(value: unknown): boolean;
|
|
38
39
|
export declare function parseAmount(amount: string | number, tokenType: string, network?: ENTRYPOINT): Promise<ParsedAmount>;
|
|
39
|
-
export declare function smallestToDisplay(value: bigint, decimals: number): string;
|
|
40
|
-
export declare function displayStringToSmallest(display: string, decimals: number): bigint;
|
|
41
40
|
export interface FundFieldConfirmation {
|
|
42
41
|
path: string;
|
|
43
42
|
displayAmount: string;
|
|
44
43
|
tokenType: string;
|
|
45
44
|
tokenSymbol: string;
|
|
45
|
+
decimals: number;
|
|
46
|
+
smallestUnit: string;
|
|
46
47
|
verified: boolean;
|
|
47
48
|
source: TokenSource;
|
|
48
49
|
converted: boolean;
|
|
49
50
|
context: string;
|
|
50
51
|
}
|
|
52
|
+
export interface TokenCandidate {
|
|
53
|
+
type: string;
|
|
54
|
+
symbol: string;
|
|
55
|
+
name: string;
|
|
56
|
+
decimals: number;
|
|
57
|
+
source: TokenSource;
|
|
58
|
+
verified: boolean;
|
|
59
|
+
}
|
|
51
60
|
export interface TokenAmbiguity {
|
|
52
61
|
symbol: string;
|
|
53
|
-
candidates:
|
|
54
|
-
type: string;
|
|
55
|
-
decimals: number;
|
|
56
|
-
source: TokenSource;
|
|
57
|
-
verified: boolean;
|
|
58
|
-
}[];
|
|
62
|
+
candidates: TokenCandidate[];
|
|
59
63
|
}
|
|
60
64
|
export interface FundConfirmationRequest {
|
|
61
65
|
requiresConfirmation: boolean;
|
|
@@ -110,7 +114,7 @@ export declare function convertTokenValue(tokenType: string, value: {
|
|
|
110
114
|
unit?: string | number;
|
|
111
115
|
}, network?: ENTRYPOINT): Promise<TokenValueConversion>;
|
|
112
116
|
export declare const TOKEN_GENERIC_OBJECT_TYPES: readonly string[];
|
|
113
|
-
export declare
|
|
117
|
+
export declare const extractGenericTokenType: typeof extractGenericTypeArg;
|
|
114
118
|
export interface ObjectTokenResolution {
|
|
115
119
|
tokenType?: string;
|
|
116
120
|
objectType?: string;
|