agentic-qe 3.8.5 → 3.8.6

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 (32) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/dist/cli/bundle.js +543 -543
  3. package/dist/coordination/mincut/phase-executor.d.ts +27 -0
  4. package/dist/coordination/mincut/phase-executor.js +70 -0
  5. package/dist/coordination/mincut/time-crystal-analysis.d.ts +35 -0
  6. package/dist/coordination/mincut/time-crystal-analysis.js +237 -0
  7. package/dist/coordination/mincut/time-crystal-persistence.d.ts +35 -0
  8. package/dist/coordination/mincut/time-crystal-persistence.js +81 -0
  9. package/dist/coordination/mincut/time-crystal-scheduling.d.ts +34 -0
  10. package/dist/coordination/mincut/time-crystal-scheduling.js +213 -0
  11. package/dist/coordination/mincut/time-crystal-types.d.ts +278 -0
  12. package/dist/coordination/mincut/time-crystal-types.js +67 -0
  13. package/dist/coordination/mincut/time-crystal.d.ts +8 -438
  14. package/dist/coordination/mincut/time-crystal.js +87 -905
  15. package/dist/learning/agent-routing.d.ts +53 -0
  16. package/dist/learning/agent-routing.js +142 -0
  17. package/dist/learning/embedding-utils.d.ts +34 -0
  18. package/dist/learning/embedding-utils.js +95 -0
  19. package/dist/learning/pattern-promotion.d.ts +63 -0
  20. package/dist/learning/pattern-promotion.js +187 -0
  21. package/dist/learning/pretrained-patterns.d.ts +14 -0
  22. package/dist/learning/pretrained-patterns.js +726 -0
  23. package/dist/learning/qe-reasoning-bank-types.d.ts +174 -0
  24. package/dist/learning/qe-reasoning-bank-types.js +24 -0
  25. package/dist/learning/qe-reasoning-bank.d.ts +9 -192
  26. package/dist/learning/qe-reasoning-bank.js +48 -1093
  27. package/dist/mcp/bundle.js +320 -320
  28. package/dist/shared/security/command-validator.js +2 -2
  29. package/dist/shared/security/input-sanitizer.js +1 -1
  30. package/dist/shared/security/path-traversal-validator.js +1 -1
  31. package/dist/shared/security/regex-safety-validator.js +7 -7
  32. package/package.json +1 -1
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Agentic QE v3 - Agent Routing
3
+ * ADR-021: QE ReasoningBank for Pattern Learning
4
+ *
5
+ * Static agent capability mapping and routing score calculation
6
+ * used by QEReasoningBank.routeTask().
7
+ */
8
+ import type { QEDomain } from './qe-patterns.js';
9
+ /**
10
+ * Profile describing an agent's domains, capabilities, and performance.
11
+ */
12
+ export interface AgentCapabilityProfile {
13
+ domains: QEDomain[];
14
+ capabilities: string[];
15
+ performanceScore: number;
16
+ }
17
+ /**
18
+ * Static mapping of QE agent types to their capability profiles.
19
+ */
20
+ export declare const AGENT_CAPABILITIES: Record<string, AgentCapabilityProfile>;
21
+ /**
22
+ * Scored agent with reasoning trace.
23
+ */
24
+ export interface ScoredAgent {
25
+ agent: string;
26
+ score: number;
27
+ reasoning: string[];
28
+ }
29
+ /**
30
+ * Routing weight configuration.
31
+ */
32
+ export interface RoutingWeights {
33
+ similarity: number;
34
+ performance: number;
35
+ capabilities: number;
36
+ }
37
+ /**
38
+ * Calculate agent scores for a routing request.
39
+ *
40
+ * @param detectedDomains - Domains detected from the task description
41
+ * @param requestCapabilities - Required capabilities from the routing request
42
+ * @param agentDomainPatternCounts - Map from agent type to number of matching patterns
43
+ * @param routingWeights - Weights for the scoring components
44
+ * @param agentCapabilities - Agent capability map (defaults to AGENT_CAPABILITIES)
45
+ * @returns Sorted array of scored agents (highest score first)
46
+ */
47
+ export declare function calculateAgentScores(detectedDomains: QEDomain[], requestCapabilities: string[] | undefined, agentDomainPatternCounts: Map<string, number>, routingWeights: RoutingWeights, agentCapabilities?: Record<string, AgentCapabilityProfile>): ScoredAgent[];
48
+ /**
49
+ * Domain compatibility matrix for cross-domain pattern transfer.
50
+ * Maps each domain to its related domains (same as TransferSpecialistService).
51
+ */
52
+ export declare const RELATED_DOMAINS: Record<QEDomain, QEDomain[]>;
53
+ //# sourceMappingURL=agent-routing.d.ts.map
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Agentic QE v3 - Agent Routing
3
+ * ADR-021: QE ReasoningBank for Pattern Learning
4
+ *
5
+ * Static agent capability mapping and routing score calculation
6
+ * used by QEReasoningBank.routeTask().
7
+ */
8
+ // ============================================================================
9
+ // Agent Capabilities Map
10
+ // ============================================================================
11
+ /**
12
+ * Static mapping of QE agent types to their capability profiles.
13
+ */
14
+ export const AGENT_CAPABILITIES = {
15
+ 'qe-test-generator': {
16
+ domains: ['test-generation'],
17
+ capabilities: ['test-generation', 'tdd', 'bdd', 'unit-test', 'integration-test'],
18
+ performanceScore: 0.85,
19
+ },
20
+ 'qe-coverage-analyzer': {
21
+ domains: ['coverage-analysis'],
22
+ capabilities: ['coverage-analysis', 'gap-detection', 'risk-scoring'],
23
+ performanceScore: 0.92,
24
+ },
25
+ 'qe-coverage-specialist': {
26
+ domains: ['coverage-analysis'],
27
+ capabilities: ['sublinear-analysis', 'branch-coverage', 'mutation-testing'],
28
+ performanceScore: 0.88,
29
+ },
30
+ 'qe-test-architect': {
31
+ domains: ['test-generation', 'coverage-analysis'],
32
+ capabilities: ['test-strategy', 'test-pyramid', 'architecture'],
33
+ performanceScore: 0.9,
34
+ },
35
+ 'qe-api-contract-validator': {
36
+ domains: ['contract-testing'],
37
+ capabilities: ['contract-testing', 'openapi', 'graphql', 'pact'],
38
+ performanceScore: 0.87,
39
+ },
40
+ 'qe-security-auditor': {
41
+ domains: ['security-compliance'],
42
+ capabilities: ['sast', 'dast', 'vulnerability', 'owasp'],
43
+ performanceScore: 0.82,
44
+ },
45
+ 'qe-visual-tester': {
46
+ domains: ['visual-accessibility'],
47
+ capabilities: ['screenshot', 'visual-regression', 'percy', 'chromatic'],
48
+ performanceScore: 0.8,
49
+ },
50
+ 'qe-a11y-ally': {
51
+ domains: ['visual-accessibility'],
52
+ capabilities: ['wcag', 'aria', 'screen-reader', 'contrast'],
53
+ performanceScore: 0.85,
54
+ },
55
+ 'qe-performance-tester': {
56
+ domains: ['chaos-resilience'],
57
+ capabilities: ['load-testing', 'stress-testing', 'k6', 'artillery'],
58
+ performanceScore: 0.83,
59
+ },
60
+ 'qe-flaky-investigator': {
61
+ domains: ['test-execution'],
62
+ capabilities: ['flaky-detection', 'test-stability', 'retry'],
63
+ performanceScore: 0.78,
64
+ },
65
+ 'qe-chaos-engineer': {
66
+ domains: ['chaos-resilience'],
67
+ capabilities: ['chaos-testing', 'resilience', 'fault-injection'],
68
+ performanceScore: 0.75,
69
+ },
70
+ };
71
+ /**
72
+ * Calculate agent scores for a routing request.
73
+ *
74
+ * @param detectedDomains - Domains detected from the task description
75
+ * @param requestCapabilities - Required capabilities from the routing request
76
+ * @param agentDomainPatternCounts - Map from agent type to number of matching patterns
77
+ * @param routingWeights - Weights for the scoring components
78
+ * @param agentCapabilities - Agent capability map (defaults to AGENT_CAPABILITIES)
79
+ * @returns Sorted array of scored agents (highest score first)
80
+ */
81
+ export function calculateAgentScores(detectedDomains, requestCapabilities, agentDomainPatternCounts, routingWeights, agentCapabilities = AGENT_CAPABILITIES) {
82
+ const agentScores = [];
83
+ for (const [agentType, profile] of Object.entries(agentCapabilities)) {
84
+ let score = 0;
85
+ const reasoning = [];
86
+ // Domain match (0-0.4)
87
+ const domainMatch = detectedDomains.filter((d) => profile.domains.includes(d)).length;
88
+ const domainScore = domainMatch > 0 ? (domainMatch / detectedDomains.length) * 0.4 : 0;
89
+ score += domainScore * routingWeights.similarity;
90
+ if (domainScore > 0) {
91
+ reasoning.push(`Domain match: ${(domainScore * 100).toFixed(0)}%`);
92
+ }
93
+ // Capability match (0-0.3)
94
+ if (requestCapabilities && requestCapabilities.length > 0) {
95
+ const capMatch = requestCapabilities.filter((c) => profile.capabilities.some((pc) => pc.toLowerCase().includes(c.toLowerCase()))).length;
96
+ const capScore = capMatch > 0 ? (capMatch / requestCapabilities.length) * 0.3 : 0;
97
+ score += capScore * routingWeights.capabilities;
98
+ if (capScore > 0) {
99
+ reasoning.push(`Capability match: ${(capScore * 100).toFixed(0)}%`);
100
+ }
101
+ }
102
+ else {
103
+ score += 0.15 * routingWeights.capabilities;
104
+ }
105
+ // Historical performance (0-0.3)
106
+ score += profile.performanceScore * 0.3 * routingWeights.performance;
107
+ reasoning.push(`Performance score: ${(profile.performanceScore * 100).toFixed(0)}%`);
108
+ // Pattern similarity boost
109
+ const patternCount = agentDomainPatternCounts.get(agentType) || 0;
110
+ if (patternCount > 0) {
111
+ const patternBoost = Math.min(0.1, patternCount * 0.02);
112
+ score += patternBoost;
113
+ reasoning.push(`Pattern matches: ${patternCount}`);
114
+ }
115
+ agentScores.push({ agent: agentType, score, reasoning });
116
+ }
117
+ // Sort by score descending
118
+ agentScores.sort((a, b) => b.score - a.score);
119
+ return agentScores;
120
+ }
121
+ // ============================================================================
122
+ // Cross-Domain Compatibility Matrix
123
+ // ============================================================================
124
+ /**
125
+ * Domain compatibility matrix for cross-domain pattern transfer.
126
+ * Maps each domain to its related domains (same as TransferSpecialistService).
127
+ */
128
+ export const RELATED_DOMAINS = {
129
+ 'test-generation': ['test-execution', 'coverage-analysis', 'requirements-validation'],
130
+ 'test-execution': ['test-generation', 'coverage-analysis', 'quality-assessment'],
131
+ 'coverage-analysis': ['test-generation', 'test-execution', 'quality-assessment'],
132
+ 'quality-assessment': ['test-execution', 'coverage-analysis', 'defect-intelligence'],
133
+ 'defect-intelligence': ['quality-assessment', 'code-intelligence'],
134
+ 'requirements-validation': ['test-generation', 'quality-assessment'],
135
+ 'code-intelligence': ['defect-intelligence', 'security-compliance'],
136
+ 'security-compliance': ['code-intelligence', 'quality-assessment'],
137
+ 'contract-testing': ['test-generation', 'test-execution'],
138
+ 'visual-accessibility': ['quality-assessment'],
139
+ 'chaos-resilience': ['test-execution', 'quality-assessment'],
140
+ 'learning-optimization': ['test-generation', 'test-execution', 'coverage-analysis', 'quality-assessment', 'defect-intelligence'],
141
+ };
142
+ //# sourceMappingURL=agent-routing.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Agentic QE v3 - Embedding Utilities
3
+ * ADR-021: QE ReasoningBank for Pattern Learning
4
+ *
5
+ * Pure functions for embedding manipulation: resizing, hashing,
6
+ * and normalization. Used by QEReasoningBank.embed().
7
+ */
8
+ /**
9
+ * Resize an embedding vector to a target dimension using averaging (downscale)
10
+ * or interpolation (upscale), then normalize to unit length.
11
+ *
12
+ * @param embedding - Source embedding vector
13
+ * @param targetDim - Desired output dimension
14
+ * @returns Resized and normalized embedding
15
+ */
16
+ export declare function resizeEmbedding(embedding: number[], targetDim: number): number[];
17
+ /**
18
+ * Generate a hash-based embedding for text. This is a deterministic fallback
19
+ * that always works (including ARM64) when ONNX embeddings are unavailable.
20
+ *
21
+ * @param text - Input text to embed
22
+ * @param dimension - Output embedding dimension
23
+ * @returns Hash-based embedding vector normalized to unit length
24
+ */
25
+ export declare function hashEmbedding(text: string, dimension: number): number[];
26
+ /**
27
+ * Normalize a vector to unit length (L2 normalization).
28
+ * Returns the input unchanged if magnitude is zero.
29
+ *
30
+ * @param vector - Input vector
31
+ * @returns Normalized vector
32
+ */
33
+ export declare function normalizeVector(vector: number[]): number[];
34
+ //# sourceMappingURL=embedding-utils.d.ts.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Agentic QE v3 - Embedding Utilities
3
+ * ADR-021: QE ReasoningBank for Pattern Learning
4
+ *
5
+ * Pure functions for embedding manipulation: resizing, hashing,
6
+ * and normalization. Used by QEReasoningBank.embed().
7
+ */
8
+ // ============================================================================
9
+ // Embedding Resize
10
+ // ============================================================================
11
+ /**
12
+ * Resize an embedding vector to a target dimension using averaging (downscale)
13
+ * or interpolation (upscale), then normalize to unit length.
14
+ *
15
+ * @param embedding - Source embedding vector
16
+ * @param targetDim - Desired output dimension
17
+ * @returns Resized and normalized embedding
18
+ */
19
+ export function resizeEmbedding(embedding, targetDim) {
20
+ if (embedding.length === targetDim) {
21
+ return embedding;
22
+ }
23
+ if (embedding.length > targetDim) {
24
+ // Average adjacent values to reduce dimension
25
+ const ratio = embedding.length / targetDim;
26
+ const result = new Array(targetDim).fill(0);
27
+ for (let i = 0; i < targetDim; i++) {
28
+ const start = Math.floor(i * ratio);
29
+ const end = Math.floor((i + 1) * ratio);
30
+ let sum = 0;
31
+ for (let j = start; j < end; j++) {
32
+ sum += embedding[j];
33
+ }
34
+ result[i] = sum / (end - start);
35
+ }
36
+ return normalizeVector(result);
37
+ }
38
+ else {
39
+ // Interpolate to increase dimension (less common)
40
+ const result = new Array(targetDim).fill(0);
41
+ const ratio = (embedding.length - 1) / (targetDim - 1);
42
+ for (let i = 0; i < targetDim; i++) {
43
+ const pos = i * ratio;
44
+ const lower = Math.floor(pos);
45
+ const upper = Math.min(lower + 1, embedding.length - 1);
46
+ const weight = pos - lower;
47
+ result[i] = embedding[lower] * (1 - weight) + embedding[upper] * weight;
48
+ }
49
+ return normalizeVector(result);
50
+ }
51
+ }
52
+ // ============================================================================
53
+ // Hash-Based Embedding
54
+ // ============================================================================
55
+ /**
56
+ * Generate a hash-based embedding for text. This is a deterministic fallback
57
+ * that always works (including ARM64) when ONNX embeddings are unavailable.
58
+ *
59
+ * @param text - Input text to embed
60
+ * @param dimension - Output embedding dimension
61
+ * @returns Hash-based embedding vector normalized to unit length
62
+ */
63
+ export function hashEmbedding(text, dimension) {
64
+ const embedding = new Array(dimension).fill(0);
65
+ const normalized = text.toLowerCase().trim();
66
+ // Use multiple hash passes for better distribution
67
+ for (let pass = 0; pass < 3; pass++) {
68
+ for (let i = 0; i < normalized.length; i++) {
69
+ const charCode = normalized.charCodeAt(i);
70
+ const idx = (charCode * (i + 1) * (pass + 1)) % dimension;
71
+ embedding[idx] += Math.sin(charCode * (pass + 1)) / (i + 1);
72
+ }
73
+ }
74
+ return normalizeVector(embedding);
75
+ }
76
+ // ============================================================================
77
+ // Vector Normalization
78
+ // ============================================================================
79
+ /**
80
+ * Normalize a vector to unit length (L2 normalization).
81
+ * Returns the input unchanged if magnitude is zero.
82
+ *
83
+ * @param vector - Input vector
84
+ * @returns Normalized vector
85
+ */
86
+ export function normalizeVector(vector) {
87
+ const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));
88
+ if (magnitude > 0) {
89
+ for (let i = 0; i < vector.length; i++) {
90
+ vector[i] /= magnitude;
91
+ }
92
+ }
93
+ return vector;
94
+ }
95
+ //# sourceMappingURL=embedding-utils.js.map
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Agentic QE v3 - Pattern Promotion & Cross-Domain Seeding
3
+ * Extracted from qe-reasoning-bank.ts for file size discipline
4
+ *
5
+ * Handles pattern promotion (short-term → long-term) with coherence gating (ADR-052),
6
+ * and cross-domain pattern seeding/transfer.
7
+ */
8
+ import type { EventBus } from '../kernel/interfaces.js';
9
+ import type { QEPattern } from './qe-patterns.js';
10
+ import type { PatternStore, PatternSearchResult } from './pattern-store.js';
11
+ import type { SQLitePatternStore } from './sqlite-persistence.js';
12
+ import type { RvfDualWriter } from '../integrations/ruvector/rvf-dual-writer.js';
13
+ import type { Result } from '../shared/types/index.js';
14
+ /**
15
+ * Dependencies needed for promotion checks
16
+ */
17
+ export interface PromotionDeps {
18
+ patternStore: PatternStore;
19
+ coherenceService?: {
20
+ isInitialized(): boolean;
21
+ checkCoherence(nodes: unknown[]): Promise<{
22
+ energy: number;
23
+ contradictions?: {
24
+ nodeIds: string[];
25
+ }[];
26
+ }>;
27
+ };
28
+ eventBus?: EventBus;
29
+ coherenceThreshold: number;
30
+ getSqliteStore: () => SQLitePatternStore;
31
+ rvfDualWriter: RvfDualWriter | null;
32
+ searchPatterns: (query: string | number[], options?: Record<string, unknown>) => Promise<Result<PatternSearchResult[]>>;
33
+ getPattern: (id: string) => Promise<QEPattern | null>;
34
+ }
35
+ /**
36
+ * Check if a pattern should be promoted with coherence gate (ADR-052)
37
+ *
38
+ * Two-stage check:
39
+ * 1. Basic criteria (usage and quality) - cheap
40
+ * 2. Coherence criteria (only if basic passes) - expensive
41
+ */
42
+ export declare function checkPatternPromotionWithCoherence(pattern: QEPattern, deps: PromotionDeps): Promise<boolean>;
43
+ /**
44
+ * Promote a pattern to long-term storage
45
+ */
46
+ export declare function promotePattern(patternId: string, deps: PromotionDeps): Promise<void>;
47
+ /**
48
+ * Dependencies for cross-domain seeding
49
+ */
50
+ export interface SeedingDeps {
51
+ searchPatterns: (query: string | number[], options?: Record<string, unknown>) => Promise<Result<PatternSearchResult[]>>;
52
+ storePattern: (options: Record<string, unknown>) => Promise<Result<QEPattern>>;
53
+ patternStore: PatternStore;
54
+ }
55
+ /**
56
+ * Seed cross-domain patterns by transferring generalizable patterns
57
+ * from populated domains to their related domains.
58
+ */
59
+ export declare function seedCrossDomainPatterns(deps: SeedingDeps): Promise<{
60
+ transferred: number;
61
+ skipped: number;
62
+ }>;
63
+ //# sourceMappingURL=pattern-promotion.d.ts.map
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Agentic QE v3 - Pattern Promotion & Cross-Domain Seeding
3
+ * Extracted from qe-reasoning-bank.ts for file size discipline
4
+ *
5
+ * Handles pattern promotion (short-term → long-term) with coherence gating (ADR-052),
6
+ * and cross-domain pattern seeding/transfer.
7
+ */
8
+ import { LoggerFactory } from '../logging/index.js';
9
+ import { toErrorMessage } from '../shared/error-utils.js';
10
+ import { shouldPromotePattern } from './qe-patterns.js';
11
+ import { getWitnessChain } from '../audit/witness-chain.js';
12
+ import { RELATED_DOMAINS } from './agent-routing.js';
13
+ const logger = LoggerFactory.create('PatternPromotion');
14
+ /**
15
+ * Check if a pattern should be promoted with coherence gate (ADR-052)
16
+ *
17
+ * Two-stage check:
18
+ * 1. Basic criteria (usage and quality) - cheap
19
+ * 2. Coherence criteria (only if basic passes) - expensive
20
+ */
21
+ export async function checkPatternPromotionWithCoherence(pattern, deps) {
22
+ const basicCheck = shouldPromotePattern(pattern);
23
+ if (!basicCheck.meetsUsageCriteria || !basicCheck.meetsQualityCriteria) {
24
+ return false;
25
+ }
26
+ if (deps.coherenceService && deps.coherenceService.isInitialized()) {
27
+ const longTermResult = await deps.searchPatterns('', {
28
+ tier: 'long-term',
29
+ limit: 1000,
30
+ });
31
+ const longTermPatterns = longTermResult.success
32
+ ? longTermResult.value.map((r) => r.pattern)
33
+ : [];
34
+ const allPatterns = [...longTermPatterns, pattern];
35
+ const coherenceNodes = allPatterns.map((p) => ({
36
+ id: p.id,
37
+ embedding: p.embedding || [],
38
+ weight: p.confidence,
39
+ metadata: { name: p.name, domain: p.qeDomain },
40
+ }));
41
+ const coherenceResult = await deps.coherenceService.checkCoherence(coherenceNodes);
42
+ if (coherenceResult.energy >= deps.coherenceThreshold) {
43
+ const event = {
44
+ patternId: pattern.id,
45
+ patternName: pattern.name,
46
+ reason: 'coherence_violation',
47
+ energy: coherenceResult.energy,
48
+ existingPatternConflicts: coherenceResult.contradictions
49
+ ?.map((c) => c.nodeIds)
50
+ .flat(),
51
+ };
52
+ if (deps.eventBus) {
53
+ await deps.eventBus.publish({
54
+ id: `pattern-promotion-blocked-${pattern.id}`,
55
+ type: 'pattern:promotion_blocked',
56
+ timestamp: new Date(),
57
+ source: 'learning-optimization',
58
+ payload: event,
59
+ });
60
+ }
61
+ logger.info('Pattern promotion blocked due to coherence violation', {
62
+ name: pattern.name,
63
+ energy: coherenceResult.energy,
64
+ });
65
+ return false;
66
+ }
67
+ }
68
+ return true;
69
+ }
70
+ /**
71
+ * Promote a pattern to long-term storage
72
+ */
73
+ export async function promotePattern(patternId, deps) {
74
+ const result = await deps.patternStore.promote(patternId);
75
+ if (result.success) {
76
+ try {
77
+ deps.getSqliteStore().promotePattern(patternId);
78
+ }
79
+ catch (e) {
80
+ logger.warn('SQLite pattern promotion persist failed', {
81
+ error: toErrorMessage(e),
82
+ });
83
+ }
84
+ if (deps.rvfDualWriter) {
85
+ try {
86
+ const promoted = await deps.getPattern(patternId);
87
+ if (promoted?.embedding && promoted.embedding.length > 0) {
88
+ deps.rvfDualWriter.writePattern(patternId, promoted.embedding);
89
+ }
90
+ }
91
+ catch (rvfErr) {
92
+ logger.warn('RVF dual-write on promote failed (non-fatal)', {
93
+ patternId,
94
+ error: toErrorMessage(rvfErr),
95
+ });
96
+ }
97
+ }
98
+ getWitnessChain()
99
+ .then((wc) => wc.append('PATTERN_PROMOTE', { patternId }, 'reasoning-bank'))
100
+ .catch((e) => {
101
+ logger.warn('Witness chain PATTERN_PROMOTE failed', {
102
+ error: toErrorMessage(e),
103
+ });
104
+ });
105
+ logger.info('Promoted pattern to long-term', { patternId });
106
+ if (deps.eventBus) {
107
+ await deps.eventBus.publish({
108
+ id: `pattern-promoted-${patternId}`,
109
+ type: 'pattern:promoted',
110
+ timestamp: new Date(),
111
+ source: 'learning-optimization',
112
+ payload: { patternId, newTier: 'long-term' },
113
+ });
114
+ }
115
+ }
116
+ else {
117
+ logger.error('Failed to promote pattern', result.error, { patternId });
118
+ }
119
+ }
120
+ /**
121
+ * Seed cross-domain patterns by transferring generalizable patterns
122
+ * from populated domains to their related domains.
123
+ */
124
+ export async function seedCrossDomainPatterns(deps) {
125
+ const stats = await deps.patternStore.getStats();
126
+ let transferred = 0;
127
+ let skipped = 0;
128
+ for (const [sourceDomainStr, targetDomains] of Object.entries(RELATED_DOMAINS)) {
129
+ const sourceDomain = sourceDomainStr;
130
+ const sourceCount = stats.byDomain[sourceDomain] || 0;
131
+ if (sourceCount === 0)
132
+ continue;
133
+ const sourceResult = await deps.searchPatterns('', {
134
+ domain: sourceDomain,
135
+ limit: 50,
136
+ });
137
+ if (!sourceResult.success)
138
+ continue;
139
+ for (const targetDomain of targetDomains) {
140
+ const targetCount = stats.byDomain[targetDomain] || 0;
141
+ if (targetCount >= sourceCount) {
142
+ skipped++;
143
+ continue;
144
+ }
145
+ for (const { pattern: sourcePattern } of sourceResult.value) {
146
+ const existingCheck = await deps.searchPatterns(sourcePattern.name, {
147
+ domain: targetDomain,
148
+ limit: 1,
149
+ });
150
+ if (existingCheck.success && existingCheck.value.length > 0) {
151
+ const bestMatch = existingCheck.value[0];
152
+ if (bestMatch.score > 0.8) {
153
+ skipped++;
154
+ continue;
155
+ }
156
+ }
157
+ const transferredConfidence = Math.max(0.3, (sourcePattern.confidence || 0.5) * 0.8);
158
+ const transferResult = await deps.storePattern({
159
+ patternType: sourcePattern.patternType,
160
+ qeDomain: targetDomain,
161
+ name: `${sourcePattern.name} (from ${sourceDomain})`,
162
+ description: `${sourcePattern.description} [Transferred from ${sourceDomain} domain]`,
163
+ template: sourcePattern.template,
164
+ context: {
165
+ ...sourcePattern.context,
166
+ relatedDomains: [sourceDomain, targetDomain],
167
+ tags: [
168
+ ...sourcePattern.context.tags,
169
+ 'cross-domain-transfer',
170
+ `source:${sourceDomain}`,
171
+ ],
172
+ },
173
+ confidence: transferredConfidence,
174
+ });
175
+ if (transferResult.success) {
176
+ transferred++;
177
+ }
178
+ else {
179
+ skipped++;
180
+ }
181
+ }
182
+ }
183
+ }
184
+ logger.info('Cross-domain transfer complete', { transferred, skipped });
185
+ return { transferred, skipped };
186
+ }
187
+ //# sourceMappingURL=pattern-promotion.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Agentic QE v3 - Pretrained Patterns
3
+ * ADR-021: QE ReasoningBank for Pattern Learning
4
+ *
5
+ * Static pretrained pattern definitions that seed the QE ReasoningBank
6
+ * on first initialization when no existing patterns are found.
7
+ */
8
+ import type { CreateQEPatternOptions } from './qe-patterns.js';
9
+ /**
10
+ * Foundational QE patterns loaded on first initialization.
11
+ * These cover all 8+ QE domains with seed patterns.
12
+ */
13
+ export declare const PRETRAINED_PATTERNS: CreateQEPatternOptions[];
14
+ //# sourceMappingURL=pretrained-patterns.d.ts.map