@sovr/engine 3.3.0 → 3.4.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/index.d.ts CHANGED
@@ -349,6 +349,856 @@ declare class PricingRulesEngine {
349
349
  private globMatch;
350
350
  }
351
351
 
352
+ /**
353
+ * @sovr/engine — Recalculation Engine (Pure Memory Mode)
354
+ *
355
+ * Aggregation layer recalculation capabilities:
356
+ * - G3: Recalculation triggers (manual/automatic)
357
+ * - G4: Consistency verification (compare pre/post values)
358
+ * - G5: Incremental recalculation (from checkpoint)
359
+ * - G6: Recalculation audit (via onAudit callback)
360
+ *
361
+ * Zero external dependencies. Audit via callback injection.
362
+ */
363
+ type RecalcTaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
364
+ type RecalcTriggerType = 'manual' | 'scheduled' | 'drift_detected' | 'data_correction' | 'policy_change';
365
+ type RecalcGranularity = '5m' | '1h' | '1d' | 'all';
366
+ interface RecalcTask {
367
+ id: string;
368
+ tenantId: string;
369
+ triggerType: RecalcTriggerType;
370
+ triggeredBy: string;
371
+ reason: string;
372
+ fromTs: number;
373
+ toTs: number;
374
+ granularity: RecalcGranularity;
375
+ incremental: boolean;
376
+ incrementalCheckpoint?: string;
377
+ status: RecalcTaskStatus;
378
+ startedAt?: number;
379
+ completedAt?: number;
380
+ progress: number;
381
+ bucketsProcessed: number;
382
+ rowsUpserted: number;
383
+ consistencyResult?: ConsistencyResult;
384
+ error?: string;
385
+ createdAt: number;
386
+ traceId: string;
387
+ }
388
+ interface ConsistencyResult {
389
+ id: string;
390
+ taskId: string;
391
+ status: 'consistent' | 'inconsistent' | 'partial';
392
+ totalComparisons: number;
393
+ matchCount: number;
394
+ mismatchCount: number;
395
+ consistencyRate: number;
396
+ mismatches: ConsistencyMismatch[];
397
+ verifiedAt: number;
398
+ verificationHash: string;
399
+ }
400
+ interface ConsistencyMismatch {
401
+ metric: string;
402
+ bucket: string;
403
+ currentValue: number;
404
+ recalculatedValue: number;
405
+ deviation: number;
406
+ deviationPercent: number;
407
+ severity: 'low' | 'medium' | 'high' | 'critical';
408
+ }
409
+ interface AggregateSnapshot {
410
+ id: string;
411
+ tenantId: string;
412
+ snapshotType: 'pre_recalc' | 'post_recalc' | 'scheduled';
413
+ taskId?: string;
414
+ metrics: Record<string, number>;
415
+ hash: string;
416
+ createdAt: number;
417
+ }
418
+ type RecalcHandler = (task: RecalcTask) => Promise<{
419
+ bucketsProcessed: number;
420
+ rowsUpserted: number;
421
+ metrics: Record<string, number>;
422
+ }>;
423
+ interface RecalcEngineConfig {
424
+ maxRangeDays: number;
425
+ onAudit?: (event: {
426
+ type: string;
427
+ details: Record<string, unknown>;
428
+ timestamp: number;
429
+ }) => void;
430
+ }
431
+ declare class RecalculationEngine {
432
+ private tasks;
433
+ private consistencyResults;
434
+ private snapshots;
435
+ private handlers;
436
+ private config;
437
+ constructor(config?: Partial<RecalcEngineConfig>);
438
+ /** G3: Trigger recalculation */
439
+ triggerRecalculation(input: {
440
+ tenantId: string;
441
+ triggerType: RecalcTriggerType;
442
+ triggeredBy: string;
443
+ reason: string;
444
+ fromTs: number;
445
+ toTs: number;
446
+ granularity?: RecalcGranularity;
447
+ incremental?: boolean;
448
+ incrementalCheckpoint?: string;
449
+ }): RecalcTask;
450
+ /** Execute recalculation task */
451
+ executeTask(taskId: string): Promise<RecalcTask>;
452
+ /** G4: Verify consistency */
453
+ verifyConsistency(taskId: string, preSnapshot: AggregateSnapshot, postSnapshot: AggregateSnapshot, recalculatedMetrics?: Record<string, number>): ConsistencyResult;
454
+ /** G5: Incremental recalculation */
455
+ triggerIncremental(input: {
456
+ tenantId: string;
457
+ triggeredBy: string;
458
+ reason: string;
459
+ granularity?: RecalcGranularity;
460
+ }): RecalcTask;
461
+ /** Create aggregate snapshot */
462
+ createSnapshot(tenantId: string, snapshotType: AggregateSnapshot['snapshotType'], taskId?: string, metrics?: Record<string, number>): AggregateSnapshot;
463
+ /** Register recalculation handler */
464
+ registerHandler(granularity: RecalcGranularity, handler: RecalcHandler): void;
465
+ /** Query functions */
466
+ getTask(taskId: string): RecalcTask | undefined;
467
+ getTasks(tenantId: string, limit?: number): RecalcTask[];
468
+ getConsistencyResult(taskId: string): ConsistencyResult | undefined;
469
+ getSnapshot(snapshotId: string): AggregateSnapshot | undefined;
470
+ cancelTask(taskId: string): boolean;
471
+ private audit;
472
+ }
473
+ declare function createRecalculationEngine(config?: Partial<RecalcEngineConfig>): RecalculationEngine;
474
+
475
+ /**
476
+ * @sovr/engine — AutoHarden Module (Pure Memory Mode)
477
+ *
478
+ * Automatic security hardening when adversarial threats detected:
479
+ * - B7: Auto-harden capability
480
+ * - Gate level upgrade, rate limit reduction, enhanced audit
481
+ * - Configurable measures with auto-rollback
482
+ *
483
+ * Zero external dependencies. Audit via callback injection.
484
+ */
485
+ type HardenLevel = 'normal' | 'elevated' | 'hardened' | 'lockdown';
486
+ type HardenMeasureType = 'gate_level_upgrade' | 'rate_limit_reduce' | 'enhanced_audit' | 'ip_block' | 'session_invalidate' | 'feature_disable' | 'alert_admin';
487
+ interface HardenMeasure {
488
+ id: string;
489
+ type: HardenMeasureType;
490
+ description: string;
491
+ applied: boolean;
492
+ appliedAt?: number;
493
+ rolledBackAt?: number;
494
+ }
495
+ interface HardenEvent {
496
+ id: string;
497
+ tenantId: string;
498
+ triggeredBy: string;
499
+ reason: string;
500
+ previousLevel: HardenLevel;
501
+ newLevel: HardenLevel;
502
+ measures: HardenMeasure[];
503
+ createdAt: number;
504
+ rolledBack: boolean;
505
+ rolledBackAt?: number;
506
+ traceId: string;
507
+ }
508
+ interface HardenConfig {
509
+ enabled: boolean;
510
+ levelMeasures: Record<HardenLevel, HardenMeasureType[]>;
511
+ autoRollbackMs: number;
512
+ rateLimitReductionFactor: number;
513
+ notifyAdmin: boolean;
514
+ onNotifyAdmin?: (event: HardenEvent) => Promise<void>;
515
+ onAudit?: (event: {
516
+ type: string;
517
+ details: Record<string, unknown>;
518
+ timestamp: number;
519
+ }) => void;
520
+ }
521
+ interface HardenState {
522
+ currentLevel: HardenLevel;
523
+ lastEvent?: HardenEvent;
524
+ activeMeasures: HardenMeasure[];
525
+ hardenedSince?: number;
526
+ expectedRollbackAt?: number;
527
+ }
528
+ declare class AutoHardenEngine {
529
+ private states;
530
+ private history;
531
+ private config;
532
+ private rollbackTimers;
533
+ private maxHistory;
534
+ constructor(config?: Partial<HardenConfig>);
535
+ /** Get tenant harden state */
536
+ getState(tenantId: string): HardenState;
537
+ /** Get current harden level */
538
+ getLevel(tenantId: string): HardenLevel;
539
+ /** Auto-harden (main entry) */
540
+ harden(input: {
541
+ tenantId: string;
542
+ triggeredBy: string;
543
+ reason: string;
544
+ targetLevel?: HardenLevel;
545
+ manipulationScore?: number;
546
+ reasonCodes?: string[];
547
+ }): Promise<HardenEvent>;
548
+ /** Manual rollback */
549
+ rollback(tenantId: string, rolledBackBy: string, reason?: string): Promise<HardenEvent>;
550
+ /** Update config */
551
+ updateConfig(config: Partial<HardenConfig>): HardenConfig;
552
+ /** Get config */
553
+ getConfig(): HardenConfig;
554
+ /** Get history */
555
+ getHistory(tenantId?: string, limit?: number): HardenEvent[];
556
+ /** Get all active hardened states */
557
+ getActiveStates(): Array<{
558
+ tenantId: string;
559
+ state: HardenState;
560
+ }>;
561
+ /** Cleanup timers */
562
+ destroy(): void;
563
+ private determineLevel;
564
+ private applyMeasures;
565
+ private getMeasureDescription;
566
+ private scheduleAutoRollback;
567
+ private audit;
568
+ }
569
+ declare function createAutoHardenEngine(config?: Partial<HardenConfig>): AutoHardenEngine;
570
+
571
+ /**
572
+ * SOVR Cost Estimator
573
+ * 成本预估精确化引擎 — 补齐 F3 缺口
574
+ *
575
+ * 功能:
576
+ * 1. Token 级成本预估(基于模型定价表)
577
+ * 2. 工具调用成本预估
578
+ * 3. 人工审批成本预估(基于费率)
579
+ * 4. 总成本预估(模型 + 工具 + 人工)
580
+ * 5. 预估准确度追踪
581
+ *
582
+ * 设计原则:
583
+ * - 模型定价表可配置、可更新
584
+ * - 支持多种计费模式(按 token、按调用、按时间)
585
+ * - 预估结果包含置信区间
586
+ * - 与 CostGate 协作
587
+ */
588
+ /** 模型定价 */
589
+ interface ModelPricing {
590
+ /** 模型 ID */
591
+ modelId: string;
592
+ /** 模型名称 */
593
+ modelName: string;
594
+ /** 输入 token 单价(美元/1K tokens) */
595
+ inputPricePerKToken: number;
596
+ /** 输出 token 单价(美元/1K tokens) */
597
+ outputPricePerKToken: number;
598
+ /** 缓存 token 单价(如有) */
599
+ cachedInputPricePerKToken?: number;
600
+ /** 最大上下文长度 */
601
+ maxContextLength: number;
602
+ /** 最后更新 */
603
+ updatedAt: Date;
604
+ }
605
+ /** 工具定价 */
606
+ interface ToolPricing {
607
+ /** 工具 ID */
608
+ toolId: string;
609
+ /** 工具名称 */
610
+ toolName: string;
611
+ /** 每次调用成本(美元) */
612
+ costPerCall: number;
613
+ /** 乘算因子(如有额外成本) */
614
+ multiplier: number;
615
+ /** 最后更新 */
616
+ updatedAt: Date;
617
+ }
618
+ /** 成本预估请求 */
619
+ interface CostEstimateRequest {
620
+ /** 模型 ID */
621
+ modelId: string;
622
+ /** 预估输入 token 数 */
623
+ estimatedInputTokens: number;
624
+ /** 预估输出 token 数 */
625
+ estimatedOutputTokens: number;
626
+ /** 工具调用列表 */
627
+ toolCalls?: Array<{
628
+ toolId: string;
629
+ estimatedCalls: number;
630
+ }>;
631
+ /** 是否需要人工审批 */
632
+ requiresHumanReview?: boolean;
633
+ /** 人工审批级别 */
634
+ humanReviewLevel?: 'standard' | 'senior' | 'executive';
635
+ }
636
+ /** 成本预估结果 */
637
+ interface CostEstimate {
638
+ /** 预估 ID */
639
+ id: string;
640
+ /** 模型成本 */
641
+ modelCost: {
642
+ inputCost: number;
643
+ outputCost: number;
644
+ total: number;
645
+ };
646
+ /** 工具成本 */
647
+ toolCost: {
648
+ items: Array<{
649
+ toolId: string;
650
+ calls: number;
651
+ costPerCall: number;
652
+ total: number;
653
+ }>;
654
+ total: number;
655
+ };
656
+ /** 人工审批成本 */
657
+ humanCost: {
658
+ level: string;
659
+ hourlyRate: number;
660
+ estimatedMinutes: number;
661
+ total: number;
662
+ } | null;
663
+ /** 总成本 */
664
+ totalCost: number;
665
+ /** 置信区间 */
666
+ confidence: {
667
+ low: number;
668
+ high: number;
669
+ level: number;
670
+ };
671
+ /** 预估时间 */
672
+ estimatedAt: Date;
673
+ }
674
+ /** 预估准确度记录 */
675
+ interface EstimateAccuracy {
676
+ estimateId: string;
677
+ estimatedCost: number;
678
+ actualCost: number;
679
+ deviation: number;
680
+ deviationPercent: number;
681
+ recordedAt: Date;
682
+ }
683
+ /**
684
+ * 预估成本
685
+ */
686
+ declare function estimateCost(request: CostEstimateRequest): CostEstimate;
687
+ /**
688
+ * 记录实际成本(用于准确度追踪)
689
+ */
690
+ declare function recordActualCost(estimateId: string, actualCost: number): EstimateAccuracy | null;
691
+ /**
692
+ * 更新模型定价
693
+ */
694
+ declare function updateModelPricing(pricing: ModelPricing): void;
695
+ /**
696
+ * 更新工具定价
697
+ */
698
+ declare function updateToolPricing(pricing: ToolPricing): void;
699
+ /**
700
+ * 获取模型定价表
701
+ */
702
+ declare function getModelPricingTable(): ModelPricing[];
703
+ /**
704
+ * 获取工具定价表
705
+ */
706
+ declare function getToolPricingTable(): ToolPricing[];
707
+ /**
708
+ * 获取预估准确度统计
709
+ */
710
+ declare function getAccuracyStats(): {
711
+ totalRecords: number;
712
+ avgDeviation: number;
713
+ avgDeviationPercent: number;
714
+ confidenceLevel: number;
715
+ };
716
+
717
+ /**
718
+ * server/sovr/semanticDriftDetector.ts
719
+ *
720
+ * 语义漂移检测器 — 补齐 K10 缺口
721
+ *
722
+ * 功能:
723
+ * - 策略语义指纹计算(基于规则结构的哈希)
724
+ * - 版本间语义差异检测
725
+ * - 漂移评分(0-1,0=完全一致,1=完全不同)
726
+ * - 漂移告警(超过阈值时触发)
727
+ * - 漂移审计链
728
+ *
729
+ * 设计原则:纯逻辑模块,无外部依赖
730
+ */
731
+ interface SemanticFingerprint {
732
+ version: string;
733
+ hash: string;
734
+ ruleCount: number;
735
+ allowCount: number;
736
+ denyCount: number;
737
+ reviewCount: number;
738
+ resourceSet: string[];
739
+ actionSet: string[];
740
+ conditionDepth: number;
741
+ timestamp: number;
742
+ }
743
+ interface DriftResult {
744
+ fromVersion: string;
745
+ toVersion: string;
746
+ driftScore: number;
747
+ ruleCountDelta: number;
748
+ addedRules: string[];
749
+ removedRules: string[];
750
+ modifiedRules: string[];
751
+ decisionChanges: {
752
+ ruleId: string;
753
+ from: string;
754
+ to: string;
755
+ }[];
756
+ newResources: string[];
757
+ removedResources: string[];
758
+ severity: 'none' | 'low' | 'medium' | 'high' | 'critical';
759
+ timestamp: number;
760
+ }
761
+ interface PolicySnapshot {
762
+ version: string;
763
+ rules: PolicyRuleForDrift[];
764
+ metadata?: Record<string, unknown>;
765
+ }
766
+ interface PolicyRuleForDrift {
767
+ id: string;
768
+ action: string;
769
+ resource: string;
770
+ decision: 'ALLOW' | 'DENY' | 'REVIEW';
771
+ conditions?: Record<string, unknown>;
772
+ priority: number;
773
+ }
774
+ interface DriftConfig {
775
+ lowThreshold: number;
776
+ mediumThreshold: number;
777
+ highThreshold: number;
778
+ criticalThreshold: number;
779
+ onDriftDetected?: (result: DriftResult) => void;
780
+ onAudit?: (event: {
781
+ type: string;
782
+ details: Record<string, unknown>;
783
+ timestamp: number;
784
+ }) => void;
785
+ }
786
+ declare class SemanticDriftDetectorEngine {
787
+ private fingerprints;
788
+ private history;
789
+ private config;
790
+ constructor(config?: Partial<DriftConfig>);
791
+ /**
792
+ * 计算策略语义指纹
793
+ */
794
+ computeFingerprint(snapshot: PolicySnapshot): SemanticFingerprint;
795
+ /**
796
+ * 检测两个版本间的语义漂移
797
+ */
798
+ detectDrift(from: PolicySnapshot, to: PolicySnapshot): DriftResult;
799
+ /**
800
+ * 获取漂移历史
801
+ */
802
+ getDriftHistory(): DriftResult[];
803
+ /**
804
+ * 获取指纹
805
+ */
806
+ getFingerprint(version: string): SemanticFingerprint | null;
807
+ /**
808
+ * 获取漂移趋势
809
+ */
810
+ getDriftTrend(): {
811
+ version: string;
812
+ driftScore: number;
813
+ timestamp: number;
814
+ }[];
815
+ private hashRules;
816
+ private ruleChanged;
817
+ private maxConditionDepth;
818
+ private objectDepth;
819
+ }
820
+ declare function createSemanticDriftDetector(config?: Partial<DriftConfig>): SemanticDriftDetectorEngine;
821
+
822
+ /**
823
+ * server/sovr/costGateEnhanced.ts
824
+ *
825
+ * 经济约束层增强 — 补齐 E2/E4/E5/E6/E7/E9/E10 缺口
826
+ *
827
+ * 功能:
828
+ * - E2: 成本汇总表(1h/24h/7d 滑动窗口)
829
+ * - E4: BUDGET_EXCEEDED 标准原因码
830
+ * - E5: 成本超限审计事件
831
+ * - E6: Cockpit 成本仪表板数据源
832
+ * - E7: getDailyCostStats API
833
+ * - E9: 工具调用成本代理(按工具计费)
834
+ * - E10: 人工审批时成本计算
835
+ *
836
+ * 设计原则:纯逻辑模块,审计通过回调注入
837
+ */
838
+ interface CostRecord {
839
+ id: string;
840
+ tenantId: string;
841
+ agentId: string;
842
+ action: string;
843
+ toolName?: string;
844
+ costUsd: number;
845
+ tokenCount?: number;
846
+ modelName?: string;
847
+ timestamp: number;
848
+ category: CostCategory;
849
+ metadata?: Record<string, unknown>;
850
+ }
851
+ type CostCategory = 'llm_inference' | 'tool_call' | 'human_review' | 'storage' | 'network' | 'compute' | 'other';
852
+ interface CostSummary {
853
+ period: '1h' | '24h' | '7d' | '30d';
854
+ totalCostUsd: number;
855
+ byCategory: Record<CostCategory, number>;
856
+ byAgent: Record<string, number>;
857
+ byTool: Record<string, number>;
858
+ recordCount: number;
859
+ avgCostPerAction: number;
860
+ peakHour?: number;
861
+ startTime: number;
862
+ endTime: number;
863
+ }
864
+ interface DailyCostStats {
865
+ date: string;
866
+ totalCostUsd: number;
867
+ byCategory: Record<CostCategory, number>;
868
+ actionCount: number;
869
+ uniqueAgents: number;
870
+ budgetUtilization: number;
871
+ }
872
+ interface BudgetExceededEvent {
873
+ code: 'BUDGET_EXCEEDED';
874
+ tenantId: string;
875
+ agentId: string;
876
+ action: string;
877
+ currentCostUsd: number;
878
+ budgetLimitUsd: number;
879
+ overage: number;
880
+ period: string;
881
+ timestamp: number;
882
+ severity: 'warning' | 'critical' | 'blocked';
883
+ }
884
+ interface ToolCostConfig {
885
+ toolName: string;
886
+ baseCostUsd: number;
887
+ perCallCostUsd: number;
888
+ perTokenCostUsd?: number;
889
+ maxCostPerCallUsd?: number;
890
+ }
891
+ interface HumanReviewCost {
892
+ reviewId: string;
893
+ reviewerType: 'human' | 'escalated';
894
+ waitTimeMs: number;
895
+ reviewTimeMs: number;
896
+ costUsd: number;
897
+ hourlyRateUsd: number;
898
+ }
899
+ interface CostGateEnhancedConfig {
900
+ defaultBudgetUsd: number;
901
+ warningThreshold: number;
902
+ criticalThreshold: number;
903
+ humanReviewHourlyRateUsd: number;
904
+ toolCosts: ToolCostConfig[];
905
+ onAudit?: (event: CostAuditEvent) => void;
906
+ onBudgetExceeded?: (event: BudgetExceededEvent) => void;
907
+ }
908
+ interface CostAuditEvent {
909
+ type: 'cost_recorded' | 'budget_warning' | 'budget_critical' | 'budget_exceeded' | 'summary_generated';
910
+ tenantId: string;
911
+ details: Record<string, unknown>;
912
+ timestamp: number;
913
+ }
914
+ declare class CostGateEnhancedEngine {
915
+ private records;
916
+ private budgets;
917
+ private config;
918
+ private toolCostMap;
919
+ constructor(config?: Partial<CostGateEnhancedConfig>);
920
+ /**
921
+ * E2: 记录成本并生成汇总
922
+ */
923
+ recordCost(record: CostRecord): BudgetExceededEvent | null;
924
+ /**
925
+ * E2: 获取成本汇总(滑动窗口)
926
+ */
927
+ getCostSummary(tenantId: string, period: CostSummary['period']): CostSummary;
928
+ /**
929
+ * E7: getDailyCostStats — 按天统计
930
+ */
931
+ getDailyCostStats(tenantId: string, days?: number): DailyCostStats[];
932
+ /**
933
+ * E9: 计算工具调用成本
934
+ */
935
+ calculateToolCost(toolName: string, tokenCount?: number): number;
936
+ /**
937
+ * E10: 计算人工审批成本
938
+ */
939
+ calculateHumanReviewCost(waitTimeMs: number, reviewTimeMs: number): HumanReviewCost;
940
+ /**
941
+ * 设置租户预算
942
+ */
943
+ setBudget(tenantId: string, budgetUsd: number): void;
944
+ /**
945
+ * 获取租户预算使用率
946
+ */
947
+ getBudgetUtilization(tenantId: string): {
948
+ used: number;
949
+ limit: number;
950
+ utilization: number;
951
+ };
952
+ private checkBudget;
953
+ private audit;
954
+ }
955
+ declare function createCostGateEnhanced(config?: Partial<CostGateEnhancedConfig>): CostGateEnhancedEngine;
956
+
957
+ /**
958
+ * server/sovr/budgetMultiLevel.ts
959
+ *
960
+ * 多层预算引擎 — 补齐 F6/F7/F8 缺口
961
+ *
962
+ * 功能:
963
+ * - F6: 多层预算(组织 → 团队 → 项目 → Agent 四级)
964
+ * - F7: 预算告警(阈值触发 + 趋势预测)
965
+ * - F8: 成本报告(多维度分析 + 导出)
966
+ *
967
+ * 设计原则:纯逻辑模块,告警通过回调注入
968
+ */
969
+ type BudgetLevel = 'organization' | 'team' | 'project' | 'agent';
970
+ interface BudgetNode {
971
+ id: string;
972
+ name: string;
973
+ level: BudgetLevel;
974
+ parentId: string | null;
975
+ budgetUsd: number;
976
+ spentUsd: number;
977
+ children: string[];
978
+ alertRules: AlertRule[];
979
+ metadata?: Record<string, unknown>;
980
+ }
981
+ interface AlertRule {
982
+ id: string;
983
+ threshold: number;
984
+ severity: 'info' | 'warning' | 'critical';
985
+ action: 'notify' | 'throttle' | 'block';
986
+ cooldownMs: number;
987
+ lastTriggeredAt?: number;
988
+ }
989
+ interface BudgetAlert {
990
+ ruleId: string;
991
+ nodeId: string;
992
+ nodeName: string;
993
+ level: BudgetLevel;
994
+ severity: AlertRule['severity'];
995
+ action: AlertRule['action'];
996
+ utilization: number;
997
+ budgetUsd: number;
998
+ spentUsd: number;
999
+ remainingUsd: number;
1000
+ predictedExhaustionDate?: string;
1001
+ timestamp: number;
1002
+ }
1003
+ interface CostReport {
1004
+ reportId: string;
1005
+ generatedAt: number;
1006
+ period: {
1007
+ start: number;
1008
+ end: number;
1009
+ };
1010
+ totalBudgetUsd: number;
1011
+ totalSpentUsd: number;
1012
+ utilization: number;
1013
+ byLevel: Record<BudgetLevel, {
1014
+ budget: number;
1015
+ spent: number;
1016
+ count: number;
1017
+ }>;
1018
+ topSpenders: {
1019
+ id: string;
1020
+ name: string;
1021
+ level: BudgetLevel;
1022
+ spent: number;
1023
+ }[];
1024
+ alerts: BudgetAlert[];
1025
+ trend: {
1026
+ date: string;
1027
+ spent: number;
1028
+ }[];
1029
+ }
1030
+ interface MultiLevelBudgetConfig {
1031
+ defaultAlertRules: AlertRule[];
1032
+ trendWindowDays: number;
1033
+ onAlert?: (alert: BudgetAlert) => void;
1034
+ onAudit?: (event: {
1035
+ type: string;
1036
+ details: Record<string, unknown>;
1037
+ timestamp: number;
1038
+ }) => void;
1039
+ }
1040
+ declare class MultiLevelBudgetEngine {
1041
+ private nodes;
1042
+ private spendHistory;
1043
+ private config;
1044
+ constructor(config?: Partial<MultiLevelBudgetConfig>);
1045
+ /**
1046
+ * F6: 创建预算节点
1047
+ */
1048
+ createNode(node: Omit<BudgetNode, 'spentUsd' | 'children' | 'alertRules'> & {
1049
+ alertRules?: AlertRule[];
1050
+ }): BudgetNode;
1051
+ /**
1052
+ * F6: 记录支出(向上冒泡到所有父级)
1053
+ */
1054
+ recordSpend(nodeId: string, amount: number): BudgetAlert[];
1055
+ /**
1056
+ * F6: 获取节点预算状态(含子节点汇总)
1057
+ */
1058
+ getNodeStatus(nodeId: string): {
1059
+ node: BudgetNode;
1060
+ utilization: number;
1061
+ childrenSpent: number;
1062
+ remaining: number;
1063
+ } | null;
1064
+ /**
1065
+ * F7: 预测预算耗尽日期
1066
+ */
1067
+ predictExhaustion(nodeId: string): string | null;
1068
+ /**
1069
+ * F8: 生成成本报告
1070
+ */
1071
+ generateReport(rootNodeId?: string): CostReport;
1072
+ /**
1073
+ * 获取所有节点
1074
+ */
1075
+ listNodes(level?: BudgetLevel): BudgetNode[];
1076
+ private checkAlerts;
1077
+ private getChildrenSpent;
1078
+ private getSubtree;
1079
+ private generateTrend;
1080
+ }
1081
+ declare function createMultiLevelBudget(config?: Partial<MultiLevelBudgetConfig>): MultiLevelBudgetEngine;
1082
+
1083
+ /**
1084
+ * server/sovr/evolutionChannel.ts
1085
+ *
1086
+ * 受控演化通道 — 补齐 B8 缺口
1087
+ *
1088
+ * 功能:
1089
+ * - 策略版本管理(版本化策略发布)
1090
+ * - 灰度发布(canary release for policies)
1091
+ * - A/B 测试策略(双策略并行评估)
1092
+ * - 回滚机制(一键回退到上一版本)
1093
+ * - 演化审计(所有策略变更记录)
1094
+ *
1095
+ * 设计原则:纯逻辑模块,无数据库依赖
1096
+ */
1097
+ interface PolicyVersion {
1098
+ id: string;
1099
+ version: string;
1100
+ name: string;
1101
+ rules: PolicyRule$1[];
1102
+ createdAt: number;
1103
+ createdBy: string;
1104
+ status: 'draft' | 'canary' | 'active' | 'deprecated' | 'rollback';
1105
+ canaryPercent: number;
1106
+ metadata?: Record<string, unknown>;
1107
+ }
1108
+ interface PolicyRule$1 {
1109
+ id: string;
1110
+ action: string;
1111
+ resource: string;
1112
+ decision: 'ALLOW' | 'DENY' | 'REVIEW';
1113
+ conditions?: Record<string, unknown>;
1114
+ priority: number;
1115
+ }
1116
+ interface EvolutionEvent {
1117
+ type: 'publish' | 'canary_start' | 'canary_promote' | 'canary_rollback' | 'deprecate' | 'ab_test_start' | 'ab_test_end';
1118
+ policyId: string;
1119
+ version: string;
1120
+ timestamp: number;
1121
+ actor: string;
1122
+ details?: Record<string, unknown>;
1123
+ }
1124
+ interface ABTestConfig {
1125
+ id: string;
1126
+ controlVersionId: string;
1127
+ treatmentVersionId: string;
1128
+ trafficSplit: number;
1129
+ startedAt: number;
1130
+ metrics: ABTestMetrics;
1131
+ status: 'running' | 'completed' | 'aborted';
1132
+ }
1133
+ interface ABTestMetrics {
1134
+ controlDecisions: number;
1135
+ treatmentDecisions: number;
1136
+ controlAllowRate: number;
1137
+ treatmentAllowRate: number;
1138
+ controlAvgLatencyMs: number;
1139
+ treatmentAvgLatencyMs: number;
1140
+ }
1141
+ interface EvolutionConfig {
1142
+ maxVersions: number;
1143
+ canaryMinDurationMs: number;
1144
+ autoPromoteThreshold: number;
1145
+ onAudit?: (event: EvolutionEvent) => void;
1146
+ }
1147
+ declare class EvolutionChannelEngine {
1148
+ private versions;
1149
+ private activeVersionId;
1150
+ private canaryVersionId;
1151
+ private abTests;
1152
+ private config;
1153
+ constructor(config?: Partial<EvolutionConfig>);
1154
+ /**
1155
+ * 发布新策略版本
1156
+ */
1157
+ publish(version: PolicyVersion): PolicyVersion;
1158
+ /**
1159
+ * 启动灰度发布
1160
+ */
1161
+ startCanary(versionId: string, percent: number, actor: string): boolean;
1162
+ /**
1163
+ * 灰度晋升为正式版本
1164
+ */
1165
+ promoteCanary(actor: string): boolean;
1166
+ /**
1167
+ * 灰度回滚
1168
+ */
1169
+ rollbackCanary(actor: string): boolean;
1170
+ /**
1171
+ * 路由决策:根据灰度百分比选择策略版本
1172
+ */
1173
+ resolveVersion(requestHash?: number): PolicyVersion | null;
1174
+ /**
1175
+ * 启动 A/B 测试
1176
+ */
1177
+ startABTest(testId: string, controlId: string, treatmentId: string, trafficSplit: number, actor: string): ABTestConfig | null;
1178
+ /**
1179
+ * A/B 测试路由
1180
+ */
1181
+ resolveABTest(testId: string, requestHash?: number): {
1182
+ version: PolicyVersion;
1183
+ group: 'control' | 'treatment';
1184
+ } | null;
1185
+ /**
1186
+ * 结束 A/B 测试
1187
+ */
1188
+ endABTest(testId: string, actor: string): ABTestConfig | null;
1189
+ /**
1190
+ * 获取所有版本
1191
+ */
1192
+ listVersions(): PolicyVersion[];
1193
+ /**
1194
+ * 获取当前 active 版本
1195
+ */
1196
+ getActiveVersion(): PolicyVersion | null;
1197
+ private cleanupOldVersions;
1198
+ private audit;
1199
+ }
1200
+ declare function createEvolutionChannel(config?: Partial<EvolutionConfig>): EvolutionChannelEngine;
1201
+
352
1202
  /**
353
1203
  * @sovr/engine — Unified Policy Engine
354
1204
  *
@@ -565,4 +1415,4 @@ declare class PolicyEngine {
565
1415
  }): void;
566
1416
  }
567
1417
 
568
- export { AdaptiveThresholdManager, type AdaptiveThresholdOptions, type AdjustmentResult, type AuditEvent, type Channel, type ComparisonNode, type CompiledExpression, DEFAULT_RULES, type DecisionFeedback, type EngineConfig, type EngineTier, type EngineTierLimits, type EvalContext, type EvalRequest, type EvalResult, type ExecContext, type ExprTreePolicyRule, type ExpressionNode, type FeatureSwitchDef, type FeatureSwitchState, FeatureSwitchesManager, type FeatureSwitchesOptions, type FunctionNode, type HttpContext, type LiteralNode, type LogicalNode, type McpContext, type NotNode, PolicyEngine, type PolicyRule, type PricingEvalRequest, type PricingEvalResult, type PricingRule, PricingRulesEngine, type RiskLevel, type RuleCondition, type RuleEvalResult, SOVR_FEATURE_SWITCHES, type SqlContext, type ThresholdConfig, type VariableNode, type Verdict, compileFromJSON, compileRuleSet, PolicyEngine as default, evaluateRules, registerFunction };
1418
+ export { type ABTestConfig, AdaptiveThresholdManager, type AdaptiveThresholdOptions, type AdjustmentResult, type AggregateSnapshot, type AuditEvent, AutoHardenEngine, type BudgetAlert, type BudgetLevel, type BudgetNode, type Channel, type ComparisonNode, type CompiledExpression, type ConsistencyMismatch, type ConsistencyResult, type CostAuditEvent, type CostCategory, type CostEstimate, type CostEstimateRequest, type CostGateEnhancedConfig, CostGateEnhancedEngine, type CostRecord, type CostReport, type CostSummary, DEFAULT_RULES, type DecisionFeedback, type DriftConfig, type DriftResult, type EngineConfig, type EngineTier, type EngineTierLimits, type EstimateAccuracy, type EvalContext, type EvalRequest, type EvalResult, EvolutionChannelEngine, type EvolutionConfig, type EvolutionEvent, type ExecContext, type ExprTreePolicyRule, type ExpressionNode, type FeatureSwitchDef, type FeatureSwitchState, FeatureSwitchesManager, type FeatureSwitchesOptions, type FunctionNode, type HardenConfig, type HardenEvent, type HardenLevel, type HardenMeasure, type HardenMeasureType, type HardenState, type HttpContext, type LiteralNode, type LogicalNode, type McpContext, type ModelPricing, type MultiLevelBudgetConfig, MultiLevelBudgetEngine, type NotNode, PolicyEngine, type PolicyRule, type PolicySnapshot, type PolicyVersion, type PricingEvalRequest, type PricingEvalResult, type PricingRule, PricingRulesEngine, type RecalcEngineConfig, type RecalcGranularity, type RecalcHandler, type RecalcTask, type RecalcTaskStatus, type RecalcTriggerType, RecalculationEngine, type RiskLevel, type RuleCondition, type RuleEvalResult, SOVR_FEATURE_SWITCHES, SemanticDriftDetectorEngine, type SemanticFingerprint, type SqlContext, type ThresholdConfig, type ToolPricing, type VariableNode, type Verdict, compileFromJSON, compileRuleSet, createAutoHardenEngine, createCostGateEnhanced, createEvolutionChannel, createMultiLevelBudget, createRecalculationEngine, createSemanticDriftDetector, PolicyEngine as default, estimateCost, evaluateRules, getAccuracyStats, getModelPricingTable, getToolPricingTable, recordActualCost, registerFunction, updateModelPricing, updateToolPricing };