-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingest.js
More file actions
1404 lines (1270 loc) · 65.8 KB
/
ingest.js
File metadata and controls
1404 lines (1270 loc) · 65.8 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// Ingest ai_devboard repo structure into FalkorDB graph org_ai_dev_dashboard
// Creates: Space nodes (dirs), Thing nodes (files), BELONGS_TO + DEPENDS_ON links
//
// Usage: node ingest.js [--dry-run]
import { createClient } from 'redis'
import { readdir, stat, readFile } from 'fs/promises'
import { join, relative, extname, basename, dirname } from 'path'
const GRAPH = 'org_ai_dev_dashboard'
const ROOT = '.'
const DRY_RUN = process.argv.includes('--dry-run')
// Dirs to skip entirely (by name — matched against the directory basename)
const SKIP_DIRS = new Set([
'node_modules', '.git', 'dist', '.claude',
'puppeteer_dev_chrome_profile-b9HpXs',
'.org.chromium.Chromium.scoped_dir.IbepjR',
'claude-1000', 'snap-private-tmp', 'v8-compile-cache-1000',
'node-compile-cache', 'mind_ideogram', 'mind_telegram_voice',
'__pycache__', 'assets', 'public',
'uploads', 'static', 'shrine', 'android', 'lyrics',
])
// Skip dirs matching these prefixes
const SKIP_PREFIXES = ['systemd-private-', 'tmp', '.X11']
// Skip paths matching these patterns (checked against relPath)
const SKIP_PATHS = [
'citizens/', // 186 citizen folders — skip individual dirs, keep the top-level
]
// File extensions to ingest
const CODE_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.py', '.yaml', '.yml', '.json', '.css', '.md', '.html'])
function shouldSkipDir(name, relPath) {
if (SKIP_DIRS.has(name)) return true
for (const p of SKIP_PREFIXES) {
if (name.startsWith(p)) return true
}
for (const sp of SKIP_PATHS) {
// Skip subdirectories under this path (but not the path itself)
if (relPath.startsWith(sp) && relPath !== sp.replace(/\/$/, '')) return true
}
return false
}
function slugify(s) {
return s.replace(/[^a-zA-Z0-9]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '').toLowerCase()
}
function fileSubtype(ext, name) {
if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) return 'code_file'
if (['.py'].includes(ext)) return 'code_file'
if (['.yaml', '.yml'].includes(ext)) return 'config'
if (['.json'].includes(ext)) return name === 'package.json' ? 'config' : 'data_source'
if (['.md'].includes(ext)) return 'document'
if (['.css'].includes(ext)) return 'code_file'
if (['.html'].includes(ext)) return 'code_file'
return 'code_file'
}
// Parse imports from source files
function parseImports(content, filePath) {
const imports = []
// ES module: import ... from '...' or import '...'
const esRe = /import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g
// require: require('...')
const cjsRe = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g
// Python: from X import Y or import X
const pyFromRe = /from\s+([\w.]+)\s+import/g
const pyImportRe = /^import\s+([\w.]+)/gm
const ext = extname(filePath)
if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
for (const re of [esRe, cjsRe]) {
let m
while ((m = re.exec(content)) !== null) {
const spec = m[1]
if (spec.startsWith('.') || spec.startsWith('/')) {
imports.push({ spec, type: 'local' })
} else {
imports.push({ spec, type: 'external' })
}
}
}
} else if (ext === '.py') {
for (const re of [pyFromRe, pyImportRe]) {
let m
while ((m = re.exec(content)) !== null) {
const spec = m[1]
if (spec.startsWith('.')) {
imports.push({ spec, type: 'local' })
} else {
imports.push({ spec, type: 'external' })
}
}
}
}
return imports
}
// Resolve a relative import to a file path
function resolveImport(importSpec, fromFile) {
const dir = dirname(fromFile)
let resolved = join(dir, importSpec)
// Normalize: remove leading ./
resolved = relative('.', resolved)
return resolved
}
async function walk(dir) {
const dirs = [] // { relPath, name }
const files = [] // { relPath, name, ext }
async function _walk(current) {
const entries = await readdir(current, { withFileTypes: true })
for (const entry of entries) {
const fullPath = join(current, entry.name)
const relPath = relative(ROOT, fullPath)
if (entry.isDirectory()) {
if (shouldSkipDir(entry.name, relPath)) continue
dirs.push({ relPath, name: entry.name })
await _walk(fullPath)
} else if (entry.isFile()) {
const ext = extname(entry.name)
if (CODE_EXTS.has(ext)) {
files.push({ relPath, name: entry.name, ext })
}
}
}
}
await _walk(dir)
return { dirs, files }
}
// Escape Cypher string
function esc(s) {
return s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')
}
// Deep code parser — extracts granular elements from JS/JSX/PY files
function parseCodeDeep(content, filePath) {
const ext = extname(filePath)
const fileSlug = slugify(filePath)
const elements = { functions: [], state: [], constants: [], hooks: [], routes: [], apiCalls: [], jsxElements: [] }
if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
// --- Functions ---
// function name() / const name = () => / const name = async () => / const name = function
const fnPatterns = [
/(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/g,
/(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>/g,
/(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s+)?function/g,
]
for (const re of fnPatterns) {
let m
while ((m = re.exec(content)) !== null) {
const name = m[1]
if (['require', 'import'].includes(name)) continue
const line = content.slice(0, m.index).split('\n').length
// Infer purpose from nearby comments or function body
const bodyStart = content.indexOf('{', m.index)
const bodySnippet = bodyStart > -1 ? content.slice(bodyStart, bodyStart + 300) : ''
elements.functions.push({ name, line, bodySnippet })
}
}
// --- React State (useState) ---
const stateRe = /const\s+\[(\w+),\s*(\w+)\]\s*=\s*useState\(([^)]*)\)/g
let m
while ((m = stateRe.exec(content)) !== null) {
elements.state.push({ getter: m[1], setter: m[2], initial: m[3], line: content.slice(0, m.index).split('\n').length })
}
// --- Refs (useRef) ---
const refRe = /const\s+(\w+)\s*=\s*useRef\(([^)]*)\)/g
while ((m = refRe.exec(content)) !== null) {
elements.state.push({ getter: m[1], setter: null, initial: m[2] || 'null', type: 'ref', line: content.slice(0, m.index).split('\n').length })
}
// --- Constants (top-level const objects/values) ---
const constRe = /^const\s+(\w+)\s*=\s*(\{[\s\S]*?\n\}|'[^']*'|"[^"]*"|`[^`]*`|\d+(?:\.\d+)?|true|false|null)\s*;?\s*$/gm
while ((m = constRe.exec(content)) !== null) {
const name = m[1]
if (['app', 'redis', 'PORT'].includes(name) || name.startsWith('_')) continue
elements.constants.push({ name, value: m[2].slice(0, 100), line: content.slice(0, m.index).split('\n').length })
}
// --- useEffect hooks ---
const effectRe = /useEffect\(\s*\(\)\s*=>\s*\{/g
let effectIdx = 0
while ((m = effectRe.exec(content)) !== null) {
effectIdx++
const line = content.slice(0, m.index).split('\n').length
// Find deps array — look for ], [deps]) pattern after this effect
const after = content.slice(m.index, m.index + 2000)
const depsMatch = after.match(/\},\s*\[([^\]]*)\]\s*\)/)
const deps = depsMatch ? depsMatch[1].split(',').map(d => d.trim()).filter(Boolean) : []
// Infer purpose from first comment or first meaningful line
const bodyStart = content.indexOf('{', m.index)
const bodySnippet = bodyStart > -1 ? content.slice(bodyStart + 1, bodyStart + 200).trim() : ''
const commentMatch = bodySnippet.match(/\/\/\s*(.+)/)
const purpose = commentMatch ? commentMatch[1] : bodySnippet.split('\n')[0].slice(0, 80)
elements.hooks.push({ type: 'useEffect', index: effectIdx, deps, purpose, line })
}
// --- Express routes (server-side) ---
const routeRe = /app\.(get|post|put|delete|patch)\s*\(\s*['"`]([^'"`]+)['"`]/g
while ((m = routeRe.exec(content)) !== null) {
const line = content.slice(0, m.index).split('\n').length
elements.routes.push({ method: m[1].toUpperCase(), path: m[2], line })
}
// --- API calls (client-side fetch / EventSource) ---
const fetchRe = /fetch\s*\(\s*['"`]([^'"`]+)['"`](?:.*?method:\s*['"`](\w+)['"`])?/gs
while ((m = fetchRe.exec(content)) !== null) {
elements.apiCalls.push({ url: m[1], method: (m[2] || 'GET').toUpperCase(), line: content.slice(0, m.index).split('\n').length })
}
const esRe = /new\s+EventSource\s*\(\s*[`'"]([^`'"]+)[`'"]/g
while ((m = esRe.exec(content)) !== null) {
elements.apiCalls.push({ url: m[1], method: 'SSE', line: content.slice(0, m.index).split('\n').length })
}
// --- JSX top-level elements (className or tag patterns) ---
const jsxRe = /<(\w+)\s+className=["']([^"']+)["']/g
while ((m = jsxRe.exec(content)) !== null) {
elements.jsxElements.push({ tag: m[1], className: m[2] })
}
}
if (ext === '.py') {
// --- Python functions ---
const pyFnRe = /^(?:async\s+)?def\s+(\w+)\s*\(/gm
while ((m = pyFnRe.exec(content)) !== null) {
elements.functions.push({ name: m[1], line: content.slice(0, m.index).split('\n').length })
}
// --- Python classes ---
const pyClassRe = /^class\s+(\w+)(?:\(([^)]*)\))?:/gm
while ((m = pyClassRe.exec(content)) !== null) {
elements.functions.push({ name: m[1], line: content.slice(0, m.index).split('\n').length, type: 'class', bases: m[2] })
}
// --- Python constants (ALL_CAPS) ---
const pyConstRe = /^([A-Z][A-Z_0-9]+)\s*=\s*(.+)/gm
while ((m = pyConstRe.exec(content)) !== null) {
elements.constants.push({ name: m[1], value: m[2].slice(0, 100), line: content.slice(0, m.index).split('\n').length })
}
}
return elements
}
// Generate Cypher queries for deep code elements
function deepElementQueries(elements, filePath) {
const queries = []
const fileSlug = slugify(filePath)
const fileId = `thing:file:${fileSlug}`
// stability = trust proxy on nodes:
// 1.0 = parsed from code (function def, state decl, route)
// 0.7 = inferred (hooks, intra-file calls)
// 0.3 = proposed (from doc mention, skeleton)
// Functions → Thing(subtype=code_function)
for (const fn of elements.functions) {
const fnId = `thing:fn:${fileSlug}:${slugify(fn.name)}`
const fnType = fn.type === 'class' ? 'code_class' : 'code_function'
queries.push(
`MERGE (n:Thing {id: '${esc(fnId)}'}) SET n.name = '${esc(fn.name)}', n.subtype = '${fnType}', n.weight = 0.6, n.energy = 0.4, n.stability = 1.0, n.line = ${fn.line || 0}, n.source_file = '${esc(filePath)}'`
)
queries.push(
`MATCH (fn:Thing {id: '${esc(fnId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (fn)-[r:link]->(file) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.5, r.permanence = 0.9, r.trust = 1.0, r.friction = 0.0, r.weight = 0.7`
)
}
// State vars → Thing(subtype=state_var)
for (const s of elements.state) {
const stateId = `thing:state:${fileSlug}:${slugify(s.getter)}`
const sub = s.type === 'ref' ? 'ref' : 'state_var'
queries.push(
`MERGE (n:Thing {id: '${esc(stateId)}'}) SET n.name = '${esc(s.getter)}', n.subtype = '${sub}', n.weight = 0.5, n.energy = 0.3, n.stability = 0.6, n.initial_value = '${esc(s.initial || 'undefined')}', n.setter = '${esc(s.setter || '')}', n.source_file = '${esc(filePath)}'`
)
queries.push(
`MATCH (sv:Thing {id: '${esc(stateId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (sv)-[r:link]->(file) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.5, r.permanence = 0.85, r.trust = 1.0, r.friction = 0.0, r.weight = 0.5`
)
// Link setter function to state if setter is used in a function
if (s.setter) {
for (const fn of elements.functions) {
if (fn.bodySnippet && fn.bodySnippet.includes(s.setter)) {
const fnId = `thing:fn:${fileSlug}:${slugify(fn.name)}`
queries.push(
`MATCH (fn:Thing {id: '${esc(fnId)}'}), (sv:Thing {id: '${esc(stateId)}'}) MERGE (fn)-[r:link]->(sv) SET r.r_type = 'MUTATES', r.hierarchy = 0.1, r.permanence = 0.7, r.trust = 0.9, r.friction = 0.1, r.weight = 0.5`
)
}
}
}
}
// Constants → Thing(subtype=config)
for (const c of elements.constants) {
const constId = `thing:const:${fileSlug}:${slugify(c.name)}`
queries.push(
`MERGE (n:Thing {id: '${esc(constId)}'}) SET n.name = '${esc(c.name)}', n.subtype = 'config', n.weight = 0.4, n.energy = 0.2, n.stability = 0.9, n.value = '${esc(c.value)}', n.source_file = '${esc(filePath)}'`
)
queries.push(
`MATCH (c:Thing {id: '${esc(constId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (c)-[r:link]->(file) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.4, r.permanence = 0.9, r.trust = 1.0, r.friction = 0.0, r.weight = 0.4`
)
}
// Hooks → Narrative(subtype=hook)
for (const h of elements.hooks) {
const hookId = `narrative:hook:${fileSlug}:${h.type}_${h.index}`
queries.push(
`MERGE (n:Narrative {id: '${esc(hookId)}'}) SET n.name = '${esc(h.type + ' #' + h.index + ': ' + h.purpose.slice(0, 60))}', n.subtype = 'hook', n.weight = 0.6, n.energy = 0.4, n.stability = 0.7, n.deps = '${esc(h.deps.join(', '))}', n.source_file = '${esc(filePath)}'`
)
queries.push(
`MATCH (hook:Narrative {id: '${esc(hookId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (hook)-[r:link]->(file) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.4, r.permanence = 0.85, r.trust = 1.0, r.friction = 0.0, r.weight = 0.6`
)
// Link hook to state it depends on
for (const dep of h.deps) {
const depStateId = `thing:state:${fileSlug}:${slugify(dep)}`
queries.push(
`MATCH (hook:Narrative {id: '${esc(hookId)}'}), (sv:Thing {id: '${esc(depStateId)}'}) MERGE (hook)-[r:link]->(sv) SET r.r_type = 'DEPENDS_ON', r.hierarchy = -0.2, r.permanence = 0.7, r.trust = 0.9, r.friction = 0.1, r.weight = 0.5`
)
}
}
// Routes → Thing(subtype=api_endpoint)
for (const rt of elements.routes) {
const routeId = `thing:route:${slugify(rt.method + '_' + rt.path)}`
queries.push(
`MERGE (n:Thing {id: '${esc(routeId)}'}) SET n.name = '${esc(rt.method + ' ' + rt.path)}', n.subtype = 'api_endpoint', n.weight = 0.8, n.energy = 0.5, n.stability = 0.8, n.method = '${rt.method}', n.path = '${esc(rt.path)}', n.source_file = '${esc(filePath)}'`
)
queries.push(
`MATCH (rt:Thing {id: '${esc(routeId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (rt)-[r:link]->(file) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.3, r.permanence = 0.9, r.trust = 1.0, r.friction = 0.0, r.weight = 0.8`
)
}
// API calls → links to routes (cross-file CALLS)
for (const call of elements.apiCalls) {
// Normalize URL: strip template literals → /api/stream/:graph
const normalizedPath = call.url.replace(/\$\{[^}]+\}/g, ':param').replace(/\/:[^/]+/g, '/:param')
// Try to match to a route
const routeId = `thing:route:${slugify(call.method + '_' + normalizedPath)}`
// Find which function makes this call
let callerFnId = null
for (const fn of elements.functions) {
if (fn.bodySnippet && (fn.bodySnippet.includes(call.url.slice(0, 20)) || fn.bodySnippet.includes('fetch') || fn.bodySnippet.includes('EventSource'))) {
callerFnId = `thing:fn:${fileSlug}:${slugify(fn.name)}`
break
}
}
const fromId = callerFnId || fileId
queries.push(
`MATCH (caller {id: '${esc(fromId)}'}) MERGE (caller)-[r:link]->(rt:Thing {id: '${esc(routeId)}'}) SET r.r_type = 'CALLS', r.hierarchy = 0.0, r.permanence = 0.8, r.trust = 0.85, r.friction = 0.15, r.weight = 0.6, r.method = '${call.method}', r.url = '${esc(call.url)}'`
)
}
// Intra-file function calls: if function A's body mentions function B's name
for (const fnA of elements.functions) {
if (!fnA.bodySnippet) continue
for (const fnB of elements.functions) {
if (fnA.name === fnB.name) continue
if (fnA.bodySnippet.includes(fnB.name + '(') || fnA.bodySnippet.includes(fnB.name + '\n')) {
const aId = `thing:fn:${fileSlug}:${slugify(fnA.name)}`
const bId = `thing:fn:${fileSlug}:${slugify(fnB.name)}`
queries.push(
`MATCH (a:Thing {id: '${esc(aId)}'}), (b:Thing {id: '${esc(bId)}'}) MERGE (a)-[r:link]->(b) SET r.r_type = 'CALLS', r.hierarchy = 0.1, r.permanence = 0.8, r.trust = 0.9, r.friction = 0.05, r.weight = 0.5`
)
}
}
}
return queries
}
async function main() {
console.log(`Scanning ${ROOT}...`)
const { dirs, files } = await walk(ROOT)
console.log(`Found ${dirs.length} directories, ${files.length} files`)
const queries = []
// Create Space nodes for directories
for (const d of dirs) {
const id = `space:dir:${slugify(d.relPath)}`
const parentRel = dirname(d.relPath)
const parentId = parentRel === '.' ? null : `space:dir:${slugify(parentRel)}`
queries.push(
`MERGE (n:Space {id: '${esc(id)}'}) SET n.name = '${esc(d.relPath)}', n.subtype = 'module', n.weight = 0.7, n.stability = 0.8, n.energy = 0.3, n.space_hint = 'directory'`
)
if (parentId) {
queries.push(
`MATCH (child:Space {id: '${esc(id)}'}), (parent:Space {id: '${esc(parentId)}'}) MERGE (child)-[r:link]->(parent) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.5, r.permanence = 0.9, r.trust = 1.0, r.friction = 0.0, r.weight = 0.8`
)
}
}
// Create Thing nodes for files
for (const f of files) {
const id = `thing:file:${slugify(f.relPath)}`
const parentRel = dirname(f.relPath)
const parentId = parentRel === '.' ? null : `space:dir:${slugify(parentRel)}`
const sub = fileSubtype(f.ext, f.name)
queries.push(
`MERGE (n:Thing {id: '${esc(id)}'}) SET n.name = '${esc(f.relPath)}', n.subtype = '${sub}', n.weight = 0.5, n.stability = 0.7, n.energy = 0.3`
)
if (parentId) {
queries.push(
`MATCH (child:Thing {id: '${esc(id)}'}), (parent:Space {id: '${esc(parentId)}'}) MERGE (child)-[r:link]->(parent) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.5, r.permanence = 0.9, r.trust = 1.0, r.friction = 0.0, r.weight = 0.6`
)
}
}
// ==========================================================================
// PHASE 0: AUTO-RESOLVE COMPLETED TASKS
// ==========================================================================
// Check existing task_run nodes: if their AFFECTS link condition is now met,
// mark status='done' and set energy=0 (L7 will prune them on decay).
if (!DRY_RUN) {
const redisP0 = createClient({ url: `redis://${process.env.FALKORDB_HOST || 'localhost'}:${process.env.FALKORDB_PORT || 6379}` })
await redisP0.connect()
try {
const pendingTasks = await redisP0.sendCommand(['GRAPH.QUERY', GRAPH,
`MATCH (task:Moment)-[r:link]->(target) WHERE task.type = 'task_run' AND task.status = 'pending' AND r.condition IS NOT NULL RETURN task.id, r.condition, r.condition_target`])
let resolved = 0
for (const row of (pendingTasks?.[1] || [])) {
if (!Array.isArray(row) || row.length < 3) continue
const [taskId, condition, condTarget] = row
let met = false
if (condition === 'file_exists') {
met = files.some(f => f.relPath === condTarget)
} else if (condition === 'no_throw_not_implemented') {
try {
const content = await readFile(condTarget, 'utf-8')
met = !content.includes('throw new Error(\'Not implemented') && !content.includes('raise NotImplementedError')
} catch (_) { met = false }
} else if (condition === 'doc_mentions') {
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
if (content.includes('`' + condTarget + '()`')) { met = true; break }
} catch (_) {}
}
} else if (condition === 'function_implemented') {
const [fnName, fnFile] = (condTarget || '').split(':')
if (fnFile) {
try {
const content = await readFile(fnFile, 'utf-8')
met = content.includes(`function ${fnName}`) || content.includes(`def ${fnName}`)
// Also check it's not just a stub
if (met && (content.includes('throw new Error(\'Not implemented') || content.includes('raise NotImplementedError'))) met = false
} catch (_) { met = false }
}
} else if (condition === 'status_canonical') {
try {
const content = await readFile(condTarget, 'utf-8')
met = /^STATUS:\s*(CANONICAL|STABLE)/m.test(content)
} catch (_) { met = false }
} else if (condition === 'has_caller') {
// Check if any client file calls this route
met = allApiCalls.length > 0 // will be populated later — skip for now
}
if (met) {
await redisP0.sendCommand(['GRAPH.QUERY', GRAPH,
`MATCH (task:Moment {id: '${esc(taskId)}'}) SET task.status = 'done', task.energy = 0, task.completed_at_s = ${Math.floor(Date.now() / 1000)}`])
resolved++
}
}
if (resolved > 0) console.log(`Phase 0: Auto-resolved ${resolved} completed tasks`)
} catch (e) { console.log(`Phase 0 skipped: ${e.message?.slice(0, 60)}`) }
await redisP0.quit()
}
// --- DEEP CODE PARSING ---
// Extract granular elements from code files and wire them together
let deepCount = 0
const allRoutes = [] // collect across files for cross-file wiring
const allApiCalls = [] // collect across files for cross-file wiring
for (const f of files) {
if (!['.js', '.jsx', '.ts', '.tsx', '.py'].includes(f.ext)) continue
if (f.relPath.startsWith('')) continue // skip vendored
try {
const content = await readFile(f.relPath, 'utf-8')
const elements = parseCodeDeep(content, f.relPath)
const deepQueries = deepElementQueries(elements, f.relPath)
queries.push(...deepQueries)
deepCount += deepQueries.length
// Collect routes and API calls for cross-file wiring
for (const rt of elements.routes) allRoutes.push({ ...rt, file: f.relPath })
for (const call of elements.apiCalls) allApiCalls.push({ ...call, file: f.relPath })
} catch (_) {}
}
// Cross-file wiring: API calls in client → routes in server
for (const call of allApiCalls) {
const normalizedUrl = call.url.replace(/\$\{[^}]+\}/g, ':param')
for (const rt of allRoutes) {
// Match: same method and path pattern
const routePattern = rt.path.replace(/:[^/]+/g, ':param')
if (call.method === rt.method && normalizedUrl.includes(routePattern.replace('/api', ''))) {
const callFileId = `thing:file:${slugify(call.file)}`
const routeId = `thing:route:${slugify(rt.method + '_' + rt.path)}`
queries.push(
`MATCH (caller:Thing {id: '${esc(callFileId)}'}), (route:Thing {id: '${esc(routeId)}'}) MERGE (caller)-[r:link]->(route) SET r.r_type = 'CALLS', r.hierarchy = 0.0, r.permanence = 0.8, r.trust = 0.85, r.friction = 0.15, r.weight = 0.7`
)
}
// SSE special case
if (call.method === 'SSE' && rt.path.includes('stream')) {
const callFileId = `thing:file:${slugify(call.file)}`
const routeId = `thing:route:${slugify(rt.method + '_' + rt.path)}`
queries.push(
`MATCH (caller:Thing {id: '${esc(callFileId)}'}), (route:Thing {id: '${esc(routeId)}'}) MERGE (caller)-[r:link]->(route) SET r.r_type = 'SUBSCRIBES', r.hierarchy = -0.1, r.permanence = 0.8, r.trust = 0.85, r.friction = 0.1, r.weight = 0.7`
)
}
}
}
console.log(`Deep parsing: ${deepCount} granular element queries`)
// --- DOC-TO-CODE WIRING ---
// Parse doc chain files for function/class/behavior references and link to code elements
let docCodeLinks = 0
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
const docFileId = `thing:file:${slugify(f.relPath)}`
// Find function references in docs: `functionName()` or `ClassName`
const fnRefs = [...content.matchAll(/`(\w+)\(\)`/g)].map(m => m[1])
const classRefs = [...content.matchAll(/`(\w+)`\s*(?:class|object|instance)/gi)].map(m => m[1])
// Find ALGORITHM step headings → link to functions that match
const algoSteps = [...content.matchAll(/^###\s+(?:Step\s+\d+:\s*)?(.+)/gm)].map(m => m[1].trim())
// Find BEHAVIOR headings → B1: Observable Result
const behaviors = [...content.matchAll(/^###\s+B(\d+):\s*(.+)/gm)].map(m => ({ id: `B${m[1]}`, name: m[2].trim() }))
// Find flow steps referencing files: file: path/to/file.py, function: name
const flowFns = [...content.matchAll(/function:\s*(\w+)/g)].map(m => m[1])
// Combine all referenced function names
const allRefs = new Set([...fnRefs, ...classRefs, ...flowFns])
// For each referenced function, use MATCH-based MERGE so links only created if both exist
for (const ref of allRefs) {
const refSlug = slugify(ref)
// Use a Cypher pattern that finds the function node by name suffix
queries.push(
`MATCH (fn:Thing), (doc:Thing {id: '${esc(docFileId)}'}) WHERE fn.subtype IN ['code_function', 'code_class'] AND fn.name = '${esc(ref)}' MERGE (fn)-[r:link]->(doc) SET r.r_type = 'IMPLEMENTS', r.hierarchy = -0.4, r.permanence = 0.8, r.trust = 0.8, r.friction = 0.1, r.weight = 0.7`
)
docCodeLinks++
}
// Link API endpoints mentioned in docs to route nodes
const apiRefs = [...content.matchAll(/(?:GET|POST|PUT|DELETE)\s+(\/api\/[^\s`"']+)/g)]
for (const apiRef of apiRefs) {
const routeId = `thing:route:${slugify(apiRef[0].replace(/\s+/g, '_'))}`
queries.push(
`MATCH (rt:Thing {id: '${esc(routeId)}'}), (doc:Thing {id: '${esc(docFileId)}'}) MERGE (rt)-[r:link]->(doc) SET r.r_type = 'IMPLEMENTS', r.hierarchy = -0.3, r.permanence = 0.8, r.trust = 0.85, r.friction = 0.1, r.weight = 0.7`
)
docCodeLinks++
}
} catch (_) {}
}
console.log(`Doc↔Code wiring: ${docCodeLinks} potential links`)
// Build a file lookup set for fast resolution
const fileSet = new Set(files.map(f => f.relPath))
// Parse imports for code files and create DEPENDS_ON links
let depCount = 0
let externalDeps = new Set()
for (const f of files) {
if (!['.js', '.jsx', '.ts', '.tsx', '.py'].includes(f.ext)) continue
try {
const content = await readFile(f.relPath, 'utf-8')
const imports = parseImports(content, f.relPath)
const sourceId = `thing:file:${slugify(f.relPath)}`
for (const imp of imports) {
if (imp.type === 'external') {
externalDeps.add(imp.spec.split('/')[0]) // top-level package name
continue
}
const resolved = resolveImport(imp.spec, f.relPath)
// Try to find the target file (with or without extension)
const candidates = [resolved]
if (!extname(resolved)) {
candidates.push(
resolved + '.js', resolved + '.jsx', resolved + '.ts', resolved + '.tsx',
resolved + '.css', resolved + '.py',
resolved + '/index.js', resolved + '/index.jsx',
)
}
for (const candidate of candidates) {
if (fileSet.has(candidate)) {
const targetId = `thing:file:${slugify(candidate)}`
queries.push(
`MATCH (src:Thing {id: '${esc(sourceId)}'}), (tgt:Thing {id: '${esc(targetId)}'}) MERGE (src)-[r:link]->(tgt) SET r.r_type = 'DEPENDS_ON', r.hierarchy = 0.1, r.permanence = 0.85, r.trust = 0.9, r.friction = 0.1, r.weight = 0.5`
)
depCount++
break
}
}
}
} catch (_) { /* skip unreadable files */ }
}
// Parse doc chain IMPL pointers: "IMPL: path/to/file.py" → REFERENCES link
let implCount = 0
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
const implMatch = content.match(/^IMPL:\s+(.+)$/m)
if (implMatch) {
const implPath = implMatch[1].trim()
const sourceId = `thing:file:${slugify(f.relPath)}`
const targetId = `thing:file:${slugify(implPath)}`
if (fileSet.has(implPath)) {
queries.push(
`MATCH (doc:Thing {id: '${esc(sourceId)}'}), (code:Thing {id: '${esc(targetId)}'}) MERGE (doc)-[r:link]->(code) SET r.r_type = 'REFERENCES', r.hierarchy = 0.3, r.permanence = 0.85, r.trust = 0.9, r.friction = 0.1, r.weight = 0.7`
)
implCount++
}
}
} catch (_) {}
}
// --- HEALTH FLAGS ---
// Detect missing implementations, undocumented code, broken IMPL pointers
const issues = []
// 1. Docs with IMPL pointing to non-existent files
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
const implMatch = content.match(/^IMPL:\s+(.+)$/m)
if (implMatch) {
const implPath = implMatch[1].trim()
if (!implPath.includes('{') && !fileSet.has(implPath)) {
issues.push({ type: 'missing_impl', doc: f.relPath, target: implPath, severity: 'high' })
}
}
} catch (_) {}
}
// 2. Code files with no doc chain referencing them (undocumented code)
const referencedByDocs = new Set()
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
const implMatch = content.match(/^IMPL:\s+(.+)$/m)
if (implMatch) referencedByDocs.add(implMatch[1].trim())
} catch (_) {}
}
for (const f of files) {
if (!['.js', '.jsx', '.py'].includes(f.ext)) continue
if (f.relPath.startsWith('')) continue // skip vendored code
if (!referencedByDocs.has(f.relPath)) {
issues.push({ type: 'undocumented_code', file: f.relPath, severity: 'medium' })
}
}
// 3. IMPLEMENTATION docs listing PROPOSED files (lines ~0)
for (const f of files) {
if (f.ext !== '.md' || !f.name.startsWith('IMPLEMENTATION')) continue
try {
const content = await readFile(f.relPath, 'utf-8')
const proposed = [...content.matchAll(/\|\s*`([^`]+)`\s*\|[^|]+\|[^|]+\|\s*~?0\s*\|\s*PROPOSED\s*\|/g)]
for (const m of proposed) {
issues.push({ type: 'proposed_not_built', doc: f.relPath, file: m[1], severity: 'high' })
}
} catch (_) {}
}
// 4. Doc chain files with STATUS: DRAFT or PROPOSED
for (const f of files) {
if (f.ext !== '.md') continue
try {
const content = await readFile(f.relPath, 'utf-8')
const statusMatch = content.match(/^STATUS:\s+(DRAFT|PROPOSED)/m)
if (statusMatch) {
issues.push({ type: 'draft_doc', file: f.relPath, status: statusMatch[1], severity: 'low' })
}
} catch (_) {}
}
// Create task_run nodes for each issue — auto-assignment picks them up
// via task_assignment.py select_best_agent() (cosine_sim × weight × energy × 0.5^active)
const now = Math.floor(Date.now() / 1000)
for (const issue of issues) {
const desc = issue.type === 'missing_impl' ? `IMPL points to missing file: ${issue.target} (from ${issue.doc})`
: issue.type === 'undocumented_code' ? `Code file has no doc chain: ${issue.file}`
: issue.type === 'proposed_not_built' ? `PROPOSED file not built: ${issue.file} (in ${issue.doc})`
: issue.type === 'draft_doc' ? `Doc is ${issue.status}: ${issue.file}`
: `Unknown issue: ${JSON.stringify(issue)}`
const issueId = `task:ingest:${slugify(issue.type + '_' + (issue.target || issue.file || issue.doc))}`
const frictionMap = { high: 0.8, medium: 0.5, low: 0.2 }
// task_run node — pending status → auto-assignment engine claims it
queries.push(
`MERGE (n:Moment {id: '${esc(issueId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.content = '${esc(desc)}', n.severity = '${issue.severity}', n.issue_type = '${issue.type}', n.weight = ${frictionMap[issue.severity] + 0.2}, n.energy = ${frictionMap[issue.severity]}, n.friction = ${frictionMap[issue.severity]}, n.stability = 0.3, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
// Link task to target via AFFECTS — condition encodes exit criteria
const targetFile = issue.target || issue.file || issue.doc
const targetId = `thing:file:${slugify(targetFile)}`
// Map issue_type → verifiable condition
const conditionMap = {
missing_impl: 'file_exists', // file must exist on disk
undocumented_code: 'doc_mentions', // a doc chain file must reference this function
proposed_not_built: 'file_exists', // the proposed file must exist with >0 lines
draft_doc: 'status_canonical', // doc STATUS must be CANONICAL or STABLE
}
const condition = conditionMap[issue.type] || 'manual'
if (fileSet.has(targetFile)) {
queries.push(
`MATCH (task:Moment {id: '${esc(issueId)}'}), (file:Thing {id: '${esc(targetId)}'}) MERGE (task)-[r:link]->(file) SET r.r_type = 'AFFECTS', r.hierarchy = -0.3, r.permanence = 0.5, r.trust = 0.7, r.friction = ${frictionMap[issue.severity]}, r.weight = 0.6, r.condition = '${condition}', r.condition_target = '${esc(targetFile)}'`
)
}
// Link task to the org so auto-assignment can find it
queries.push(
`MATCH (task:Moment {id: '${esc(issueId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.8, r.weight = 0.5`
)
}
// ==========================================================================
// PHASE 4: VERIFY / BUILD / LINT / AUTO-FIX
// ==========================================================================
const { execSync } = await import('child_process')
const { mkdir: mkdirV, writeFile: writeFileV, access } = await import('fs/promises')
// --- 4a. GRAPH INTEGRITY ---
console.log('\n--- PHASE 4a: Graph integrity ---')
let integrityIssues = 0
// Orphan code_function nodes (no BELONGS_TO link to a file)
for (const f of files) {
if (!['.js', '.jsx', '.py'].includes(f.ext)) continue
if (f.relPath.startsWith('')) continue
try {
const content = await readFile(f.relPath, 'utf-8')
const elements = parseCodeDeep(content, f.relPath)
const fileSlug = slugify(f.relPath)
// Check: every function that calls another — does the callee exist?
for (const fnA of elements.functions) {
if (!fnA.bodySnippet) continue
// Extract function calls from body
const callMatches = [...fnA.bodySnippet.matchAll(/(\w+)\s*\(/g)]
for (const cm of callMatches) {
const callee = cm[1]
if (['if', 'for', 'while', 'switch', 'return', 'catch', 'console', 'JSON', 'Math', 'Object',
'Array', 'Promise', 'Error', 'Date', 'Set', 'Map', 'parseInt', 'parseFloat', 'setTimeout',
'setInterval', 'clearInterval', 'fetch', 'require', 'import'].includes(callee)) continue
if (callee.startsWith('set') && callee.length > 3) continue // React setters
// Check if callee exists in this file or as an import
const calleeExists = elements.functions.some(fn => fn.name === callee)
const isImported = content.includes(`import`) && content.includes(callee)
if (!calleeExists && !isImported && callee.length > 2) {
// Possible missing function — low severity, might be from a library
const taskId = `task:verify:missing_fn_${slugify(callee + '_' + f.relPath)}`
const desc = `${fnA.name}() calls ${callee}() but it's not defined locally or imported — check if it exists (${f.relPath}:${fnA.line})`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'low', n.issue_type = 'verify_missing_callee', n.weight = 0.3, n.energy = 0.3, n.friction = 0.2, n.stability = 0.5, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.4, r.trust = 0.7, r.weight = 0.3`
)
integrityIssues++
}
}
}
} catch (_) {}
}
console.log(` ${integrityIssues} potential missing callees`)
// --- 4b. BUILD CHECK ---
console.log('\n--- PHASE 4b: Build check ---')
if (!DRY_RUN) {
try {
const buildResult = execSync('npx vite build --mode development 2>&1 || true', {
maxBuffer: 10 * 1024 * 1024, encoding: 'utf-8', timeout: 60000, cwd: '.'
})
const buildErrors = []
// Parse vite build errors
const errorLines = buildResult.split('\n').filter(l => l.includes('ERROR') || l.includes('error') || l.includes('Could not resolve'))
for (const line of errorLines) {
buildErrors.push(line.trim())
}
if (buildErrors.length > 0) {
console.log(` ${buildErrors.length} build errors:`)
for (const e of buildErrors.slice(0, 10)) console.log(` ${e}`)
const taskId = `task:verify:build_errors`
const desc = `Build failed with ${buildErrors.length} errors: ${buildErrors[0].slice(0, 80)}`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'high', n.issue_type = 'build_error', n.weight = 1.0, n.energy = 0.9, n.friction = 0.9, n.stability = 0.2, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.9, r.weight = 0.8`
)
issues.push({ type: 'build_error', file: 'vite build', severity: 'high' })
} else {
console.log(' Build OK')
}
} catch (e) { console.log(` Build check skipped: ${e.message?.slice(0, 60)}`) }
}
// --- 4c. SYNTAX VALIDATION (JS files with skeleton stubs) ---
console.log('\n--- PHASE 4c: Skeleton validation ---')
let syntaxFixes = 0
for (const f of files) {
if (!['.js', '.jsx'].includes(f.ext)) continue
if (f.relPath.startsWith('') || f.relPath.startsWith('node_modules/')) continue
try {
const content = await readFile(f.relPath, 'utf-8')
// Check for missing imports that are used
const usedGlobals = new Set()
const importedNames = new Set()
// Collect imports
for (const m of content.matchAll(/import\s+\{([^}]+)\}\s+from/g)) {
for (const name of m[1].split(',')) importedNames.add(name.trim())
}
for (const m of content.matchAll(/import\s+(\w+)\s+from/g)) {
importedNames.add(m[1])
}
for (const m of content.matchAll(/import\s+\*\s+as\s+(\w+)\s+from/g)) {
importedNames.add(m[1])
}
// Check: file uses 'express' but doesn't import it?
if (content.includes('express()') && !importedNames.has('express') && !content.includes("import express")) {
const fix = `import express from 'express'`
if (!DRY_RUN) {
// Auto-fix: prepend import
const fixed = fix + '\n' + content
await writeFileV(f.relPath, fixed)
console.log(` ✓ auto-fixed missing import in ${f.relPath}: ${fix}`)
syntaxFixes++
} else {
console.log(` Would fix: ${f.relPath} — ${fix}`)
}
}
// Check: file has NotImplementedError throws (skeleton) → track as needing implementation
const notImplCount = (content.match(/throw new Error\('Not implemented/g) || []).length
if (notImplCount > 0) {
const taskId = `task:verify:skeleton_${slugify(f.relPath)}`
const desc = `${f.relPath} has ${notImplCount} skeleton stub(s) — implement the TODO functions`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'high', n.issue_type = 'skeleton_stub', n.weight = 0.9, n.energy = 0.8, n.friction = 0.6, n.stability = 0.2, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
const fileId = `thing:file:${slugify(f.relPath)}`
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (file:Thing {id: '${esc(fileId)}'}) MERGE (task)-[r:link]->(file) SET r.r_type = 'AFFECTS', r.hierarchy = -0.3, r.permanence = 0.5, r.trust = 0.9, r.friction = 0.6, r.weight = 0.7, r.condition = 'no_throw_not_implemented', r.condition_target = '${esc(f.relPath)}'`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.8, r.weight = 0.5`
)
issues.push({ type: 'skeleton_stub', file: f.relPath, severity: 'high' })
}
} catch (_) {}
}
// Same for Python skeletons
for (const f of files) {
if (f.ext !== '.py') continue
if (f.relPath.startsWith('')) continue
try {
const content = await readFile(f.relPath, 'utf-8')
const notImplCount = (content.match(/raise NotImplementedError/g) || []).length
if (notImplCount > 0) {
const taskId = `task:verify:skeleton_${slugify(f.relPath)}`
const desc = `${f.relPath} has ${notImplCount} skeleton stub(s) — implement the TODO functions`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'high', n.issue_type = 'skeleton_stub', n.weight = 0.9, n.energy = 0.8, n.friction = 0.6, n.stability = 0.2, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.8, r.weight = 0.5`
)
issues.push({ type: 'skeleton_stub', file: f.relPath, severity: 'high' })
}
} catch (_) {}
}
console.log(` ${syntaxFixes} auto-fixes applied`)
// --- 4d. CROSS-REFERENCE VALIDATION ---
// Check that every API route has at least one client calling it
console.log('\n--- PHASE 4d: API coverage ---')
const calledRoutes = new Set()
for (const call of allApiCalls) {
const normalizedUrl = call.url.replace(/\$\{[^}]+\}/g, ':param')
calledRoutes.add(normalizedUrl)
}
for (const rt of allRoutes) {
const normalizedPath = rt.path.replace(/:[^/]+/g, ':param')
let isCalled = false
for (const called of calledRoutes) {
if (called.includes(normalizedPath.replace('/api', ''))) { isCalled = true; break }
}
if (!isCalled) {
console.log(` UNCALLED: ${rt.method} ${rt.path} (${rt.file}:${rt.line})`)
const taskId = `task:verify:uncalled_route_${slugify(rt.method + '_' + rt.path)}`
const desc = `API route ${rt.method} ${rt.path} has no client caller — dead code or missing integration`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'medium', n.issue_type = 'uncalled_route', n.weight = 0.5, n.energy = 0.4, n.friction = 0.3, n.stability = 0.5, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
const routeId = `thing:route:${slugify(rt.method + '_' + rt.path)}`
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (rt:Thing {id: '${esc(routeId)}'}) MERGE (task)-[r:link]->(rt) SET r.r_type = 'AFFECTS', r.hierarchy = -0.3, r.permanence = 0.4, r.trust = 0.7, r.friction = 0.3, r.weight = 0.5, r.condition = 'has_caller', r.condition_target = '${esc(rt.method + ' ' + rt.path)}'`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.8, r.weight = 0.5`
)
issues.push({ type: 'uncalled_route', file: rt.file, severity: 'medium' })
}
}
// --- 4e. TEST RUNNER ---
console.log('\n--- PHASE 4e: Test runner ---')
if (!DRY_RUN) {
// Try npm test
try {
const testResult = execSync('npm test 2>&1 || true', {
maxBuffer: 10 * 1024 * 1024, encoding: 'utf-8', timeout: 60000, cwd: '.'
})
const testFailures = []
// Parse common test output patterns
// Jest: FAIL src/path/to/test.js
for (const m of testResult.matchAll(/FAIL\s+(\S+)/g)) {
testFailures.push({ file: m[1], framework: 'jest' })
}
// Vitest: ✗ test name (file)
for (const m of testResult.matchAll(/[✗×]\s+(.+)\s+\((\S+)\)/g)) {
testFailures.push({ file: m[2], test: m[1], framework: 'vitest' })
}
// pytest: FAILED path/to/test.py::test_name
for (const m of testResult.matchAll(/FAILED\s+(\S+)::(\S+)/g)) {
testFailures.push({ file: m[1], test: m[2], framework: 'pytest' })
}
// Generic: error/Error in output with file path
if (testFailures.length === 0) {
for (const m of testResult.matchAll(/(?:Error|error|FAILED).*?(\S+\.(?:js|jsx|ts|tsx|py))/g)) {
testFailures.push({ file: m[1], framework: 'generic' })
}
}
if (testFailures.length > 0) {
console.log(` ${testFailures.length} test failures:`)
for (const tf of testFailures.slice(0, 10)) {
console.log(` FAIL: ${tf.file}${tf.test ? '::' + tf.test : ''}`)
const taskId = `task:test:${slugify(tf.file + '_' + (tf.test || 'suite'))}`
const desc = `Test failure: ${tf.file}${tf.test ? '::' + tf.test : ''}`
queries.push(
`MERGE (n:Moment {id: '${esc(taskId)}'}) SET n.name = '${esc(desc.slice(0, 120))}', n.type = 'task_run', n.subtype = 'task_run', n.status = 'pending', n.synthesis = '${esc(desc)}', n.severity = 'high', n.issue_type = 'test_failure', n.weight = 0.9, n.energy = 0.9, n.friction = 0.9, n.stability = 0.1, n.created_at_s = ${now}, n.updated_at_s = ${now}`
)
const testFileId = `thing:file:${slugify(tf.file)}`
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (file:Thing {id: '${esc(testFileId)}'}) MERGE (task)-[r:link]->(file) SET r.r_type = 'AFFECTS', r.hierarchy = -0.3, r.permanence = 0.5, r.trust = 0.9, r.friction = 0.9, r.weight = 0.8, r.condition = 'test_passes', r.condition_target = '${esc(tf.file + (tf.test ? '::' + tf.test : ''))}'`
)
queries.push(
`MATCH (task:Moment {id: '${esc(taskId)}'}), (org:Actor {id: 'org:ai_dev_dashboard'}) MERGE (task)-[r:link]->(org) SET r.r_type = 'BELONGS_TO', r.hierarchy = -0.6, r.permanence = 0.5, r.trust = 0.8, r.weight = 0.5`
)
issues.push({ type: 'test_failure', file: tf.file, severity: 'high' })
}
} else {
console.log(' Tests passed (or no test suite found)')
}
} catch (e) { console.log(` Test runner skipped: ${e.message?.slice(0, 60)}`) }
}
// 6. Detect incomplete doc chains and generate fix commands
// A complete chain has: OBJECTIVES, PATTERNS, BEHAVIORS, ALGORITHM, VALIDATION, IMPLEMENTATION, HEALTH, SYNC
const CHAIN_DOCS = ['OBJECTIVES', 'PATTERNS', 'BEHAVIORS', 'ALGORITHM', 'VALIDATION', 'IMPLEMENTATION', 'HEALTH', 'SYNC']
const docChainDirs = new Set()
for (const f of files) {