-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct.ts
More file actions
406 lines (357 loc) · 10.3 KB
/
Copy pathconstruct.ts
File metadata and controls
406 lines (357 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// construct.ts
// Event 013: Morphism Construction from Principles
import type { IntentRequirements, MatchedPrinciple, SynthesisPlan } from './types.js';
import type { EvolvableMorphism, Algebra, Coalgebra } from '../evolution/operators.js';
/**
* Construct morphism from matched principles
*/
export const constructMorphism = <A = any, B = any, C = any>(
plan: SynthesisPlan
): EvolvableMorphism<A, B, C> & { postProcess?: (result: B) => any } => {
const { requirements, matchedPrinciples, intent } = plan;
// Default coalgebra (unfold from array)
const coalgebra: Coalgebra<A, C> = (state: any) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail as any];
}
if (typeof state === 'number' && state > 0) {
return [state as any, (state - 1) as any];
}
return null;
};
// Construct based on intent
switch (requirements.intent) {
case 'median':
return constructMedian(matchedPrinciples);
case 'mode':
return constructMode(matchedPrinciples);
case 'variance':
return constructVariance(matchedPrinciples);
case 'standard_deviation':
return constructStdDev(matchedPrinciples);
case 'range':
return constructRange(matchedPrinciples);
case 'first':
return constructFirst(matchedPrinciples);
case 'last':
return constructLast(matchedPrinciples);
// Event 014: distinct NOT in switch initially - will use generic fallback
// After Set-based principle added, generic will handle it
default:
// Fallback: try generic construction
return constructGeneric(requirements, matchedPrinciples);
}
};
/**
* Construct median morphism
*/
const constructMedian = (principles: MatchedPrinciple[]): any => {
// Apply "Information Preservation" principle → collect algebra
const algebra: Algebra<any, any[]> = (acc, val) => [...acc, val];
const init: any[] = [];
// Apply "Order-dependent" + "Positional Selection" principles → sort + select middle
const postProcess = (values: any[]) => {
if (values.length === 0) return null;
const sorted = [...values].sort((a, b) => a - b);
const middleIndex = Math.floor(sorted.length / 2);
return sorted[middleIndex];
};
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'median',
algebra,
coalgebra,
init,
postProcess,
metadata: {
generation: 0,
parents: ['collect'],
mutations: ['synthesized']
}
};
};
/**
* Construct mode morphism
*/
const constructMode = (principles: MatchedPrinciple[]): any => {
// Apply "count frequencies" principle → frequency map algebra
// Event 014: Made immutable (pure)
const algebra: Algebra<any, Record<string, number>> = (freqMap, val) => {
const key = String(val);
return { ...freqMap, [key]: (freqMap[key] || 0) + 1 };
};
const init: Record<string, number> = {};
// Apply "find maximum" principle → find max frequency in postProcess
const postProcess = (freqMap: Record<string, number>) => {
let maxFreq = 0;
let mode = null;
for (const [val, freq] of Object.entries(freqMap)) {
if (freq > maxFreq) {
maxFreq = freq;
mode = val;
}
}
// Try to parse back to number if possible
return mode !== null && !isNaN(Number(mode)) ? Number(mode) : mode;
};
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'mode',
algebra,
coalgebra,
init,
postProcess,
metadata: {
generation: 0,
parents: ['count', 'max'],
mutations: ['synthesized']
}
};
};
/**
* Construct variance morphism
*/
const constructVariance = (principles: MatchedPrinciple[]): any => {
// Apply "variance computation" principle → {sum, sumSq, count} algebra
const algebra: Algebra<number, { sum: number; sumSq: number; count: number }> = (acc, val) => ({
sum: acc.sum + val,
sumSq: acc.sumSq + val * val,
count: acc.count + 1
});
const init = { sum: 0, sumSq: 0, count: 0 };
// Apply variance formula: E[X²] - (E[X])²
const postProcess = ({ sum, sumSq, count }: { sum: number; sumSq: number; count: number }) => {
if (count === 0) return 0;
const mean = sum / count;
const meanSq = sumSq / count;
return meanSq - mean * mean;
};
const coalgebra: Coalgebra<number, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'variance',
algebra,
coalgebra,
init,
postProcess,
metadata: {
generation: 0,
parents: ['sum', 'sumSq', 'count'],
mutations: ['synthesized']
}
};
};
/**
* Construct standard deviation morphism
*/
const constructStdDev = (principles: MatchedPrinciple[]): any => {
// Reuse variance construction
const varianceMorphism = constructVariance(principles);
// Add square root in postProcess
const variancePostProcess = varianceMorphism.postProcess!;
const postProcess = (acc: any) => {
const variance = variancePostProcess(acc);
return Math.sqrt(variance);
};
return {
...varianceMorphism,
name: 'standard_deviation',
postProcess,
metadata: {
generation: 0,
parents: ['variance'],
mutations: ['synthesized']
}
};
};
/**
* Construct range morphism
*/
const constructRange = (principles: MatchedPrinciple[]): any => {
// Apply "extremum" principle → track {min, max}
const algebra: Algebra<number, { min: number; max: number }> = (acc, val) => ({
min: Math.min(acc.min, val),
max: Math.max(acc.max, val)
});
const init = { min: Infinity, max: -Infinity };
// Compute range = max - min
const postProcess = ({ min, max }: { min: number; max: number }) => max - min;
const coalgebra: Coalgebra<number, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'range',
algebra,
coalgebra,
init,
postProcess,
metadata: {
generation: 0,
parents: ['min', 'max'],
mutations: ['synthesized']
}
};
};
/**
* Construct first morphism
*/
const constructFirst = (principles: MatchedPrinciple[]): any => {
// Simply take first value
const algebra: Algebra<any, any> = (acc, val) => (acc === null ? val : acc);
const init = null;
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'first',
algebra,
coalgebra,
init,
metadata: {
generation: 0,
parents: [],
mutations: ['synthesized']
}
};
};
/**
* Construct last morphism
*/
const constructLast = (principles: MatchedPrinciple[]): any => {
// Keep updating to last value seen
const algebra: Algebra<any, any> = (acc, val) => val;
const init = null;
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'last',
algebra,
coalgebra,
init,
metadata: {
generation: 0,
parents: [],
mutations: ['synthesized']
}
};
};
/**
* Construct distinct morphism
* Event 014: Added for self-improvement demo
* Uses Set-based accumulation to track uniqueness
*/
const constructDistinct = (principles: MatchedPrinciple[]): any => {
// Apply "Set-based accumulation" principle → array to track seen values
// (Using array with includes for simplicity - pure and ≤2 compliant)
const algebra: Algebra<any, any[]> = (seen, val) => {
// Check if value already seen
if (seen.some(v => JSON.stringify(v) === JSON.stringify(val))) {
return seen; // Skip duplicate
}
return [...seen, val]; // Add new unique value
};
const init: any[] = [];
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
return {
name: 'distinct',
algebra,
coalgebra,
init,
metadata: {
generation: 0,
parents: ['set-based-accumulation'],
mutations: ['synthesized']
}
};
};
/**
* Generic construction (fallback)
*/
const constructGeneric = (
requirements: IntentRequirements,
principles: MatchedPrinciple[]
): any => {
// Event 014: Check for deduplicate transformation (needs Set-based principle)
const needsDeduplication = requirements.transformation.includes('deduplicate');
// Check if we have Set-based principle
const hasSetPrinciple = principles.some(p =>
p.principle.name.toLowerCase().includes('set') ||
p.principle.statement.toLowerCase().includes('unique') ||
p.principle.statement.toLowerCase().includes('distinct')
);
let algebra: Algebra<any, any[]>;
if (needsDeduplication && hasSetPrinciple) {
// Use Set-based deduplication (from learned principle)
algebra = (seen, val) => {
if (seen.some(v => JSON.stringify(v) === JSON.stringify(val))) {
return seen; // Skip duplicate
}
return [...seen, val]; // Add unique value
};
} else {
// Default: collect all values
algebra = (acc, val) => [...acc, val];
}
const init: any[] = [];
const coalgebra: Coalgebra<any, any> = (state) => {
if (Array.isArray(state) && state.length > 0) {
const [head, ...tail] = state;
return [head, tail];
}
return null;
};
// If requirements include sort, add sort in postProcess
let postProcess: ((result: any) => any) | undefined;
if (requirements.transformation.includes('sort')) {
postProcess = (values: any[]) => [...values].sort((a, b) => a - b);
}
return {
name: requirements.intent,
algebra,
coalgebra,
init,
postProcess,
metadata: {
generation: 0,
parents: ['generic'],
mutations: ['synthesized']
}
};
};