-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimmune-adapter.js
More file actions
executable file
·1696 lines (1463 loc) · 61.7 KB
/
Copy pathimmune-adapter.js
File metadata and controls
executable file
·1696 lines (1463 loc) · 61.7 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
'use strict';
const fs = require('fs');
const path = require('path');
const lockfile = require('proper-lockfile');
const { sanitize } = require('./sanitizer');
const IMMUNE_DIR = __dirname;
const DB_PATH = path.join(IMMUNE_DIR, 'immune.sqlite');
const JSON_AB = path.join(IMMUNE_DIR, 'immune_memory.json');
const JSON_CS = path.join(IMMUNE_DIR, 'cheatsheet_memory.json');
const MIGRATION_FILE = path.join(IMMUNE_DIR, 'migration_state.json');
const CONTEXT_DIR = path.join(IMMUNE_DIR, 'context');
const ARCHIVE_DIR = path.join(CONTEXT_DIR, 'archive');
const MEMORY_MD = path.join(IMMUNE_DIR, '..', 'MEMORY.md'); // override via MEMORY_MD env var
const USER_MD = path.join(IMMUNE_DIR, 'USER.md');
const ARCHIVE_AB = path.join(IMMUNE_DIR, 'archived_antibodies.json');
const ARCHIVE_CS = path.join(IMMUNE_DIR, 'archived_strategies.json');
const LOCK_FILE = DB_PATH + '.lock';
const MAX_CHUNKS = 2000;
const RETENTION_DAYS = 90;
const LIMITS = { max_antibodies: 500, max_strategies: 300, max_sqlite_mb: 50, max_context_files: 500 };
// ── Deduplication Config ────────────────────────────────
const DEDUP_THRESHOLD_JACCARD = 0.55;
const DEDUP_THRESHOLD_EMBEDDING = 0.7;
const DEDUP_WEIGHTS = { jaccard: 0.5, substring: 0.3, domain: 0.2 };
const EMBEDDING_MODEL = 'Xenova/all-MiniLM-L6-v2';
const STOPWORDS = new Set(['the', 'a', 'an', 'is', 'are', 'was', 'were', 'be',
'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
'could', 'should', 'may', 'might', 'must', 'shall', 'can', 'need', 'dare',
'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by', 'from', 'as', 'into',
'through', 'during', 'before', 'after', 'above', 'below', 'between',
'and', 'but', 'or', 'nor', 'not', 'so', 'yet', 'both', 'either', 'neither',
'this', 'that', 'these', 'those', 'it', 'its', 'use', 'using', 'used']);
// ── Helpers ─────────────────────────────────────────────
function today() { return new Date().toISOString().slice(0, 10); }
function daysDiff(dateStr) {
return Math.floor((Date.now() - new Date(dateStr).getTime()) / 86400000);
}
function readJSON(p) {
try { return JSON.parse(fs.readFileSync(p, 'utf8')); }
catch { return null; }
}
function writeJSON(p, data) {
fs.writeFileSync(p, JSON.stringify(data, null, 2), 'utf8');
}
function ensureLockFile() {
if (!fs.existsSync(LOCK_FILE)) fs.writeFileSync(LOCK_FILE, '', 'utf8');
}
function getMigrationState() {
let state = readJSON(MIGRATION_FILE);
if (!state) {
state = { version: '5.1.0', phase: 1, started: today(), sessions_in_phase: 0,
sessions_required: 10, parity_passed: 0, last_parity: null,
frozen: false, frozen_since: null, total_frozen_days: 0 };
writeJSON(MIGRATION_FILE, state);
}
// Ensure freeze fields exist (migration from older state files)
if (state.frozen === undefined) {
state.frozen = false;
state.frozen_since = null;
state.total_frozen_days = 0;
writeJSON(MIGRATION_FILE, state);
}
return state;
}
function getFrozenDays() {
const state = getMigrationState();
let frozen = state.total_frozen_days || 0;
// If currently frozen, add days since freeze started
if (state.frozen && state.frozen_since) {
frozen += daysDiff(state.frozen_since);
}
return frozen;
}
// Adjusted daysDiff that subtracts frozen time
function daysDiffAdjusted(dateStr) {
return Math.max(0, daysDiff(dateStr) - getFrozenDays());
}
// ── TF-IDF Re-Ranking Engine ───────────────────────────
// Auto-switches: full-scan if < RERANK_THRESHOLD items, FTS4 pre-filter + re-rank if >=
const RERANK_THRESHOLD = 200; // switch from full-scan to FTS4+rerank
const RERANK_ALPHA = 0.6; // weight: textual similarity vs heat
const RERANK_MIN_SCORE = 0.08; // minimum composite score to include
const RERANK_FTS_CANDIDATES = 100; // max candidates from FTS4 pre-filter
let _dfTable = null;
let _dfCorpusSize = 0;
let _dfDirty = true; // rebuild on first use and after add/update
function buildDFTable(items) {
const df = {};
for (const item of items) {
const terms = tokenize(item.pattern + ' ' + (item.correction || item.example || ''));
for (const t of terms) df[t] = (df[t] || 0) + 1;
}
_dfTable = df;
_dfCorpusSize = items.length;
_dfDirty = false;
return df;
}
function tfidfVector(text, df, N) {
const terms = tokenize(text);
const tf = {};
for (const t of terms) tf[t] = (tf[t] || 0) + 1;
const vec = {};
for (const [t, count] of Object.entries(tf)) {
vec[t] = count * Math.log((N + 1) / ((df[t] || 0) + 1));
}
return vec;
}
function cosineSparse(a, b) {
let dot = 0, normA = 0, normB = 0;
for (const k in a) { normA += a[k] * a[k]; if (k in b) dot += a[k] * b[k]; }
for (const k in b) normB += b[k] * b[k];
return (normA && normB) ? dot / (Math.sqrt(normA) * Math.sqrt(normB)) : 0;
}
function charTrigrams(text) {
const s = text.toLowerCase().replace(/[^a-z0-9àâäéèêëïîôùûüÿçœæ]/g, ' ').replace(/\s+/g, ' ').trim();
const trigrams = new Set();
for (let i = 0; i <= s.length - 3; i++) trigrams.add(s.substring(i, i + 3));
return trigrams;
}
function jaccardTrigrams(setA, setB) {
if (setA.size === 0 && setB.size === 0) return 0;
let inter = 0;
for (const t of setA) { if (setB.has(t)) inter++; }
return inter / (setA.size + setB.size - inter);
}
function heatScore(item) {
const sevWeight = { critical: 1.0, warning: 0.6, info: 0.3 };
const sev = sevWeight[item.severity] || (item.effectiveness || 0.5); // strategies use effectiveness
const recency = Math.max(0, 1 - daysDiffAdjusted(item.last_seen || item.first_seen || today()) / 90);
const frequency = Math.min(1, (item.seen_count || 1) / 5);
return 0.4 * sev + 0.3 * recency + 0.3 * frequency;
}
async function rerankItems(items, query, domains, limit, type) {
if (!query || items.length === 0) return items;
// Try embeddings first (universal semantic), fallback to TF-IDF + trigrams
await ensureTransformersInstalled();
let queryEmbedding = null;
if (_embeddingsAvailable === true) {
queryEmbedding = await embedText(query);
}
// Ensure TF-IDF DF table is built (used as fallback or secondary signal)
if (_dfDirty || !_dfTable) {
const allItems = type === 'antibody'
? loadAntibodies().antibodies
: loadStrategies().strategies;
buildDFTable(allItems);
}
const queryVec = tfidfVector(query, _dfTable, _dfCorpusSize);
const queryTrigrams = charTrigrams(query);
// Score each candidate
const scored = [];
for (const item of items) {
const itemText = item.pattern + ' ' + (item.correction || item.example || '');
let textSim;
let engine;
if (queryEmbedding) {
// Embeddings available: use as primary similarity
const itemEmbedding = await embedText(itemText);
if (itemEmbedding) {
const embSim = cosineSimilarity(queryEmbedding, itemEmbedding);
// Normalize: MiniLM cosine is typically 0-1, but can be negative
textSim = Math.max(0, embSim);
engine = 'embedding';
} else {
// Fallback for this item
const tfidfSim = cosineSparse(queryVec, tfidfVector(itemText, _dfTable, _dfCorpusSize));
const trigramSim = jaccardTrigrams(queryTrigrams, charTrigrams(itemText));
textSim = 0.7 * tfidfSim + 0.3 * trigramSim;
engine = 'tfidf+trigrams';
}
} else {
// No embeddings: TF-IDF + trigrams
const tfidfSim = cosineSparse(queryVec, tfidfVector(itemText, _dfTable, _dfCorpusSize));
const trigramSim = jaccardTrigrams(queryTrigrams, charTrigrams(itemText));
textSim = 0.7 * tfidfSim + 0.3 * trigramSim;
engine = 'tfidf+trigrams';
}
const heat = heatScore(item);
const composite = RERANK_ALPHA * textSim + (1 - RERANK_ALPHA) * heat;
scored.push({ ...item, _score: { composite, textSim, heat, engine } });
}
// Sort ALL by composite score (criticals and non-criticals alike)
scored.sort((a, b) => b._score.composite - a._score.composite);
// Apply minimum score threshold on non-criticals only
const aboveThreshold = scored.filter(i =>
i._score.composite >= RERANK_MIN_SCORE || i.severity === 'critical'
);
// Take top results, but guarantee at least the top 3 criticals make it
const topCriticals = aboveThreshold.filter(i => i.severity === 'critical').slice(0, 3);
const topCriticalIds = new Set(topCriticals.map(c => c.id));
const others = aboveThreshold.filter(i => !topCriticalIds.has(i.id)).slice(0, limit - topCriticals.length);
const result = [...topCriticals, ...others]
.sort((a, b) => b._score.composite - a._score.composite)
.slice(0, limit);
// Diagnostic
if (result.length > 0 && result[0]._score.composite < 0.1) {
result._retrieval_warning = `Low relevance: best score ${result[0]._score.composite.toFixed(3)}`;
}
result._engine = scored.length > 0 ? scored[0]._score.engine : 'none';
return result;
}
// Escape a single FTS4 token by: (1) stripping FTS4 special chars, (2) doubling internal quotes,
// (3) wrapping in double quotes so the result is always treated as a literal phrase.
// Defends against user-controlled patterns leaking wildcards/operators into MATCH syntax.
function ftsEscapeTerm(term) {
const cleaned = term.replace(/["^()*]/g, ''); // strip FTS4 metacharacters
if (!cleaned) return null;
return `"${cleaned.replace(/"/g, '""')}"`;
}
function ftsBuildQuery(query) {
const terms = [...tokenize(query)].filter(t => t.length >= 2);
const escaped = terms.map(ftsEscapeTerm).filter(Boolean);
return escaped.length ? escaped.join(' OR ') : null;
}
async function getFTSCandidates(query, domains, type, limit) {
const db = await getDB();
const sourceType = type === 'antibody' ? 'antibody' : 'strategy';
const ftsQuery = ftsBuildQuery(query);
if (!ftsQuery) return new Set();
const sql = `SELECT source_id FROM chunks_fts WHERE chunks_fts MATCH ? AND source_type = ? LIMIT ?`;
const stmt = db.prepare(sql);
stmt.bind([ftsQuery, sourceType, limit]);
const ids = [];
while (stmt.step()) {
ids.push(stmt.getAsObject().source_id);
}
stmt.free();
return new Set(ids);
}
// ── Hot/Cold Classification ─────────────────────────────
function isHotAntibody(ab) {
if (ab.severity === 'critical') return true;
if (ab.seen_count >= 3) return true;
if (ab.last_seen && daysDiffAdjusted(ab.last_seen) < 30) return true;
return false;
}
function isHotStrategy(cs) {
if (cs.effectiveness >= 0.7) return true;
if (cs.seen_count >= 3) return true;
if (cs.last_seen && daysDiffAdjusted(cs.last_seen) < 30) return true;
return false;
}
function domainMatch(itemDomains, targetDomains) {
const d = Array.isArray(itemDomains) ? itemDomains : [itemDomains || '_global'];
return d.some(x => targetDomains.includes(x) || x === '_global');
}
// ── JSON Operations ─────────────────────────────────────
function loadAntibodies() {
const data = readJSON(JSON_AB);
if (!data) return { version: 4, antibodies: [], stats: { outputs_checked: 0, issues_caught: 0, antibodies_total: 0 } };
// v2 migration
if (data.version === 2) {
data.antibodies.forEach(ab => { if (ab.domain && !ab.domains) { ab.domains = [ab.domain]; delete ab.domain; } });
data.version = 3;
writeJSON(JSON_AB, data);
}
return data;
}
function loadStrategies() {
const data = readJSON(JSON_CS);
if (!data) return { version: 4, strategies: [], stats: { outputs_assisted: 0, strategies_applied: 0, strategies_total: 0 } };
return data;
}
// ── SQLite Operations ───────────────────────────────────
let _db = null;
async function getDB() {
if (_db) return _db;
const initSqlJs = require('sql.js');
const SQL = await initSqlJs();
if (fs.existsSync(DB_PATH)) {
const buf = fs.readFileSync(DB_PATH);
_db = new SQL.Database(buf);
} else {
_db = new SQL.Database();
}
initSchema(_db);
return _db;
}
function initSchema(db) {
db.run(`CREATE TABLE IF NOT EXISTS antibodies (
id TEXT PRIMARY KEY, domains TEXT NOT NULL, pattern TEXT NOT NULL,
severity TEXT NOT NULL, correction TEXT NOT NULL,
seen_count INTEGER DEFAULT 1, first_seen TEXT NOT NULL, last_seen TEXT NOT NULL,
quality_gate INTEGER DEFAULT 0
)`);
db.run(`CREATE TABLE IF NOT EXISTS strategies (
id TEXT PRIMARY KEY, domains TEXT NOT NULL, pattern TEXT NOT NULL,
example TEXT, effectiveness REAL DEFAULT 0.5,
seen_count INTEGER DEFAULT 1, first_seen TEXT NOT NULL, last_seen TEXT NOT NULL,
quality_gate INTEGER DEFAULT 0
)`);
db.run(`CREATE TABLE IF NOT EXISTS session_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, type TEXT NOT NULL,
domains TEXT, summary TEXT NOT NULL, details TEXT,
created_at TEXT DEFAULT (datetime('now'))
)`);
db.run(`CREATE TABLE IF NOT EXISTS stats (key TEXT PRIMARY KEY, value TEXT)`);
// FTS4
try {
db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts4(
text, source_type, source_id, domains, tokenize=porter
)`);
} catch (e) {}
// Embeddings cache
db.run(`CREATE TABLE IF NOT EXISTS embeddings (
id TEXT PRIMARY KEY, type TEXT NOT NULL,
vector BLOB NOT NULL, pattern_hash TEXT NOT NULL
)`);
}
function saveDB(db) {
const data = db.export();
const buffer = Buffer.from(data);
fs.writeFileSync(DB_PATH, buffer);
}
function syncToSQLite(db, antibodies, strategies) {
// Upsert antibodies
const stmtAb = db.prepare(`INSERT OR REPLACE INTO antibodies
(id, domains, pattern, severity, correction, seen_count, first_seen, last_seen, quality_gate)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
for (const ab of antibodies) {
const domains = JSON.stringify(Array.isArray(ab.domains) ? ab.domains : [ab.domains || '_global']);
stmtAb.run([ab.id, domains, ab.pattern, ab.severity, ab.correction,
ab.seen_count || 1, ab.first_seen || today(), ab.last_seen || today(), ab.quality_gate || 0]);
}
stmtAb.free();
// Upsert strategies
const stmtCs = db.prepare(`INSERT OR REPLACE INTO strategies
(id, domains, pattern, example, effectiveness, seen_count, first_seen, last_seen, quality_gate)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
for (const cs of strategies) {
const domains = JSON.stringify(Array.isArray(cs.domains) ? cs.domains : [cs.domains || '_global']);
stmtCs.run([cs.id, domains, cs.pattern, cs.example || '', cs.effectiveness || 0.5,
cs.seen_count || 1, cs.first_seen || today(), cs.last_seen || today(), cs.quality_gate || 0]);
}
stmtCs.free();
}
function rebuildFTS(db) {
db.run(`DELETE FROM chunks_fts`);
let count = 0;
const stmt = db.prepare(`INSERT INTO chunks_fts (text, source_type, source_id, domains) VALUES (?, ?, ?, ?)`);
// Index antibodies
const abs = db.prepare(`SELECT id, domains, pattern, correction FROM antibodies`);
while (abs.step()) {
if (count >= MAX_CHUNKS) break;
const row = abs.getAsObject();
stmt.run([`${row.pattern} ${row.correction}`, 'antibody', row.id, row.domains]);
count++;
}
abs.free();
// Index strategies
const css = db.prepare(`SELECT id, domains, pattern, example FROM strategies`);
while (css.step()) {
if (count >= MAX_CHUNKS) break;
const row = css.getAsObject();
stmt.run([`${row.pattern} ${row.example || ''}`, 'strategy', row.id, row.domains]);
count++;
}
css.free();
stmt.free();
return count;
}
// ── Commands ────────────────────────────────────────────
async function cmdGetAntibodies(args) {
const domains = JSON.parse(args.domains || '["_global"]');
const tier = args.tier || 'hot';
const limit = parseInt(args.limit) || 15;
const query = args.query || null;
const data = loadAntibodies();
let filtered = data.antibodies.filter(ab => domainMatch(ab.domains, domains));
if (tier === 'hot') {
filtered = filtered.filter(isHotAntibody);
} else if (tier === 'cold') {
filtered = filtered.filter(ab => !isHotAntibody(ab));
}
// tier === 'all' → no filter
// Re-ranking: if --query provided, use TF-IDF + heat composite scoring
if (query && tier !== 'cold') {
let candidates = filtered;
// Auto-switch: FTS4 pre-filter for large corpus, full-scan for small
if (data.antibodies.length >= RERANK_THRESHOLD) {
const ftsIds = await getFTSCandidates(query, domains, 'antibody', RERANK_FTS_CANDIDATES);
// Include all FTS matches + all criticals (guaranteed)
candidates = filtered.filter(ab => ftsIds.has(ab.id) || ab.severity === 'critical');
}
filtered = await rerankItems(candidates, query, domains, limit, 'antibody');
} else {
// Original sort (no query)
if (tier === 'hot') {
filtered.sort((a, b) => {
const sev = { critical: 3, warning: 2, info: 1 };
const sa = sev[a.severity] || 0, sb = sev[b.severity] || 0;
if (sa !== sb) return sb - sa;
return (b.seen_count || 0) - (a.seen_count || 0);
});
filtered = filtered.slice(0, limit);
}
}
const result = { count: filtered.length, antibodies: filtered };
if (query && tier !== 'cold') result.reranked = true;
if (filtered._retrieval_warning) result.retrieval_warning = filtered._retrieval_warning;
return result;
}
async function cmdGetStrategies(args) {
const domains = JSON.parse(args.domains || '["_global"]');
const tier = args.tier || 'hot';
const limit = parseInt(args.limit) || 15;
const query = args.query || null;
const data = loadStrategies();
let filtered = data.strategies.filter(cs => domainMatch(cs.domains, domains));
if (tier === 'hot') {
filtered = filtered.filter(isHotStrategy);
} else if (tier === 'cold') {
filtered = filtered.filter(cs => !isHotStrategy(cs));
}
// Re-ranking: if --query provided, use TF-IDF + heat composite scoring
if (query && tier !== 'cold') {
let candidates = filtered;
if (data.strategies.length >= RERANK_THRESHOLD) {
const ftsIds = await getFTSCandidates(query, domains, 'strategy', RERANK_FTS_CANDIDATES);
candidates = filtered.filter(cs => ftsIds.has(cs.id));
}
filtered = await rerankItems(candidates, query, domains, limit, 'strategy');
} else {
if (tier === 'hot') {
filtered.sort((a, b) => (b.effectiveness || 0) - (a.effectiveness || 0));
filtered = filtered.slice(0, limit);
}
}
const result = { count: filtered.length, strategies: filtered };
if (query && tier !== 'cold') result.reranked = true;
if (filtered._retrieval_warning) result.retrieval_warning = filtered._retrieval_warning;
return result;
}
async function cmdAddAntibody(args) {
const ab = JSON.parse(args.json);
if (!ab.id || !ab.pattern || !ab.severity || !ab.correction) {
return { error: 'Missing required fields: id, pattern, severity, correction' };
}
if (!ab.domains) ab.domains = ['_global'];
if (!ab.seen_count) ab.seen_count = 1;
if (!ab.first_seen) ab.first_seen = today();
if (!ab.last_seen) ab.last_seen = today();
// Write to JSON
const data = loadAntibodies();
const idx = data.antibodies.findIndex(x => x.id === ab.id);
if (idx >= 0) data.antibodies[idx] = ab;
else data.antibodies.push(ab);
data.stats.antibodies_total = data.antibodies.length;
writeJSON(JSON_AB, data);
// Write to SQLite (dual-write)
const db = await getDB();
syncToSQLite(db, [ab], []);
saveDB(db);
_dfDirty = true; // invalidate TF-IDF cache
return { ok: true, id: ab.id, total: data.antibodies.length };
}
async function cmdAddStrategy(args) {
const cs = JSON.parse(args.json);
if (!cs.id || !cs.pattern) {
return { error: 'Missing required fields: id, pattern' };
}
if (!cs.domains) cs.domains = ['_global'];
if (!cs.effectiveness) cs.effectiveness = 0.5;
if (!cs.seen_count) cs.seen_count = 1;
if (!cs.first_seen) cs.first_seen = today();
if (!cs.last_seen) cs.last_seen = today();
const data = loadStrategies();
const idx = data.strategies.findIndex(x => x.id === cs.id);
if (idx >= 0) data.strategies[idx] = cs;
else data.strategies.push(cs);
data.stats.strategies_total = data.strategies.length;
writeJSON(JSON_CS, data);
const db = await getDB();
syncToSQLite(db, [], [cs]);
saveDB(db);
_dfDirty = true; // invalidate TF-IDF cache
return { ok: true, id: cs.id, total: data.strategies.length };
}
async function cmdImport(args) {
if (!args.file) return { error: 'Usage: import --file <path.immune.json>' };
const fs = require('fs');
const content = fs.readFileSync(args.file, 'utf-8');
const pack = JSON.parse(content);
let abCount = 0, csCount = 0;
if (pack.antibodies && Array.isArray(pack.antibodies)) {
const abData = loadAntibodies();
for (const ab of pack.antibodies) {
if (!ab.id || !ab.pattern) continue;
if (!ab.domains) ab.domains = ['_global'];
if (!ab.seen_count) ab.seen_count = 1;
if (!ab.first_seen) ab.first_seen = today();
if (!ab.last_seen) ab.last_seen = today();
const idx = abData.antibodies.findIndex(x => x.id === ab.id);
if (idx >= 0) abData.antibodies[idx] = ab;
else abData.antibodies.push(ab);
abCount++;
}
abData.stats.antibodies_total = abData.antibodies.length;
writeJSON(JSON_AB, abData);
const db = await getDB();
syncToSQLite(db, pack.antibodies, []);
saveDB(db);
}
if (pack.strategies && Array.isArray(pack.strategies)) {
const csData = loadStrategies();
for (const cs of pack.strategies) {
if (!cs.id || !cs.pattern) continue;
if (!cs.domains) cs.domains = ['_global'];
if (!cs.effectiveness) cs.effectiveness = 0.5;
if (!cs.seen_count) cs.seen_count = 1;
if (!cs.first_seen) cs.first_seen = today();
if (!cs.last_seen) cs.last_seen = today();
const idx = csData.strategies.findIndex(x => x.id === cs.id);
if (idx >= 0) csData.strategies[idx] = cs;
else csData.strategies.push(cs);
csCount++;
}
csData.stats.strategies_total = csData.strategies.length;
writeJSON(JSON_CS, csData);
const db = await getDB();
syncToSQLite(db, [], pack.strategies);
saveDB(db);
}
return { ok: true, imported: { antibodies: abCount, strategies: csCount } };
}
async function cmdUpdateAntibody(args) {
const data = loadAntibodies();
const ab = data.antibodies.find(x => x.id === args.id);
if (!ab) return { error: `Antibody ${args.id} not found` };
if (args.seen_count) ab.seen_count = parseInt(args.seen_count);
if (args.last_seen) ab.last_seen = args.last_seen;
if (args.increment_seen) ab.seen_count = (ab.seen_count || 0) + 1;
writeJSON(JSON_AB, data);
const db = await getDB();
syncToSQLite(db, [ab], []);
saveDB(db);
return { ok: true, id: ab.id, seen_count: ab.seen_count, last_seen: ab.last_seen };
}
async function cmdUpdateStrategy(args) {
const data = loadStrategies();
const cs = data.strategies.find(x => x.id === args.id);
if (!cs) return { error: `Strategy ${args.id} not found` };
if (args.seen_count) cs.seen_count = parseInt(args.seen_count);
if (args.last_seen) cs.last_seen = args.last_seen;
if (args.effectiveness) cs.effectiveness = parseFloat(args.effectiveness);
if (args.increment_seen) cs.seen_count = (cs.seen_count || 0) + 1;
writeJSON(JSON_CS, data);
const db = await getDB();
syncToSQLite(db, [], [cs]);
saveDB(db);
return { ok: true, id: cs.id, seen_count: cs.seen_count, effectiveness: cs.effectiveness };
}
// ── Reciprocal Rank Fusion (RRF) ─────────────────────────
// Merges ranked lists from multiple retrievers using ranks, not raw scores.
// RRF(doc) = Σ 1/(k + rank(doc)) where k=60 (Cormack et al. SIGIR 2009)
const RRF_K = 60;
function reciprocalRankFusion(rankedLists) {
// rankedLists: array of arrays, each is [{id, data, score?}, ...] ordered by relevance
const scores = new Map(); // id -> { rrfScore, data }
for (const list of rankedLists) {
for (let rank = 0; rank < list.length; rank++) {
const item = list[rank];
const key = item.id;
const contribution = 1.0 / (RRF_K + rank + 1); // rank is 0-indexed, formula uses 1-indexed
if (!scores.has(key)) {
scores.set(key, { rrfScore: 0, data: item.data, engines: [] });
}
const entry = scores.get(key);
entry.rrfScore += contribution;
entry.engines.push(item.engine || 'unknown');
}
}
// Sort by fused score descending
return [...scores.entries()]
.map(([id, val]) => ({ id, ...val }))
.sort((a, b) => b.rrfScore - a.rrfScore);
}
// ── Search: embedding + keyword via RRF ──────────────────
async function fts4Search(query, type, limit) {
const db = await getDB();
const countRes = db.exec(`SELECT count(*) FROM chunks_fts`);
if (!countRes.length || countRes[0].values[0][0] === 0) {
const abData = loadAntibodies();
const csData = loadStrategies();
syncToSQLite(db, abData.antibodies, csData.strategies);
rebuildFTS(db);
saveDB(db);
}
// Quote each token to neutralize FTS4 special syntax (* " ( ) : AND OR NOT NEAR ^)
const safeQuery = ftsBuildQuery(query);
if (!safeQuery) return [];
let sql = `SELECT source_type, source_id, snippet(chunks_fts, '>>>', '<<<', '...') as snippet
FROM chunks_fts WHERE chunks_fts MATCH ?`;
const params = [safeQuery];
if (type !== 'all') {
sql += ` AND source_type = ?`;
params.push(type === 'antibodies' ? 'antibody' : type === 'strategies' ? 'strategy' : type);
}
sql += ` LIMIT ?`;
params.push(limit);
const stmt = db.prepare(sql);
stmt.bind(params);
const results = [];
while (stmt.step()) {
const row = stmt.getAsObject();
results.push({
id: `${row.source_type}:${row.source_id}`,
data: { source_type: row.source_type, source_id: row.source_id, snippet: row.snippet },
engine: 'fts4',
});
}
stmt.free();
return results;
}
async function embeddingSearch(query, type, limit) {
// Local embedding-based search using rerankItems
await ensureTransformersInstalled();
if (_embeddingsAvailable !== true) return [];
const searchType = type === 'antibodies' ? 'antibody'
: type === 'strategies' ? 'strategy'
: type;
let items = [];
if (searchType === 'antibody' || searchType === 'all') {
const abData = loadAntibodies();
items.push(...abData.antibodies.map(ab => ({ ...ab, _searchType: 'antibody' })));
}
if (searchType === 'strategy' || searchType === 'all') {
const csData = loadStrategies();
items.push(...csData.strategies.map(cs => ({ ...cs, _searchType: 'strategy' })));
}
if (items.length === 0) return [];
const queryEmbedding = await embedText(query);
if (!queryEmbedding) return [];
const scored = [];
for (const item of items) {
const itemText = item.pattern + ' ' + (item.correction || item.example || '');
const itemEmbedding = await embedText(itemText);
if (!itemEmbedding) continue;
const score = cosineSimilarity(queryEmbedding, itemEmbedding);
scored.push({
id: `${item._searchType}:${item.id}`,
data: { source_type: item._searchType, source_id: item.id, snippet: itemText.slice(0, 200), score },
engine: 'embedding',
});
}
scored.sort((a, b) => (b.data.score || 0) - (a.data.score || 0));
return scored.slice(0, limit);
}
async function cmdSearch(args) {
const query = args.query;
const type = args.type || 'all';
const limit = parseInt(args.limit) || 10;
// Hybrid: run both engines in parallel, fuse with RRF
const [embResults, ftsResults] = await Promise.all([
embeddingSearch(query, type, limit).catch(() => []),
fts4Search(query, type, limit).catch(() => []),
]);
if (embResults.length === 0 && ftsResults.length === 0) {
return { count: 0, results: [], engine: 'none' };
}
if (embResults.length > 0 && ftsResults.length > 0) {
const fused = reciprocalRankFusion([embResults, ftsResults]);
return {
count: fused.length,
results: fused.slice(0, limit).map(f => ({
...f.data,
rrf_score: Math.round(f.rrfScore * 10000) / 10000,
engines: [...new Set(f.engines)],
})),
engine: 'rrf',
engine_detail: { embedding: embResults.length, fts4: ftsResults.length },
};
}
// Single engine available
const results = embResults.length > 0 ? embResults : ftsResults;
return {
count: results.length,
results: results.slice(0, limit).map(r => r.data),
engine: embResults.length > 0 ? 'embedding' : 'fts4',
};
}
async function cmdIndex(args) {
const db = await getDB();
const abData = loadAntibodies();
const csData = loadStrategies();
syncToSQLite(db, abData.antibodies, csData.strategies);
const count = rebuildFTS(db);
saveDB(db);
return { ok: true, chunks_indexed: count, antibodies: abData.antibodies.length,
strategies: csData.strategies.length };
}
async function cmdStats() {
const abData = loadAntibodies();
const csData = loadStrategies();
const migration = getMigrationState();
return {
antibodies: { total: abData.antibodies.length, ...abData.stats },
strategies: { total: csData.strategies.length, ...csData.stats },
migration
};
}
async function cmdMigrateStatus() {
return getMigrationState();
}
async function cmdMigrateAdvance() {
const state = getMigrationState();
if (state.phase >= 3) return { ok: false, message: 'Already at phase 3 (final)' };
state.phase++;
state.sessions_in_phase = 0;
state.last_parity = today();
writeJSON(MIGRATION_FILE, state);
return { ok: true, phase: state.phase, message: `Advanced to phase ${state.phase}` };
}
async function cmdIntegrityCheck() {
try {
const db = await getDB();
const res = db.exec(`PRAGMA integrity_check`);
const ok = res.length && res[0].values[0][0] === 'ok';
return { ok, result: res.length ? res[0].values[0][0] : 'empty' };
} catch (e) {
return { ok: false, error: e.message };
}
}
// ── ContextMemory Commands ──────────────────────────────
async function cmdLogSession(args) {
const date = args.date || today();
const domains = args.domains || '["_global"]';
const result = args.result || 'clean';
const summary = args.summary || '';
const score = args.score ? parseInt(args.score) : null;
// Write to context/YYYY-MM-DD.md (append)
if (!fs.existsSync(CONTEXT_DIR)) fs.mkdirSync(CONTEXT_DIR, { recursive: true });
const logFile = path.join(CONTEXT_DIR, `${date}.md`);
const timestamp = new Date().toISOString().slice(11, 19);
const entry = `\n## ${timestamp} | ${result} | domains=${domains}${score !== null ? ` | score=${score}` : ''}\n${summary}\n`;
fs.appendFileSync(logFile, entry, 'utf8');
// Write to SQLite session_logs
const db = await getDB();
db.run(`INSERT INTO session_logs (date, type, domains, summary, details) VALUES (?, ?, ?, ?, ?)`,
[date, result, domains, summary, args.details || '']);
saveDB(db);
// Index into FTS4
const sanitized = sanitize(summary);
const stmt = db.prepare(`INSERT INTO chunks_fts (text, source_type, source_id, domains) VALUES (?, ?, ?, ?)`);
stmt.run([sanitized, 'session', `session-${date}-${timestamp}`, domains]);
stmt.free();
saveDB(db);
return { ok: true, file: logFile, date, result };
}
async function cmdGetContext(args) {
const query = args.query;
const days = parseInt(args.days) || 90;
const limit = parseInt(args.limit) || 5;
// FTS4 search on sessions (escape query tokens)
const db = await getDB();
const cutoff = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);
const safeSessionQuery = ftsBuildQuery(query);
if (!safeSessionQuery) return { count: 0, results: [], recent_logs: [], engine: 'fts4' };
let sql = `SELECT source_type, source_id, snippet(chunks_fts, '>>>', '<<<', '...') as snippet
FROM chunks_fts WHERE chunks_fts MATCH ? AND source_type = 'session' LIMIT ?`;
const stmt = db.prepare(sql);
stmt.bind([safeSessionQuery, limit]);
const results = [];
while (stmt.step()) {
const row = stmt.getAsObject();
results.push({ source_id: row.source_id, snippet: row.snippet });
}
stmt.free();
const logs = db.prepare(`SELECT date, type, domains, summary FROM session_logs
WHERE date >= ? ORDER BY date DESC LIMIT ?`);
logs.bind([cutoff, limit]);
const recentLogs = [];
while (logs.step()) {
recentLogs.push(logs.getAsObject());
}
logs.free();
return { count: results.length, results, recent_logs: recentLogs, engine: 'fts4' };
}
async function cmdIndexContext() {
const db = await getDB();
let count = 0;
const stmt = db.prepare(`INSERT INTO chunks_fts (text, source_type, source_id, domains) VALUES (?, ?, ?, ?)`);
// Index MEMORY.md if it exists
if (fs.existsSync(MEMORY_MD)) {
const content = sanitize(fs.readFileSync(MEMORY_MD, 'utf8'));
// Chunk into ~400 token blocks (~1600 chars)
const chunks = chunkText(content, 1600);
for (const [i, chunk] of chunks.entries()) {
stmt.run([chunk, 'memory_md', `memory-md-${i}`, '["_global"]']);
count++;
}
}
// Index USER.md if it exists
if (fs.existsSync(USER_MD)) {
const content = sanitize(fs.readFileSync(USER_MD, 'utf8'));
const chunks = chunkText(content, 1600);
for (const [i, chunk] of chunks.entries()) {
stmt.run([chunk, 'user_md', `user-md-${i}`, '["_global"]']);
count++;
}
}
// Index context/*.md files
if (fs.existsSync(CONTEXT_DIR)) {
const files = fs.readdirSync(CONTEXT_DIR).filter(f => f.endsWith('.md'));
for (const file of files) {
const content = sanitize(fs.readFileSync(path.join(CONTEXT_DIR, file), 'utf8'));
const chunks = chunkText(content, 1600);
for (const [i, chunk] of chunks.entries()) {
stmt.run([chunk, 'context', `ctx-${file}-${i}`, '["_global"]']);
count++;
}
}
}
stmt.free();
saveDB(db);
return { ok: true, chunks_indexed: count };
}
function chunkText(text, maxChars) {
const chunks = [];
let start = 0;
while (start < text.length) {
let end = Math.min(start + maxChars, text.length);
// Try to break at newline
if (end < text.length) {
const nl = text.lastIndexOf('\n', end);
if (nl > start + maxChars * 0.5) end = nl + 1;
}
chunks.push(text.slice(start, end));
start = end;
}
return chunks;
}
async function cmdRetentionCleanup() {
if (!fs.existsSync(CONTEXT_DIR)) return { ok: true, archived: 0 };
if (!fs.existsSync(ARCHIVE_DIR)) fs.mkdirSync(ARCHIVE_DIR, { recursive: true });
const cutoff = new Date(Date.now() - RETENTION_DAYS * 86400000).toISOString().slice(0, 10);
const files = fs.readdirSync(CONTEXT_DIR).filter(f => f.endsWith('.md'));
let archived = 0;
for (const file of files) {
const dateMatch = file.match(/^(\d{4}-\d{2}-\d{2})\.md$/);
if (dateMatch && dateMatch[1] < cutoff) {
fs.renameSync(path.join(CONTEXT_DIR, file), path.join(ARCHIVE_DIR, file));
archived++;
}
}
return { ok: true, archived, cutoff };
}
// ── Score Command ───────────────────────────────────────
async function cmdScore(args) {
const domains = JSON.parse(args.domains || '["_global"]');
const corrections = parseInt(args.corrections) || 0;
const threats = parseInt(args.threats) || 0;
const severities = args.severities ? JSON.parse(args.severities) : [];
// severities: array of {severity, count}
// Base 100, deductions