agentic-qe 3.6.19 → 3.7.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.
Files changed (118) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/README.md +29 -1
  3. package/package.json +2 -1
  4. package/scripts/rvf-baseline-benchmark.ts +843 -0
  5. package/v3/CHANGELOG.md +30 -0
  6. package/v3/dist/audit/witness-chain.d.ts +148 -0
  7. package/v3/dist/audit/witness-chain.d.ts.map +1 -0
  8. package/v3/dist/audit/witness-chain.js +269 -0
  9. package/v3/dist/audit/witness-chain.js.map +1 -0
  10. package/v3/dist/cli/brain-commands.d.ts +39 -0
  11. package/v3/dist/cli/brain-commands.d.ts.map +1 -0
  12. package/v3/dist/cli/brain-commands.js +60 -0
  13. package/v3/dist/cli/brain-commands.js.map +1 -0
  14. package/v3/dist/cli/bundle.js +4509 -2452
  15. package/v3/dist/cli/command-registry.d.ts.map +1 -1
  16. package/v3/dist/cli/command-registry.js +3 -1
  17. package/v3/dist/cli/command-registry.js.map +1 -1
  18. package/v3/dist/cli/handlers/brain-handler.d.ts +22 -0
  19. package/v3/dist/cli/handlers/brain-handler.d.ts.map +1 -0
  20. package/v3/dist/cli/handlers/brain-handler.js +148 -0
  21. package/v3/dist/cli/handlers/brain-handler.js.map +1 -0
  22. package/v3/dist/cli/handlers/index.d.ts +1 -0
  23. package/v3/dist/cli/handlers/index.d.ts.map +1 -1
  24. package/v3/dist/cli/handlers/index.js +1 -0
  25. package/v3/dist/cli/handlers/index.js.map +1 -1
  26. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts +31 -44
  27. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts.map +1 -1
  28. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js +73 -178
  29. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js.map +1 -1
  30. package/v3/dist/domains/quality-assessment/coordinator.d.ts.map +1 -1
  31. package/v3/dist/domains/quality-assessment/coordinator.js +8 -0
  32. package/v3/dist/domains/quality-assessment/coordinator.js.map +1 -1
  33. package/v3/dist/domains/test-execution/coordinator.d.ts +14 -0
  34. package/v3/dist/domains/test-execution/coordinator.d.ts.map +1 -1
  35. package/v3/dist/domains/test-execution/coordinator.js +18 -0
  36. package/v3/dist/domains/test-execution/coordinator.js.map +1 -1
  37. package/v3/dist/domains/test-execution/services/index.d.ts +1 -0
  38. package/v3/dist/domains/test-execution/services/index.d.ts.map +1 -1
  39. package/v3/dist/domains/test-execution/services/index.js +1 -0
  40. package/v3/dist/domains/test-execution/services/index.js.map +1 -1
  41. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.d.ts +118 -0
  42. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.d.ts.map +1 -0
  43. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.js +358 -0
  44. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.js.map +1 -0
  45. package/v3/dist/integrations/ruvector/brain-exporter.d.ts +66 -0
  46. package/v3/dist/integrations/ruvector/brain-exporter.d.ts.map +1 -0
  47. package/v3/dist/integrations/ruvector/brain-exporter.js +537 -0
  48. package/v3/dist/integrations/ruvector/brain-exporter.js.map +1 -0
  49. package/v3/dist/integrations/ruvector/index.d.ts +4 -0
  50. package/v3/dist/integrations/ruvector/index.d.ts.map +1 -1
  51. package/v3/dist/integrations/ruvector/index.js +5 -0
  52. package/v3/dist/integrations/ruvector/index.js.map +1 -1
  53. package/v3/dist/integrations/ruvector/mincut-wrapper.d.ts +204 -0
  54. package/v3/dist/integrations/ruvector/mincut-wrapper.d.ts.map +1 -0
  55. package/v3/dist/integrations/ruvector/mincut-wrapper.js +310 -0
  56. package/v3/dist/integrations/ruvector/mincut-wrapper.js.map +1 -0
  57. package/v3/dist/integrations/ruvector/rvf-dual-writer.d.ts +141 -0
  58. package/v3/dist/integrations/ruvector/rvf-dual-writer.d.ts.map +1 -0
  59. package/v3/dist/integrations/ruvector/rvf-dual-writer.js +367 -0
  60. package/v3/dist/integrations/ruvector/rvf-dual-writer.js.map +1 -0
  61. package/v3/dist/integrations/ruvector/rvf-native-adapter.d.ts +60 -0
  62. package/v3/dist/integrations/ruvector/rvf-native-adapter.d.ts.map +1 -0
  63. package/v3/dist/integrations/ruvector/rvf-native-adapter.js +240 -0
  64. package/v3/dist/integrations/ruvector/rvf-native-adapter.js.map +1 -0
  65. package/v3/dist/kernel/hnsw-adapter.d.ts +99 -0
  66. package/v3/dist/kernel/hnsw-adapter.d.ts.map +1 -0
  67. package/v3/dist/kernel/hnsw-adapter.js +218 -0
  68. package/v3/dist/kernel/hnsw-adapter.js.map +1 -0
  69. package/v3/dist/kernel/hnsw-index-provider.d.ts +90 -0
  70. package/v3/dist/kernel/hnsw-index-provider.d.ts.map +1 -0
  71. package/v3/dist/kernel/hnsw-index-provider.js +23 -0
  72. package/v3/dist/kernel/hnsw-index-provider.js.map +1 -0
  73. package/v3/dist/kernel/progressive-hnsw-backend.d.ts +67 -0
  74. package/v3/dist/kernel/progressive-hnsw-backend.d.ts.map +1 -0
  75. package/v3/dist/kernel/progressive-hnsw-backend.js +266 -0
  76. package/v3/dist/kernel/progressive-hnsw-backend.js.map +1 -0
  77. package/v3/dist/kernel/unified-memory-hnsw.d.ts +71 -0
  78. package/v3/dist/kernel/unified-memory-hnsw.d.ts.map +1 -1
  79. package/v3/dist/kernel/unified-memory-hnsw.js +87 -0
  80. package/v3/dist/kernel/unified-memory-hnsw.js.map +1 -1
  81. package/v3/dist/kernel/unified-memory-schemas.d.ts +1 -0
  82. package/v3/dist/kernel/unified-memory-schemas.d.ts.map +1 -1
  83. package/v3/dist/kernel/unified-memory-schemas.js +16 -0
  84. package/v3/dist/kernel/unified-memory-schemas.js.map +1 -1
  85. package/v3/dist/learning/dream/dream-engine.d.ts +16 -0
  86. package/v3/dist/learning/dream/dream-engine.d.ts.map +1 -1
  87. package/v3/dist/learning/dream/dream-engine.js +70 -0
  88. package/v3/dist/learning/dream/dream-engine.js.map +1 -1
  89. package/v3/dist/learning/dream/index.d.ts +2 -0
  90. package/v3/dist/learning/dream/index.d.ts.map +1 -1
  91. package/v3/dist/learning/dream/index.js +8 -0
  92. package/v3/dist/learning/dream/index.js.map +1 -1
  93. package/v3/dist/learning/dream/rvcow-branch-manager.d.ts +170 -0
  94. package/v3/dist/learning/dream/rvcow-branch-manager.d.ts.map +1 -0
  95. package/v3/dist/learning/dream/rvcow-branch-manager.js +263 -0
  96. package/v3/dist/learning/dream/rvcow-branch-manager.js.map +1 -0
  97. package/v3/dist/learning/dream/speculative-dreamer.d.ts +129 -0
  98. package/v3/dist/learning/dream/speculative-dreamer.d.ts.map +1 -0
  99. package/v3/dist/learning/dream/speculative-dreamer.js +214 -0
  100. package/v3/dist/learning/dream/speculative-dreamer.js.map +1 -0
  101. package/v3/dist/learning/qe-reasoning-bank.d.ts +9 -0
  102. package/v3/dist/learning/qe-reasoning-bank.d.ts.map +1 -1
  103. package/v3/dist/learning/qe-reasoning-bank.js +50 -1
  104. package/v3/dist/learning/qe-reasoning-bank.js.map +1 -1
  105. package/v3/dist/mcp/bundle.js +8900 -7163
  106. package/v3/dist/mcp/services/mincut-routing-service.d.ts +148 -0
  107. package/v3/dist/mcp/services/mincut-routing-service.d.ts.map +1 -0
  108. package/v3/dist/mcp/services/mincut-routing-service.js +198 -0
  109. package/v3/dist/mcp/services/mincut-routing-service.js.map +1 -0
  110. package/v3/dist/mcp/services/task-router.d.ts +4 -0
  111. package/v3/dist/mcp/services/task-router.d.ts.map +1 -1
  112. package/v3/dist/mcp/services/task-router.js +57 -15
  113. package/v3/dist/mcp/services/task-router.js.map +1 -1
  114. package/v3/dist/monitoring/structural-health.d.ts +142 -0
  115. package/v3/dist/monitoring/structural-health.d.ts.map +1 -0
  116. package/v3/dist/monitoring/structural-health.js +201 -0
  117. package/v3/dist/monitoring/structural-health.js.map +1 -0
  118. package/v3/package.json +1 -1
@@ -0,0 +1,204 @@
1
+ /**
2
+ * QE Wrapper for MinCut Calculator
3
+ *
4
+ * This wrapper provides a QE-specific interface on top of the TypeScript
5
+ * MinCutCalculator (v3/src/coordination/mincut/mincut-calculator.ts).
6
+ * Follows the same pattern as gnn-wrapper.ts and sona-wrapper.ts.
7
+ *
8
+ * ADR-068: Mincut-Gated Model Routing
9
+ *
10
+ * @module integrations/ruvector/mincut-wrapper
11
+ */
12
+ import { SwarmGraph } from '../../coordination/mincut/swarm-graph.js';
13
+ /**
14
+ * Task graph node representing a task or agent in the routing context
15
+ */
16
+ export interface TaskGraphNode {
17
+ /** Unique node identifier */
18
+ readonly id: string;
19
+ /** Node label for display */
20
+ readonly label: string;
21
+ /**
22
+ * Node type:
23
+ * - 'task': A task to be routed
24
+ * - 'agent': An agent in the fleet
25
+ * - 'domain': A domain grouping
26
+ */
27
+ readonly type: 'task' | 'agent' | 'domain';
28
+ /** Associated domain name */
29
+ readonly domain?: string;
30
+ /** Node weight (importance) */
31
+ readonly weight: number;
32
+ /** Additional metadata */
33
+ readonly metadata?: Record<string, unknown>;
34
+ }
35
+ /**
36
+ * Edge connecting two nodes in the task graph
37
+ */
38
+ export interface TaskGraphEdge {
39
+ /** Source node ID */
40
+ readonly source: string;
41
+ /** Target node ID */
42
+ readonly target: string;
43
+ /** Edge weight representing connection strength */
44
+ readonly weight: number;
45
+ /** Edge type */
46
+ readonly edgeType: 'dependency' | 'communication' | 'coordination' | 'workflow';
47
+ }
48
+ /**
49
+ * Task graph used for mincut-based routing analysis
50
+ */
51
+ export interface TaskGraph {
52
+ /** All nodes in the graph */
53
+ readonly nodes: TaskGraphNode[];
54
+ /** All edges in the graph */
55
+ readonly edges: TaskGraphEdge[];
56
+ }
57
+ /**
58
+ * An agent node in the fleet topology
59
+ */
60
+ export interface AgentNode {
61
+ /** Agent identifier */
62
+ readonly id: string;
63
+ /** Agent display name */
64
+ readonly name: string;
65
+ /** Agent domain */
66
+ readonly domain: string;
67
+ /** Agent capabilities */
68
+ readonly capabilities: string[];
69
+ /** IDs of agents this one depends on */
70
+ readonly dependsOn: string[];
71
+ /** Agent importance weight (0-1) */
72
+ readonly weight: number;
73
+ }
74
+ /**
75
+ * Routing tier determined by mincut analysis
76
+ */
77
+ export interface RoutingTier {
78
+ /** Numeric tier (1 = Haiku, 2 = Sonnet, 3+ = Opus) */
79
+ readonly tier: number;
80
+ /** Tier label */
81
+ readonly label: string;
82
+ /** Lambda value that determined this tier */
83
+ readonly lambda: number;
84
+ /** Normalized lambda (0-1) */
85
+ readonly normalizedLambda: number;
86
+ /** Confidence in the routing decision */
87
+ readonly confidence: number;
88
+ /** Explanation of why this tier was selected */
89
+ readonly rationale: string;
90
+ }
91
+ /**
92
+ * Health report from structural analysis
93
+ */
94
+ export interface HealthReport {
95
+ /** Overall lambda (min-cut value) */
96
+ readonly lambda: number;
97
+ /** Normalized lambda (0-1, higher = healthier) */
98
+ readonly normalizedLambda: number;
99
+ /** Whether the fleet is structurally healthy */
100
+ readonly healthy: boolean;
101
+ /** Vertices identified as weak points */
102
+ readonly weakPoints: string[];
103
+ /** Risk score (0-1, higher = riskier) */
104
+ readonly riskScore: number;
105
+ /** Number of connected components */
106
+ readonly componentCount: number;
107
+ /** Whether the graph is fully connected */
108
+ readonly isConnected: boolean;
109
+ /** Suggestions for improving structural health */
110
+ readonly suggestions: string[];
111
+ /** Timestamp of analysis */
112
+ readonly analyzedAt: Date;
113
+ }
114
+ /**
115
+ * QE MinCut Service - Unified interface over the TypeScript MinCutCalculator
116
+ *
117
+ * Provides mincut-based graph analysis for routing decisions, fleet health
118
+ * monitoring, and structural complexity assessment.
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * const service = new QEMinCutService();
123
+ *
124
+ * // Compute lambda for a task graph
125
+ * const lambda = service.computeLambda(taskGraph);
126
+ *
127
+ * // Determine routing tier
128
+ * const tier = service.computeRoutingTier('Implement auth flow', agents);
129
+ *
130
+ * // Get fleet health
131
+ * const health = service.getStructuralHealth(taskGraph);
132
+ * ```
133
+ */
134
+ export declare class QEMinCutService {
135
+ private readonly calculator;
136
+ constructor();
137
+ /**
138
+ * Compute the min-cut lambda value for a task graph.
139
+ *
140
+ * Lambda represents the minimum edge weight that must be removed to
141
+ * disconnect the graph. Higher lambda = more connected = simpler routing.
142
+ *
143
+ * @param graph - The task graph to analyze
144
+ * @returns The min-cut lambda value (0 if graph is empty/disconnected)
145
+ */
146
+ computeLambda(graph: TaskGraph): number;
147
+ /**
148
+ * Determine the optimal routing tier based on task description and agent topology.
149
+ *
150
+ * Builds a task graph from the agent topology, computes lambda, and maps
151
+ * the normalized lambda to a routing tier:
152
+ * - lambda >= 0.8 (highly connected, simple) -> Tier 1 (Haiku)
153
+ * - lambda 0.4-0.8 (moderate connectivity) -> Tier 2 (Sonnet)
154
+ * - lambda < 0.4 (fragmented, complex) -> Tier 3 (Opus)
155
+ *
156
+ * @param taskDescription - Description of the task to route
157
+ * @param agentTopology - Current agent fleet topology
158
+ * @returns Routing tier recommendation
159
+ */
160
+ computeRoutingTier(taskDescription: string, agentTopology: AgentNode[]): RoutingTier;
161
+ /**
162
+ * Compute structural health of the agent fleet using mincut lambda.
163
+ *
164
+ * Uses Stoer-Wagner style analysis (via weighted degree heuristic) to
165
+ * assess the robustness of the fleet topology.
166
+ *
167
+ * @param graph - The task graph to analyze
168
+ * @returns Health report with lambda, weak points, and suggestions
169
+ */
170
+ getStructuralHealth(graph: TaskGraph): HealthReport;
171
+ /**
172
+ * Convert a TaskGraph to a SwarmGraph for use with MinCutCalculator
173
+ */
174
+ toSwarmGraph(graph: TaskGraph): SwarmGraph;
175
+ /**
176
+ * Build a TaskGraph from agent topology
177
+ */
178
+ buildTaskGraphFromTopology(agents: AgentNode[]): TaskGraph;
179
+ /**
180
+ * Map normalized lambda to routing tier
181
+ */
182
+ private lambdaToTier;
183
+ /**
184
+ * Compute confidence in the routing decision
185
+ */
186
+ private computeConfidence;
187
+ /**
188
+ * Build human-readable rationale for the routing decision
189
+ */
190
+ private buildRationale;
191
+ /**
192
+ * Generate health improvement suggestions
193
+ */
194
+ private generateHealthSuggestions;
195
+ /**
196
+ * Create an empty health report for empty graphs
197
+ */
198
+ private emptyHealthReport;
199
+ }
200
+ /**
201
+ * Create a new QEMinCutService instance
202
+ */
203
+ export declare function createQEMinCutService(): QEMinCutService;
204
+ //# sourceMappingURL=mincut-wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mincut-wrapper.d.ts","sourceRoot":"","sources":["../../../src/integrations/ruvector/mincut-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,0CAA0C,CAAC;AAOtE;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAEpB,6BAA6B;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;IAE3C,6BAA6B;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAEzB,+BAA+B;IAC/B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,0BAA0B;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC7C;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,qBAAqB;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,qBAAqB;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,mDAAmD;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,gBAAgB;IAChB,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,eAAe,GAAG,cAAc,GAAG,UAAU,CAAC;CACjF;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,6BAA6B;IAC7B,QAAQ,CAAC,KAAK,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C;IAE3B,qCAAqC;IACrC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,2CAA2C;IAC3C,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;IAE9B,kDAAkD;IAClD,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC;IAE/B,4BAA4B;IAC5B,QAAQ,CAAC,UAAU,EAAE,IAAI,CAAC;CAC3B;AAMD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;;IAM9C;;;;;;;;OAQG;IACH,aAAa,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM;IAKvC;;;;;;;;;;;;OAYG;IACH,kBAAkB,CAChB,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,SAAS,EAAE,GACzB,WAAW;IAoCd;;;;;;;;OAQG;IACH,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,YAAY;IA8CnD;;OAEG;IACH,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,UAAU;IAqC1C;;OAEG;IACH,0BAA0B,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,SAAS;IAqD1D;;OAEG;IACH,OAAO,CAAC,YAAY;IAUpB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAuBzB;;OAEG;IACH,OAAO,CAAC,cAAc;IAoBtB;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAuCjC;;OAEG;IACH,OAAO,CAAC,iBAAiB;CAa1B;AAMD;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,eAAe,CAEvD"}
@@ -0,0 +1,310 @@
1
+ /**
2
+ * QE Wrapper for MinCut Calculator
3
+ *
4
+ * This wrapper provides a QE-specific interface on top of the TypeScript
5
+ * MinCutCalculator (v3/src/coordination/mincut/mincut-calculator.ts).
6
+ * Follows the same pattern as gnn-wrapper.ts and sona-wrapper.ts.
7
+ *
8
+ * ADR-068: Mincut-Gated Model Routing
9
+ *
10
+ * @module integrations/ruvector/mincut-wrapper
11
+ */
12
+ import { MinCutCalculator } from '../../coordination/mincut/mincut-calculator.js';
13
+ import { SwarmGraph } from '../../coordination/mincut/swarm-graph.js';
14
+ // ============================================================================
15
+ // QEMinCutService
16
+ // ============================================================================
17
+ /**
18
+ * QE MinCut Service - Unified interface over the TypeScript MinCutCalculator
19
+ *
20
+ * Provides mincut-based graph analysis for routing decisions, fleet health
21
+ * monitoring, and structural complexity assessment.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const service = new QEMinCutService();
26
+ *
27
+ * // Compute lambda for a task graph
28
+ * const lambda = service.computeLambda(taskGraph);
29
+ *
30
+ * // Determine routing tier
31
+ * const tier = service.computeRoutingTier('Implement auth flow', agents);
32
+ *
33
+ * // Get fleet health
34
+ * const health = service.getStructuralHealth(taskGraph);
35
+ * ```
36
+ */
37
+ export class QEMinCutService {
38
+ calculator;
39
+ constructor() {
40
+ this.calculator = new MinCutCalculator();
41
+ }
42
+ /**
43
+ * Compute the min-cut lambda value for a task graph.
44
+ *
45
+ * Lambda represents the minimum edge weight that must be removed to
46
+ * disconnect the graph. Higher lambda = more connected = simpler routing.
47
+ *
48
+ * @param graph - The task graph to analyze
49
+ * @returns The min-cut lambda value (0 if graph is empty/disconnected)
50
+ */
51
+ computeLambda(graph) {
52
+ const swarmGraph = this.toSwarmGraph(graph);
53
+ return this.calculator.getMinCutValue(swarmGraph);
54
+ }
55
+ /**
56
+ * Determine the optimal routing tier based on task description and agent topology.
57
+ *
58
+ * Builds a task graph from the agent topology, computes lambda, and maps
59
+ * the normalized lambda to a routing tier:
60
+ * - lambda >= 0.8 (highly connected, simple) -> Tier 1 (Haiku)
61
+ * - lambda 0.4-0.8 (moderate connectivity) -> Tier 2 (Sonnet)
62
+ * - lambda < 0.4 (fragmented, complex) -> Tier 3 (Opus)
63
+ *
64
+ * @param taskDescription - Description of the task to route
65
+ * @param agentTopology - Current agent fleet topology
66
+ * @returns Routing tier recommendation
67
+ */
68
+ computeRoutingTier(taskDescription, agentTopology) {
69
+ // Build task graph from agent topology
70
+ const graph = this.buildTaskGraphFromTopology(agentTopology);
71
+ const swarmGraph = this.toSwarmGraph(graph);
72
+ // Get raw lambda
73
+ const rawLambda = this.calculator.getMinCutValue(swarmGraph);
74
+ // Normalize lambda to 0-1 range
75
+ // Use vertex count as normalization factor (fully connected = vertex count - 1)
76
+ const maxPossibleLambda = Math.max(agentTopology.length - 1, 1);
77
+ const normalizedLambda = Math.min(rawLambda / maxPossibleLambda, 1.0);
78
+ // Determine tier based on normalized lambda
79
+ const { tier, label } = this.lambdaToTier(normalizedLambda);
80
+ // Compute confidence based on graph size and connectivity
81
+ const confidence = this.computeConfidence(swarmGraph, normalizedLambda);
82
+ const rationale = this.buildRationale(taskDescription, normalizedLambda, tier, agentTopology.length);
83
+ return {
84
+ tier,
85
+ label,
86
+ lambda: rawLambda,
87
+ normalizedLambda,
88
+ confidence,
89
+ rationale,
90
+ };
91
+ }
92
+ /**
93
+ * Compute structural health of the agent fleet using mincut lambda.
94
+ *
95
+ * Uses Stoer-Wagner style analysis (via weighted degree heuristic) to
96
+ * assess the robustness of the fleet topology.
97
+ *
98
+ * @param graph - The task graph to analyze
99
+ * @returns Health report with lambda, weak points, and suggestions
100
+ */
101
+ getStructuralHealth(graph) {
102
+ const swarmGraph = this.toSwarmGraph(graph);
103
+ if (swarmGraph.isEmpty()) {
104
+ return this.emptyHealthReport();
105
+ }
106
+ const rawLambda = this.calculator.getMinCutValue(swarmGraph);
107
+ const stats = swarmGraph.getStats();
108
+ const maxPossibleLambda = Math.max(stats.vertexCount - 1, 1);
109
+ const normalizedLambda = Math.min(rawLambda / maxPossibleLambda, 1.0);
110
+ // Find weak vertices
111
+ const weakVertices = this.calculator.findWeakVertices(swarmGraph);
112
+ const weakPoints = weakVertices.map(wv => wv.vertexId);
113
+ // Compute risk score (inverse of normalized lambda)
114
+ const riskScore = 1 - normalizedLambda;
115
+ // Health threshold: lambda >= 0.4 normalized is healthy
116
+ const healthy = normalizedLambda >= 0.4;
117
+ // Generate suggestions
118
+ const suggestions = this.generateHealthSuggestions(normalizedLambda, weakVertices.length, stats);
119
+ return {
120
+ lambda: rawLambda,
121
+ normalizedLambda,
122
+ healthy,
123
+ weakPoints,
124
+ riskScore,
125
+ componentCount: stats.componentCount,
126
+ isConnected: stats.isConnected,
127
+ suggestions,
128
+ analyzedAt: new Date(),
129
+ };
130
+ }
131
+ // ==========================================================================
132
+ // Graph Conversion
133
+ // ==========================================================================
134
+ /**
135
+ * Convert a TaskGraph to a SwarmGraph for use with MinCutCalculator
136
+ */
137
+ toSwarmGraph(graph) {
138
+ const swarmGraph = new SwarmGraph();
139
+ // Add vertices
140
+ for (const node of graph.nodes) {
141
+ const vertex = {
142
+ id: node.id,
143
+ type: node.type === 'task' ? 'agent' : node.type === 'agent' ? 'agent' : 'domain',
144
+ domain: node.domain,
145
+ weight: node.weight,
146
+ createdAt: new Date(),
147
+ metadata: node.metadata,
148
+ };
149
+ swarmGraph.addVertex(vertex);
150
+ }
151
+ // Add edges
152
+ for (const edge of graph.edges) {
153
+ // Only add edges if both vertices exist
154
+ if (swarmGraph.hasVertex(edge.source) && swarmGraph.hasVertex(edge.target)) {
155
+ const swarmEdge = {
156
+ source: edge.source,
157
+ target: edge.target,
158
+ weight: edge.weight,
159
+ type: edge.edgeType === 'dependency' ? 'dependency'
160
+ : edge.edgeType === 'communication' ? 'communication'
161
+ : edge.edgeType === 'workflow' ? 'workflow'
162
+ : 'coordination',
163
+ bidirectional: edge.edgeType !== 'dependency',
164
+ };
165
+ swarmGraph.addEdge(swarmEdge);
166
+ }
167
+ }
168
+ return swarmGraph;
169
+ }
170
+ /**
171
+ * Build a TaskGraph from agent topology
172
+ */
173
+ buildTaskGraphFromTopology(agents) {
174
+ const nodes = agents.map(agent => ({
175
+ id: agent.id,
176
+ label: agent.name,
177
+ type: 'agent',
178
+ domain: agent.domain,
179
+ weight: agent.weight,
180
+ }));
181
+ const edges = [];
182
+ const agentIds = new Set(agents.map(a => a.id));
183
+ for (const agent of agents) {
184
+ for (const depId of agent.dependsOn) {
185
+ if (agentIds.has(depId)) {
186
+ edges.push({
187
+ source: agent.id,
188
+ target: depId,
189
+ weight: 1.0,
190
+ edgeType: 'dependency',
191
+ });
192
+ }
193
+ }
194
+ }
195
+ // Add coordination edges between agents in the same domain
196
+ const domainGroups = new Map();
197
+ for (const agent of agents) {
198
+ const group = domainGroups.get(agent.domain) || [];
199
+ group.push(agent.id);
200
+ domainGroups.set(agent.domain, group);
201
+ }
202
+ for (const [, group] of domainGroups) {
203
+ for (let i = 0; i < group.length; i++) {
204
+ for (let j = i + 1; j < group.length; j++) {
205
+ edges.push({
206
+ source: group[i],
207
+ target: group[j],
208
+ weight: 0.5,
209
+ edgeType: 'coordination',
210
+ });
211
+ }
212
+ }
213
+ }
214
+ return { nodes, edges };
215
+ }
216
+ // ==========================================================================
217
+ // Private Helpers
218
+ // ==========================================================================
219
+ /**
220
+ * Map normalized lambda to routing tier
221
+ */
222
+ lambdaToTier(normalizedLambda) {
223
+ if (normalizedLambda >= 0.8) {
224
+ return { tier: 1, label: 'Haiku' };
225
+ }
226
+ if (normalizedLambda >= 0.4) {
227
+ return { tier: 2, label: 'Sonnet' };
228
+ }
229
+ return { tier: 3, label: 'Opus' };
230
+ }
231
+ /**
232
+ * Compute confidence in the routing decision
233
+ */
234
+ computeConfidence(graph, normalizedLambda) {
235
+ const stats = graph.getStats();
236
+ // Low confidence if graph is too small
237
+ if (stats.vertexCount < 3) {
238
+ return 0.4;
239
+ }
240
+ // High confidence if lambda is clearly in a tier range (not near boundary)
241
+ const distFromBoundary = Math.min(Math.abs(normalizedLambda - 0.4), Math.abs(normalizedLambda - 0.8));
242
+ // Scale: 0.0 distance from boundary = 0.5 confidence, 0.2+ = 0.95
243
+ const boundaryConfidence = Math.min(0.95, 0.5 + distFromBoundary * 2.25);
244
+ // Also consider graph density for confidence
245
+ const densityFactor = Math.min(1.0, stats.density * 2);
246
+ return Math.min(0.99, boundaryConfidence * (0.7 + 0.3 * densityFactor));
247
+ }
248
+ /**
249
+ * Build human-readable rationale for the routing decision
250
+ */
251
+ buildRationale(taskDescription, normalizedLambda, tier, agentCount) {
252
+ const taskPreview = taskDescription.slice(0, 80);
253
+ const connectivity = normalizedLambda >= 0.8 ? 'highly connected'
254
+ : normalizedLambda >= 0.4 ? 'moderately connected'
255
+ : 'fragmented';
256
+ const tierName = tier === 1 ? 'Haiku' : tier === 2 ? 'Sonnet' : 'Opus';
257
+ return (`Task "${taskPreview}" routed to ${tierName} (Tier ${tier}). ` +
258
+ `Fleet topology is ${connectivity} (lambda=${normalizedLambda.toFixed(3)}) ` +
259
+ `across ${agentCount} agents.`);
260
+ }
261
+ /**
262
+ * Generate health improvement suggestions
263
+ */
264
+ generateHealthSuggestions(normalizedLambda, weakCount, stats) {
265
+ const suggestions = [];
266
+ if (!stats.isConnected) {
267
+ suggestions.push(`Graph has ${stats.componentCount} disconnected components. ` +
268
+ 'Add cross-domain coordination edges to improve connectivity.');
269
+ }
270
+ if (normalizedLambda < 0.2) {
271
+ suggestions.push('Critical: Fleet connectivity is very low. Consider spawning coordination agents.');
272
+ }
273
+ else if (normalizedLambda < 0.4) {
274
+ suggestions.push('Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections.');
275
+ }
276
+ if (weakCount > 0) {
277
+ suggestions.push(`${weakCount} weak point(s) detected. Add redundant connections to these agents.`);
278
+ }
279
+ if (stats.vertexCount < 3) {
280
+ suggestions.push('Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies.');
281
+ }
282
+ return suggestions;
283
+ }
284
+ /**
285
+ * Create an empty health report for empty graphs
286
+ */
287
+ emptyHealthReport() {
288
+ return {
289
+ lambda: 0,
290
+ normalizedLambda: 0,
291
+ healthy: false,
292
+ weakPoints: [],
293
+ riskScore: 1.0,
294
+ componentCount: 0,
295
+ isConnected: true,
296
+ suggestions: ['No agents in fleet. Spawn agents to build a topology.'],
297
+ analyzedAt: new Date(),
298
+ };
299
+ }
300
+ }
301
+ // ============================================================================
302
+ // Factory Functions
303
+ // ============================================================================
304
+ /**
305
+ * Create a new QEMinCutService instance
306
+ */
307
+ export function createQEMinCutService() {
308
+ return new QEMinCutService();
309
+ }
310
+ //# sourceMappingURL=mincut-wrapper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mincut-wrapper.js","sourceRoot":"","sources":["../../../src/integrations/ruvector/mincut-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,gDAAgD,CAAC;AAClF,OAAO,EAAE,UAAU,EAAE,MAAM,0CAA0C,CAAC;AA6ItE,+EAA+E;AAC/E,kBAAkB;AAClB,+EAA+E;AAE/E;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,OAAO,eAAe;IACT,UAAU,CAAmB;IAE9C;QACE,IAAI,CAAC,UAAU,GAAG,IAAI,gBAAgB,EAAE,CAAC;IAC3C,CAAC;IAED;;;;;;;;OAQG;IACH,aAAa,CAAC,KAAgB;QAC5B,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACpD,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,kBAAkB,CAChB,eAAuB,EACvB,aAA0B;QAE1B,uCAAuC;QACvC,MAAM,KAAK,GAAG,IAAI,CAAC,0BAA0B,CAAC,aAAa,CAAC,CAAC;QAC7D,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAE5C,iBAAiB;QACjB,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;QAE7D,gCAAgC;QAChC,gFAAgF;QAChF,MAAM,iBAAiB,GAAG,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE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G,SAAS,qEAAqE,CAClF,CAAC;QACJ,CAAC;QAED,IAAI,KAAK,CAAC,WAAW,GAAG,CAAC,EAAE,CAAC;YAC1B,WAAW,CAAC,IAAI,CACd,uFAAuF,CACxF,CAAC;QACJ,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;IAED;;OAEG;IACK,iBAAiB;QACvB,OAAO;YACL,MAAM,EAAE,CAAC;YACT,gBAAgB,EAAE,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,UAAU,EAAE,EAAE;YACd,SAAS,EAAE,GAAG;YACd,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,IAAI;YACjB,WAAW,EAAE,CAAC,uDAAuD,CAAC;YACtE,UAAU,EAAE,IAAI,IAAI,EAAE;SACvB,CAAC;IACJ,CAAC;CACF;AAED,+EAA+E;AAC/E,oBAAoB;AACpB,+EAA+E;AAE/E;;GAEG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC"}
@@ -0,0 +1,141 @@
1
+ /**
2
+ * RVF Dual-Writer Service
3
+ *
4
+ * Phase 3 Task 3.1: Writes learning data to both SQLite (existing) and
5
+ * an RVF container (new native backend). Ensures SQLite writes are never
6
+ * broken by RVF failures, and supports gradual promotion from SQLite-only
7
+ * to dual-write to RVF-primary mode.
8
+ *
9
+ * The dual-writer sits between the QEReasoningBank and the storage layer,
10
+ * intercepting pattern embedding writes/deletes/searches and routing them
11
+ * to one or both backends depending on the configured mode.
12
+ */
13
+ /**
14
+ * Simplified RVF store interface used internally by the dual-writer.
15
+ * Abstracts over the native adapter so tests can provide mocks
16
+ * without depending on the @ruvector/rvf-node native binding.
17
+ */
18
+ export interface RvfStore {
19
+ ingest(entries: Array<{
20
+ id: string;
21
+ vector: number[] | Float32Array;
22
+ }>): void;
23
+ search(query: number[] | Float32Array, k: number): Array<{
24
+ id: string;
25
+ score: number;
26
+ }>;
27
+ delete(ids: string[]): void;
28
+ status(): RvfStatus;
29
+ close(): void;
30
+ }
31
+ export interface RvfStatus {
32
+ totalVectors: number;
33
+ dimensions?: number;
34
+ /** Fields from the native adapter, forwarded when available */
35
+ totalSegments?: number;
36
+ fileSizeBytes?: number;
37
+ epoch?: number;
38
+ witnessValid?: boolean;
39
+ witnessEntries?: number;
40
+ }
41
+ export interface DualWriteConfig {
42
+ /** Path to the RVF container file */
43
+ rvfPath: string;
44
+ /** Vector dimensions (default 384) */
45
+ dimensions?: number;
46
+ /** Write mode */
47
+ mode: 'dual-write' | 'rvf-primary' | 'sqlite-only';
48
+ /** Whether to verify witness chain on startup */
49
+ verifyOnStartup?: boolean;
50
+ }
51
+ export interface DualWriteResult {
52
+ sqliteSuccess: boolean;
53
+ rvfSuccess: boolean;
54
+ divergence?: string;
55
+ }
56
+ export interface DivergenceReport {
57
+ totalChecked: number;
58
+ divergences: number;
59
+ details: Array<{
60
+ patternId: string;
61
+ issue: 'missing-in-rvf' | 'missing-in-sqlite' | 'count-mismatch';
62
+ }>;
63
+ }
64
+ export declare class RvfDualWriter {
65
+ private readonly db;
66
+ private readonly config;
67
+ private rvfStore;
68
+ private rvfAvailable;
69
+ constructor(db: unknown, config: DualWriteConfig);
70
+ /**
71
+ * Initialize the RVF store (create or open).
72
+ *
73
+ * If the native adapter is not available, the writer degrades gracefully
74
+ * to sqlite-only regardless of the configured mode.
75
+ */
76
+ initialize(): Promise<void>;
77
+ /**
78
+ * Allow injecting an RVF store directly (useful for testing).
79
+ */
80
+ setRvfStore(store: RvfStore): void;
81
+ /**
82
+ * Write a pattern embedding to both stores.
83
+ *
84
+ * SQLite is always written first. RVF failures never propagate to SQLite.
85
+ */
86
+ writePattern(patternId: string, embedding: number[] | Float32Array): DualWriteResult;
87
+ /**
88
+ * Delete a pattern embedding from both stores.
89
+ */
90
+ deletePattern(patternId: string): DualWriteResult;
91
+ /**
92
+ * Search for similar vectors. In rvf-primary mode, tries RVF first and
93
+ * falls back to SQLite on error. Otherwise uses SQLite.
94
+ */
95
+ search(query: number[] | Float32Array, k: number): Array<{
96
+ id: string;
97
+ score: number;
98
+ }>;
99
+ /**
100
+ * Generate a divergence report between SQLite embeddings and RVF vectors.
101
+ */
102
+ getDivergenceReport(): DivergenceReport;
103
+ /**
104
+ * Returns true when promotion from dual-write to rvf-primary is safe
105
+ * (zero divergences between the two stores).
106
+ */
107
+ isPromotionSafe(): boolean;
108
+ /**
109
+ * Combined status from both backends.
110
+ */
111
+ status(): {
112
+ sqlite: {
113
+ patternCount: number;
114
+ vectorCount: number;
115
+ };
116
+ rvf: RvfStatus | null;
117
+ mode: string;
118
+ };
119
+ /**
120
+ * Close the RVF store. SQLite is managed externally.
121
+ */
122
+ close(): void;
123
+ private shouldWriteRvf;
124
+ private writeSqliteEmbedding;
125
+ private deleteSqliteEmbedding;
126
+ private getSqliteEmbeddingCount;
127
+ private getSqlitePatternCount;
128
+ /**
129
+ * Brute-force cosine similarity search over SQLite embeddings.
130
+ * This is the fallback when RVF is unavailable.
131
+ */
132
+ private searchSqlite;
133
+ }
134
+ /**
135
+ * Create a new RvfDualWriter instance.
136
+ *
137
+ * @param db - better-sqlite3 Database instance
138
+ * @param config - Dual-write configuration
139
+ */
140
+ export declare function createDualWriter(db: unknown, config: DualWriteConfig): RvfDualWriter;
141
+ //# sourceMappingURL=rvf-dual-writer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rvf-dual-writer.d.ts","sourceRoot":"","sources":["../../../src/integrations/ruvector/rvf-dual-writer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAWH;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,CAAA;KAAE,CAAC,GAAG,IAAI,CAAC;IAC9E,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,YAAY,EAAE,CAAC,EAAE,MAAM,GAA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