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,263 @@
1
+ /**
2
+ * RVCOWBranchManager - RVCOW Branching for Reversible Dream Cycles
3
+ * ADR-069: RVCOW Dream Cycle Branching
4
+ *
5
+ * Implements Copy-on-Write branching semantics using SQLite savepoints.
6
+ * Each dream cycle operates on an isolated branch (savepoint). After the
7
+ * dream completes, the branch is validated against quality thresholds.
8
+ * If validation passes, the savepoint is released (changes persist).
9
+ * If validation fails, the savepoint is rolled back (changes discarded).
10
+ *
11
+ * This gives us the same semantics as native RVCOW:
12
+ * - createBranch -> SAVEPOINT
13
+ * - mergeBranch -> RELEASE SAVEPOINT
14
+ * - discardBranch -> ROLLBACK TO SAVEPOINT
15
+ *
16
+ * @module v3/learning/dream/rvcow-branch-manager
17
+ */
18
+ /** Default validation thresholds */
19
+ export const DEFAULT_VALIDATION_THRESHOLDS = {
20
+ maxPatternCountDrop: 0.05,
21
+ maxAvgConfidenceDrop: 0.02,
22
+ maxHighConfidenceLoss: 0.05,
23
+ };
24
+ // ============================================================================
25
+ // RVCOWBranchManager
26
+ // ============================================================================
27
+ /**
28
+ * Manages RVCOW branches for dream cycles using SQLite savepoints.
29
+ *
30
+ * Usage:
31
+ * ```typescript
32
+ * const manager = new RVCOWBranchManager(db);
33
+ * const branch = manager.createBranch('dream-123');
34
+ * // ... run dream logic ...
35
+ * const result = manager.validateBranch(branch, baseline);
36
+ * if (result.passed) {
37
+ * manager.mergeBranch(branch);
38
+ * } else {
39
+ * manager.discardBranch(branch);
40
+ * }
41
+ * ```
42
+ */
43
+ export class RVCOWBranchManager {
44
+ db;
45
+ thresholds;
46
+ activeBranches = new Map();
47
+ listeners = [];
48
+ /** Optional RVF native adapter for COW fork snapshots of dream state */
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
+ rvfAdapter;
51
+ /** When true and rvfAdapter is set, createBranch() also forks an RVF snapshot */
52
+ useRvfFork = false;
53
+ constructor(db, thresholds = DEFAULT_VALIDATION_THRESHOLDS) {
54
+ this.db = db;
55
+ this.thresholds = thresholds;
56
+ }
57
+ /**
58
+ * Set an RVF native adapter for supplementary COW fork snapshots.
59
+ * When set with useRvfFork=true, createBranch() will additionally
60
+ * fork a portable .rvf snapshot alongside the SQLite savepoint.
61
+ * SQLite savepoints remain the primary branching mechanism.
62
+ */
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ setRvfAdapter(adapter, useRvfFork = true) {
65
+ this.rvfAdapter = adapter;
66
+ this.useRvfFork = useRvfFork;
67
+ }
68
+ // --------------------------------------------------------------------------
69
+ // Branch Lifecycle
70
+ // --------------------------------------------------------------------------
71
+ /**
72
+ * Create a new RVCOW branch by issuing a SQLite SAVEPOINT.
73
+ * Captures a quality baseline snapshot before the savepoint.
74
+ *
75
+ * @param name - Unique branch name (used as savepoint identifier)
76
+ * @returns The created Branch
77
+ * @throws If a branch with this name already exists
78
+ */
79
+ createBranch(name) {
80
+ if (this.activeBranches.has(name)) {
81
+ throw new Error(`Branch '${name}' already exists`);
82
+ }
83
+ // Sanitize name for use as savepoint identifier
84
+ const safeName = this.sanitizeSavepointName(name);
85
+ // Capture baseline before creating savepoint
86
+ const baseline = this.captureBaseline();
87
+ // Create SQLite savepoint
88
+ this.db.exec(`SAVEPOINT "${safeName}"`);
89
+ const branch = {
90
+ name,
91
+ createdAt: new Date(),
92
+ status: 'active',
93
+ baselineSnapshot: baseline,
94
+ };
95
+ // Supplementary RVF fork for portable brain snapshots (when configured)
96
+ if (this.rvfAdapter && this.useRvfFork) {
97
+ try {
98
+ this.rvfAdapter.fork(`/tmp/dream-branch-${name}.rvf`);
99
+ }
100
+ catch {
101
+ // RVF fork is best-effort — SQLite savepoint is the primary mechanism
102
+ }
103
+ }
104
+ this.activeBranches.set(name, branch);
105
+ this.emit('dream:branch_created', branch);
106
+ return branch;
107
+ }
108
+ /**
109
+ * Validate a branch by comparing post-dream metrics against the baseline.
110
+ *
111
+ * Checks:
112
+ * 1. Pattern count did not decrease beyond threshold
113
+ * 2. Average confidence did not drop beyond threshold
114
+ * 3. No excessive high-confidence patterns were quarantined/removed
115
+ *
116
+ * @param branch - The branch to validate
117
+ * @param baseline - The quality baseline to validate against (defaults to branch's own baseline)
118
+ * @returns Validation result with pass/fail and metrics
119
+ */
120
+ validateBranch(branch, baseline) {
121
+ this.ensureBranchActive(branch.name);
122
+ const base = baseline ?? branch.baselineSnapshot;
123
+ const current = this.captureBaseline();
124
+ const patternCountDelta = current.patternCount - base.patternCount;
125
+ const avgConfidenceDelta = current.avgConfidence - base.avgConfidence;
126
+ const highConfidenceLost = base.highConfidenceCount - current.highConfidenceCount;
127
+ const reasons = [];
128
+ let passed = true;
129
+ // Check 1: Pattern count did not decrease excessively
130
+ if (base.patternCount > 0) {
131
+ const dropFraction = -patternCountDelta / base.patternCount;
132
+ if (dropFraction > this.thresholds.maxPatternCountDrop) {
133
+ passed = false;
134
+ reasons.push(`Pattern count dropped by ${(dropFraction * 100).toFixed(1)}% ` +
135
+ `(threshold: ${(this.thresholds.maxPatternCountDrop * 100).toFixed(1)}%)`);
136
+ }
137
+ }
138
+ // Check 2: Average confidence did not drop excessively
139
+ if (avgConfidenceDelta < -this.thresholds.maxAvgConfidenceDrop) {
140
+ passed = false;
141
+ reasons.push(`Avg confidence dropped by ${(-avgConfidenceDelta).toFixed(4)} ` +
142
+ `(threshold: ${this.thresholds.maxAvgConfidenceDrop})`);
143
+ }
144
+ // Check 3: High-confidence patterns not excessively quarantined
145
+ if (base.highConfidenceCount > 0 && highConfidenceLost > 0) {
146
+ const lossFraction = highConfidenceLost / base.highConfidenceCount;
147
+ if (lossFraction > this.thresholds.maxHighConfidenceLoss) {
148
+ passed = false;
149
+ reasons.push(`${highConfidenceLost} high-confidence patterns lost ` +
150
+ `(${(lossFraction * 100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss * 100).toFixed(1)}%)`);
151
+ }
152
+ }
153
+ const reason = passed
154
+ ? 'All quality checks passed'
155
+ : `Validation failed: ${reasons.join('; ')}`;
156
+ return {
157
+ passed,
158
+ reason,
159
+ patternCountDelta,
160
+ avgConfidenceDelta,
161
+ highConfidenceLost: Math.max(0, highConfidenceLost),
162
+ postDreamMetrics: current,
163
+ };
164
+ }
165
+ /**
166
+ * Merge a branch by releasing its savepoint.
167
+ * All changes made within the branch become permanent.
168
+ *
169
+ * @param branch - The branch to merge
170
+ */
171
+ mergeBranch(branch) {
172
+ this.ensureBranchActive(branch.name);
173
+ const safeName = this.sanitizeSavepointName(branch.name);
174
+ this.db.exec(`RELEASE SAVEPOINT "${safeName}"`);
175
+ branch.status = 'merged';
176
+ this.activeBranches.delete(branch.name);
177
+ this.emit('dream:branch_merged', branch);
178
+ }
179
+ /**
180
+ * Discard a branch by rolling back to its savepoint.
181
+ * All changes made within the branch are undone.
182
+ *
183
+ * @param branch - The branch to discard
184
+ */
185
+ discardBranch(branch) {
186
+ this.ensureBranchActive(branch.name);
187
+ const safeName = this.sanitizeSavepointName(branch.name);
188
+ // ROLLBACK TO keeps the savepoint active, so we release it after
189
+ this.db.exec(`ROLLBACK TO SAVEPOINT "${safeName}"`);
190
+ this.db.exec(`RELEASE SAVEPOINT "${safeName}"`);
191
+ branch.status = 'discarded';
192
+ this.activeBranches.delete(branch.name);
193
+ this.emit('dream:branch_discarded', branch);
194
+ }
195
+ /**
196
+ * List all active branches.
197
+ */
198
+ listBranches() {
199
+ return Array.from(this.activeBranches.values());
200
+ }
201
+ // --------------------------------------------------------------------------
202
+ // Event System
203
+ // --------------------------------------------------------------------------
204
+ /**
205
+ * Register a listener for branch events.
206
+ */
207
+ onEvent(listener) {
208
+ this.listeners.push(listener);
209
+ }
210
+ /**
211
+ * Remove a previously registered listener.
212
+ */
213
+ offEvent(listener) {
214
+ const idx = this.listeners.indexOf(listener);
215
+ if (idx >= 0) {
216
+ this.listeners.splice(idx, 1);
217
+ }
218
+ }
219
+ // --------------------------------------------------------------------------
220
+ // Quality Baseline Capture
221
+ // --------------------------------------------------------------------------
222
+ /**
223
+ * Capture a quality baseline from the current state of qe_patterns.
224
+ */
225
+ captureBaseline() {
226
+ const countRow = this.db.prepare('SELECT COUNT(*) as cnt FROM qe_patterns').get();
227
+ const avgRow = this.db.prepare('SELECT AVG(confidence) as avg_conf FROM qe_patterns').get();
228
+ const highRow = this.db.prepare('SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8').get();
229
+ return {
230
+ patternCount: countRow?.cnt ?? 0,
231
+ avgConfidence: avgRow?.avg_conf ?? 0,
232
+ highConfidenceCount: highRow?.cnt ?? 0,
233
+ capturedAt: new Date(),
234
+ };
235
+ }
236
+ // --------------------------------------------------------------------------
237
+ // Private Helpers
238
+ // --------------------------------------------------------------------------
239
+ ensureBranchActive(name) {
240
+ const branch = this.activeBranches.get(name);
241
+ if (!branch) {
242
+ throw new Error(`Branch '${name}' not found or not active`);
243
+ }
244
+ if (branch.status !== 'active') {
245
+ throw new Error(`Branch '${name}' is ${branch.status}, not active`);
246
+ }
247
+ }
248
+ sanitizeSavepointName(name) {
249
+ // Replace non-alphanumeric characters (except hyphens/underscores) with underscores
250
+ return name.replace(/[^a-zA-Z0-9_-]/g, '_');
251
+ }
252
+ emit(event, branch, detail) {
253
+ for (const listener of this.listeners) {
254
+ try {
255
+ listener(event, branch, detail);
256
+ }
257
+ catch {
258
+ // Swallow listener errors to avoid breaking the branch lifecycle
259
+ }
260
+ }
261
+ }
262
+ }
263
+ //# sourceMappingURL=rvcow-branch-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rvcow-branch-manager.js","sourceRoot":"","sources":["../../../src/learning/dream/rvcow-branch-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAgFH,oCAAoC;AACpC,MAAM,CAAC,MAAM,6BAA6B,GAAyB;IACjE,mBAAmB,EAAE,IAAI;IACzB,oBAAoB,EAAE,IAAI;IAC1B,qBAAqB,EAAE,IAAI;CAC5B,CAAC;AAYF,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAE/E;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,kBAAkB;IAYV;IACA;I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AAC,CAAC;QACtE,CAAC;IACH,CAAC;IAEO,qBAAqB,CAAC,IAAY;QACxC,oFAAoF;QACpF,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC;IAC9C,CAAC;IAEO,IAAI,CAAC,KAAkB,EAAE,MAAc,EAAE,MAAyB;QACxE,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;YAClC,CAAC;YAAC,MAAM,CAAC;gBACP,iEAAiE;YACnE,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,129 @@
1
+ /**
2
+ * SpeculativeDreamer - Parallel Dream Strategies with Branch Selection
3
+ * ADR-069: RVCOW Dream Cycle Branching
4
+ *
5
+ * Runs 2-3 dream strategies in parallel RVCOW branches, each with
6
+ * different parameters (decay rates, spread factors, noise levels).
7
+ * After all strategies complete, compares validation scores and merges
8
+ * the best-performing branch. All other branches are discarded.
9
+ *
10
+ * This implements the "adversarial dream" concept from the Six Thinking
11
+ * Hats analysis, where diverse strategies compete and the best wins.
12
+ *
13
+ * @module v3/learning/dream/speculative-dreamer
14
+ */
15
+ import type { Database as DatabaseType } from 'better-sqlite3';
16
+ import type { ActivationConfig } from './spreading-activation.js';
17
+ import { RVCOWBranchManager, type Branch, type ValidationResult, type ValidationThresholds } from './rvcow-branch-manager.js';
18
+ /**
19
+ * A named dream strategy with custom activation parameters.
20
+ */
21
+ export interface DreamStrategy {
22
+ /** Human-readable strategy name */
23
+ name: string;
24
+ /** Custom activation config overrides */
25
+ activationConfig: Partial<ActivationConfig>;
26
+ /** Optional description of the strategy's approach */
27
+ description?: string;
28
+ }
29
+ /**
30
+ * Result of a single speculative dream branch.
31
+ */
32
+ export interface StrategyResult {
33
+ /** The strategy that was executed */
34
+ strategy: DreamStrategy;
35
+ /** The branch used */
36
+ branch: Branch;
37
+ /** Validation result against baseline */
38
+ validation: ValidationResult;
39
+ /** Whether this strategy was selected as the winner */
40
+ selected: boolean;
41
+ /** Execution duration in milliseconds */
42
+ durationMs: number;
43
+ }
44
+ /**
45
+ * Result of the full speculative dreaming process.
46
+ */
47
+ export interface SpeculativeDreamResult {
48
+ /** All strategy results, including winner and losers */
49
+ strategies: StrategyResult[];
50
+ /** The winning strategy (or null if all failed validation) */
51
+ winner: StrategyResult | null;
52
+ /** Total wall-clock time */
53
+ totalDurationMs: number;
54
+ }
55
+ /**
56
+ * Callback that executes a dream cycle with the given activation config.
57
+ * The implementation should use the provided config overrides when running
58
+ * spreading activation. It returns the number of insights generated.
59
+ */
60
+ export type DreamExecutor = (activationConfigOverrides: Partial<ActivationConfig>) => Promise<number>;
61
+ /**
62
+ * Predefined dream strategies with different parameter profiles.
63
+ */
64
+ export declare const BUILT_IN_STRATEGIES: DreamStrategy[];
65
+ /**
66
+ * Runs multiple dream strategies in separate RVCOW branches and selects the best.
67
+ *
68
+ * Because SQLite savepoints are sequential (not truly parallel), strategies
69
+ * are executed one at a time but each in its own savepoint. The branch manager
70
+ * ensures that failed strategies leave no trace in the database.
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const dreamer = new SpeculativeDreamer(db);
75
+ * const result = await dreamer.dream(
76
+ * BUILT_IN_STRATEGIES,
77
+ * async (configOverrides) => {
78
+ * // Run dream with configOverrides applied
79
+ * return insightCount;
80
+ * }
81
+ * );
82
+ * if (result.winner) {
83
+ * console.log(`Best strategy: ${result.winner.strategy.name}`);
84
+ * }
85
+ * ```
86
+ */
87
+ export declare class SpeculativeDreamer {
88
+ private readonly db;
89
+ private readonly branchManager;
90
+ constructor(db: DatabaseType, thresholds?: ValidationThresholds);
91
+ /**
92
+ * Run multiple dream strategies sequentially in separate RVCOW branches,
93
+ * then merge the best-performing one and discard the rest.
94
+ *
95
+ * Strategy execution flow:
96
+ * 1. Capture baseline before any strategy runs
97
+ * 2. For each strategy:
98
+ * a. Create branch (SAVEPOINT)
99
+ * b. Execute dream with strategy params
100
+ * c. Validate branch against baseline
101
+ * d. Discard branch (ROLLBACK) -- we keep results in memory only
102
+ * 3. Replay the winning strategy in a final branch and merge it
103
+ *
104
+ * Note: Because we must discard each branch before starting the next
105
+ * (SQLite savepoint semantics), the winning strategy is re-executed
106
+ * in step 3. This is acceptable because dream cycles are deterministic
107
+ * given the same input state and parameters.
108
+ *
109
+ * @param strategies - 2-3 strategies to compete
110
+ * @param executor - Callback that runs the dream with given config
111
+ * @returns Result with winner and all strategy details
112
+ */
113
+ dream(strategies: DreamStrategy[], executor: DreamExecutor): Promise<SpeculativeDreamResult>;
114
+ /**
115
+ * Get the underlying branch manager (for event subscription).
116
+ */
117
+ getBranchManager(): RVCOWBranchManager;
118
+ /**
119
+ * Execute a single strategy in a branch, validate, then discard.
120
+ * We discard because we need to try all strategies from the same baseline.
121
+ */
122
+ private executeStrategy;
123
+ /**
124
+ * Score a validation result for comparison.
125
+ * Higher score = better dream result.
126
+ */
127
+ private scoreValidation;
128
+ }
129
+ //# sourceMappingURL=speculative-dreamer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speculative-dreamer.d.ts","sourceRoot":"","sources":["../../../src/learning/dream/speculative-dreamer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,KAAK,MAAM,EAEX,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EAE1B,MAAM,2BAA2B,CAAC;AAMnC;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAC;IAEb,yCAAyC;IACzC,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAE5C,sDAAsD;IACt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 * ADR-069: RVCOW Dream Cycle Branching
4
+ *
5
+ * Runs 2-3 dream strategies in parallel RVCOW branches, each with
6
+ * different parameters (decay rates, spread factors, noise levels).
7
+ * After all strategies complete, compares validation scores and merges
8
+ * the best-performing branch. All other branches are discarded.
9
+ *
10
+ * This implements the "adversarial dream" concept from the Six Thinking
11
+ * Hats analysis, where diverse strategies compete and the best wins.
12
+ *
13
+ * @module v3/learning/dream/speculative-dreamer
14
+ */
15
+ import { RVCOWBranchManager, DEFAULT_VALIDATION_THRESHOLDS, } from './rvcow-branch-manager.js';
16
+ // ============================================================================
17
+ // Built-in Strategies
18
+ // ============================================================================
19
+ /**
20
+ * Predefined dream strategies with different parameter profiles.
21
+ */
22
+ export const BUILT_IN_STRATEGIES = [
23
+ {
24
+ name: 'aggressive-exploration',
25
+ description: 'High noise, fast decay -- explores widely but forgets quickly',
26
+ activationConfig: {
27
+ decayRate: 0.2,
28
+ spreadFactor: 0.7,
29
+ noiseLevel: 0.15,
30
+ maxIterations: 30,
31
+ },
32
+ },
33
+ {
34
+ name: 'conservative-consolidation',
35
+ description: 'Low noise, slow decay -- strengthens existing associations',
36
+ activationConfig: {
37
+ decayRate: 0.05,
38
+ spreadFactor: 0.3,
39
+ noiseLevel: 0.02,
40
+ maxIterations: 15,
41
+ },
42
+ },
43
+ {
44
+ name: 'balanced-discovery',
45
+ description: 'Moderate parameters -- balanced between exploration and consolidation',
46
+ activationConfig: {
47
+ decayRate: 0.1,
48
+ spreadFactor: 0.5,
49
+ noiseLevel: 0.05,
50
+ maxIterations: 20,
51
+ },
52
+ },
53
+ ];
54
+ // ============================================================================
55
+ // SpeculativeDreamer
56
+ // ============================================================================
57
+ /**
58
+ * Runs multiple dream strategies in separate RVCOW branches and selects the best.
59
+ *
60
+ * Because SQLite savepoints are sequential (not truly parallel), strategies
61
+ * are executed one at a time but each in its own savepoint. The branch manager
62
+ * ensures that failed strategies leave no trace in the database.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const dreamer = new SpeculativeDreamer(db);
67
+ * const result = await dreamer.dream(
68
+ * BUILT_IN_STRATEGIES,
69
+ * async (configOverrides) => {
70
+ * // Run dream with configOverrides applied
71
+ * return insightCount;
72
+ * }
73
+ * );
74
+ * if (result.winner) {
75
+ * console.log(`Best strategy: ${result.winner.strategy.name}`);
76
+ * }
77
+ * ```
78
+ */
79
+ export class SpeculativeDreamer {
80
+ db;
81
+ branchManager;
82
+ constructor(db, thresholds) {
83
+ this.db = db;
84
+ this.branchManager = new RVCOWBranchManager(db, thresholds ?? DEFAULT_VALIDATION_THRESHOLDS);
85
+ }
86
+ /**
87
+ * Run multiple dream strategies sequentially in separate RVCOW branches,
88
+ * then merge the best-performing one and discard the rest.
89
+ *
90
+ * Strategy execution flow:
91
+ * 1. Capture baseline before any strategy runs
92
+ * 2. For each strategy:
93
+ * a. Create branch (SAVEPOINT)
94
+ * b. Execute dream with strategy params
95
+ * c. Validate branch against baseline
96
+ * d. Discard branch (ROLLBACK) -- we keep results in memory only
97
+ * 3. Replay the winning strategy in a final branch and merge it
98
+ *
99
+ * Note: Because we must discard each branch before starting the next
100
+ * (SQLite savepoint semantics), the winning strategy is re-executed
101
+ * in step 3. This is acceptable because dream cycles are deterministic
102
+ * given the same input state and parameters.
103
+ *
104
+ * @param strategies - 2-3 strategies to compete
105
+ * @param executor - Callback that runs the dream with given config
106
+ * @returns Result with winner and all strategy details
107
+ */
108
+ async dream(strategies, executor) {
109
+ if (strategies.length < 1) {
110
+ throw new Error('At least one strategy is required');
111
+ }
112
+ if (strategies.length > 5) {
113
+ throw new Error('Maximum 5 strategies allowed to limit resource usage');
114
+ }
115
+ const totalStart = Date.now();
116
+ const baseline = this.branchManager.captureBaseline();
117
+ const results = [];
118
+ // Execute each strategy in its own branch, collect validation results
119
+ for (const strategy of strategies) {
120
+ const result = await this.executeStrategy(strategy, baseline, executor);
121
+ results.push(result);
122
+ }
123
+ // Find the best passing strategy
124
+ const passingResults = results.filter(r => r.validation.passed);
125
+ let winner = null;
126
+ if (passingResults.length > 0) {
127
+ // Score strategies: prefer higher confidence delta, then more patterns
128
+ winner = passingResults.reduce((best, current) => {
129
+ const bestScore = this.scoreValidation(best.validation);
130
+ const currentScore = this.scoreValidation(current.validation);
131
+ return currentScore > bestScore ? current : best;
132
+ });
133
+ // Re-execute the winning strategy and merge it
134
+ const finalBranch = this.branchManager.createBranch(`dream-final-${winner.strategy.name}-${Date.now()}`);
135
+ try {
136
+ await executor(winner.strategy.activationConfig);
137
+ this.branchManager.mergeBranch(finalBranch);
138
+ winner.selected = true;
139
+ }
140
+ catch {
141
+ // If re-execution fails, discard and report no winner
142
+ this.branchManager.discardBranch(finalBranch);
143
+ winner.selected = false;
144
+ winner = null;
145
+ }
146
+ }
147
+ return {
148
+ strategies: results,
149
+ winner,
150
+ totalDurationMs: Date.now() - totalStart,
151
+ };
152
+ }
153
+ /**
154
+ * Get the underlying branch manager (for event subscription).
155
+ */
156
+ getBranchManager() {
157
+ return this.branchManager;
158
+ }
159
+ // --------------------------------------------------------------------------
160
+ // Private Helpers
161
+ // --------------------------------------------------------------------------
162
+ /**
163
+ * Execute a single strategy in a branch, validate, then discard.
164
+ * We discard because we need to try all strategies from the same baseline.
165
+ */
166
+ async executeStrategy(strategy, baseline, executor) {
167
+ const branchName = `dream-spec-${strategy.name}-${Date.now()}`;
168
+ const branch = this.branchManager.createBranch(branchName);
169
+ const start = Date.now();
170
+ try {
171
+ await executor(strategy.activationConfig);
172
+ const validation = this.branchManager.validateBranch(branch, baseline);
173
+ // Discard so next strategy starts from same baseline
174
+ this.branchManager.discardBranch(branch);
175
+ return {
176
+ strategy,
177
+ branch,
178
+ validation,
179
+ selected: false,
180
+ durationMs: Date.now() - start,
181
+ };
182
+ }
183
+ catch {
184
+ // Dream execution failed -- discard and mark as failed
185
+ this.branchManager.discardBranch(branch);
186
+ return {
187
+ strategy,
188
+ branch,
189
+ validation: {
190
+ passed: false,
191
+ reason: 'Dream execution threw an error',
192
+ patternCountDelta: 0,
193
+ avgConfidenceDelta: 0,
194
+ highConfidenceLost: 0,
195
+ postDreamMetrics: baseline,
196
+ },
197
+ selected: false,
198
+ durationMs: Date.now() - start,
199
+ };
200
+ }
201
+ }
202
+ /**
203
+ * Score a validation result for comparison.
204
+ * Higher score = better dream result.
205
+ */
206
+ scoreValidation(v) {
207
+ // Weighted scoring: confidence improvement matters most,
208
+ // then pattern growth, penalize high-confidence loss
209
+ return (v.avgConfidenceDelta * 100 +
210
+ v.patternCountDelta * 0.1 -
211
+ v.highConfidenceLost * 5);
212
+ }
213
+ }
214
+ //# sourceMappingURL=speculative-dreamer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speculative-dreamer.js","sourceRoot":"","sources":["../../../src/learning/dream/speculative-dreamer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EACL,kBAAkB,EAKlB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AA+DnC,+EAA+E;AAC/E,sBAAsB;AACtB,+EAA+E;AAE/E;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAoB;IAClD;QACE,IAAI,EAAE,wBAAwB;QAC9B,WAAW,EAAE,+DAA+D;QAC5E,gBAAgB,EAAE;YAChB,SAAS,EAAE,GAAG;YACd,YAAY,EAAE,GAAG;YACjB,UAAU,EAAE,IAAI;YAChB,aAAa,EAAE,EAAE;SAClB;KACF;IACD;QACE,IAAI,EAAE,4BAA4B;QAClC,WAAW,EAAE,4DAA4D;QACzE,gBAAgB,EAAE;YAChB,SAAS,EAAE,IAAI;YACf,YAAY,EAAE,GAAG;YACjB,UAAU,EAAE,IAAI;YAChB,aAAa,EAAE,EAAE;SAClB;KACF;IACD;QACE,IAAI,EAAE,oBAAoB;QAC1B,WAAW,EAAE,uEAAuE;QACpF,gBAAgB,EAAE;YAChB,SAAS,EAAE,GAAG;YACd,YAAY,EAAE,GAAG;YACjB,UAAU,EAAE,IAAI;YAChB,aAAa,EAAE,EAAE;SAClB;KAC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,GAAG,GAAG;YACzB,CAAC,CAAC,kBAAkB,GAAG,CAAC,CACzB,CAAC;IACJ,CAAC;CACF"}
@@ -18,6 +18,7 @@ import type { Result } from '../shared/types/index.js';
18
18
  import { QEPattern, QEPatternContext, QEDomain, ProgrammingLanguage, TestFramework, CreateQEPatternOptions } from './qe-patterns.js';
19
19
  import { QEGuidance, checkAntiPatterns } from './qe-guidance.js';
20
20
  import { PatternSearchOptions, PatternSearchResult } from './pattern-store.js';
21
+ import type { RvfDualWriter } from '../integrations/ruvector/rvf-dual-writer.js';
21
22
  /**
22
23
  * QEReasoningBank configuration
23
24
  */
@@ -44,6 +45,8 @@ export interface QEReasoningBankConfig {
44
45
  patternStore?: Partial<import('./pattern-store.js').PatternStoreConfig>;
45
46
  /** Coherence energy threshold for pattern promotion (ADR-052) */
46
47
  coherenceThreshold?: number;
48
+ /** Optional RVF dual-writer for vector replication (Phase 3) */
49
+ rvfDualWriter?: RvfDualWriter;
47
50
  }
48
51
  /**
49
52
  * Default configuration
@@ -208,11 +211,17 @@ export declare class QEReasoningBank implements IQEReasoningBank {
208
211
  private patternStore;
209
212
  private initialized;
210
213
  private sqliteStore;
214
+ private rvfDualWriter;
211
215
  /**
212
216
  * Lazy getter for SQLitePatternStore — persists pattern usage/promotion
213
217
  * to the qe_patterns table (same DB as UnifiedMemory).
214
218
  */
215
219
  private getSqliteStore;
220
+ /**
221
+ * Set the RVF dual-writer at runtime (Phase 3 vector replication).
222
+ * When set, pattern writes will be replicated to the RVF store best-effort.
223
+ */
224
+ setRvfDualWriter(writer: RvfDualWriter): void;
216
225
  private stats;
217
226
  private readonly agentCapabilities;
218
227
  constructor(memory: MemoryBackend, eventBus?: EventBus | undefined, config?: Partial<QEReasoningBankConfig>, coherenceService?: import("../integrations/coherence/coherence-service.js").ICoherenceService | undefined);