-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathledger.test.js
More file actions
960 lines (893 loc) · 38.1 KB
/
Copy pathledger.test.js
File metadata and controls
960 lines (893 loc) · 38.1 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
import assert from "node:assert/strict";
import { test } from "node:test";
import {
authorTrust,
beliefDiff,
canonicalize,
claimId,
claimText,
clusters,
EQ3_WEIGHTS,
isDormant,
jaccard,
liveClaims,
mergeStates,
mintClaim,
outcomeRecord,
rec,
refStrength,
retrieve,
score,
sealRecord,
shingles,
sketch,
sortRecords,
stateAt,
stateRoot,
sticky,
UNRESOLVED_VAL_CAP,
val,
} from "../src/ledger.js";
import { SERVE_FLOOR } from "../src/reuse.js";
import { fakeAnthropic } from "./_fixtures.js";
// --- canonicalization & content addressing -----------------------------------------
test("canonicalize: key order never changes the bytes (id stability)", () => {
const a = canonicalize({ b: 1, a: [{ y: 2, x: 1 }], c: "s" });
const b = canonicalize({ c: "s", a: [{ x: 1, y: 2 }], b: 1 });
assert.equal(a, b);
});
test("canonicalize: drops undefined/function values, keeps null", () => {
assert.equal(canonicalize({ a: undefined, b: null, c: () => 1 }), '{"b":null}');
});
test("canonicalize: keys are NFC-normalized BEFORE sorting — NFD and NFC spellings give one byte string", () => {
const nfd = "é"; // é as e + combining acute
const nfc = "é";
// Sorting the raw NFD key ("é" < "f") and then normalizing it produced {"é":1,"f":2},
// while the NFC spelling sorts after "f" — two byte strings for one value, so a claim with
// an NFD key failed its own address check on reload.
assert.equal(canonicalize({ [nfd]: 1, f: 2 }), canonicalize({ [nfc]: 1, f: 2 }));
assert.equal(canonicalize({ [nfc]: 1, f: 2 }), '{"f":2,"é":1}');
const m = mintClaim({ kind: "fact", body: { name: "x", meta: { [nfd]: 1, f: 2 } } });
const reparsed = JSON.parse(canonicalize({ body: m.claim.body, kind: "fact", scope: {} }));
assert.equal(claimId("fact", reparsed.body, reparsed.scope), m.claim.id, "id survives a reload");
});
test("canonicalize: a CRLF checkout and an LF checkout mint ONE claim id", () => {
// `core.autocrlf` hands the same file to a Windows worktree with \r\n and to a Linux one
// with \n. Before this, the same logical claim minted on each side landed on two content
// addresses and never merged: one fact, two "copies", evidence split between them forever.
const lf = "the parser rejects a trailing comma\nreproduced on node 20 and 22";
const crlf = lf.replace(/\n/g, "\r\n");
const body = (text) => ({ name: "parser", text });
assert.equal(
claimId("fact", body(crlf), { level: "repo" }),
claimId("fact", body(lf), { level: "repo" }),
"line endings are a property of the machine, not of the claim",
);
const a = mintClaim({ kind: "fact", body: body(crlf), t: 1 });
const b = mintClaim({ kind: "fact", body: body(lf), t: 1 });
assert.ok(a.ok && b.ok);
assert.equal(a.claim.id, b.claim.id, "two teammates converge on one claim");
assert.equal(canonicalize(body(crlf)), canonicalize(body(lf)), "and on one byte string");
// The same rule for a key, so a CRLF-spelled key can't fork an id either.
assert.equal(canonicalize({ "a\r\nb": 1 }), canonicalize({ "a\nb": 1 }));
});
test("canonicalize: text that legitimately differs still gets two ids (no over-folding)", () => {
const id = (text) => claimId("fact", { name: "n", text }, { level: "repo" });
const base = "line one\nline two";
assert.notEqual(id(base), id("line one\nline three"), "different words, different claims");
// A LONE \r is a control character in captured terminal output (a progress bar), not a
// line ending — folding it into \n would edit the evidence a diagnosis claim carries.
assert.notEqual(id("a\rb"), id("a\nb"), "a bare carriage return is content, not formatting");
assert.notEqual(id(" indented"), id("indented"), "whitespace is content");
assert.notEqual(id("Fix"), id("fix"), "case is content");
assert.notEqual(id("line one\n\nline two"), id(base), "a blank line is content");
assert.notEqual(id("file"), id("file"), "NFC only — no compatibility folding (NFKC)");
});
test("claimId: pinned fixture — the protocol's address must never drift across versions", () => {
// If this fixture ever fails, existing ledgers on disk stop resolving. Bump v and
// write a migration before changing canonicalization or the id recipe.
const id = claimId("fact", { name: "n", text: "t" }, { level: "repo" });
assert.match(id, /^[0-9a-f]{64}$/);
assert.equal(id, claimId("fact", { text: "t", name: "n" }, { level: "repo" }));
});
test("claimId: provenance and evidence never affect the address (teammates converge)", () => {
const a = mintClaim({
kind: "fact",
body: { name: "x", text: "y" },
provenance: { author: "alice" },
t: 1,
});
const b = mintClaim({
kind: "fact",
body: { name: "x", text: "y" },
provenance: { author: "bob" },
t: 9,
});
assert.ok(a.ok && b.ok);
assert.equal(a.claim.id, b.claim.id);
});
test("mintClaim: normalizes non-JSON values so different Dates can't collide on one id", () => {
const d1 = mintClaim({
kind: "fact",
body: { name: "d", text: new Date(0) },
});
const d2 = mintClaim({
kind: "fact",
body: { name: "d", text: new Date(86400000) },
});
assert.ok(d1.ok && d2.ok);
assert.notEqual(d1.claim.id, d2.claim.id, "Dates serialize to ISO strings, not {}");
});
test("mintClaim: refuses secrets, unknown kinds, and non-object bodies", () => {
const s = mintClaim({
kind: "fact",
body: { name: "k", text: fakeAnthropic() },
});
assert.equal(s.ok, false);
assert.match(s.reason, /secret/);
assert.equal(mintClaim({ kind: "nope", body: {} }).ok, false);
assert.equal(mintClaim({ kind: "fact", body: "text" }).ok, false);
});
test("outcomeRecord: requires a known oracle, a valid result, and a verifiable ref", () => {
assert.equal(outcomeRecord({ oracle: "vibes", result: "confirm", ref: "r" }).ok, false);
assert.equal(outcomeRecord({ oracle: "test.run", result: "maybe", ref: "r" }).ok, false);
assert.equal(outcomeRecord({ oracle: "test.run", result: "confirm", ref: "" }).ok, false);
const ok = outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "run:1",
t: 3,
});
assert.ok(ok.ok);
assert.match(ok.outcome.h, /^[0-9a-f]{64}$/);
assert.equal(ok.outcome.w, 0.8);
});
test("outcomeRecord: typed git ref is resolved; unresolvable is rejected, untyped is accepted", () => {
const resolveGit = (sha) => sha === "cafebabe"; // pretend only this object exists
// a git: ref whose object resolves is accepted
const good = outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "git:cafebabe",
resolveGit,
});
assert.ok(good.ok, "resolvable git ref accepted");
// a git: ref that does not resolve is rejected with a reason
const bad = outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "git:deadbeef",
resolveGit,
});
assert.equal(bad.ok, false, "unresolvable git ref rejected");
assert.match(bad.reason, /unresolvable/);
// a typed-but-empty ref is rejected on format
assert.equal(outcomeRecord({ oracle: "test.run", result: "confirm", ref: "git:" }).ok, false);
// an untyped/legacy ref is accepted unchanged (back-compat)
assert.ok(outcomeRecord({ oracle: "test.run", result: "confirm", ref: "run:1" }).ok);
});
test("validateRef: ci: must be a locator, human: must be a ratification (ME-05 format grammars)", () => {
const ok = (ref) => outcomeRecord({ oracle: "ci.run", result: "confirm", ref }).ok;
// A CI locator: URL, owner/repo@run, or a bare run id — but not prose.
assert.ok(ok("ci:https://ci.example.com/run/7"), "URL accepted");
assert.ok(ok("ci:acme/app@1234"), "owner/repo@run accepted");
assert.ok(ok("ci:42"), "bare run id accepted (back-compat)");
assert.equal(ok("ci:not-a-url"), false, "made-up CI string refused on format");
// human: is an explicit ratification (author@ref), never the model's own say-so.
const okH = (ref) => outcomeRecord({ oracle: "human.accept", result: "confirm", ref }).ok;
assert.ok(okH("human:alice@decision-42"), "explicit human ratification accepted");
assert.equal(okH("human:the-model-said-yes"), false, "self-assertion refused on format");
});
test("refStrength: only a git object id (or a bridge pointer on its own bridge oracle) is resolved", () => {
assert.equal(refStrength("git:cafebabe"), "resolved");
assert.equal(refStrength(`git:${"a1".repeat(20)}`), "resolved", "full sha1");
assert.equal(refStrength("episode:ep_m0_x#n1", "cortex.episode"), "resolved");
assert.equal(refStrength("legacy:lsn_a#confirm0", "legacy.import"), "resolved");
// C2: none of these is something forge resolved — they are pointers anyone can type.
for (const ref of [
"lgtm",
"run:1",
"session:x",
"foo:bar",
"ci:1",
"ci:https://ci.example.com/run/7",
"human:claude@yes",
"git:HEAD",
"git:main",
"git:HEAD~0",
"test:made-up-run",
"file:/some/path",
])
assert.equal(refStrength(ref, "test.run"), "format", ref);
assert.equal(
refStrength("episode:ep_m0_x#n1", "test.run"),
"format",
"a bridge pointer only counts on the bridge oracle that mints it",
);
});
test("val (C2): made-up refs are capped below the serving floor — no prefix buys full trust", () => {
for (const ref of ["lgtm", "session:x", "ci:1", "human:claude@yes", "git:HEAD"]) {
const records = Array.from({ length: 3 }, (_, i) =>
outcomeRecord({ oracle: "human.accept", result: "confirm", ref, t: i }),
);
assert.ok(
records.every((r) => r.ok),
`${ref} passes the format check`,
);
const c = mkClaim(records.map((r) => ("outcome" in r ? r.outcome : null)));
assert.ok(val(c, 0) <= UNRESOLVED_VAL_CAP + 1e-9, `${ref}: val ${val(c, 0)} is capped`);
assert.ok(val(c, 0) < SERVE_FLOOR, `${ref} never reaches the serving floor`);
}
});
test("val (C2): an agent identity never supplies human-family evidence at resolved strength", () => {
const human = (author) =>
mkClaim([
outcomeRecord({ oracle: "human.accept", result: "confirm", ref: "git:cafebabe", author })
.outcome,
]);
assert.ok(val(human("Alice <a@x>"), 0) >= SERVE_FLOOR, "a person's git-anchored accept counts");
assert.ok(val(human("agent:mcp"), 0) <= UNRESOLVED_VAL_CAP + 1e-9, "agent:mcp is not a human");
});
test("val: format-only evidence (test:/file:) cannot lift confidence into the serving band", () => {
// A single confirm on a resolved (git object) ref clears the serving floor.
const resolved = mkClaim([
outcomeRecord({ oracle: "test.run", result: "confirm", ref: "git:c0ffee1" }).outcome,
]);
assert.ok(val(resolved, 0) >= SERVE_FLOOR, "resolved evidence still earns trust (no regression)");
// But test:/file: refs — however many — are capped below the serving/trusted band.
const madeUp = mkClaim(
Array.from(
{ length: 6 },
(_, i) =>
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: `test:made-up-run-${i}`,
}).outcome,
),
);
assert.ok(val(madeUp, 0) < SERVE_FLOOR, "test:made-up-run never reaches the serving floor");
assert.ok(val(madeUp, 0) <= UNRESOLVED_VAL_CAP + 1e-9, "capped at UNRESOLVED_VAL_CAP");
const fileGhost = mkClaim([
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "file:/does/not/exist",
}).outcome,
]);
assert.ok(val(fileGhost, 0) < SERVE_FLOOR, "file:/does/not/exist cannot lift into serving band");
});
test("val: a resolvable git-ref confirmation raises confidence as before (no regression)", () => {
const git = mkClaim([
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "git:cafebabe",
}).outcome,
]);
assert.ok(val(git, 0) >= SERVE_FLOOR, "git evidence lifts confidence past the serving floor");
// A single resolved confirm lifts the whole claim even if a format-only one rides along.
const mixed = mkClaim([
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "git:cafebabe",
}).outcome,
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: "test:made-up",
}).outcome,
]);
assert.ok(val(mixed, 0) >= SERVE_FLOOR, "one resolved confirm removes the format-only cap");
});
// --- confidence: the decayed Beta posterior -----------------------------------------
const mkClaim = (evidence = []) => {
const m = mintClaim({
kind: "fact",
body: { name: "f", text: "body" },
t: 0,
});
return { ...m.claim, evidence };
};
// A resolved (git object id) ref, unique per (result, t, oracle) so records never dedupe.
const gitRef = (s) => `git:${Buffer.from(String(s)).toString("hex").padEnd(8, "0").slice(0, 40)}`;
const ev = (result, t, oracle = "test.run") =>
outcomeRecord({ oracle, result, ref: gitRef(`${result}${t}${oracle}`), t }).outcome;
test("val: fresh claim sits at the 0.5 prior; confirms raise; contradictions lower", () => {
assert.equal(val(mkClaim(), 0), 0.5);
assert.ok(val(mkClaim([ev("confirm", 0)]), 0) > 0.5);
assert.ok(val(mkClaim([ev("contradict", 0)]), 0) < 0.5);
});
test("val: monotone in confirmations (more independent evidence is never worse)", () => {
let prev = 0.5;
for (let n = 1; n <= 5; n++) {
const outs = Array.from(
{ length: n },
(_, i) =>
outcomeRecord({
oracle: "ci.run",
result: "confirm",
ref: gitRef(`ci${i}`),
t: 0,
}).outcome,
);
const v = val(mkClaim(outs), 0);
assert.ok(v > prev, `val(${n} confirms)=${v} must exceed ${prev}`);
prev = v;
}
});
test("val: decays toward the PRIOR (uncertainty), never toward false", () => {
const confirmed = mkClaim([ev("confirm", 0), ev("confirm", 0, "ci.run")]);
const now = val(confirmed, 0);
const later = val(confirmed, 90); // two half-lives
const muchLater = val(confirmed, 900);
assert.ok(later < now, "unreviewed confirmation loses weight");
assert.ok(later > 0.5, "decayed-but-confirmed stays above the prior");
assert.ok(Math.abs(muchLater - 0.5) < 0.01, "fully decayed → back to uncertainty, not 0");
// Same shape from below: an old contradiction also relaxes toward 0.5.
const contradicted = mkClaim([ev("contradict", 0)]);
assert.ok(val(contradicted, 900) > val(contradicted, 0));
});
test("val: oracle weight matters — a human revert outweighs a behavioral signal", () => {
const human = val(mkClaim([ev("contradict", 0, "human.revert")]), 0);
const behav = val(mkClaim([ev("contradict", 0, "behavioral")]), 0);
assert.ok(human < behav, "stronger oracle pulls harder");
});
test("val: forged evidence buys nothing — weight comes from the ORACLES table, unknown oracles are ignored", () => {
// A hand-edited log line claiming w=50 on the strongest oracle:
const forgedWeight = { ...ev("confirm", 0, "human.revert"), w: 50 };
const honest = val(mkClaim([ev("confirm", 0, "human.revert")]), 0);
assert.equal(
val(mkClaim([forgedWeight]), 0),
honest,
"stored w is audit metadata, never trusted",
);
// A record naming an oracle that doesn't exist:
const ghost = sealRecord({
oracle: "made.up",
result: "confirm",
ref: "x",
t: 0,
w: 1,
author: "",
});
assert.equal(val(mkClaim([ghost]), 0), 0.5, "unknown oracle contributes nothing");
});
test("rec: recency keys on the latest evidence, else the mint day", () => {
assert.equal(rec(mkClaim(), 0), 1);
assert.ok(rec(mkClaim(), 45) < rec(mkClaim(), 1));
const fresh = mkClaim([ev("confirm", 40)]);
assert.ok(rec(fresh, 45) > rec(mkClaim(), 45), "new evidence refreshes recency");
});
test("isDormant: repeated strong contradictions sink a claim below the retrieval floor", () => {
assert.equal(isDormant(mkClaim(), 0), false, "the prior is not dormant");
const sunk = mkClaim([
ev("contradict", 0, "human.revert"),
ev("contradict", 0, "human.accept"),
ev("contradict", 0, "test.run"),
ev("contradict", 0, "ci.run"),
]);
assert.equal(isDormant(sunk, 0), true);
});
// --- similarity ----------------------------------------------------------------------
test("shingles: 4-token windows over normalized text; short texts fall back to tokens", () => {
assert.equal([...shingles("Check the CALLERS first, always")].length, 2);
assert.deepEqual([...shingles("two words")], ["two words"]);
assert.deepEqual([...shingles("")], []);
});
test("sketch/jaccard: identical text = 1, disjoint ≈ 0, near-duplicates score high", () => {
const a = sketch("always run the impacted tests before editing shared utils");
assert.equal(jaccard(a, sketch("always run the impacted tests before editing shared utils")), 1);
assert.ok(jaccard(a, sketch("completely unrelated words about cooking pasta dinner")) < 0.15);
const near = sketch("always run the impacted tests before editing shared utilities");
assert.ok(jaccard(a, near) > 0.5, "one-word change stays similar");
});
test("sketch: deterministic across calls (no randomness — ids and sketches are stable)", () => {
assert.deepEqual(sketch("some stable text here"), sketch("some stable text here"));
});
test("claimText: every retrievable kind exposes its human text (not canonical JSON)", () => {
const lesson = mintClaim({
kind: "lesson",
body: {
whatWentWrong: "w",
correctedBehavior: "c",
trigger: { keywords: ["k"], symbols: ["s"] },
},
}).claim;
assert.equal(claimText(lesson), "w c k s");
const fact = mintClaim({
kind: "fact",
body: { name: "n", text: "t" },
}).claim;
assert.equal(claimText(fact), "n t");
const diag = mintClaim({
kind: "diagnosis",
body: { signature: "sig", note: "root cause" },
}).claim;
assert.equal(claimText(diag), "sig root cause");
});
test("clusters: near-duplicates group, distinct claims stay apart", () => {
const long =
"before renaming any exported symbol in the shared utilities package always query the " +
"atlas for reverse dependents and run the impacted test selection so silent breakage";
const c1 = mintClaim({
kind: "fact",
body: { name: "note", text: `${long} is impossible` },
}).claim;
const c2 = mintClaim({
kind: "fact",
body: { name: "note", text: `${long} is unlikely` },
}).claim;
const c3 = mintClaim({
kind: "fact",
body: {
name: "note",
text: "the deploy pipeline needs the staging flag set first",
},
}).claim;
const groups = clusters([c1, c2, c3], { tau: 0.5 });
assert.equal(groups.length, 1);
assert.deepEqual(groups[0], [c1.id, c2.id].sort());
});
// --- retrieval (Eq. 3) ---------------------------------------------------------------
test("score: outcome-confirmed claims outrank merely-similar unconfirmed ones", () => {
const q = "renaming a shared symbol";
const confirmed = {
...mintClaim({
kind: "fact",
body: {
name: "a",
text: "check callers before renaming a shared symbol",
},
t: 0,
}).claim,
evidence: [ev("confirm", 0), ev("confirm", 0, "human.accept")],
};
const unconfirmed = mintClaim({
kind: "fact",
body: { name: "b", text: "check callers before renaming a shared symbol" },
t: 0,
}).claim;
assert.ok(score(q, confirmed, { nowDay: 0 }) > score(q, unconfirmed, { nowDay: 0 }));
});
test("retrieve: excludes tombstoned and dormant claims, caps at budget", () => {
const alive = mkClaim([ev("confirm", 0)]);
const dead = {
...mkClaim(),
tombstone: { reason: "retracted", t: 0, author: "" },
};
const dormant = mkClaim([
ev("contradict", 0, "human.revert"),
ev("contradict", 0, "human.accept"),
ev("contradict", 0, "test.run"),
ev("contradict", 0, "ci.run"),
]);
const out = retrieve("body", [alive, dead, dormant], {
nowDay: 0,
budget: 10,
});
assert.deepEqual(
out.map((r) => r.claim.id),
[alive.id],
);
assert.equal(retrieve("body", [alive, alive, alive], { budget: 2 }).length, 2);
});
// --- the CRDT merge: the semilattice laws property-tested ----------------------------
const tomb = (reason, t, author = "") => sealRecord({ author, reason, t });
const prov = (author, t) => sealRecord({ agent: "test", author, t });
const state = (claims, evidence = {}, tombstones = {}, provenance = {}) => ({
claims: Object.fromEntries(claims.map((c) => [c.id, c])),
evidence,
provenance,
tombstones,
});
test("mergeStates: commutative, associative, idempotent — replicas converge in any order", () => {
const c1 = mintClaim({
kind: "fact",
body: { name: "1", text: "one" },
t: 1,
}).claim;
const c2 = mintClaim({
kind: "fact",
body: { name: "2", text: "two" },
t: 2,
}).claim;
const c3 = mintClaim({
kind: "lesson",
body: { whatWentWrong: "w", correctedBehavior: "c", trigger: {} },
t: 3,
}).claim;
const sA = state([c1, c2], { [c1.id]: [ev("confirm", 1)] }, {}, { [c1.id]: [prov("alice", 1)] });
const sB = state(
[c2, c3],
{ [c1.id]: [ev("confirm", 1), ev("contradict", 2)] },
{ [c2.id]: [tomb("retracted", 4, "bob")] },
{ [c1.id]: [prov("bob", 2)] },
);
const sC = state([c3], {}, { [c2.id]: [tomb("duplicate", 5, "carol")] });
const canon = (s) => canonicalize(liveClaims(s));
// commutativity
assert.equal(canon(mergeStates(sA, sB)), canon(mergeStates(sB, sA)));
// associativity
assert.equal(
canon(mergeStates(mergeStates(sA, sB), sC)),
canon(mergeStates(sA, mergeStates(sB, sC))),
);
// idempotence
const m = mergeStates(sA, sB);
assert.equal(canon(mergeStates(m, m)), canon(m));
assert.equal(canon(mergeStates(m, sA)), canon(m), "absorbing a subset is a no-op");
});
test("mergeStates: concurrent retractions both survive; the view picks one deterministically", () => {
const c = mintClaim({
kind: "fact",
body: { name: "x", text: "y" },
t: 0,
}).claim;
const sA = state([c], {}, { [c.id]: [tomb("wrong", 3, "alice")] });
const sB = state([c], {}, { [c.id]: [tomb("stale", 2, "bob")] });
const ab = mergeStates(sA, sB);
const ba = mergeStates(sB, sA);
assert.equal(ab.tombstones[c.id].length, 2, "both retraction records kept (grow-only set)");
assert.equal(
canonicalize(liveClaims(ab)[0].tombstone),
canonicalize(liveClaims(ba)[0].tombstone),
"the single-record view is merge-order independent",
);
assert.equal(liveClaims(ab)[0].tombstone.author, "bob", "earliest by (t, h) wins the view");
});
test("mergeStates: evidence unions dedupe by hash; val is identical after any merge order", () => {
const c = mintClaim({
kind: "fact",
body: { name: "x", text: "y" },
t: 0,
}).claim;
const e1 = ev("confirm", 1);
const e2 = ev("contradict", 2);
const sA = state([c], { [c.id]: [e1] });
const sB = state([c], { [c.id]: [e1, e2] });
const ab = mergeStates(sA, sB);
const ba = mergeStates(sB, sA);
assert.equal(ab.evidence[c.id].length, 2, "duplicate outcome merged away");
assert.equal(
val(liveClaims(ab)[0], 10),
val(liveClaims(ba)[0], 10),
"confidence is merge-order-independent",
);
});
// --- per-author trust (P2) -------------------------------------------------------------
test("authorTrust: bootstrap 1.0, degrades with contradicted claims, floors at 0.5, ignores self-confirmation", () => {
const mint = (name, author) =>
mintClaim({
kind: "fact",
body: { name, text: `${name} content` },
provenance: { author },
t: 0,
}).claim;
const out = (result, ref, author) =>
outcomeRecord({ oracle: "test.run", result, ref, author, t: 0 }).outcome;
const fresh = { ...mint("a", "newbie"), evidence: [] };
const good = {
...mint("b", "alice"),
evidence: [out("confirm", "r1", "ci"), out("confirm", "r2", "ci")],
};
const selfServing = {
...mint("c", "bob"),
evidence: [out("confirm", "r3", "bob")],
};
const wrongOften = {
...mint("d", "carol"),
evidence: Array.from({ length: 20 }, (_, i) => out("contradict", `r${i}`, "ci")),
};
const trust = authorTrust([fresh, good, selfServing, wrongOften]);
assert.equal(trust.newbie, 1, "no history → full trust (never punish the new teammate)");
assert.equal(trust.alice, 1, "only confirmations → full trust");
assert.equal(trust.bob, 1, "self-confirmation is excluded, so bob has NO history — bootstrap");
assert.equal(trust.carol, 0.5, "heavily contradicted → floored, never silenced");
assert.ok(!("" in trust), "anonymous claims don't accumulate trust");
});
test("val with trust: a distrusted author's evidence moves confidence less", () => {
const claim = mkClaim([
outcomeRecord({
oracle: "test.run",
result: "confirm",
ref: gitRef("r"),
author: "carol",
t: 0,
}).outcome,
]);
const flat = val(claim, 0);
const weighted = val(claim, 0, { trust: { carol: 0.5 } });
assert.ok(weighted < flat, "trust scales the evidence weight down");
assert.ok(weighted > 0.5, "but a confirmation still counts for something");
});
// --- temporal views + Merkle state root ----------------------------------------------
test("stateAt hides a claim minted later and evidence appended later; val returns to the prior", () => {
const early = mintClaim({ kind: "fact", body: { name: "e", text: "early" }, t: 5 }).claim;
const late = mintClaim({ kind: "fact", body: { name: "l", text: "late" }, t: 50 }).claim;
const s = state(
[early, late],
{ [early.id]: [ev("confirm", 6), ev("confirm", 40)] },
{},
{ [early.id]: [prov("alice", 5)], [late.id]: [prov("bob", 50)] },
);
const then = liveClaims(stateAt(s, 10));
assert.deepEqual(
then.map((c) => c.id),
[early.id],
"the day-50 claim did not exist on day 10",
);
assert.equal(then[0].evidence.length, 1, "day-40 evidence is not visible on day 10");
const now = liveClaims(stateAt(s, 60));
assert.equal(now.length, 2, "both claims exist by day 60");
assert.ok(
val(then[0], 10) !==
val(
now.find((c) => c.id === early.id),
60,
),
"belief strength is recomputed with that day's evidence and clock",
);
});
test("stateAt commutes with mergeStates — a lattice morphism, so replicas agree on history", () => {
const c1 = mintClaim({ kind: "fact", body: { name: "m1", text: "one" }, t: 1 }).claim;
const c2 = mintClaim({ kind: "fact", body: { name: "m2", text: "two" }, t: 2 }).claim;
const sA = state([c1], { [c1.id]: [ev("confirm", 3)] }, {}, { [c1.id]: [prov("alice", 1)] });
const sB = state(
[c1, c2],
{ [c1.id]: [ev("contradict", 30)] },
{ [c2.id]: [tomb("dup", 40, "bob")] },
{ [c1.id]: [prov("bob", 1)], [c2.id]: [prov("bob", 2)] },
);
const canon = (s) => canonicalize(liveClaims(s));
for (const day of [0, 1, 5, 30, 40, 99])
assert.equal(
canon(stateAt(mergeStates(sA, sB), day)),
canon(mergeStates(stateAt(sA, day), stateAt(sB, day))),
`morphism holds at day ${day}`,
);
assert.equal(
canon(stateAt(sA, 7)),
canon(stateAt(stateAt(sA, 7), 7)),
"stateAt is idempotent at the same day",
);
});
test("beliefDiff classifies appeared / retired / strengthened / weakened and respects epsilon", () => {
const grew = mintClaim({ kind: "fact", body: { name: "g", text: "grew" }, t: 1 }).claim;
const sank = mintClaim({ kind: "fact", body: { name: "s", text: "sank" }, t: 1 }).claim;
const born = mintClaim({ kind: "fact", body: { name: "b", text: "born" }, t: 20 }).claim;
const gone = mintClaim({ kind: "fact", body: { name: "x", text: "gone" }, t: 1 }).claim;
const still = mintClaim({ kind: "fact", body: { name: "q", text: "still" }, t: 1 }).claim;
const s = state(
[grew, sank, born, gone, still],
{
[grew.id]: [ev("confirm", 12), ev("confirm", 13), ev("confirm", 14)],
[sank.id]: [ev("confirm", 2), ev("contradict", 12), ev("contradict", 13)],
},
{ [gone.id]: [tomb("obsolete", 15, "alice")] },
{
[grew.id]: [prov("a", 1)],
[sank.id]: [prov("a", 1)],
[born.id]: [prov("a", 20)],
[gone.id]: [prov("a", 1)],
[still.id]: [prov("a", 1)],
},
);
const d = beliefDiff(s, 10, 30);
assert.deepEqual(
d.appeared.map((r) => r.id),
[born.id],
"minted inside the window",
);
assert.deepEqual(
d.retired.map((r) => r.id),
[gone.id],
"tombstoned inside the window",
);
assert.deepEqual(
d.strengthened.map((r) => r.id),
[grew.id],
"confirms raised val",
);
assert.deepEqual(
d.weakened.map((r) => r.id),
[sank.id],
"contradictions sank val",
);
assert.ok(!d.strengthened.some((r) => r.id === still.id), "no-news claim stays out");
const strict = beliefDiff(s, 10, 30, { epsilon: 0.99 });
assert.equal(
strict.strengthened.length + strict.weakened.length,
0,
"a large epsilon silences movement rows",
);
});
test("stateRoot: replicas merged in any order share one root; one new record moves exactly one shard", () => {
const c1 = mintClaim({ kind: "fact", body: { name: "r1", text: "one" }, t: 1 }).claim;
const c2 = mintClaim({ kind: "fact", body: { name: "r2", text: "two" }, t: 2 }).claim;
const sA = state([c1], { [c1.id]: [ev("confirm", 3)] }, {}, { [c1.id]: [prov("alice", 1)] });
const sB = state([c1, c2], {}, {}, { [c2.id]: [prov("bob", 2)] });
const ab = stateRoot(mergeStates(sA, sB));
const ba = stateRoot(mergeStates(sB, sA));
assert.equal(ab.root, ba.root, "merge order cannot leak into the root");
assert.equal(ab.claims, 2);
const grown = mergeStates(sA, sB);
grown.evidence[c2.id] = sortRecords([ev("confirm", 9)]);
const after = stateRoot(grown);
assert.notEqual(after.root, ab.root, "new evidence changes the root");
const changed = Object.keys(after.shards).filter((p) => after.shards[p] !== ab.shards[p]);
assert.deepEqual(changed, [c2.id.slice(0, 2)], "divergence is localized to the touched shard");
});
test("stateRoot distinguishes states that liveClaims-level summaries could conflate", () => {
const c = mintClaim({ kind: "fact", body: { name: "t", text: "tomb" }, t: 1 }).claim;
const plain = state([c], {}, {}, { [c.id]: [prov("a", 1)] });
const tombed = state([c], {}, { [c.id]: [tomb("done", 2, "a")] }, { [c.id]: [prov("a", 1)] });
assert.notEqual(stateRoot(plain).root, stateRoot(tombed).root);
assert.notEqual(stateRoot(state([])).root, stateRoot(plain).root, "empty ≠ one-claim");
});
test("beliefDiff routes a claim minted AND tombstoned inside the window to retired, not appeared", () => {
const c = mintClaim({
kind: "fact",
body: { name: "flash", text: "came and went" },
t: 15,
}).claim;
const s = state(
[c],
{},
{ [c.id]: [tomb("wrong", 20, "alice")] },
{ [c.id]: [prov("alice", 15)] },
);
const d = beliefDiff(s, 10, 30);
assert.deepEqual(d.appeared, [], "a retracted claim is never presented as a live belief");
assert.equal(d.retired.length, 1, "the retraction inside the window is reported");
assert.equal(d.retired[0].from, null, "it did not exist at dayA");
assert.equal(d.retired[0].to, null, "and is not believed at dayB");
});
test("beliefDiff ignores claims already tombstoned before the window — dead beliefs do not move", () => {
const c = mintClaim({ kind: "fact", body: { name: "old", text: "long dead" }, t: 1 }).claim;
const s = state(
[c],
{ [c.id]: [ev("confirm", 2)] },
{ [c.id]: [tomb("obsolete", 5, "alice")] },
{ [c.id]: [prov("alice", 1)] },
);
const d = beliefDiff(s, 10, 90);
assert.deepEqual(d.appeared, []);
assert.deepEqual(d.retired, [], "the retirement predates the window");
assert.deepEqual(d.strengthened, []);
assert.deepEqual(d.weakened, [], "pure decay on a dead claim is not a belief change");
});
// --- Eq. 3 retrieval fixes (review C5) -------------------------------------------------
const factAt = (text, level = "repo", evidence = [], t = 0) => ({
...mintClaim({ kind: "fact", body: { name: text.slice(0, 12), text }, scope: { level }, t })
.claim,
evidence,
});
test("score (C5): scope is a bounded term inside σ — never a strict priority over relevance", () => {
const q = "retry the payment webhook with exponential backoff and jitter on 503";
const perfectRepo = factAt(q, "repo", [ev("confirm", 0, "human.accept"), ev("confirm", 0)]);
const unrelatedSymbol = factAt(
"css grid gutter width is 12px in the dashboard layout",
"symbol",
[ev("contradict", 0, "typecheck")],
);
const ranked = retrieve(q, [unrelatedSymbol, perfectRepo], { nowDay: 400 });
assert.equal(ranked[0].claim.id, perfectRepo.id, "a perfect match beats an unrelated symbol");
// Scope still breaks ties among equally relevant claims.
const sym = factAt("check callers before renaming", "symbol");
const glob = factAt("check callers before renaming", "global");
assert.ok(
score("check callers before renaming", sym) > score("check callers before renaming", glob),
);
});
test("rel (C5): a short query finds its fact — unigram coverage backs 4-token shingles", () => {
const csrf = factAt("the login handler must validate the csrf token on every POST");
const fonts = factAt("fonts are self-hosted from the static assets folder");
const ports = factAt("the dev server listens on port 5173 by default");
for (const q of ["csrf login", "validate csrf in the login handler"]) {
const ranked = retrieve(q, [fonts, ports, csrf], { nowDay: 0 });
assert.equal(ranked[0].claim.id, csrf.id, `"${q}" ranks the CSRF fact first`);
assert.ok(ranked[0].rel > 0.5, `"${q}": rel ${ranked[0].rel} reflects the overlap`);
assert.equal(ranked.find((r) => r.claim.id === fonts.id).rel, 0, "unrelated stays at 0");
}
});
test("rel (C5): non-ASCII text tokenizes — unrelated scripts are NOT identical, empty ≠ everything", () => {
assert.equal(jaccard(sketch("مصادقة الرمز تفشل"), sketch("数据库连接超时")), 0);
assert.equal(jaccard(sketch(""), sketch("!!!")), 0, "two empty token sets share nothing");
assert.equal(jaccard(sketch("مصادقة الرمز تفشل"), sketch("مصادقة الرمز تفشل")), 1);
assert.deepEqual([...shingles("café au lait")], ["café au lait"], "accented letters are kept");
const ar = factAt("مصادقة الرمز تفشل عند انتهاء الجلسة");
const zh = factAt("数据库连接超时");
const [top] = retrieve("مصادقة الرمز", [zh, ar], { nowDay: 0 });
assert.equal(top.claim.id, ar.id);
assert.equal(retrieve("مصادقة الرمز", [zh], { nowDay: 0 })[0].rel, 0);
});
test("rec (C5): a contradiction is not recent evidence — it never raises a stale claim's score", () => {
const base = factAt("use yarn not npm", "repo", [], 19910);
const now = 20000;
const contradicted = { ...base, evidence: [ev("contradict", now)] };
assert.equal(rec(contradicted, now), rec(base, now), "recency keys on confirms and mint only");
assert.ok(
score("unrelated query text here", contradicted, { nowDay: now }) <
score("unrelated query text here", base, { nowDay: now }),
"fresh negative evidence lowers the score",
);
const confirmed = { ...base, evidence: [ev("confirm", now)] };
assert.equal(rec(confirmed, now), 1, "a fresh confirm still refreshes recency");
});
test("val/rec (C11): future-dated evidence decays by its distance from now — no pinning", () => {
const today = 20000;
const skewed = factAt("x", "repo", [ev("confirm", today + 3650)], today);
const honest = factAt("x", "repo", [ev("confirm", today)], today);
assert.ok(rec(skewed, today + 730) < 0.01, `rec ${rec(skewed, today + 730)} is not pinned at 1`);
assert.ok(val(skewed, today + 730) < 0.51, "a 10-year-future confirm carries ~no weight");
assert.ok(val(skewed, today) < val(honest, today), "the skewed record never beats an honest one");
assert.ok(
Math.abs(
val(factAt("x", "repo", [ev("confirm", today + 1)], today), today) - val(honest, today),
) < 0.01,
"a one-day clock skew is negligible",
);
});
test("retrieve (C5): one similarity scale per ranking — cosine and Jaccard are never mixed", () => {
const unrelatedEmbedded = factAt("render the marketing landing page hero section");
const relevantLexical = factAt("rotate the api signing keys every ninety days");
// The provider embedded only one claim, at a typical same-domain cosine for unrelated text.
const sim = (_q, c) => (c.id === unrelatedEmbedded.id ? 0.6 : null);
const ranked = retrieve("rotate the signing keys", [unrelatedEmbedded, relevantLexical], {
nowDay: 0,
sim,
});
assert.equal(ranked[0].claim.id, relevantLexical.id, "a partial embedding falls back for all");
const full = (_q, c) => (c.id === unrelatedEmbedded.id ? 0.1 : 0.9);
const both = retrieve("rotate the signing keys", [unrelatedEmbedded, relevantLexical], {
nowDay: 0,
sim: full,
});
assert.equal(both[0].claim.id, relevantLexical.id);
assert.equal(both[0].rel, 0.9, "a complete embedding ranks by cosine");
});
test("EQ3_WEIGHTS: defaults are the spec's (a, b, g) plus a small scope term — not 'calibrated'", () => {
assert.deepEqual(EQ3_WEIGHTS, { a: 0.55, b: 0.15, g: 0.3, s: 0.1 });
});
test("isDormant (C7): dormancy latches — decay alone never revives a refuted claim", () => {
const refuted = mkClaim([ev("contradict", 0, "human.revert")]); // val 1/3 ≈ 0.333
assert.equal(isDormant(refuted, 0), true);
assert.equal(isDormant(refuted, 11), true, "11 days of decay used to bring it back");
assert.equal(isDormant(refuted, 400), true);
assert.equal(retrieve("x", [refuted], { nowDay: 400 }).length, 0, "and it stays out of reach");
// Review restores weight: a later CONFIRMATION is the only way back.
const reviewed = mkClaim([
ev("contradict", 0, "human.revert"),
ev("confirm", 30, "human.accept"),
]);
assert.equal(isDormant(reviewed, 30), false);
assert.equal(retrieve("f body", [reviewed], { nowDay: 30 }).length, 1);
});
test("sticky: hysteresis — on at `high`, off only below `low` (never one-day flapping)", () => {
const c = mkClaim([ev("confirm", 0, "cortex.episode")]); // val exactly 0.6
assert.equal(sticky(c, { high: 0.6, low: 0.55, nowDay: 0 }), true);
assert.equal(
sticky(c, { high: 0.6, low: 0.55, nowDay: 1 }),
true,
"one day of decay is not a demotion",
);
assert.equal(sticky(c, { high: 0.6, low: 0.55, nowDay: 52 }), true);
assert.equal(
sticky(c, { high: 0.6, low: 0.55, nowDay: 60 }),
false,
"it still expires unreviewed",
);
const never = mkClaim([ev("confirm", 0, "behavioral")]); // val 0.535 — never reaches high
assert.equal(sticky(never, { high: 0.6, low: 0.55, nowDay: 0 }), false);
const refuted = mkClaim([
ev("confirm", 0, "cortex.episode"),
ev("contradict", 1, "human.revert"),
]);
assert.equal(
sticky(refuted, { high: 0.6, low: 0.55, nowDay: 1 }),
false,
"a contradiction demotes",
);
});