agentic-qe 3.6.18 → 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 (166) 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 +53 -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 +4604 -2486
  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/commands/hooks.js +4 -4
  19. package/v3/dist/cli/commands/hooks.js.map +1 -1
  20. package/v3/dist/cli/commands/learning-helpers.js +2 -2
  21. package/v3/dist/cli/commands/learning-helpers.js.map +1 -1
  22. package/v3/dist/cli/handlers/brain-handler.d.ts +22 -0
  23. package/v3/dist/cli/handlers/brain-handler.d.ts.map +1 -0
  24. package/v3/dist/cli/handlers/brain-handler.js +148 -0
  25. package/v3/dist/cli/handlers/brain-handler.js.map +1 -0
  26. package/v3/dist/cli/handlers/index.d.ts +1 -0
  27. package/v3/dist/cli/handlers/index.d.ts.map +1 -1
  28. package/v3/dist/cli/handlers/index.js +1 -0
  29. package/v3/dist/cli/handlers/index.js.map +1 -1
  30. package/v3/dist/coordination/queen-coordinator.d.ts.map +1 -1
  31. package/v3/dist/coordination/queen-coordinator.js +18 -12
  32. package/v3/dist/coordination/queen-coordinator.js.map +1 -1
  33. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts +31 -44
  34. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts.map +1 -1
  35. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js +73 -178
  36. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js.map +1 -1
  37. package/v3/dist/domains/quality-assessment/coordinator.d.ts.map +1 -1
  38. package/v3/dist/domains/quality-assessment/coordinator.js +8 -0
  39. package/v3/dist/domains/quality-assessment/coordinator.js.map +1 -1
  40. package/v3/dist/domains/test-execution/coordinator.d.ts +14 -0
  41. package/v3/dist/domains/test-execution/coordinator.d.ts.map +1 -1
  42. package/v3/dist/domains/test-execution/coordinator.js +18 -0
  43. package/v3/dist/domains/test-execution/coordinator.js.map +1 -1
  44. package/v3/dist/domains/test-execution/services/index.d.ts +1 -0
  45. package/v3/dist/domains/test-execution/services/index.d.ts.map +1 -1
  46. package/v3/dist/domains/test-execution/services/index.js +1 -0
  47. package/v3/dist/domains/test-execution/services/index.js.map +1 -1
  48. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.d.ts +118 -0
  49. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.d.ts.map +1 -0
  50. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.js +358 -0
  51. package/v3/dist/domains/test-execution/services/mincut-test-optimizer.js.map +1 -0
  52. package/v3/dist/domains/test-generation/generators/base-test-generator.d.ts.map +1 -1
  53. package/v3/dist/domains/test-generation/generators/base-test-generator.js +13 -3
  54. package/v3/dist/domains/test-generation/generators/base-test-generator.js.map +1 -1
  55. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.d.ts.map +1 -1
  56. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.js +12 -3
  57. package/v3/dist/domains/test-generation/generators/jest-vitest-generator.js.map +1 -1
  58. package/v3/dist/domains/test-generation/generators/mocha-generator.d.ts.map +1 -1
  59. package/v3/dist/domains/test-generation/generators/mocha-generator.js +22 -6
  60. package/v3/dist/domains/test-generation/generators/mocha-generator.js.map +1 -1
  61. package/v3/dist/domains/test-generation/generators/node-test-generator.d.ts.map +1 -1
  62. package/v3/dist/domains/test-generation/generators/node-test-generator.js +11 -3
  63. package/v3/dist/domains/test-generation/generators/node-test-generator.js.map +1 -1
  64. package/v3/dist/domains/test-generation/generators/pytest-generator.d.ts.map +1 -1
  65. package/v3/dist/domains/test-generation/generators/pytest-generator.js +22 -6
  66. package/v3/dist/domains/test-generation/generators/pytest-generator.js.map +1 -1
  67. package/v3/dist/integrations/agentic-flow/reasoning-bank/index.d.ts.map +1 -1
  68. package/v3/dist/integrations/agentic-flow/reasoning-bank/index.js +14 -0
  69. package/v3/dist/integrations/agentic-flow/reasoning-bank/index.js.map +1 -1
  70. package/v3/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.d.ts +5 -0
  71. package/v3/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.d.ts.map +1 -1
  72. package/v3/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +27 -0
  73. package/v3/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js.map +1 -1
  74. package/v3/dist/integrations/ruvector/brain-exporter.d.ts +66 -0
  75. package/v3/dist/integrations/ruvector/brain-exporter.d.ts.map +1 -0
  76. package/v3/dist/integrations/ruvector/brain-exporter.js +537 -0
  77. package/v3/dist/integrations/ruvector/brain-exporter.js.map +1 -0
  78. package/v3/dist/integrations/ruvector/index.d.ts +4 -0
  79. package/v3/dist/integrations/ruvector/index.d.ts.map +1 -1
  80. package/v3/dist/integrations/ruvector/index.js +5 -0
  81. package/v3/dist/integrations/ruvector/index.js.map +1 -1
  82. package/v3/dist/integrations/ruvector/mincut-wrapper.d.ts +204 -0
  83. package/v3/dist/integrations/ruvector/mincut-wrapper.d.ts.map +1 -0
  84. package/v3/dist/integrations/ruvector/mincut-wrapper.js +310 -0
  85. package/v3/dist/integrations/ruvector/mincut-wrapper.js.map +1 -0
  86. package/v3/dist/integrations/ruvector/rvf-dual-writer.d.ts +141 -0
  87. package/v3/dist/integrations/ruvector/rvf-dual-writer.d.ts.map +1 -0
  88. package/v3/dist/integrations/ruvector/rvf-dual-writer.js +367 -0
  89. package/v3/dist/integrations/ruvector/rvf-dual-writer.js.map +1 -0
  90. package/v3/dist/integrations/ruvector/rvf-native-adapter.d.ts +60 -0
  91. package/v3/dist/integrations/ruvector/rvf-native-adapter.d.ts.map +1 -0
  92. package/v3/dist/integrations/ruvector/rvf-native-adapter.js +240 -0
  93. package/v3/dist/integrations/ruvector/rvf-native-adapter.js.map +1 -0
  94. package/v3/dist/kernel/hnsw-adapter.d.ts +99 -0
  95. package/v3/dist/kernel/hnsw-adapter.d.ts.map +1 -0
  96. package/v3/dist/kernel/hnsw-adapter.js +218 -0
  97. package/v3/dist/kernel/hnsw-adapter.js.map +1 -0
  98. package/v3/dist/kernel/hnsw-index-provider.d.ts +90 -0
  99. package/v3/dist/kernel/hnsw-index-provider.d.ts.map +1 -0
  100. package/v3/dist/kernel/hnsw-index-provider.js +23 -0
  101. package/v3/dist/kernel/hnsw-index-provider.js.map +1 -0
  102. package/v3/dist/kernel/progressive-hnsw-backend.d.ts +67 -0
  103. package/v3/dist/kernel/progressive-hnsw-backend.d.ts.map +1 -0
  104. package/v3/dist/kernel/progressive-hnsw-backend.js +266 -0
  105. package/v3/dist/kernel/progressive-hnsw-backend.js.map +1 -0
  106. package/v3/dist/kernel/unified-memory-hnsw.d.ts +71 -0
  107. package/v3/dist/kernel/unified-memory-hnsw.d.ts.map +1 -1
  108. package/v3/dist/kernel/unified-memory-hnsw.js +87 -0
  109. package/v3/dist/kernel/unified-memory-hnsw.js.map +1 -1
  110. package/v3/dist/kernel/unified-memory-schemas.d.ts +1 -0
  111. package/v3/dist/kernel/unified-memory-schemas.d.ts.map +1 -1
  112. package/v3/dist/kernel/unified-memory-schemas.js +16 -0
  113. package/v3/dist/kernel/unified-memory-schemas.js.map +1 -1
  114. package/v3/dist/kernel/unified-memory.d.ts +5 -0
  115. package/v3/dist/kernel/unified-memory.d.ts.map +1 -1
  116. package/v3/dist/kernel/unified-memory.js +18 -0
  117. package/v3/dist/kernel/unified-memory.js.map +1 -1
  118. package/v3/dist/learning/dream/dream-engine.d.ts +16 -0
  119. package/v3/dist/learning/dream/dream-engine.d.ts.map +1 -1
  120. package/v3/dist/learning/dream/dream-engine.js +70 -0
  121. package/v3/dist/learning/dream/dream-engine.js.map +1 -1
  122. package/v3/dist/learning/dream/index.d.ts +2 -0
  123. package/v3/dist/learning/dream/index.d.ts.map +1 -1
  124. package/v3/dist/learning/dream/index.js +8 -0
  125. package/v3/dist/learning/dream/index.js.map +1 -1
  126. package/v3/dist/learning/dream/rvcow-branch-manager.d.ts +170 -0
  127. package/v3/dist/learning/dream/rvcow-branch-manager.d.ts.map +1 -0
  128. package/v3/dist/learning/dream/rvcow-branch-manager.js +263 -0
  129. package/v3/dist/learning/dream/rvcow-branch-manager.js.map +1 -0
  130. package/v3/dist/learning/dream/speculative-dreamer.d.ts +129 -0
  131. package/v3/dist/learning/dream/speculative-dreamer.d.ts.map +1 -0
  132. package/v3/dist/learning/dream/speculative-dreamer.js +214 -0
  133. package/v3/dist/learning/dream/speculative-dreamer.js.map +1 -0
  134. package/v3/dist/learning/pattern-store.js +1 -1
  135. package/v3/dist/learning/pattern-store.js.map +1 -1
  136. package/v3/dist/learning/qe-reasoning-bank.d.ts +9 -0
  137. package/v3/dist/learning/qe-reasoning-bank.d.ts.map +1 -1
  138. package/v3/dist/learning/qe-reasoning-bank.js +51 -2
  139. package/v3/dist/learning/qe-reasoning-bank.js.map +1 -1
  140. package/v3/dist/mcp/bundle.js +146048 -140244
  141. package/v3/dist/mcp/handlers/core-handlers.d.ts.map +1 -1
  142. package/v3/dist/mcp/handlers/core-handlers.js +37 -0
  143. package/v3/dist/mcp/handlers/core-handlers.js.map +1 -1
  144. package/v3/dist/mcp/handlers/memory-handlers.d.ts.map +1 -1
  145. package/v3/dist/mcp/handlers/memory-handlers.js +27 -36
  146. package/v3/dist/mcp/handlers/memory-handlers.js.map +1 -1
  147. package/v3/dist/mcp/handlers/task-handlers.d.ts +9 -0
  148. package/v3/dist/mcp/handlers/task-handlers.d.ts.map +1 -1
  149. package/v3/dist/mcp/handlers/task-handlers.js +58 -4
  150. package/v3/dist/mcp/handlers/task-handlers.js.map +1 -1
  151. package/v3/dist/mcp/services/mincut-routing-service.d.ts +148 -0
  152. package/v3/dist/mcp/services/mincut-routing-service.d.ts.map +1 -0
  153. package/v3/dist/mcp/services/mincut-routing-service.js +198 -0
  154. package/v3/dist/mcp/services/mincut-routing-service.js.map +1 -0
  155. package/v3/dist/mcp/services/task-router.d.ts +4 -0
  156. package/v3/dist/mcp/services/task-router.d.ts.map +1 -1
  157. package/v3/dist/mcp/services/task-router.js +57 -15
  158. package/v3/dist/mcp/services/task-router.js.map +1 -1
  159. package/v3/dist/mcp/tools/coherence/audit.js +1 -1
  160. package/v3/dist/mcp/types.d.ts +10 -0
  161. package/v3/dist/mcp/types.d.ts.map +1 -1
  162. package/v3/dist/monitoring/structural-health.d.ts +142 -0
  163. package/v3/dist/monitoring/structural-health.d.ts.map +1 -0
  164. package/v3/dist/monitoring/structural-health.js +201 -0
  165. package/v3/dist/monitoring/structural-health.js.map +1 -0
  166. package/v3/package.json +1 -1
@@ -0,0 +1,170 @@
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
+ import type { Database as DatabaseType } from 'better-sqlite3';
19
+ /**
20
+ * Represents an active RVCOW branch backed by a SQLite savepoint.
21
+ */
22
+ export interface Branch {
23
+ /** Unique branch name (also the savepoint name) */
24
+ name: string;
25
+ /** When the branch was created */
26
+ createdAt: Date;
27
+ /** Current status */
28
+ status: 'active' | 'merged' | 'discarded';
29
+ /** Snapshot of pattern metrics at branch creation time */
30
+ baselineSnapshot: QualityBaseline;
31
+ }
32
+ /**
33
+ * Quality baseline captured before a dream cycle.
34
+ * Used to validate that the dream did not degrade knowledge quality.
35
+ */
36
+ export interface QualityBaseline {
37
+ /** Total number of patterns */
38
+ patternCount: number;
39
+ /** Average confidence across all patterns */
40
+ avgConfidence: number;
41
+ /** Number of high-confidence patterns (confidence >= 0.8) */
42
+ highConfidenceCount: number;
43
+ /** Timestamp of baseline capture */
44
+ capturedAt: Date;
45
+ }
46
+ /**
47
+ * Result of validating a branch against a quality baseline.
48
+ */
49
+ export interface ValidationResult {
50
+ /** Whether the branch passed validation */
51
+ passed: boolean;
52
+ /** Human-readable reason */
53
+ reason: string;
54
+ /** Delta in pattern count (positive = patterns added) */
55
+ patternCountDelta: number;
56
+ /** Delta in average confidence */
57
+ avgConfidenceDelta: number;
58
+ /** Number of high-confidence patterns that were lost */
59
+ highConfidenceLost: number;
60
+ /** Post-dream metrics for comparison */
61
+ postDreamMetrics: QualityBaseline;
62
+ }
63
+ /**
64
+ * Thresholds for dream branch validation.
65
+ */
66
+ export interface ValidationThresholds {
67
+ /** Maximum allowed decrease in pattern count (as fraction). Default: 0.05 (5%) */
68
+ maxPatternCountDrop: number;
69
+ /** Maximum allowed decrease in average confidence. Default: 0.02 */
70
+ maxAvgConfidenceDrop: number;
71
+ /** Maximum fraction of high-confidence patterns that can be lost. Default: 0.05 (5%) */
72
+ maxHighConfidenceLoss: number;
73
+ }
74
+ /** Default validation thresholds */
75
+ export declare const DEFAULT_VALIDATION_THRESHOLDS: ValidationThresholds;
76
+ /**
77
+ * Events emitted by the branch manager.
78
+ */
79
+ export type BranchEvent = 'dream:branch_created' | 'dream:branch_merged' | 'dream:branch_discarded';
80
+ export type BranchEventListener = (event: BranchEvent, branch: Branch, detail?: ValidationResult) => void;
81
+ /**
82
+ * Manages RVCOW branches for dream cycles using SQLite savepoints.
83
+ *
84
+ * Usage:
85
+ * ```typescript
86
+ * const manager = new RVCOWBranchManager(db);
87
+ * const branch = manager.createBranch('dream-123');
88
+ * // ... run dream logic ...
89
+ * const result = manager.validateBranch(branch, baseline);
90
+ * if (result.passed) {
91
+ * manager.mergeBranch(branch);
92
+ * } else {
93
+ * manager.discardBranch(branch);
94
+ * }
95
+ * ```
96
+ */
97
+ export declare class RVCOWBranchManager {
98
+ private readonly db;
99
+ private readonly thresholds;
100
+ private activeBranches;
101
+ private listeners;
102
+ /** Optional RVF native adapter for COW fork snapshots of dream state */
103
+ private rvfAdapter?;
104
+ /** When true and rvfAdapter is set, createBranch() also forks an RVF snapshot */
105
+ private useRvfFork;
106
+ constructor(db: DatabaseType, thresholds?: ValidationThresholds);
107
+ /**
108
+ * Set an RVF native adapter for supplementary COW fork snapshots.
109
+ * When set with useRvfFork=true, createBranch() will additionally
110
+ * fork a portable .rvf snapshot alongside the SQLite savepoint.
111
+ * SQLite savepoints remain the primary branching mechanism.
112
+ */
113
+ setRvfAdapter(adapter: any, useRvfFork?: boolean): void;
114
+ /**
115
+ * Create a new RVCOW branch by issuing a SQLite SAVEPOINT.
116
+ * Captures a quality baseline snapshot before the savepoint.
117
+ *
118
+ * @param name - Unique branch name (used as savepoint identifier)
119
+ * @returns The created Branch
120
+ * @throws If a branch with this name already exists
121
+ */
122
+ createBranch(name: string): Branch;
123
+ /**
124
+ * Validate a branch by comparing post-dream metrics against the baseline.
125
+ *
126
+ * Checks:
127
+ * 1. Pattern count did not decrease beyond threshold
128
+ * 2. Average confidence did not drop beyond threshold
129
+ * 3. No excessive high-confidence patterns were quarantined/removed
130
+ *
131
+ * @param branch - The branch to validate
132
+ * @param baseline - The quality baseline to validate against (defaults to branch's own baseline)
133
+ * @returns Validation result with pass/fail and metrics
134
+ */
135
+ validateBranch(branch: Branch, baseline?: QualityBaseline): ValidationResult;
136
+ /**
137
+ * Merge a branch by releasing its savepoint.
138
+ * All changes made within the branch become permanent.
139
+ *
140
+ * @param branch - The branch to merge
141
+ */
142
+ mergeBranch(branch: Branch): void;
143
+ /**
144
+ * Discard a branch by rolling back to its savepoint.
145
+ * All changes made within the branch are undone.
146
+ *
147
+ * @param branch - The branch to discard
148
+ */
149
+ discardBranch(branch: Branch): void;
150
+ /**
151
+ * List all active branches.
152
+ */
153
+ listBranches(): Branch[];
154
+ /**
155
+ * Register a listener for branch events.
156
+ */
157
+ onEvent(listener: BranchEventListener): void;
158
+ /**
159
+ * Remove a previously registered listener.
160
+ */
161
+ offEvent(listener: BranchEventListener): void;
162
+ /**
163
+ * Capture a quality baseline from the current state of qe_patterns.
164
+ */
165
+ captureBaseline(): QualityBaseline;
166
+ private ensureBranchActive;
167
+ private sanitizeSavepointName;
168
+ private emit;
169
+ }
170
+ //# sourceMappingURL=rvcow-branch-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rvcow-branch-manager.d.ts","sourceRoot":"","sources":["../../../src/learning/dream/rvcow-branch-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAM/D;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAC;IAEb,kCAAkC;IAClC,SAAS,EAAE,IAAI,CAAC;IAEhB,qBAAqB;IACrB,MAAM,EAAE,QAAQ,GAAG,QAAQ,GAAG,WAAW,CAAC;IAE1C,0DAA0D;IAC1D,gBAAgB,EAAE,eAAe,CAAC;CACnC;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,+B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AiF;IACjF,OAAO,CAAC,UAAU,CAAS;gBAGR,EAAE,EAAE,YAAY,EAChB,UAAU,GAAE,oBAAoD;IAGnF;;;;;OAKG;IAEH,aAAa,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,UAAO,GAAG,IAAI;IASpD;;;;;;;OAOG;IACH,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAoClC;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,eAAe,GAAG,gBAAgB;IA4D5E;;;;;OAKG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAWjC;;;;;OAKG;IACH,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAanC;;OAEG;IACH,YAAY,IAAI,MAAM,EAAE;IAQxB;;OAEG;IACH,OAAO,CAAC,QAAQ,EAAE,mBAAmB,GAAG,IAAI;IAI5C;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,GAAG,IAAI;IAW7C;;OAEG;IACH,eAAe,IAAI,eAAe;IAyBlC,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,IAAI;CASb"}
@@ -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;IAZX,cAAc,GAAwB,IAAI,GAAG,EAAE,CAAC;IAChD,SAAS,GAA0B,EAAE,CAAC;IAE9C,wEAAwE;IACxE,8DAA8D;IACtD,UAAU,CAAO;IAEzB,iFAAiF;IACzE,UAAU,GAAG,KAAK,CAAC;IAE3B,YACmB,EAAgB,EAChB,aAAmC,6BAA6B;QADhE,OAAE,GAAF,EAAE,CAAc;QAChB,eAAU,GAAV,UAAU,CAAsD;IAChF,CAAC;IAEJ;;;;;OAKG;IACH,8DAA8D;IAC9D,aAAa,CAAC,OAAY,EAAE,UAAU,GAAG,IAAI;QAC3C,IAAI,CAAC,UAAU,GAAG,OAAO,CAA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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;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,QAAQ,EAAE,aAAa,CAAC;IAExB,sBAAsB;IACtB,MAAM,EAAE,MAAM,CAAC;IAEf,yCAAyC;IACzC,UAAU,EAAE,gBAAgB,CAAC;IAE7B,uDAAuD;IACvD,QAAQ,EAAE,OAAO,CAAC;IAElB,yCAAyC;IACzC,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,wDAAwD;IACxD,UAAU,EAAE,cAAc,EAAE,CAAC;IAE7B,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