@nahisaho/musubix-wake-sleep 1.0.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 (41) hide show
  1. package/dist/cycle/cycle-manager.d.ts +40 -0
  2. package/dist/cycle/cycle-manager.d.ts.map +1 -0
  3. package/dist/cycle/cycle-manager.js +99 -0
  4. package/dist/cycle/cycle-manager.js.map +1 -0
  5. package/dist/cycle/index.d.ts +6 -0
  6. package/dist/cycle/index.d.ts.map +1 -0
  7. package/dist/cycle/index.js +6 -0
  8. package/dist/cycle/index.js.map +1 -0
  9. package/dist/index.d.ts +12 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +17 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/resource/index.d.ts +6 -0
  14. package/dist/resource/index.d.ts.map +1 -0
  15. package/dist/resource/index.js +6 -0
  16. package/dist/resource/index.js.map +1 -0
  17. package/dist/resource/resource-limiter.d.ts +54 -0
  18. package/dist/resource/resource-limiter.d.ts.map +1 -0
  19. package/dist/resource/resource-limiter.js +91 -0
  20. package/dist/resource/resource-limiter.js.map +1 -0
  21. package/dist/sleep/index.d.ts +6 -0
  22. package/dist/sleep/index.d.ts.map +1 -0
  23. package/dist/sleep/index.js +6 -0
  24. package/dist/sleep/index.js.map +1 -0
  25. package/dist/sleep/sleep-phase.d.ts +40 -0
  26. package/dist/sleep/sleep-phase.d.ts.map +1 -0
  27. package/dist/sleep/sleep-phase.js +105 -0
  28. package/dist/sleep/sleep-phase.js.map +1 -0
  29. package/dist/types.d.ts +121 -0
  30. package/dist/types.d.ts.map +1 -0
  31. package/dist/types.js +6 -0
  32. package/dist/types.js.map +1 -0
  33. package/dist/wake/index.d.ts +6 -0
  34. package/dist/wake/index.d.ts.map +1 -0
  35. package/dist/wake/index.js +6 -0
  36. package/dist/wake/index.js.map +1 -0
  37. package/dist/wake/wake-phase.d.ts +111 -0
  38. package/dist/wake/wake-phase.d.ts.map +1 -0
  39. package/dist/wake/wake-phase.js +398 -0
  40. package/dist/wake/wake-phase.js.map +1 -0
  41. package/package.json +47 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @fileoverview Wake-Sleep type definitions
3
+ * @traceability REQ-WAKE-001
4
+ */
5
+ /**
6
+ * Wake phase task for learning
7
+ */
8
+ export interface WakeTask {
9
+ id: string;
10
+ type: 'code' | 'requirements' | 'design';
11
+ content: string;
12
+ metadata?: Record<string, unknown>;
13
+ timestamp: string;
14
+ }
15
+ /**
16
+ * Wake phase result
17
+ */
18
+ export interface WakeResult {
19
+ taskId: string;
20
+ success: boolean;
21
+ extractedPatterns: string[];
22
+ confidence: number;
23
+ processingTime: number;
24
+ metadata?: Record<string, unknown>;
25
+ error?: string;
26
+ }
27
+ /**
28
+ * Sleep phase consolidation input
29
+ */
30
+ export interface ConsolidationInput {
31
+ patterns: PatternCandidate[];
32
+ existingLibrary: string[];
33
+ }
34
+ /**
35
+ * Pattern candidate for consolidation
36
+ */
37
+ export interface PatternCandidate {
38
+ id?: string;
39
+ name: string;
40
+ code?: string;
41
+ structure: unknown;
42
+ occurrences: number;
43
+ confidence: number;
44
+ source: 'code' | 'requirements' | 'design';
45
+ frequency?: number;
46
+ contexts?: string[];
47
+ }
48
+ /**
49
+ * Sleep phase result
50
+ */
51
+ export interface SleepResult {
52
+ consolidatedPatterns: string[];
53
+ abstractedPatterns: AbstractedPattern[];
54
+ prunedPatterns: string[];
55
+ mdlScore: number;
56
+ }
57
+ /**
58
+ * Abstracted pattern after sleep phase
59
+ */
60
+ export interface AbstractedPattern {
61
+ id: string;
62
+ originalPatterns: string[];
63
+ abstractedCode: string;
64
+ compressionRatio: number;
65
+ }
66
+ /**
67
+ * Wake-sleep cycle configuration
68
+ */
69
+ export interface CycleConfig {
70
+ /** Number of wake tasks before sleep */
71
+ wakeTaskThreshold: number;
72
+ /** Maximum cycle duration in ms */
73
+ maxCycleDuration: number;
74
+ /** Minimum pattern frequency for consolidation */
75
+ minPatternFrequency: number;
76
+ /** MDL threshold for abstraction */
77
+ mdlThreshold: number;
78
+ }
79
+ /**
80
+ * Cycle status
81
+ */
82
+ export interface CycleStatus {
83
+ currentPhase: 'wake' | 'sleep' | 'idle';
84
+ taskCount: number;
85
+ patternCount: number;
86
+ cycleNumber: number;
87
+ lastCycleTime: string | null;
88
+ }
89
+ /**
90
+ * Resource limits configuration
91
+ */
92
+ export interface ResourceLimits {
93
+ /** Maximum memory usage in MB */
94
+ maxMemoryMB: number;
95
+ /** Maximum CPU time per operation in ms */
96
+ maxCpuTimeMs: number;
97
+ /** Maximum patterns in library */
98
+ maxPatterns: number;
99
+ /** Maximum concurrent operations */
100
+ maxConcurrency: number;
101
+ }
102
+ /**
103
+ * Resource usage metrics
104
+ */
105
+ export interface ResourceMetrics {
106
+ memoryUsedMB: number;
107
+ cpuTimeMs: number;
108
+ patternCount: number;
109
+ activeOperations: number;
110
+ }
111
+ /**
112
+ * Quality metrics for learning
113
+ */
114
+ export interface QualityMetrics {
115
+ accuracy: number;
116
+ precision: number;
117
+ recall: number;
118
+ f1Score: number;
119
+ mdlScore: number;
120
+ }
121
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,UAAU,EAAE,MAAM,CA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AED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,YAAY,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IACxC,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAC;IACrB,kCAAkC;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,oCAAoC;IACpC,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CAClB"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview Wake-Sleep type definitions
3
+ * @traceability REQ-WAKE-001
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview Wake phase module
3
+ * @traceability TSK-WAKE-001
4
+ */
5
+ export { WakePhase } from './wake-phase.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/wake/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview Wake phase module
3
+ * @traceability TSK-WAKE-001
4
+ */
5
+ export { WakePhase } from './wake-phase.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/wake/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @fileoverview Wake phase executor for pattern collection
3
+ * @traceability TSK-WAKE-001, REQ-WAKE-001-F001
4
+ */
5
+ import type { WakeTask, WakeResult, PatternCandidate } from '../types.js';
6
+ /**
7
+ * Pattern extractor configuration
8
+ */
9
+ export interface PatternExtractorConfig {
10
+ minPatternSize: number;
11
+ maxPatternSize: number;
12
+ minOccurrences: number;
13
+ similarityThreshold: number;
14
+ }
15
+ /**
16
+ * Wake phase executor
17
+ *
18
+ * @description
19
+ * Collects patterns from tasks during the wake phase.
20
+ * - Processes code, requirements, and design tasks
21
+ * - Extracts pattern candidates using AST analysis
22
+ * - Supports TypeScript, JavaScript, and pseudo-code
23
+ */
24
+ export declare class WakePhase {
25
+ private tasks;
26
+ private results;
27
+ private extractorConfig;
28
+ private patternCache;
29
+ constructor(config?: Partial<PatternExtractorConfig>);
30
+ /**
31
+ * Add task for processing
32
+ */
33
+ addTask(task: WakeTask): void;
34
+ /**
35
+ * Process single task and extract patterns
36
+ */
37
+ processTask(task: WakeTask): Promise<WakeResult>;
38
+ /**
39
+ * Process all pending tasks
40
+ */
41
+ processAll(): Promise<WakeResult[]>;
42
+ /**
43
+ * Extract patterns from task content
44
+ */
45
+ private extractPatterns;
46
+ /**
47
+ * Extract patterns from code
48
+ */
49
+ private extractCodePatterns;
50
+ /**
51
+ * Extract patterns from requirements
52
+ */
53
+ private extractRequirementPatterns;
54
+ /**
55
+ * Extract patterns from design documents
56
+ */
57
+ private extractDesignPatterns;
58
+ /**
59
+ * Parse content to simple AST
60
+ */
61
+ private parseToAST;
62
+ /**
63
+ * Find repeated subtrees in AST
64
+ */
65
+ private findRepeatedSubtrees;
66
+ /**
67
+ * Hash AST node for comparison
68
+ */
69
+ private hashNode;
70
+ /**
71
+ * Anti-unify multiple AST nodes to create abstracted pattern
72
+ */
73
+ private antiUnify;
74
+ /**
75
+ * Detect common design pattern usage in AST
76
+ */
77
+ private detectDesignPatternUsage;
78
+ /**
79
+ * Generate pattern name from abstracted AST
80
+ */
81
+ private generatePatternName;
82
+ /**
83
+ * Calculate confidence for pattern
84
+ */
85
+ private calculatePatternConfidence;
86
+ /**
87
+ * Calculate overall confidence from patterns
88
+ */
89
+ private calculateConfidence;
90
+ /**
91
+ * Get accumulated results
92
+ */
93
+ getResults(): WakeResult[];
94
+ /**
95
+ * Get cached patterns for a task
96
+ */
97
+ getCachedPatterns(taskId: string): PatternCandidate[];
98
+ /**
99
+ * Get all cached patterns
100
+ */
101
+ getAllCachedPatterns(): Map<string, PatternCandidate[]>;
102
+ /**
103
+ * Get task count
104
+ */
105
+ get taskCount(): number;
106
+ /**
107
+ * Clear all state
108
+ */
109
+ reset(): void;
110
+ }
111
+ //# sourceMappingURL=wake-phase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wake-phase.d.ts","sourceRoot":"","sources":["../../src/wake/wake-phase.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAcD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* @traceability TSK-WAKE-001, REQ-WAKE-001-F001
4
+ */
5
+ /**
6
+ * Wake phase executor
7
+ *
8
+ * @description
9
+ * Collects patterns from tasks during the wake phase.
10
+ * - Processes code, requirements, and design tasks
11
+ * - Extracts pattern candidates using AST analysis
12
+ * - Supports TypeScript, JavaScript, and pseudo-code
13
+ */
14
+ export class WakePhase {
15
+ tasks = [];
16
+ results = [];
17
+ extractorConfig;
18
+ patternCache = new Map();
19
+ constructor(config) {
20
+ this.extractorConfig = {
21
+ minPatternSize: config?.minPatternSize ?? 3,
22
+ maxPatternSize: config?.maxPatternSize ?? 50,
23
+ minOccurrences: config?.minOccurrences ?? 2,
24
+ similarityThreshold: config?.similarityThreshold ?? 0.7,
25
+ };
26
+ }
27
+ /**
28
+ * Add task for processing
29
+ */
30
+ addTask(task) {
31
+ this.tasks.push(task);
32
+ }
33
+ /**
34
+ * Process single task and extract patterns
35
+ */
36
+ async processTask(task) {
37
+ const startTime = Date.now();
38
+ try {
39
+ // Extract patterns based on task type
40
+ const patterns = await this.extractPatterns(task);
41
+ const patternNames = patterns.map(p => p.name);
42
+ // Cache patterns for later analysis
43
+ this.patternCache.set(task.id, patterns);
44
+ const result = {
45
+ taskId: task.id,
46
+ success: true,
47
+ extractedPatterns: patternNames,
48
+ confidence: this.calculateConfidence(patterns),
49
+ processingTime: Date.now() - startTime,
50
+ metadata: {
51
+ patternCount: patterns.length,
52
+ taskType: task.type,
53
+ contentLength: task.content.length,
54
+ },
55
+ };
56
+ this.results.push(result);
57
+ return result;
58
+ }
59
+ catch (error) {
60
+ const result = {
61
+ taskId: task.id,
62
+ success: false,
63
+ extractedPatterns: [],
64
+ confidence: 0,
65
+ processingTime: Date.now() - startTime,
66
+ error: error instanceof Error ? error.message : String(error),
67
+ };
68
+ this.results.push(result);
69
+ return result;
70
+ }
71
+ }
72
+ /**
73
+ * Process all pending tasks
74
+ */
75
+ async processAll() {
76
+ const results = [];
77
+ for (const task of this.tasks) {
78
+ const result = await this.processTask(task);
79
+ results.push(result);
80
+ }
81
+ this.tasks = [];
82
+ return results;
83
+ }
84
+ /**
85
+ * Extract patterns from task content
86
+ */
87
+ async extractPatterns(task) {
88
+ const patterns = [];
89
+ switch (task.type) {
90
+ case 'code':
91
+ patterns.push(...this.extractCodePatterns(task.content));
92
+ break;
93
+ case 'requirements':
94
+ patterns.push(...this.extractRequirementPatterns(task.content));
95
+ break;
96
+ case 'design':
97
+ patterns.push(...this.extractDesignPatterns(task.content));
98
+ break;
99
+ }
100
+ return patterns;
101
+ }
102
+ /**
103
+ * Extract patterns from code
104
+ */
105
+ extractCodePatterns(content) {
106
+ const patterns = [];
107
+ const ast = this.parseToAST(content);
108
+ // Find repeated subtrees
109
+ const subtrees = this.findRepeatedSubtrees(ast);
110
+ for (const [subtreeHash, nodes] of subtrees.entries()) {
111
+ if (nodes.length >= this.extractorConfig.minOccurrences) {
112
+ const abstracted = this.antiUnify(nodes);
113
+ if (abstracted) {
114
+ patterns.push({
115
+ name: `${this.generatePatternName(abstracted)}_${subtreeHash.slice(0, 8)}`,
116
+ structure: abstracted,
117
+ occurrences: nodes.length,
118
+ confidence: this.calculatePatternConfidence(abstracted, nodes),
119
+ source: 'code',
120
+ });
121
+ }
122
+ }
123
+ }
124
+ // Detect common design patterns
125
+ patterns.push(...this.detectDesignPatternUsage(ast));
126
+ return patterns;
127
+ }
128
+ /**
129
+ * Extract patterns from requirements
130
+ */
131
+ extractRequirementPatterns(content) {
132
+ const patterns = [];
133
+ // EARS pattern detection
134
+ const earsPatterns = [
135
+ { regex: /WHEN\s+(.+?),?\s+THE\s+(.+?)\s+SHALL\s+(.+)/gi, name: 'EARS-Event' },
136
+ { regex: /WHILE\s+(.+?),?\s+THE\s+(.+?)\s+SHALL\s+(.+)/gi, name: 'EARS-State' },
137
+ { regex: /THE\s+(.+?)\s+SHALL\s+(.+)/gi, name: 'EARS-Ubiquitous' },
138
+ { regex: /THE\s+(.+?)\s+SHALL\s+NOT\s+(.+)/gi, name: 'EARS-Unwanted' },
139
+ { regex: /IF\s+(.+?),?\s+THEN\s+THE\s+(.+?)\s+SHALL\s+(.+)/gi, name: 'EARS-Optional' },
140
+ ];
141
+ for (const { regex, name } of earsPatterns) {
142
+ const matches = [...content.matchAll(regex)];
143
+ if (matches.length > 0) {
144
+ patterns.push({
145
+ name,
146
+ structure: { type: 'requirement-pattern', template: name, groups: matches[0].slice(1) },
147
+ occurrences: matches.length,
148
+ confidence: 0.9,
149
+ source: 'requirements',
150
+ });
151
+ }
152
+ }
153
+ return patterns;
154
+ }
155
+ /**
156
+ * Extract patterns from design documents
157
+ */
158
+ extractDesignPatterns(content) {
159
+ const patterns = [];
160
+ // C4 pattern detection
161
+ const c4Patterns = [
162
+ { marker: /container|component|context|code/gi, name: 'C4-Model' },
163
+ { marker: /service|repository|factory|controller/gi, name: 'LayeredArchitecture' },
164
+ { marker: /API|REST|GraphQL/gi, name: 'APIDesign' },
165
+ ];
166
+ for (const { marker, name } of c4Patterns) {
167
+ const matches = content.match(marker);
168
+ if (matches && matches.length >= 2) {
169
+ patterns.push({
170
+ name,
171
+ structure: { type: 'design-pattern', matches: matches.slice(0, 5) },
172
+ occurrences: matches.length,
173
+ confidence: 0.7,
174
+ source: 'design',
175
+ });
176
+ }
177
+ }
178
+ return patterns;
179
+ }
180
+ /**
181
+ * Parse content to simple AST
182
+ */
183
+ parseToAST(content) {
184
+ // Simplified AST parser for common patterns
185
+ const lines = content.split('\n').filter(l => l.trim());
186
+ const root = { type: 'Program', children: [] };
187
+ for (const line of lines) {
188
+ const trimmed = line.trim();
189
+ // Function detection
190
+ if (/^(async\s+)?function\s+\w+|^(const|let|var)\s+\w+\s*=\s*(async\s+)?\(/.test(trimmed)) {
191
+ root.children.push({ type: 'FunctionDeclaration', value: trimmed });
192
+ }
193
+ // Class detection
194
+ else if (/^(export\s+)?(abstract\s+)?class\s+\w+/.test(trimmed)) {
195
+ root.children.push({ type: 'ClassDeclaration', value: trimmed });
196
+ }
197
+ // Interface detection
198
+ else if (/^(export\s+)?interface\s+\w+/.test(trimmed)) {
199
+ root.children.push({ type: 'InterfaceDeclaration', value: trimmed });
200
+ }
201
+ // Import detection
202
+ else if (/^import\s+/.test(trimmed)) {
203
+ root.children.push({ type: 'ImportDeclaration', value: trimmed });
204
+ }
205
+ // Method call detection
206
+ else if (/\.\w+\(/.test(trimmed)) {
207
+ root.children.push({ type: 'CallExpression', value: trimmed });
208
+ }
209
+ }
210
+ return root;
211
+ }
212
+ /**
213
+ * Find repeated subtrees in AST
214
+ */
215
+ findRepeatedSubtrees(ast) {
216
+ const subtrees = new Map();
217
+ const traverse = (node) => {
218
+ const hash = this.hashNode(node);
219
+ if (!subtrees.has(hash)) {
220
+ subtrees.set(hash, []);
221
+ }
222
+ subtrees.get(hash).push(node);
223
+ if (node.children) {
224
+ for (const child of node.children) {
225
+ traverse(child);
226
+ }
227
+ }
228
+ };
229
+ traverse(ast);
230
+ return subtrees;
231
+ }
232
+ /**
233
+ * Hash AST node for comparison
234
+ */
235
+ hashNode(node) {
236
+ const parts = [node.type];
237
+ if (node.children) {
238
+ for (const child of node.children) {
239
+ parts.push(child.type);
240
+ }
241
+ }
242
+ return parts.join(':');
243
+ }
244
+ /**
245
+ * Anti-unify multiple AST nodes to create abstracted pattern
246
+ */
247
+ antiUnify(nodes) {
248
+ if (nodes.length === 0)
249
+ return null;
250
+ if (nodes.length === 1)
251
+ return nodes[0];
252
+ const first = nodes[0];
253
+ const result = { type: first.type };
254
+ // Check if all nodes have same type
255
+ if (!nodes.every(n => n.type === first.type)) {
256
+ return { type: 'Hole', isHole: true, holeId: `H${Date.now()}` };
257
+ }
258
+ // Anti-unify values
259
+ if (first.value !== undefined) {
260
+ const allSame = nodes.every(n => n.value === first.value);
261
+ if (allSame) {
262
+ result.value = first.value;
263
+ }
264
+ else {
265
+ result.isHole = true;
266
+ result.holeId = `V${Date.now()}`;
267
+ }
268
+ }
269
+ // Anti-unify children
270
+ if (first.children) {
271
+ const minChildren = Math.min(...nodes.map(n => n.children?.length ?? 0));
272
+ result.children = [];
273
+ for (let i = 0; i < minChildren; i++) {
274
+ const childNodes = nodes
275
+ .map(n => n.children?.[i])
276
+ .filter((c) => c !== undefined);
277
+ const unifiedChild = this.antiUnify(childNodes);
278
+ if (unifiedChild) {
279
+ result.children.push(unifiedChild);
280
+ }
281
+ }
282
+ }
283
+ return result;
284
+ }
285
+ /**
286
+ * Detect common design pattern usage in AST
287
+ */
288
+ detectDesignPatternUsage(ast) {
289
+ const patterns = [];
290
+ const children = ast.children ?? [];
291
+ // Repository pattern detection
292
+ const repoIndicators = children.filter(c => String(c.value).includes('Repository') ||
293
+ String(c.value).includes('findBy') ||
294
+ String(c.value).includes('save('));
295
+ if (repoIndicators.length >= 2) {
296
+ patterns.push({
297
+ name: 'RepositoryPattern',
298
+ structure: { type: 'design-pattern', indicators: repoIndicators.length },
299
+ occurrences: repoIndicators.length,
300
+ confidence: 0.8,
301
+ source: 'code',
302
+ });
303
+ }
304
+ // Factory pattern detection
305
+ const factoryIndicators = children.filter(c => String(c.value).includes('create') ||
306
+ String(c.value).includes('Factory') ||
307
+ String(c.value).includes('build('));
308
+ if (factoryIndicators.length >= 2) {
309
+ patterns.push({
310
+ name: 'FactoryPattern',
311
+ structure: { type: 'design-pattern', indicators: factoryIndicators.length },
312
+ occurrences: factoryIndicators.length,
313
+ confidence: 0.75,
314
+ source: 'code',
315
+ });
316
+ }
317
+ // Service layer detection
318
+ const serviceIndicators = children.filter(c => String(c.value).includes('Service') ||
319
+ String(c.value).includes('execute') ||
320
+ String(c.value).includes('process('));
321
+ if (serviceIndicators.length >= 2) {
322
+ patterns.push({
323
+ name: 'ServiceLayer',
324
+ structure: { type: 'design-pattern', indicators: serviceIndicators.length },
325
+ occurrences: serviceIndicators.length,
326
+ confidence: 0.7,
327
+ source: 'code',
328
+ });
329
+ }
330
+ return patterns;
331
+ }
332
+ /**
333
+ * Generate pattern name from abstracted AST
334
+ */
335
+ generatePatternName(ast) {
336
+ const typeMap = {
337
+ FunctionDeclaration: 'Function',
338
+ ClassDeclaration: 'Class',
339
+ InterfaceDeclaration: 'Interface',
340
+ CallExpression: 'Call',
341
+ ImportDeclaration: 'Import',
342
+ };
343
+ const base = typeMap[ast.type] ?? ast.type;
344
+ const childCount = ast.children?.length ?? 0;
345
+ return `${base}Pattern_${childCount}`;
346
+ }
347
+ /**
348
+ * Calculate confidence for pattern
349
+ */
350
+ calculatePatternConfidence(ast, occurrences) {
351
+ const baseConfidence = 0.5;
352
+ const occurrenceBonus = Math.min(occurrences.length * 0.1, 0.3);
353
+ const sizeBonus = ast.children ? Math.min(ast.children.length * 0.05, 0.2) : 0;
354
+ return Math.min(baseConfidence + occurrenceBonus + sizeBonus, 1.0);
355
+ }
356
+ /**
357
+ * Calculate overall confidence from patterns
358
+ */
359
+ calculateConfidence(patterns) {
360
+ if (patterns.length === 0)
361
+ return 0;
362
+ const avgConfidence = patterns.reduce((sum, p) => sum + p.confidence, 0) / patterns.length;
363
+ return Math.round(avgConfidence * 100) / 100;
364
+ }
365
+ /**
366
+ * Get accumulated results
367
+ */
368
+ getResults() {
369
+ return [...this.results];
370
+ }
371
+ /**
372
+ * Get cached patterns for a task
373
+ */
374
+ getCachedPatterns(taskId) {
375
+ return this.patternCache.get(taskId) ?? [];
376
+ }
377
+ /**
378
+ * Get all cached patterns
379
+ */
380
+ getAllCachedPatterns() {
381
+ return new Map(this.patternCache);
382
+ }
383
+ /**
384
+ * Get task count
385
+ */
386
+ get taskCount() {
387
+ return this.tasks.length;
388
+ }
389
+ /**
390
+ * Clear all state
391
+ */
392
+ reset() {
393
+ this.tasks = [];
394
+ this.results = [];
395
+ this.patternCache.clear();
396
+ }
397
+ }
398
+ //# sourceMappingURL=wake-phase.js.map