@wowok/agent-mcp 2.3.14 → 2.3.16

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.
Files changed (156) hide show
  1. package/dist/config/index.d.ts +1 -0
  2. package/dist/config/index.js +1 -0
  3. package/dist/config/runtime.d.ts +26 -0
  4. package/dist/config/runtime.js +217 -0
  5. package/dist/customer/industry-risks.d.ts +36 -0
  6. package/dist/customer/industry-risks.js +424 -0
  7. package/dist/customer/info-puzzle.d.ts +102 -0
  8. package/dist/customer/info-puzzle.js +312 -0
  9. package/dist/customer/order-monitor.d.ts +75 -0
  10. package/dist/customer/order-monitor.js +327 -0
  11. package/dist/customer/order-strategy.d.ts +36 -0
  12. package/dist/customer/order-strategy.js +373 -0
  13. package/dist/customer/post-purchase.d.ts +42 -0
  14. package/dist/customer/post-purchase.js +350 -0
  15. package/dist/customer/reminder-system.d.ts +42 -0
  16. package/dist/customer/reminder-system.js +295 -0
  17. package/dist/customer/risk-assessment.d.ts +8 -0
  18. package/dist/customer/risk-assessment.js +337 -0
  19. package/dist/customer/types.d.ts +193 -0
  20. package/dist/customer/types.js +13 -0
  21. package/dist/customer/user-preferences.d.ts +67 -0
  22. package/dist/customer/user-preferences.js +451 -0
  23. package/dist/experience/experience-reuse.d.ts +10 -0
  24. package/dist/experience/experience-reuse.js +103 -0
  25. package/dist/experience/index.d.ts +6 -0
  26. package/dist/experience/index.js +5 -0
  27. package/dist/experience/intent-distill.d.ts +3 -0
  28. package/dist/experience/intent-distill.js +83 -0
  29. package/dist/experience/realtime-feedback.d.ts +5 -0
  30. package/dist/experience/realtime-feedback.js +77 -0
  31. package/dist/experience/types.d.ts +50 -0
  32. package/dist/experience/types.js +1 -0
  33. package/dist/experience/user-profile.d.ts +25 -0
  34. package/dist/experience/user-profile.js +171 -0
  35. package/dist/index.js +570 -186
  36. package/dist/knowledge/acquisition-flywheel.d.ts +50 -0
  37. package/dist/knowledge/acquisition-flywheel.js +183 -0
  38. package/dist/knowledge/arbitration-trust.d.ts +24 -0
  39. package/dist/knowledge/arbitration-trust.js +117 -0
  40. package/dist/knowledge/audit-rules.d.ts +28 -0
  41. package/dist/knowledge/audit-rules.js +141 -0
  42. package/dist/knowledge/demand-matching.d.ts +29 -0
  43. package/dist/knowledge/demand-matching.js +132 -0
  44. package/dist/knowledge/dynamic-pricing.d.ts +31 -0
  45. package/dist/knowledge/dynamic-pricing.js +87 -0
  46. package/dist/knowledge/flywheel-loop.d.ts +87 -0
  47. package/dist/knowledge/flywheel-loop.js +378 -0
  48. package/dist/knowledge/glossary.d.ts +18 -0
  49. package/dist/knowledge/glossary.js +209 -0
  50. package/dist/knowledge/index.d.ts +64 -0
  51. package/dist/knowledge/index.js +66 -0
  52. package/dist/knowledge/industry-evolution.d.ts +82 -0
  53. package/dist/knowledge/industry-evolution.js +323 -0
  54. package/dist/knowledge/industry-generalizer.d.ts +17 -0
  55. package/dist/knowledge/industry-generalizer.js +381 -0
  56. package/dist/knowledge/industry-registry.d.ts +49 -0
  57. package/dist/knowledge/industry-registry.js +167 -0
  58. package/dist/knowledge/intent-metrics.d.ts +42 -0
  59. package/dist/knowledge/intent-metrics.js +566 -0
  60. package/dist/knowledge/process-model.d.ts +24 -0
  61. package/dist/knowledge/process-model.js +160 -0
  62. package/dist/knowledge/reputation-rules.d.ts +42 -0
  63. package/dist/knowledge/reputation-rules.js +99 -0
  64. package/dist/knowledge/reward-templates.d.ts +25 -0
  65. package/dist/knowledge/reward-templates.js +125 -0
  66. package/dist/knowledge/safety-rules.d.ts +36 -0
  67. package/dist/knowledge/safety-rules.js +171 -0
  68. package/dist/knowledge/tool-constraints.d.ts +30 -0
  69. package/dist/knowledge/tool-constraints.js +185 -0
  70. package/dist/knowledge/trust-metrics.d.ts +37 -0
  71. package/dist/knowledge/trust-metrics.js +138 -0
  72. package/dist/loop-engineering/diagnose.d.ts +3 -2
  73. package/dist/loop-engineering/diagnose.js +94 -0
  74. package/dist/loop-engineering/improve.d.ts +1 -1
  75. package/dist/loop-engineering/improve.js +52 -1
  76. package/dist/project/graph.d.ts +71 -0
  77. package/dist/project/graph.js +314 -0
  78. package/dist/project/index.d.ts +62 -0
  79. package/dist/project/index.js +167 -0
  80. package/dist/project/namespace.d.ts +62 -0
  81. package/dist/project/namespace.js +181 -0
  82. package/dist/project/query.d.ts +40 -0
  83. package/dist/project/query.js +110 -0
  84. package/dist/safety/confirm-gate.d.ts +15 -0
  85. package/dist/safety/confirm-gate.js +44 -0
  86. package/dist/safety/index.d.ts +3 -0
  87. package/dist/safety/index.js +3 -0
  88. package/dist/safety/preview.d.ts +2 -0
  89. package/dist/safety/preview.js +36 -0
  90. package/dist/schema/call/allocation.d.ts +15 -0
  91. package/dist/schema/call/arbitration.d.ts +111 -96
  92. package/dist/schema/call/base.d.ts +1070 -44
  93. package/dist/schema/call/base.js +69 -1
  94. package/dist/schema/call/bridge.d.ts +709 -52
  95. package/dist/schema/call/bridge.js +13 -2
  96. package/dist/schema/call/contact.d.ts +15 -0
  97. package/dist/schema/call/demand.d.ts +69 -54
  98. package/dist/schema/call/guard.d.ts +125 -80
  99. package/dist/schema/call/handler.d.ts +3 -0
  100. package/dist/schema/call/handler.js +14 -0
  101. package/dist/schema/call/machine.d.ts +830 -800
  102. package/dist/schema/call/order.d.ts +15 -0
  103. package/dist/schema/call/payment.d.ts +15 -0
  104. package/dist/schema/call/permission.d.ts +15 -0
  105. package/dist/schema/call/personal.d.ts +15 -0
  106. package/dist/schema/call/progress.d.ts +15 -0
  107. package/dist/schema/call/proof.d.ts +42 -12
  108. package/dist/schema/call/proof.js +3 -3
  109. package/dist/schema/call/repository.d.ts +91 -76
  110. package/dist/schema/call/reward.d.ts +45 -30
  111. package/dist/schema/call/semantic.d.ts +1 -0
  112. package/dist/schema/call/semantic.js +217 -0
  113. package/dist/schema/call/service.d.ts +407 -392
  114. package/dist/schema/call/treasury.d.ts +15 -0
  115. package/dist/schema/common/index.js +3 -3
  116. package/dist/schema/local/index.d.ts +228 -72
  117. package/dist/schema/local/index.js +33 -6
  118. package/dist/schema/messenger/index.d.ts +668 -50
  119. package/dist/schema/messenger/index.js +9 -0
  120. package/dist/schema/operations.d.ts +1693 -1369
  121. package/dist/schema/operations.js +2 -2
  122. package/dist/schema/query/index.d.ts +1614 -1614
  123. package/dist/schema/query/index.js +30 -27
  124. package/dist/schemas/account_operation.output.json +25 -16
  125. package/dist/schemas/account_operation.schema.json +1 -1
  126. package/dist/schemas/bridge_operation.output.json +520 -0
  127. package/dist/schemas/bridge_operation.schema.json +15 -0
  128. package/dist/schemas/guard2file.schema.json +15 -0
  129. package/dist/schemas/index.json +1 -1
  130. package/dist/schemas/local_info_operation.output.json +23 -0
  131. package/dist/schemas/local_info_operation.schema.json +1 -1
  132. package/dist/schemas/local_mark_operation.output.json +24 -1
  133. package/dist/schemas/local_mark_operation.schema.json +4 -4
  134. package/dist/schemas/machineNode2file.schema.json +15 -0
  135. package/dist/schemas/messenger_operation.output.json +528 -0
  136. package/dist/schemas/onchain_operations.output.json +350 -16
  137. package/dist/schemas/onchain_operations.schema.json +96 -23
  138. package/dist/schemas/onchain_operations_allocation.schema.json +15 -0
  139. package/dist/schemas/onchain_operations_arbitration.schema.json +15 -0
  140. package/dist/schemas/onchain_operations_contact.schema.json +15 -0
  141. package/dist/schemas/onchain_operations_demand.schema.json +15 -0
  142. package/dist/schemas/onchain_operations_gen_passport.schema.json +30 -0
  143. package/dist/schemas/onchain_operations_guard.schema.json +15 -0
  144. package/dist/schemas/onchain_operations_machine.schema.json +81 -23
  145. package/dist/schemas/onchain_operations_order.schema.json +15 -0
  146. package/dist/schemas/onchain_operations_payment.schema.json +15 -0
  147. package/dist/schemas/onchain_operations_permission.schema.json +15 -0
  148. package/dist/schemas/onchain_operations_personal.schema.json +15 -0
  149. package/dist/schemas/onchain_operations_progress.schema.json +15 -0
  150. package/dist/schemas/onchain_operations_repository.schema.json +15 -0
  151. package/dist/schemas/onchain_operations_reward.schema.json +15 -0
  152. package/dist/schemas/onchain_operations_service.schema.json +15 -0
  153. package/dist/schemas/onchain_operations_treasury.schema.json +15 -0
  154. package/dist/schemas/onchain_table_data.output.json +221 -69
  155. package/dist/schemas/onchain_table_data.schema.json +2 -2
  156. package/package.json +2 -2
@@ -0,0 +1,66 @@
1
+ import { CONCEPT_GLOSSARY, CONCEPT_GLOSSARY_VERSION, resolveTerm, lookupEntry, validateText, auditSchemaFields } from "./glossary.js";
2
+ import { CONFIRMATION_RULES, SAFETY_RULES_VERSION } from "./safety-rules.js";
3
+ import { TOOL_CONSTRAINTS, TOOL_CONSTRAINTS_VERSION, validateOperation, hasBlockingViolations, getWarningViolations, } from "./tool-constraints.js";
4
+ import { PERMISSION_TYPES, GAME_ELEMENTS, getPermissionType, getGameElement, getGameElementsByType, PROCESS_MODEL_VERSION, } from "./process-model.js";
5
+ import { computeTrustScore, quickRiskAssessment, ARBITRATION_TRUST_VERSION, } from "./arbitration-trust.js";
6
+ import { REWARD_TEMPLATES, REWARD_TEMPLATES_VERSION, getRewardTemplate, listRewardTemplates, suggestRewardTemplate, } from "./reward-templates.js";
7
+ import { AUDIT_RULES, AUDIT_RULES_VERSION, auditService, hasBlockingErrors, getErrors, getWarnings, summarizeFindings, } from "./audit-rules.js";
8
+ import { matchDemand, extractDemandInfo, DEMAND_MATCHING_VERSION, } from "./demand-matching.js";
9
+ import { suggestPricing, getMutableFields, getMutableField, MUTABLE_FIELDS, DYNAMIC_PRICING_VERSION, } from "./dynamic-pricing.js";
10
+ import { computeServiceTrustScore, quickTrustCheck, TRUST_METRICS_VERSION, } from "./trust-metrics.js";
11
+ import { buildReviewRepositorySetup, computeReviewStats, isVerifiedReview, filterVerifiedReviews, detectReviewManipulation, REPUTATION_RULES_VERSION, } from "./reputation-rules.js";
12
+ import { INDUSTRY_FLYWHEELS, getFlywheelForIndustry, listIndustries, suggestAcquisitionActions, generateTrustDescription, buildAcquisitionDashboard, ACQUISITION_FLYWHEEL_VERSION, } from "./acquisition-flywheel.js";
13
+ import { INDUSTRY_REGISTRY_VERSION, getIndustryProfile, registerIndustry, getIndustryTraits, resolveIndustryName, getRegistrySize, listBuiltinIndustryNames, } from "./industry-registry.js";
14
+ import { DEFAULT_TRAITS, inferTraitsFromDescription, synthesizeProfile, findSimilarIndustries, composeIndustries, } from "./industry-generalizer.js";
15
+ import { INDUSTRY_EVOLUTION_THRESHOLDS, aggregateIndustryMetrics, evaluateIndustryHealth, suggestIndustryUpdate, applyIndustryUpdate, runIndustryHealthPipeline, } from "./industry-evolution.js";
16
+ import { FLYWHEEL_LOOP_VERSION, FLYWHEEL_LOOP_MIN_SIGNALS, EVOLUTION_STATE_VERSION, recordIndustrySignal, updateIndustryCognition, injectEvolutionContext, getIndustryEvolutionStatus, getIndustrySignalCount, getIndustrySignals, listIndustriesWithSignals, getPendingSuggestions, recordDecisionContext, queryDecisionsByIndustry, queryDecisionsByNode, backfillDecisionOutcome, setEvolutionSchedule, getEvolutionSchedule, setIndustryIntent, getIndustryIntent, saveEvolutionState, loadEvolutionState, hasPersistedEvolutionState, } from "./flywheel-loop.js";
17
+ import { BUILTIN_INTENT_SPECS, registerIntentProfile, getIntentProfile, listIntents, evaluateIndustryHealthByIntent, suggestIndustryUpdateByIntent, evaluateIndustryHealthMultiIntent, getRoleAdvice, filterSuggestionsByRole, } from "./intent-metrics.js";
18
+ export { CONCEPT_GLOSSARY, CONCEPT_GLOSSARY_VERSION, resolveTerm, lookupEntry, validateText, auditSchemaFields, };
19
+ export { CONFIRMATION_RULES, SAFETY_RULES_VERSION, };
20
+ export { TOOL_CONSTRAINTS, TOOL_CONSTRAINTS_VERSION, validateOperation, hasBlockingViolations, getWarningViolations, };
21
+ export { PERMISSION_TYPES, GAME_ELEMENTS, getPermissionType, getGameElement, getGameElementsByType, PROCESS_MODEL_VERSION, };
22
+ export { computeTrustScore, quickRiskAssessment, ARBITRATION_TRUST_VERSION, };
23
+ export { REWARD_TEMPLATES, REWARD_TEMPLATES_VERSION, getRewardTemplate, listRewardTemplates, suggestRewardTemplate, };
24
+ export { AUDIT_RULES, AUDIT_RULES_VERSION, auditService, hasBlockingErrors, getErrors, getWarnings, summarizeFindings, };
25
+ export { matchDemand, extractDemandInfo, DEMAND_MATCHING_VERSION, };
26
+ export { suggestPricing, getMutableFields, getMutableField, MUTABLE_FIELDS, DYNAMIC_PRICING_VERSION, };
27
+ export { computeServiceTrustScore, quickTrustCheck, TRUST_METRICS_VERSION, };
28
+ export { buildReviewRepositorySetup, computeReviewStats, isVerifiedReview, filterVerifiedReviews, detectReviewManipulation, REPUTATION_RULES_VERSION, };
29
+ export { INDUSTRY_FLYWHEELS, getFlywheelForIndustry, listIndustries, suggestAcquisitionActions, generateTrustDescription, buildAcquisitionDashboard, ACQUISITION_FLYWHEEL_VERSION, };
30
+ export { INDUSTRY_REGISTRY_VERSION, getIndustryProfile, listIndustries as listRegistryIndustries, registerIndustry, getIndustryTraits, resolveIndustryName, getRegistrySize, listBuiltinIndustryNames, };
31
+ export { DEFAULT_TRAITS, inferTraitsFromDescription, synthesizeProfile, findSimilarIndustries, composeIndustries, };
32
+ export { INDUSTRY_EVOLUTION_THRESHOLDS, aggregateIndustryMetrics, evaluateIndustryHealth, suggestIndustryUpdate, applyIndustryUpdate, runIndustryHealthPipeline, };
33
+ export { FLYWHEEL_LOOP_VERSION, FLYWHEEL_LOOP_MIN_SIGNALS, EVOLUTION_STATE_VERSION, recordIndustrySignal, updateIndustryCognition, injectEvolutionContext, getIndustryEvolutionStatus, getIndustrySignalCount, getIndustrySignals, listIndustriesWithSignals, getPendingSuggestions, recordDecisionContext, queryDecisionsByIndustry, queryDecisionsByNode, backfillDecisionOutcome, setEvolutionSchedule, getEvolutionSchedule, setIndustryIntent, getIndustryIntent, saveEvolutionState, loadEvolutionState, hasPersistedEvolutionState, };
34
+ export { BUILTIN_INTENT_SPECS, registerIntentProfile, getIntentProfile, listIntents, evaluateIndustryHealthByIntent, suggestIndustryUpdateByIntent, evaluateIndustryHealthMultiIntent, getRoleAdvice, filterSuggestionsByRole, };
35
+ export function getKnowledgeBase() {
36
+ return {
37
+ version: {
38
+ glossary: CONCEPT_GLOSSARY_VERSION,
39
+ safety: SAFETY_RULES_VERSION,
40
+ tool_constraints: TOOL_CONSTRAINTS_VERSION,
41
+ process_model: PROCESS_MODEL_VERSION,
42
+ arbitration_trust: ARBITRATION_TRUST_VERSION,
43
+ reward_templates: REWARD_TEMPLATES_VERSION,
44
+ audit_rules: AUDIT_RULES_VERSION,
45
+ demand_matching: DEMAND_MATCHING_VERSION,
46
+ dynamic_pricing: DYNAMIC_PRICING_VERSION,
47
+ trust_metrics: TRUST_METRICS_VERSION,
48
+ reputation_rules: REPUTATION_RULES_VERSION,
49
+ acquisition_flywheel: ACQUISITION_FLYWHEEL_VERSION,
50
+ industry_registry: INDUSTRY_REGISTRY_VERSION,
51
+ flywheel_loop: FLYWHEEL_LOOP_VERSION,
52
+ },
53
+ glossary_entries: CONCEPT_GLOSSARY.length,
54
+ confirmation_rules: CONFIRMATION_RULES.length,
55
+ confirmation_rule_ids: CONFIRMATION_RULES.map((r) => r.id),
56
+ tool_constraints_count: TOOL_CONSTRAINTS.length,
57
+ permission_types_count: PERMISSION_TYPES.length,
58
+ game_elements_count: GAME_ELEMENTS.length,
59
+ reward_templates_count: REWARD_TEMPLATES.length,
60
+ audit_rules_count: AUDIT_RULES.length,
61
+ mutable_fields_count: MUTABLE_FIELDS.length,
62
+ industry_flywheels_count: INDUSTRY_FLYWHEELS.length,
63
+ industry_registry_count: getRegistrySize(),
64
+ intent_count: listIntents().length,
65
+ };
66
+ }
@@ -0,0 +1,82 @@
1
+ import type { IndustryTraits } from "./industry-registry.js";
2
+ export interface IndustryMetrics {
3
+ industry: string;
4
+ sample_size: number;
5
+ time_window_days: number;
6
+ total_orders: number;
7
+ completed_rate: number;
8
+ dispute_rate: number;
9
+ refund_rate: number;
10
+ repeat_buyer_rate: number;
11
+ avg_cycle_hours: number;
12
+ avg_ticket_size: bigint;
13
+ trait_signals: Partial<Record<keyof IndustryTraits, unknown>>;
14
+ emerging_patterns: string[];
15
+ anomalies: string[];
16
+ collected_at: number;
17
+ }
18
+ export interface OrderRawDataPoint {
19
+ industry: string;
20
+ completed: boolean;
21
+ has_dispute: boolean;
22
+ has_refund: boolean;
23
+ cycle_hours?: number;
24
+ ticket_size: bigint;
25
+ buyer_id?: string;
26
+ has_milestone?: boolean;
27
+ has_logistics_signal?: boolean;
28
+ has_deposit_signal?: boolean;
29
+ timestamp: number;
30
+ }
31
+ declare const THRESHOLDS: {
32
+ readonly min_sample_size: 10;
33
+ readonly thriving_completed_rate: 0.9;
34
+ readonly healthy_completed_rate: 0.75;
35
+ readonly stressed_completed_rate: 0.6;
36
+ readonly thriving_dispute_rate: 0.05;
37
+ readonly healthy_dispute_rate: 0.1;
38
+ readonly stressed_dispute_rate: 0.2;
39
+ readonly thriving_repeat_rate: 0.3;
40
+ readonly healthy_repeat_rate: 0.15;
41
+ };
42
+ export declare function aggregateIndustryMetrics(industry: string, rawData: OrderRawDataPoint[], timeWindowDays?: number): IndustryMetrics;
43
+ export interface TraitDrift {
44
+ trait: keyof IndustryTraits;
45
+ template_value: unknown;
46
+ observed_value: unknown;
47
+ drift_severity: "low" | "medium" | "high";
48
+ }
49
+ export interface IndustryHealthReport {
50
+ industry: string;
51
+ health_score: number;
52
+ level: "thriving" | "healthy" | "stressed" | "declining";
53
+ strengths: string[];
54
+ weaknesses: string[];
55
+ recommendations: string[];
56
+ trait_drift?: TraitDrift[];
57
+ }
58
+ export declare function evaluateIndustryHealth(industry: string, metrics: IndustryMetrics): IndustryHealthReport;
59
+ export interface IndustryUpdateSuggestion {
60
+ industry: string;
61
+ suggestion_type: "add_risk_check" | "adjust_preference" | "update_flywheel" | "trait_correction";
62
+ field: string;
63
+ current_value: unknown;
64
+ suggested_value: unknown;
65
+ evidence: string;
66
+ confidence: number;
67
+ priority: "low" | "medium" | "high";
68
+ }
69
+ export declare function suggestIndustryUpdate(industry: string, metrics: IndustryMetrics): IndustryUpdateSuggestion[];
70
+ export declare function applyIndustryUpdate(industry: string, suggestion: IndustryUpdateSuggestion, opts?: {
71
+ force?: boolean;
72
+ }): boolean;
73
+ export declare function runIndustryHealthPipeline(industry: string, rawData: OrderRawDataPoint[], opts?: {
74
+ applySuggestions?: boolean;
75
+ timeWindowDays?: number;
76
+ }): {
77
+ metrics: IndustryMetrics;
78
+ health: IndustryHealthReport;
79
+ suggestions: IndustryUpdateSuggestion[];
80
+ applied: number;
81
+ };
82
+ export { THRESHOLDS as INDUSTRY_EVOLUTION_THRESHOLDS };
@@ -0,0 +1,323 @@
1
+ import { getIndustryProfile, getIndustryTraits, registerIndustry } from "./industry-registry.js";
2
+ const THRESHOLDS = {
3
+ min_sample_size: 10,
4
+ thriving_completed_rate: 0.9,
5
+ healthy_completed_rate: 0.75,
6
+ stressed_completed_rate: 0.6,
7
+ thriving_dispute_rate: 0.05,
8
+ healthy_dispute_rate: 0.1,
9
+ stressed_dispute_rate: 0.2,
10
+ thriving_repeat_rate: 0.3,
11
+ healthy_repeat_rate: 0.15,
12
+ };
13
+ export function aggregateIndustryMetrics(industry, rawData, timeWindowDays = 30) {
14
+ const filtered = rawData.filter((d) => d.industry === industry);
15
+ const sample_size = filtered.length;
16
+ const now = Date.now();
17
+ if (sample_size === 0) {
18
+ return {
19
+ industry,
20
+ sample_size: 0,
21
+ time_window_days: timeWindowDays,
22
+ total_orders: 0,
23
+ completed_rate: 0,
24
+ dispute_rate: 0,
25
+ refund_rate: 0,
26
+ repeat_buyer_rate: 0,
27
+ avg_cycle_hours: 0,
28
+ avg_ticket_size: 0n,
29
+ trait_signals: {},
30
+ emerging_patterns: [],
31
+ anomalies: [],
32
+ collected_at: now,
33
+ };
34
+ }
35
+ const completedCount = filtered.filter((d) => d.completed).length;
36
+ const disputeCount = filtered.filter((d) => d.has_dispute).length;
37
+ const refundCount = filtered.filter((d) => d.has_refund).length;
38
+ const buyerCounts = new Map();
39
+ for (const d of filtered) {
40
+ if (d.buyer_id) {
41
+ buyerCounts.set(d.buyer_id, (buyerCounts.get(d.buyer_id) ?? 0) + 1);
42
+ }
43
+ }
44
+ const uniqueBuyers = buyerCounts.size;
45
+ const repeatBuyers = Array.from(buyerCounts.values()).filter((c) => c >= 2).length;
46
+ const repeatBuyerRate = uniqueBuyers > 0 ? repeatBuyers / uniqueBuyers : 0;
47
+ const cycleSamples = filtered.filter((d) => d.completed && typeof d.cycle_hours === "number");
48
+ const avgCycleHours = cycleSamples.length > 0
49
+ ? cycleSamples.reduce((s, d) => s + (d.cycle_hours ?? 0), 0) / cycleSamples.length
50
+ : 0;
51
+ const totalTicket = filtered.reduce((s, d) => s + d.ticket_size, 0n);
52
+ const avgTicketSize = totalTicket / BigInt(sample_size);
53
+ const traitSignals = {};
54
+ if (sample_size >= 5) {
55
+ const logisticsHit = filtered.filter((d) => d.has_logistics_signal).length / sample_size;
56
+ if (logisticsHit > 0.5)
57
+ traitSignals.has_logistics = true;
58
+ else if (logisticsHit < 0.2)
59
+ traitSignals.has_logistics = false;
60
+ const depositHit = filtered.filter((d) => d.has_deposit_signal).length / sample_size;
61
+ if (depositHit > 0.5)
62
+ traitSignals.deposit_required = true;
63
+ else if (depositHit < 0.2)
64
+ traitSignals.deposit_required = false;
65
+ const milestoneHit = filtered.filter((d) => d.has_milestone).length / sample_size;
66
+ if (milestoneHit > 0.5)
67
+ traitSignals.long_cycle = true;
68
+ }
69
+ const emerging_patterns = [];
70
+ const anomalies = [];
71
+ const disputeRate = disputeCount / sample_size;
72
+ const refundRate = refundCount / sample_size;
73
+ if (sample_size >= 20) {
74
+ if (milestoneRate(filtered) > 0.4) {
75
+ emerging_patterns.push("分阶段交付占比上升(≥40% 订单采用里程碑节点)");
76
+ }
77
+ if (repeatBuyerRate > 0.25) {
78
+ emerging_patterns.push(`复购率上升至 ${Math.round(repeatBuyerRate * 100)}%`);
79
+ }
80
+ if (disputeRate > THRESHOLDS.stressed_dispute_rate) {
81
+ anomalies.push(`争议率突增至 ${Math.round(disputeRate * 100)}%(阈值 ${THRESHOLDS.stressed_dispute_rate * 100}%)`);
82
+ }
83
+ if (refundRate > 0.2) {
84
+ anomalies.push(`退款率突增至 ${Math.round(refundRate * 100)}%`);
85
+ }
86
+ if (avgCycleHours > 24 * 30) {
87
+ anomalies.push(`平均完成周期过长(${Math.round(avgCycleHours / 24)} 天)`);
88
+ }
89
+ }
90
+ return {
91
+ industry,
92
+ sample_size,
93
+ time_window_days: timeWindowDays,
94
+ total_orders: sample_size,
95
+ completed_rate: completedCount / sample_size,
96
+ dispute_rate: disputeRate,
97
+ refund_rate: refundRate,
98
+ repeat_buyer_rate: repeatBuyerRate,
99
+ avg_cycle_hours: avgCycleHours,
100
+ avg_ticket_size: avgTicketSize,
101
+ trait_signals: traitSignals,
102
+ emerging_patterns,
103
+ anomalies,
104
+ collected_at: now,
105
+ };
106
+ }
107
+ function milestoneRate(data) {
108
+ if (data.length === 0)
109
+ return 0;
110
+ return data.filter((d) => d.has_milestone).length / data.length;
111
+ }
112
+ export function evaluateIndustryHealth(industry, metrics) {
113
+ const strengths = [];
114
+ const weaknesses = [];
115
+ const recommendations = [];
116
+ if (metrics.sample_size < THRESHOLDS.min_sample_size) {
117
+ weaknesses.push(`样本量不足(${metrics.sample_size} < ${THRESHOLDS.min_sample_size}),评估置信度低`);
118
+ recommendations.push("继续累积订单数据以提升评估精度");
119
+ }
120
+ const completedScore = metrics.completed_rate * 35;
121
+ if (metrics.completed_rate >= THRESHOLDS.thriving_completed_rate) {
122
+ strengths.push(`完成率高(${Math.round(metrics.completed_rate * 100)}%)`);
123
+ }
124
+ else if (metrics.completed_rate < THRESHOLDS.healthy_completed_rate) {
125
+ weaknesses.push(`完成率偏低(${Math.round(metrics.completed_rate * 100)}%)`);
126
+ recommendations.push("排查未完成订单根因,建议加强 Messenger 沟通与里程碑验收");
127
+ }
128
+ const disputeScore = (1 - Math.min(1, metrics.dispute_rate)) * 25;
129
+ if (metrics.dispute_rate <= THRESHOLDS.thriving_dispute_rate) {
130
+ strengths.push(`争议率低(${Math.round(metrics.dispute_rate * 100)}%)`);
131
+ }
132
+ else if (metrics.dispute_rate > THRESHOLDS.stressed_dispute_rate) {
133
+ weaknesses.push(`争议率高(${Math.round(metrics.dispute_rate * 100)}%)`);
134
+ recommendations.push("争议率超阈值,建议强制配置仲裁 + 赔偿金 + 交付 Guard");
135
+ }
136
+ const refundScore = (1 - Math.min(1, metrics.refund_rate)) * 15;
137
+ if (metrics.refund_rate > 0.2) {
138
+ weaknesses.push(`退款率高(${Math.round(metrics.refund_rate * 100)}%)`);
139
+ recommendations.push("退款率异常,建议检查交付质量或商品描述一致性");
140
+ }
141
+ const repeatScore = Math.min(1, metrics.repeat_buyer_rate) * 15;
142
+ if (metrics.repeat_buyer_rate >= THRESHOLDS.thriving_repeat_rate) {
143
+ strengths.push(`复购率高(${Math.round(metrics.repeat_buyer_rate * 100)}%)`);
144
+ }
145
+ else if (metrics.repeat_buyer_rate < THRESHOLDS.healthy_repeat_rate && metrics.sample_size >= 20) {
146
+ weaknesses.push(`复购率低(${Math.round(metrics.repeat_buyer_rate * 100)}%)`);
147
+ recommendations.push("复购率低,建议设置忠诚度 Reward + 推荐返现裂变");
148
+ }
149
+ const cycleScore = metrics.avg_cycle_hours > 0
150
+ ? Math.max(0, Math.min(10, 10 * (1 - (metrics.avg_cycle_hours / 24 - 7) / 23)))
151
+ : 0;
152
+ if (metrics.avg_cycle_hours > 0 && metrics.avg_cycle_hours <= 24 * 7) {
153
+ strengths.push(`交付周期短(${Math.round(metrics.avg_cycle_hours)} 小时)`);
154
+ }
155
+ else if (metrics.avg_cycle_hours > 24 * 30) {
156
+ weaknesses.push(`交付周期过长(${Math.round(metrics.avg_cycle_hours / 24)} 天)`);
157
+ recommendations.push("交付周期过长,建议优化 Machine 节点拆分");
158
+ }
159
+ const healthScore = Math.round(completedScore + disputeScore + refundScore + repeatScore + cycleScore);
160
+ let level;
161
+ if (healthScore >= 85)
162
+ level = "thriving";
163
+ else if (healthScore >= 65)
164
+ level = "healthy";
165
+ else if (healthScore >= 45)
166
+ level = "stressed";
167
+ else
168
+ level = "declining";
169
+ const traitDrift = detectTraitDrift(industry, metrics);
170
+ return {
171
+ industry,
172
+ health_score: healthScore,
173
+ level,
174
+ strengths,
175
+ weaknesses,
176
+ recommendations,
177
+ trait_drift: traitDrift.length > 0 ? traitDrift : undefined,
178
+ };
179
+ }
180
+ function detectTraitDrift(industry, metrics) {
181
+ const templateTraits = getIndustryTraits(industry);
182
+ if (!templateTraits)
183
+ return [];
184
+ const drifts = [];
185
+ const signals = metrics.trait_signals;
186
+ for (const [k, observed] of Object.entries(signals)) {
187
+ const templateValue = templateTraits[k];
188
+ if (templateValue !== observed) {
189
+ const isBoolean = typeof templateValue === "boolean";
190
+ const severity = isBoolean ? "medium" : "high";
191
+ drifts.push({
192
+ trait: k,
193
+ template_value: templateValue,
194
+ observed_value: observed,
195
+ drift_severity: severity,
196
+ });
197
+ }
198
+ }
199
+ return drifts;
200
+ }
201
+ export function suggestIndustryUpdate(industry, metrics) {
202
+ if (metrics.sample_size < THRESHOLDS.min_sample_size) {
203
+ return [];
204
+ }
205
+ const suggestions = [];
206
+ if (metrics.dispute_rate > THRESHOLDS.healthy_dispute_rate) {
207
+ suggestions.push({
208
+ industry,
209
+ suggestion_type: "add_risk_check",
210
+ field: "risk_checks",
211
+ current_value: "(无对应高争议行业的额外检查)",
212
+ suggested_value: {
213
+ id: `auto_dispute_check_${industry}`,
214
+ description: "争议率高发行业:强制配置仲裁 + 赔偿金",
215
+ weight: 30,
216
+ },
217
+ evidence: `dispute_rate=${(metrics.dispute_rate * 100).toFixed(1)}% 超过阈值 ${THRESHOLDS.healthy_dispute_rate * 100}%`,
218
+ confidence: Math.min(0.95, 0.5 + metrics.dispute_rate),
219
+ priority: metrics.dispute_rate > THRESHOLDS.stressed_dispute_rate ? "high" : "medium",
220
+ });
221
+ }
222
+ if (metrics.completed_rate < THRESHOLDS.healthy_completed_rate && metrics.avg_cycle_hours > 0) {
223
+ const currentCycleDays = Math.ceil(metrics.avg_cycle_hours / 24);
224
+ suggestions.push({
225
+ industry,
226
+ suggestion_type: "adjust_preference",
227
+ field: "preference_template.max_acceptable_cycle",
228
+ current_value: currentCycleDays,
229
+ suggested_value: Math.max(7, Math.floor(currentCycleDays * 0.8)),
230
+ evidence: `completed_rate=${(metrics.completed_rate * 100).toFixed(1)}% < ${THRESHOLDS.healthy_completed_rate * 100}%;avg_cycle=${currentCycleDays}天`,
231
+ confidence: 0.7,
232
+ priority: "medium",
233
+ });
234
+ }
235
+ if (metrics.repeat_buyer_rate >= THRESHOLDS.thriving_repeat_rate) {
236
+ suggestions.push({
237
+ industry,
238
+ suggestion_type: "update_flywheel",
239
+ field: "flywheel.rewardStrategy",
240
+ current_value: "(当前 Reward 策略)",
241
+ suggested_value: "强化忠诚度 Reward + 阶梯复购奖励",
242
+ evidence: `repeat_buyer_rate=${(metrics.repeat_buyer_rate * 100).toFixed(1)}% ≥ ${THRESHOLDS.thriving_repeat_rate * 100}%`,
243
+ confidence: 0.75,
244
+ priority: "low",
245
+ });
246
+ }
247
+ const drifts = detectTraitDrift(industry, metrics);
248
+ for (const d of drifts) {
249
+ suggestions.push({
250
+ industry,
251
+ suggestion_type: "trait_correction",
252
+ field: `traits.${d.trait}`,
253
+ current_value: d.template_value,
254
+ suggested_value: d.observed_value,
255
+ evidence: `模板假设 ${d.trait}=${d.template_value},但实际数据观察为 ${d.observed_value}(drift_severity=${d.drift_severity})`,
256
+ confidence: d.drift_severity === "high" ? 0.8 : 0.65,
257
+ priority: d.drift_severity === "high" ? "high" : "medium",
258
+ });
259
+ }
260
+ return suggestions;
261
+ }
262
+ export function applyIndustryUpdate(industry, suggestion, opts) {
263
+ if (!opts?.force) {
264
+ if (suggestion.confidence < 0.7)
265
+ return false;
266
+ if (suggestion.priority === "low")
267
+ return false;
268
+ }
269
+ const profile = getIndustryProfile(industry);
270
+ if (!profile)
271
+ return false;
272
+ const updated = JSON.parse(JSON.stringify(profile));
273
+ switch (suggestion.suggestion_type) {
274
+ case "trait_correction": {
275
+ const traitKey = suggestion.field.replace("traits.", "");
276
+ updated.traits[traitKey] = suggestion.suggested_value;
277
+ break;
278
+ }
279
+ case "adjust_preference": {
280
+ if (suggestion.field === "preference_template.max_acceptable_cycle") {
281
+ updated.preference_template.max_acceptable_cycle = suggestion.suggested_value;
282
+ }
283
+ break;
284
+ }
285
+ case "add_risk_check": {
286
+ const newCheck = suggestion.suggested_value;
287
+ if (!updated.risk_checks.find((c) => c.id === newCheck.id)) {
288
+ updated.risk_checks.push(newCheck);
289
+ }
290
+ break;
291
+ }
292
+ case "update_flywheel": {
293
+ if (suggestion.field === "flywheel.rewardStrategy") {
294
+ updated.flywheel.rewardStrategy = suggestion.suggested_value;
295
+ }
296
+ break;
297
+ }
298
+ }
299
+ const currentVersion = parseInt(updated.version.replace(/^v/, ""), 10) || 1;
300
+ updated.version = `v${currentVersion + 1}`;
301
+ updated.evolution = {
302
+ version: updated.evolution ? updated.evolution.version + 1 : 1,
303
+ last_updated: Date.now(),
304
+ signal_count: updated.evolution?.signal_count ?? 0,
305
+ pending_suggestions: Math.max(0, (updated.evolution?.pending_suggestions ?? 0) - 1),
306
+ last_health_score: updated.evolution?.last_health_score,
307
+ };
308
+ return registerIndustry(updated);
309
+ }
310
+ export function runIndustryHealthPipeline(industry, rawData, opts) {
311
+ const metrics = aggregateIndustryMetrics(industry, rawData, opts?.timeWindowDays ?? 30);
312
+ const health = evaluateIndustryHealth(industry, metrics);
313
+ const suggestions = suggestIndustryUpdate(industry, metrics);
314
+ let applied = 0;
315
+ if (opts?.applySuggestions) {
316
+ for (const s of suggestions) {
317
+ if (applyIndustryUpdate(industry, s))
318
+ applied++;
319
+ }
320
+ }
321
+ return { metrics, health, suggestions, applied };
322
+ }
323
+ export { THRESHOLDS as INDUSTRY_EVOLUTION_THRESHOLDS };
@@ -0,0 +1,17 @@
1
+ import { type IndustryTraits, type IndustryProfile } from "./industry-registry.js";
2
+ export declare const DEFAULT_TRAITS: IndustryTraits;
3
+ export interface TraitInferenceResult {
4
+ traits: IndustryTraits;
5
+ confidence: number;
6
+ matched_keywords: string[];
7
+ trait_confidence: Partial<Record<keyof IndustryTraits, number>>;
8
+ }
9
+ export declare function inferTraitsFromDescription(description: string): TraitInferenceResult;
10
+ export interface SimilarIndustryMatch {
11
+ industry: string;
12
+ similarity: number;
13
+ matched_traits: string[];
14
+ }
15
+ export declare function findSimilarIndustries(traits: IndustryTraits, limit?: number): SimilarIndustryMatch[];
16
+ export declare function synthesizeProfile(traits: IndustryTraits, name?: string): IndustryProfile;
17
+ export declare function composeIndustries(names: string[], newName?: string): IndustryProfile | undefined;