-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__test_e2e.mjs
More file actions
4685 lines (4181 loc) · 197 KB
/
__test_e2e.mjs
File metadata and controls
4685 lines (4181 loc) · 197 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
/**
* Vibe Science v7.0 TRACE — End-to-End Test Suite
*
* Comprehensive test coverage for the plugin infrastructure:
* B1. Syntax & Import Tests (30 JS files)
* B2. Schema SQL Tests (16 tables, FK constraints, indices)
* B3. Library Unit Tests (18 libs, export verification)
* B4. Script Integration Tests (setup, session-start, prompt-submit)
* B5. Package & Config Tests (package.json, hooks.json, plugin.json, schemas)
* B6. Content Integrity Tests (forbidden names, file references, CLAUDE.md)
* B7. Dependency Import Tests (better-sqlite3, transformers, onnxruntime)
* B8. TRACE Foundation Tests (migrations, structured blocks)
*
* Usage: node --test __test_e2e.mjs
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { execSync, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
// =====================================================
// Path resolution
// =====================================================
const ROOT = path.dirname(fileURLToPath(import.meta.url));
/** Resolve a path relative to the project root. */
function rel(...segments) {
return path.join(ROOT, ...segments);
}
/** Resolve a path relative to the project root as a file:// URL (needed for dynamic import on Windows). */
function relUrl(...segments) {
return pathToFileURL(path.join(ROOT, ...segments)).href;
}
// =====================================================
// Counters — summary printed at the end
// =====================================================
let passCount = 0;
let failCount = 0;
function pass(label) {
passCount++;
}
function fail(label) {
failCount++;
}
// =====================================================
// B1. Syntax & Import Tests
// =====================================================
describe('B1. Syntax & Import Tests', () => {
const scripts = [
'plugin/scripts/setup.js',
'plugin/scripts/session-start.js',
'plugin/scripts/prompt-submit.js',
'plugin/scripts/post-tool-use.js',
'plugin/scripts/pre-tool-use.js',
'plugin/scripts/pre-compact.js',
'plugin/scripts/stop.js',
'plugin/scripts/subagent-stop.js',
'plugin/scripts/worker-embed.js',
'evals/eval-runner.mjs',
'evals/smoke-trace.mjs',
'scripts/v7-readiness.mjs',
];
const libs = [
'plugin/lib/db.js',
'plugin/lib/gate-engine.js',
'plugin/lib/permission-engine.js',
'plugin/lib/path-utils.js',
'plugin/lib/vec-search.js',
'plugin/lib/context-builder.js',
'plugin/lib/narrative-engine.js',
'plugin/lib/pattern-extractor.js',
'plugin/lib/r2-calibration.js',
'plugin/lib/benchmark-reporter.js',
'plugin/lib/migrations.js',
'plugin/lib/structured-block-parser.js',
'plugin/lib/claim-ingestion.js',
'plugin/lib/seed-ingestion.js',
'plugin/lib/r2-ingestion.js',
'plugin/lib/citation-extractor.js',
'plugin/lib/citation-engine.js',
'plugin/lib/harness-hints.js',
];
const allJsFiles = [...scripts, ...libs];
for (const file of allJsFiles) {
it(`syntax check: ${file}`, () => {
const fullPath = rel(file);
assert.ok(fs.existsSync(fullPath), `File does not exist: ${fullPath}`);
try {
execSync(`node --check "${fullPath}"`, {
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
stdio: 'pipe',
});
pass(`syntax:${file}`);
} catch (err) {
fail(`syntax:${file}`);
assert.fail(`Syntax error in ${file}: ${err.stderr || err.message}`);
}
});
}
it('all 30 JS files are present', () => {
assert.equal(allJsFiles.length, 30, 'Expected exactly 30 JS files (12 scripts + 18 libs)');
for (const file of allJsFiles) {
assert.ok(fs.existsSync(rel(file)), `Missing: ${file}`);
}
pass('all-30-present');
});
});
// =====================================================
// B2. Schema SQL Tests
// =====================================================
describe('B2. Schema SQL Tests', () => {
const SCHEMA_PATH = rel('plugin', 'db', 'schema.sql');
const EXPECTED_TABLES = [
'meta',
'sessions',
'spine_entries',
'claim_events',
'r2_reviews',
'serendipity_seeds',
'gate_checks',
'literature_searches',
'citation_checks',
'observer_alerts',
'calibration_log',
'prompt_log',
'memory_embeddings',
'embed_queue',
'research_patterns',
'benchmark_runs',
];
let Database;
let db;
it('schema.sql file exists', () => {
assert.ok(fs.existsSync(SCHEMA_PATH), `Schema file missing: ${SCHEMA_PATH}`);
pass('schema-exists');
});
it('schema executes without error on in-memory DB', async () => {
const mod = await import('better-sqlite3');
Database = mod.default;
db = new Database(':memory:');
db.pragma('foreign_keys = ON');
const schema = fs.readFileSync(SCHEMA_PATH, 'utf-8');
db.exec(schema);
pass('schema-exec');
});
it('all 16 tables exist', () => {
assert.ok(db, 'DB not initialized');
const rows = db.prepare(
`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`
).all();
const tableNames = rows.map(r => r.name);
for (const expected of EXPECTED_TABLES) {
assert.ok(
tableNames.includes(expected),
`Missing table: ${expected}. Found: ${tableNames.join(', ')}`
);
}
assert.ok(
tableNames.length >= EXPECTED_TABLES.length,
`Expected at least ${EXPECTED_TABLES.length} tables, found ${tableNames.length}`
);
pass('16-tables');
});
it('FK constraint on calibration_log.session_id', () => {
assert.ok(db, 'DB not initialized');
// Insert a valid session first
db.prepare(
`INSERT INTO sessions (id, project_path, started_at) VALUES (?, ?, ?)`
).run('test-session-fk', '/tmp/test', new Date().toISOString());
// Insert with valid session_id should succeed
db.prepare(
`INSERT INTO calibration_log (claim_id, predicted_confidence, actual_outcome, session_id, timestamp)
VALUES (?, ?, ?, ?, ?)`
).run('C001', 0.85, 'VERIFIED', 'test-session-fk', new Date().toISOString());
// Insert with invalid session_id should throw
assert.throws(
() => {
db.prepare(
`INSERT INTO calibration_log (claim_id, predicted_confidence, actual_outcome, session_id, timestamp)
VALUES (?, ?, ?, ?, ?)`
).run('C002', 0.5, 'REJECTED', 'nonexistent-session', new Date().toISOString());
},
/FOREIGN KEY constraint failed/,
'Expected FK violation for calibration_log with invalid session_id'
);
pass('fk-calibration');
});
it('FK constraint on prompt_log.session_id', () => {
assert.ok(db, 'DB not initialized');
// Insert with valid session_id should succeed
db.prepare(
`INSERT INTO prompt_log (session_id, agent_role, prompt_hash, timestamp)
VALUES (?, ?, ?, ?)`
).run('test-session-fk', 'researcher', 'abc123hash', new Date().toISOString());
// Insert with invalid session_id should throw
assert.throws(
() => {
db.prepare(
`INSERT INTO prompt_log (session_id, agent_role, prompt_hash, timestamp)
VALUES (?, ?, ?, ?)`
).run('bad-session-id', 'researcher', 'xyz789hash', new Date().toISOString());
},
/FOREIGN KEY constraint failed/,
'Expected FK violation for prompt_log with invalid session_id'
);
pass('fk-prompt-log');
});
it('indices exist in sqlite_master', () => {
assert.ok(db, 'DB not initialized');
const rows = db.prepare(
`SELECT name FROM sqlite_master WHERE type='index' AND name LIKE 'idx_%'`
).all();
const indexNames = rows.map(r => r.name);
// Key indices from schema.sql
const expectedIndices = [
'idx_spine_session',
'idx_spine_action',
'idx_claims_id',
'idx_claims_session',
'idx_r2_session',
'idx_seeds_status',
'idx_gates_session',
'idx_gates_claim',
'idx_lit_session',
'idx_lit_layer',
'idx_citations_session',
'idx_citations_status',
'idx_citations_claim',
'idx_citations_lookup',
'idx_citations_dedupe',
'idx_observer_project',
'idx_calibration_claim',
'idx_prompt_session',
'idx_membed_project',
'idx_embed_pending',
'idx_patterns_project',
'idx_patterns_type',
'idx_bench_version',
'idx_bench_case',
'idx_bench_run',
];
for (const idx of expectedIndices) {
assert.ok(
indexNames.includes(idx),
`Missing index: ${idx}. Found: ${indexNames.join(', ')}`
);
}
pass('indices');
});
it('sessions table has correct columns', () => {
assert.ok(db, 'DB not initialized');
const info = db.prepare(`PRAGMA table_info(sessions)`).all();
const colNames = info.map(c => c.name);
const expected = [
'id', 'project_path', 'started_at', 'ended_at', 'integrity_status', 'integrity_notes',
'narrative_summary', 'total_actions', 'claims_created',
'claims_killed', 'gates_passed', 'gates_failed',
];
for (const col of expected) {
assert.ok(colNames.includes(col), `Missing column in sessions: ${col}`);
}
assert.equal(colNames.length, expected.length, `Column count mismatch in sessions`);
pass('sessions-columns');
});
it('spine_entries table has correct columns', () => {
assert.ok(db, 'DB not initialized');
const info = db.prepare(`PRAGMA table_info(spine_entries)`).all();
const colNames = info.map(c => c.name);
const expected = [
'id', 'session_id', 'timestamp', 'action_type',
'tool_name', 'input_summary', 'output_summary',
'agent_role', 'gate_result',
];
for (const col of expected) {
assert.ok(colNames.includes(col), `Missing column in spine_entries: ${col}`);
}
pass('spine-columns');
});
it('embed_queue table has correct columns', () => {
assert.ok(db, 'DB not initialized');
const info = db.prepare(`PRAGMA table_info(embed_queue)`).all();
const colNames = info.map(c => c.name);
const expected = ['id', 'text', 'metadata', 'created_at', 'processed'];
for (const col of expected) {
assert.ok(colNames.includes(col), `Missing column in embed_queue: ${col}`);
}
pass('embed-queue-columns');
// Clean up
if (db && db.open) db.close();
});
});
// =====================================================
// B3. Library Unit Tests
// =====================================================
describe('B3. Library Unit Tests', () => {
it('db.js exports openDB and closeDB', async () => {
const mod = await import(relUrl('plugin', 'lib', 'db.js'));
assert.equal(typeof mod.DEFAULT_DB_PATH, 'string', 'DEFAULT_DB_PATH should be exported');
assert.equal(typeof mod.openDB, 'function', 'openDB should be a function');
assert.equal(typeof mod.closeDB, 'function', 'closeDB should be a function');
// Also check additional expected exports
assert.equal(typeof mod.initDB, 'function', 'initDB should be a function');
assert.equal(typeof mod.createSession, 'function', 'createSession should be a function');
assert.equal(typeof mod.updateSessionIntegrity, 'function', 'updateSessionIntegrity should be a function');
assert.equal(typeof mod.openAndInit, 'function', 'openAndInit should be a function');
assert.equal(typeof mod.upsertCitationCheck, 'function', 'upsertCitationCheck should be a function');
assert.equal(typeof mod.updateCitationVerification, 'function', 'updateCitationVerification should be a function');
assert.equal(typeof mod.getCitationChecks, 'function', 'getCitationChecks should be a function');
assert.equal(typeof mod.getLatestPromptRole, 'function', 'getLatestPromptRole should be a function');
pass('db-exports');
});
it('gate-engine.js exports gate functions', async () => {
const mod = await import(relUrl('plugin', 'lib', 'gate-engine.js'));
assert.equal(typeof mod.checkGateDQ4, 'function', 'checkGateDQ4 should be a function');
assert.equal(typeof mod.checkClaimGates, 'function', 'checkClaimGates should be a function');
assert.equal(typeof mod.checkLiteratureGate, 'function', 'checkLiteratureGate should be a function');
assert.equal(typeof mod.getRequiredGatesForClaim, 'function', 'getRequiredGatesForClaim should be a function');
assert.equal(typeof mod.extractClaimId, 'function', 'extractClaimId should be a function');
// classifyAction removed from gate-engine.js (v6.0.6) — canonical impl lives in post-tool-use.js
assert.equal(typeof mod.isDirectionNode, 'function', 'isDirectionNode should be a function');
assert.equal(typeof mod.hasLiteratureSearch, 'function', 'hasLiteratureSearch should be a function');
assert.equal(typeof mod.findJsonSource, 'function', 'findJsonSource should be a function');
assert.equal(typeof mod.runSyncCheck, 'function', 'runSyncCheck should be a function');
assert.equal(typeof mod.getCitationChecks, 'function', 'getCitationChecks should be a function');
assert.equal(typeof mod.summarizeCitationValidity, 'function', 'summarizeCitationValidity should be a function');
assert.equal(typeof mod.checkSourceValidityGate, 'function', 'checkSourceValidityGate should be a function');
assert.equal(typeof mod.checkClaimPromotionSources, 'function', 'checkClaimPromotionSources should be a function');
assert.equal(mod.extractClaimId('Claim C-1234 is here'), 'C-1234', 'extractClaimId should support >999 compact IDs');
pass('gate-engine-exports');
});
it('permission-engine.js exports and role verification', async () => {
const mod = await import(relUrl('plugin', 'lib', 'permission-engine.js'));
assert.equal(typeof mod.checkPermission, 'function', 'checkPermission should be a function');
assert.equal(typeof mod.identifyAgentRole, 'function', 'identifyAgentRole should be a function');
assert.ok(mod.PERMISSIONS, 'PERMISSIONS should be exported');
// Verify known roles exist in PERMISSIONS
const knownRoles = ['researcher', 'reviewer2', 'judge', 'serendipity', 'lead', 'experimenter'];
for (const role of knownRoles) {
assert.ok(
mod.PERMISSIONS[role],
`Role "${role}" should exist in PERMISSIONS`
);
assert.ok(
Array.isArray(mod.PERMISSIONS[role].allow),
`PERMISSIONS.${role}.allow should be an array`
);
}
// Test identifyAgentRole with explicit roles
for (const role of knownRoles) {
const identified = mod.identifyAgentRole(role);
assert.equal(identified, role, `identifyAgentRole("${role}") should return "${role}"`);
}
// Test identifyAgentRole default
assert.equal(
mod.identifyAgentRole(null, ''),
'researcher',
'Default role should be "researcher"'
);
// Test checkPermission in SOLO mode (null role)
assert.equal(
mod.checkPermission(null, 'Write', {}),
null,
'SOLO mode (null role) should allow everything'
);
assert.equal(
mod.checkPermission('lead', 'MultiEdit', { file_path: 'notes.md' }),
null,
'lead should be allowed to use MultiEdit on ordinary notes'
);
assert.ok(
mod.checkPermission('experimenter', 'Write', { file_path: 'claim-ledger.md' }),
'experimenter should still be blocked from lower-case claim-ledger writes'
);
assert.ok(
mod.checkPermission('serendipity', 'Write', { file_path: 'SERENDIPITY.md.evil' }),
'serendipity should not be allowed to escape its single-file boundary via substring matches'
);
const unknownRoleViolation = mod.checkPermission('reviewer2x', 'Write', { file_path: 'RQ.md' });
assert.ok(unknownRoleViolation, 'unknown TEAM roles should not disable the permission barrier');
assert.match(unknownRoleViolation.reason, /Unknown agent role/i);
assert.ok(
mod.checkPermission('experimenter', 'Bash', { command: 'cd 05-reviewer2; echo hacked > local.txt' }),
'experimenter Bash should not be able to mutate a protected reviewer directory via shell indirection'
);
pass('permission-engine-exports');
});
it('path-utils.js canonicalizes project paths for stable DB identity', async () => {
const mod = await import(relUrl('plugin', 'lib', 'path-utils.js'));
assert.equal(typeof mod.canonicalizeProjectPath, 'function', 'canonicalizeProjectPath should be exported');
const a = mod.canonicalizeProjectPath('C:\\Repo\\Study\\');
const b = mod.canonicalizeProjectPath('c:/repo/study');
assert.equal(a, b, 'project path canonicalization should absorb slash/case drift on Windows');
pass('path-utils-exports');
});
it('vec-search.js exports vecSearch and queueForEmbedding', async () => {
const mod = await import(relUrl('plugin', 'lib', 'vec-search.js'));
assert.equal(typeof mod.vecSearch, 'function', 'vecSearch should be a function');
assert.equal(typeof mod.queueForEmbedding, 'function', 'queueForEmbedding should be a function');
pass('vec-search-exports');
});
it('TRACE canonicalizes queueForEmbedding and citation check lookup behavior', async () => {
const dbMod = await import(relUrl('plugin', 'lib', 'db.js'));
const gateMod = await import(relUrl('plugin', 'lib', 'gate-engine.js'));
const vecMod = await import(relUrl('plugin', 'lib', 'vec-search.js'));
assert.equal(
vecMod.queueForEmbedding,
dbMod.queueForEmbedding,
'vec-search should re-export the canonical DB queueForEmbedding implementation'
);
assert.deepEqual(dbMod.getCitationChecks(null, {}), []);
assert.deepEqual(gateMod.getCitationChecks(null, {}), []);
pass('trace-canonical-exports');
});
it('context-builder.js exports buildContext, formatContextForInjection, truncate', async () => {
const mod = await import(relUrl('plugin', 'lib', 'context-builder.js'));
assert.equal(typeof mod.buildContext, 'function', 'buildContext should be a function');
assert.equal(typeof mod.formatContextForInjection, 'function', 'formatContextForInjection should be a function');
assert.equal(typeof mod.truncate, 'function', 'truncate should be a function');
// Quick functional test on truncate
assert.equal(mod.truncate('hello', 10), 'hello');
assert.equal(mod.truncate('hello world this is long', 10), 'hello w...');
assert.equal(mod.truncate(null, 10), '');
assert.equal(mod.truncate('', 10), '');
pass('context-builder-exports');
});
it('formatContextForInjection preserves retrieval provenance and recency for scientific memory', async () => {
const mod = await import(relUrl('plugin', 'lib', 'context-builder.js'));
const text = mod.formatContextForInjection({
state: 'State snapshot',
memories: [{
text: 'Confounder harness previously failed on IL-6 matched cohort.',
distance: null,
metadata: {
source_type: 'narrative_summary',
session_id: 'sess-42',
created_at: '2026-03-25T08:00:00.000Z',
},
}],
pendingSeeds: [],
alerts: [],
r2Calibration: null,
integrityWarnings: [],
});
assert.match(text, /\[MEMORY\]/);
assert.match(text, /\[narrative_summary \| 2026-03-25 \| session=sess-42\]/i);
pass('context-builder-memory-provenance');
});
it('narrative-engine.js exports generateNarrativeSummary and updateStateMdFromDB', async () => {
const mod = await import(relUrl('plugin', 'lib', 'narrative-engine.js'));
assert.equal(typeof mod.generateNarrativeSummary, 'function', 'generateNarrativeSummary should be a function');
assert.equal(typeof mod.updateStateMdFromDB, 'function', 'updateStateMdFromDB should be a function');
// Quick functional test on generateNarrativeSummary with empty data
const result = mod.generateNarrativeSummary({
entries: [],
claims: [],
gates: [],
sessionId: 'test-session-000',
});
assert.ok(result.text, 'Summary text should not be empty');
assert.equal(typeof result.tokenEstimate, 'number', 'tokenEstimate should be a number');
assert.ok(result.text.includes('Session test-ses'), 'Summary should contain session ID prefix');
pass('narrative-engine-exports');
});
it('r2-calibration.js exports calibration functions', async () => {
const mod = await import(relUrl('plugin', 'lib', 'r2-calibration.js'));
assert.equal(typeof mod.loadR2CalibrationData, 'function', 'loadR2CalibrationData should be a function');
assert.equal(typeof mod.loadResearcherPatterns, 'function', 'loadResearcherPatterns should be a function');
assert.equal(typeof mod.loadPendingSeeds, 'function', 'loadPendingSeeds should be a function');
assert.equal(typeof mod.updateSeedStatuses, 'function', 'updateSeedStatuses should be a function');
pass('r2-calibration-exports');
});
it('benchmark-reporter.js exports', async () => {
const mod = await import(relUrl('plugin', 'lib', 'benchmark-reporter.js'));
assert.ok(typeof mod.recordBenchmark === 'function', 'exports recordBenchmark');
assert.ok(typeof mod.generateReport === 'function', 'exports generateReport');
assert.ok(typeof mod.compareVersions === 'function', 'exports compareVersions');
pass('benchmark-reporter-exports');
});
it('benchmark-reporter marks disappeared candidate cases as regressions', async () => {
const Database = (await import('better-sqlite3')).default;
const mod = await import(relUrl('plugin', 'lib', 'benchmark-reporter.js'));
const db = new Database(':memory:');
db.exec(fs.readFileSync(rel('plugin', 'db', 'schema.sql'), 'utf-8'));
mod.recordBenchmark(db, {
run_id: 'base-a',
skill_version: '6.0.0',
eval_case: 'A01',
category: 'trigger',
passed: true,
execution_time_ms: 1,
});
mod.recordBenchmark(db, {
run_id: 'base-b',
skill_version: '6.0.0',
eval_case: 'A02',
category: 'trigger',
passed: true,
execution_time_ms: 1,
});
mod.recordBenchmark(db, {
run_id: 'cand-a',
skill_version: '7.0.0',
eval_case: 'A01',
category: 'trigger',
passed: true,
execution_time_ms: 1,
});
const comparison = mod.compareVersions(db, '6.0.0', '7.0.0');
assert.ok(
comparison.regressed_cases.includes('A02'),
'cases present in the baseline but missing in the candidate should be treated as regressions'
);
db.close();
pass('benchmark-reporter-missing-case-regression');
});
it('migrations.js exports migration helpers', async () => {
const mod = await import(relUrl('plugin', 'lib', 'migrations.js'));
assert.equal(typeof mod.CURRENT_SCHEMA_VERSION, 'number', 'CURRENT_SCHEMA_VERSION should be numeric');
assert.equal(typeof mod.ensureMetaTable, 'function', 'ensureMetaTable should be a function');
assert.equal(typeof mod.tableExists, 'function', 'tableExists should be a function');
assert.equal(typeof mod.columnExists, 'function', 'columnExists should be a function');
assert.equal(typeof mod.getSchemaVersion, 'function', 'getSchemaVersion should be a function');
assert.equal(typeof mod.applyMigrations, 'function', 'applyMigrations should be a function');
pass('migrations-exports');
});
it('structured-block-parser.js exports parser helpers', async () => {
const mod = await import(relUrl('plugin', 'lib', 'structured-block-parser.js'));
assert.ok(mod.BLOCK_TAGS, 'BLOCK_TAGS should be exported');
assert.equal(typeof mod.canonicalizeBlockTag, 'function', 'canonicalizeBlockTag should be a function');
assert.equal(typeof mod.parseStructuredBlocks, 'function', 'parseStructuredBlocks should be a function');
assert.equal(typeof mod.parseStructuredBlock, 'function', 'parseStructuredBlock should be a function');
assert.equal(typeof mod.normalizeStructuredBlock, 'function', 'normalizeStructuredBlock should be a function');
pass('structured-parser-exports');
});
it('claim-ingestion.js exports lifecycle helpers', async () => {
const mod = await import(relUrl('plugin', 'lib', 'claim-ingestion.js'));
assert.equal(typeof mod.ingestClaimEvents, 'function', 'ingestClaimEvents should be a function');
assert.equal(typeof mod.normalizeClaimId, 'function', 'normalizeClaimId should be a function');
assert.equal(mod.normalizeClaimId('C001'), 'C-001');
pass('claim-ingestion-exports');
});
it('seed-ingestion.js exports seed ingestion helper', async () => {
const mod = await import(relUrl('plugin', 'lib', 'seed-ingestion.js'));
assert.equal(typeof mod.ingestSerendipitySeeds, 'function', 'ingestSerendipitySeeds should be a function');
pass('seed-ingestion-exports');
});
it('r2-ingestion.js exports review ingestion helper', async () => {
const mod = await import(relUrl('plugin', 'lib', 'r2-ingestion.js'));
assert.equal(typeof mod.ingestR2Reviews, 'function', 'ingestR2Reviews should be a function');
pass('r2-ingestion-exports');
});
it('citation-extractor.js exports citation extraction helpers', async () => {
const mod = await import(relUrl('plugin', 'lib', 'citation-extractor.js'));
assert.equal(typeof mod.extractCitationsFromEvent, 'function', 'extractCitationsFromEvent should be a function');
assert.equal(typeof mod.extractCitationsFromText, 'function', 'extractCitationsFromText should be a function');
assert.equal(typeof mod.normalizeDoi, 'function', 'normalizeDoi should be a function');
assert.equal(typeof mod.normalizePmid, 'function', 'normalizePmid should be a function');
assert.equal(typeof mod.normalizeArxivId, 'function', 'normalizeArxivId should be a function');
pass('citation-extractor-exports');
});
it('citation-engine.js exports verification helpers', async () => {
const mod = await import(relUrl('plugin', 'lib', 'citation-engine.js'));
assert.equal(typeof mod.verifyCitationsQuick, 'function', 'verifyCitationsQuick should be a function');
assert.equal(typeof mod.verifyCitation, 'function', 'verifyCitation should be a function');
assert.equal(typeof mod.runFetchSpike, 'function', 'runFetchSpike should be a function');
pass('citation-engine-exports');
});
});
// =====================================================
// B4. Script Integration Tests
// =====================================================
describe('B4. Script Integration Tests', () => {
it('setup.js: outputs valid JSON with schema metadata', () => {
try {
const output = execSync(
`echo {} | node plugin/scripts/setup.js`,
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
shell: true,
stdio: ['pipe', 'pipe', 'pipe'],
}
);
const trimmed = output.trim();
assert.ok(trimmed.length > 0, 'setup.js should produce output');
const result = JSON.parse(trimmed);
assert.ok('status' in result, 'setup.js output should have "status" field');
assert.ok('db_path' in result, 'setup.js output should have "db_path" field');
assert.ok('schema_version' in result, 'setup.js output should have "schema_version" field');
assert.ok('target_schema_version' in result, 'setup.js output should have "target_schema_version" field');
assert.ok('migrations_applied' in result, 'setup.js output should have "migrations_applied" field');
assert.equal(typeof result.schema_version, 'number', 'schema_version should be numeric');
assert.equal(typeof result.target_schema_version, 'number', 'target_schema_version should be numeric');
assert.ok(Array.isArray(result.migrations_applied), 'migrations_applied should be an array');
assert.equal(
result.target_schema_version >= result.schema_version,
true,
'target schema version should be >= current schema version'
);
assert.ok(
result.status === 'ready' || result.status === 'degraded' || result.status === 'error',
`Unexpected status: ${result.status}`
);
pass('setup-integration');
} catch (err) {
// If setup outputs JSON even on "error", that is still acceptable
if (err.stdout) {
try {
const result = JSON.parse(err.stdout.trim());
assert.ok('status' in result, 'setup.js error output should still have "status"');
pass('setup-integration-degraded');
return;
} catch {
// Fall through to fail
}
}
fail('setup-integration');
assert.fail(`setup.js failed: ${err.message}`);
}
});
it('setup.js reports degraded when dependency bootstrap fails', () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-trace-setup-deps-'));
const homeDir = path.join(tempRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
const result = spawnSync(
process.execPath,
['plugin/scripts/setup.js'],
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 120000,
input: JSON.stringify({}),
env: {
...process.env,
HOME: homeDir,
USERPROFILE: homeDir,
PATH: '',
},
}
);
assert.equal(result.status, 0, 'setup hook should still return JSON on degraded bootstrap');
const payload = JSON.parse(String(result.stdout || '').trim());
assert.equal(payload.status, 'degraded', 'failed dependency bootstrap must degrade setup status');
assert.equal(payload.deps_installed, false, 'deps_installed should stay false when npm/bootstrap fails');
assert.match((payload.warnings || []).join('\n'), /Dependency install failed/i);
pass('setup-degraded-on-deps-failure');
});
it('session-start.js: outputs valid JSON with sessionId', () => {
try {
const output = execSync(
`echo {"session_id":"test-e2e"} | node plugin/scripts/session-start.js`,
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
shell: true,
stdio: ['pipe', 'pipe', 'pipe'],
}
);
const trimmed = output.trim();
assert.ok(trimmed.length > 0, 'session-start.js should produce output');
const result = JSON.parse(trimmed);
assert.ok(
result.hookSpecificOutput,
'session-start.js output should have "hookSpecificOutput" field'
);
assert.equal(typeof result.sessionId, 'string', 'session-start.js should surface sessionId');
assert.ok(result.integrityStatus === 'INTEGRITY_OK' || result.integrityStatus === 'INTEGRITY_DEGRADED');
pass('session-start-integration');
} catch (err) {
if (err.stdout) {
try {
const result = JSON.parse(err.stdout.trim());
assert.ok(result.hookSpecificOutput, 'session-start.js should output hookSpecificOutput');
assert.equal(typeof result.sessionId, 'string', 'session-start.js should surface sessionId');
pass('session-start-integration-degraded');
return;
} catch {
// Fall through
}
}
fail('session-start-integration');
assert.fail(`session-start.js failed: ${err.message}`);
}
});
it('prompt-submit.js: outputs valid JSON with agentRole', () => {
try {
const output = execSync(
`echo {"prompt":"test prompt","session_id":"test-e2e"} | node plugin/scripts/prompt-submit.js`,
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
shell: true,
stdio: ['pipe', 'pipe', 'pipe'],
}
);
const trimmed = output.trim();
assert.ok(trimmed.length > 0, 'prompt-submit.js should produce output');
const result = JSON.parse(trimmed);
assert.ok(
result.hookSpecificOutput,
'prompt-submit.js output should have "hookSpecificOutput" field'
);
assert.ok(
result.hookSpecificOutput.additionalContext,
'prompt-submit.js hookSpecificOutput should have "additionalContext"'
);
pass('prompt-submit-integration');
} catch (err) {
if (err.stdout) {
try {
const result = JSON.parse(err.stdout.trim());
assert.ok(result.hookSpecificOutput, 'prompt-submit.js should output hookSpecificOutput');
pass('prompt-submit-integration-degraded');
return;
} catch {
// Fall through
}
}
fail('prompt-submit-integration');
assert.fail(`prompt-submit.js failed: ${err.message}`);
}
});
it('session-start.js marks integrity degraded in strict mode when DB persistence is unavailable', () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-trace-strict-'));
const fakeHome = path.join(tempRoot, 'home-file');
fs.writeFileSync(fakeHome, 'not-a-directory', 'utf-8');
const result = spawnSync(
process.execPath,
['plugin/scripts/session-start.js'],
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
input: JSON.stringify({ cwd: ROOT, project_path: ROOT }),
env: {
...process.env,
VIBE_SCIENCE_STRICT: '1',
HOME: fakeHome,
USERPROFILE: fakeHome,
},
}
);
assert.equal(result.status, 0, 'session-start should still return context in strict mode');
const output = JSON.parse(String(result.stdout || '').trim());
assert.equal(output.integrityStatus, 'INTEGRITY_DEGRADED');
assert.match(String(output.systemMessage || ''), /\[INTEGRITY DEGRADED\]/);
pass('session-start-strict-integrity');
});
it('session-start.js falls back to STATE.md when DB persistence is unavailable', () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-trace-state-fallback-'));
const fakeHome = path.join(tempRoot, 'home-file');
const projectDir = path.join(tempRoot, 'project');
fs.writeFileSync(fakeHome, 'not-a-directory', 'utf-8');
fs.mkdirSync(path.join(projectDir, '.vibe-science'), { recursive: true });
fs.writeFileSync(
path.join(projectDir, '.vibe-science', 'STATE.md'),
[
'# Vibe Science — State',
'_Auto-generated at 2026-03-25T12:00:00.000Z_',
'',
'## Last Session',
'- **Actions:** 12',
'### Summary',
'Recovered hypothesis about IL-6 confounding.',
].join('\n'),
'utf-8'
);
const result = spawnSync(
process.execPath,
['plugin/scripts/session-start.js'],
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 30000,
input: JSON.stringify({ cwd: projectDir, project_path: projectDir }),
env: {
...process.env,
VIBE_SCIENCE_STRICT: '1',
HOME: fakeHome,
USERPROFILE: fakeHome,
},
}
);
assert.equal(result.status, 0, 'session-start should still return degraded context');
const output = JSON.parse(String(result.stdout || '').trim());
assert.equal(output.integrityStatus, 'INTEGRITY_DEGRADED');
const injected = String(output?.hookSpecificOutput?.additionalContext || '');
assert.match(injected, /Recovered from STATE\.md/i);
assert.match(injected, /Recovered hypothesis about IL-6 confounding/i);
pass('session-start-state-md-fallback');
});
it('worker-embed.js: syntax check only (no daemon start)', () => {
const workerPath = rel('plugin', 'scripts', 'worker-embed.js');
assert.ok(fs.existsSync(workerPath), 'worker-embed.js should exist');
try {
execSync(`node --check "${workerPath}"`, {
cwd: ROOT,
encoding: 'utf-8',
timeout: 15000,
stdio: 'pipe',
});
pass('worker-syntax');
} catch (err) {
fail('worker-syntax');
assert.fail(`worker-embed.js syntax error: ${err.stderr || err.message}`);
}
});
it('eval-runner writes an artifact and records benchmark rows when requested', async () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-trace-eval-'));
const artifactPath = path.join(tempRoot, 'eval-artifact.json');
const dbPath = path.join(tempRoot, 'eval.db');
const result = spawnSync(
process.execPath,
['evals/eval-runner.mjs', '--artifact', artifactPath, '--record', '--db', dbPath, '--version', '7.0.0'],
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 60000,
}
);
assert.equal(result.status, 0, `eval-runner should succeed: ${result.stderr}`);
assert.ok(fs.existsSync(artifactPath), 'eval-runner should always write an artifact');
const artifact = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));
assert.equal(artifact.mode, 'schema_validation_only');
assert.equal(artifact.db_recorded, true);
assert.ok(artifact.total >= 24, 'artifact should include discovered eval cases');
const Database = (await import('better-sqlite3')).default;
const db = new Database(dbPath);
const row = db.prepare(`SELECT COUNT(*) AS n FROM benchmark_runs WHERE skill_version = '7.0.0'`).get();
assert.ok(row.n >= artifact.total, 'benchmark_runs should receive recorded eval cases');
db.close();
pass('eval-runner-record');
});
it('eval-runner fails honestly when benchmark rows cannot be persisted', async () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-trace-eval-trigger-'));
const artifactPath = path.join(tempRoot, 'eval-artifact.json');
const dbPath = path.join(tempRoot, 'eval.db');
const Database = (await import('better-sqlite3')).default;
const db = new Database(dbPath);
db.exec(fs.readFileSync(rel('plugin', 'db', 'schema.sql'), 'utf-8'));
db.exec(`
CREATE TRIGGER fail_benchmark_insert
BEFORE INSERT ON benchmark_runs
BEGIN
SELECT RAISE(FAIL, 'blocked insert');
END;
`);
db.close();
const result = spawnSync(
process.execPath,
['evals/eval-runner.mjs', '--artifact', artifactPath, '--record', '--db', dbPath, '--version', '7.0.0'],
{
cwd: ROOT,
encoding: 'utf-8',
timeout: 60000,
}
);
assert.equal(result.status, 1, 'eval-runner should fail when DB recording does not persist benchmark rows');
const artifact = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));
assert.equal(artifact.db_recorded, false, 'artifact must report DB recording failure honestly');
assert.match(String(artifact.record_error || ''), /inserted 0\/\d+ rows/i);
const verifyDb = new Database(dbPath, { readonly: true });
const row = verifyDb.prepare(`SELECT COUNT(*) AS n FROM benchmark_runs`).get();
assert.equal(row.n, 0, 'benchmark_runs should remain empty when trigger rejects inserts');
verifyDb.close();
pass('eval-runner-record-honesty');
});
it('eval-runner rejects multiline YAML prompts that parse as non-string schema fields', () => {
const tempCasePath = rel('evals', 'cases', `__temp_invalid_multiline_${process.pid}_${Date.now()}.yaml`);
const artifactPath = path.join(os.tmpdir(), `vibe-trace-eval-invalid-${Date.now()}.json`);
try {
fs.writeFileSync(
tempCasePath,
[
'id: TEMP-INVALID',
'name: Invalid multiline prompt',
'category: trace',
'prompt: |',
' line one',
' line two',
'expected_markers:',
' - ok',
'',
].join('\n'),
'utf-8'
);
const result = spawnSync(
process.execPath,
['evals/eval-runner.mjs', '--artifact', artifactPath],
{