@seanhogg/builderforce-memory 2026.10.62 → 2026.10.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/stats/distributions.d.ts +34 -0
  2. package/dist/stats/distributions.d.ts.map +1 -0
  3. package/dist/stats/distributions.js +180 -0
  4. package/dist/stats/distributions.js.map +1 -0
  5. package/dist/stats/estimators.d.ts +53 -0
  6. package/dist/stats/estimators.d.ts.map +1 -0
  7. package/dist/stats/estimators.js +79 -0
  8. package/dist/stats/estimators.js.map +1 -0
  9. package/dist/stats/fitting.d.ts +48 -0
  10. package/dist/stats/fitting.d.ts.map +1 -0
  11. package/dist/stats/fitting.js +209 -0
  12. package/dist/stats/fitting.js.map +1 -0
  13. package/dist/stats/index.d.ts +26 -0
  14. package/dist/stats/index.d.ts.map +1 -0
  15. package/dist/stats/index.js +18 -0
  16. package/dist/stats/index.js.map +1 -0
  17. package/dist/stats/information.d.ts +9 -0
  18. package/dist/stats/information.d.ts.map +1 -0
  19. package/dist/stats/information.js +21 -0
  20. package/dist/stats/information.js.map +1 -0
  21. package/dist/stats/multivariate.d.ts +25 -0
  22. package/dist/stats/multivariate.d.ts.map +1 -0
  23. package/dist/stats/multivariate.js +89 -0
  24. package/dist/stats/multivariate.js.map +1 -0
  25. package/dist/stats/policies.d.ts +19 -0
  26. package/dist/stats/policies.d.ts.map +1 -0
  27. package/dist/stats/policies.js +75 -0
  28. package/dist/stats/policies.js.map +1 -0
  29. package/dist/stats/prng.d.ts +11 -0
  30. package/dist/stats/prng.d.ts.map +1 -0
  31. package/dist/stats/prng.js +41 -0
  32. package/dist/stats/prng.js.map +1 -0
  33. package/dist/stats/scores.d.ts +33 -0
  34. package/dist/stats/scores.d.ts.map +1 -0
  35. package/dist/stats/scores.js +134 -0
  36. package/dist/stats/scores.js.map +1 -0
  37. package/dist/stats/tests.d.ts +48 -0
  38. package/dist/stats/tests.d.ts.map +1 -0
  39. package/dist/stats/tests.js +143 -0
  40. package/dist/stats/tests.js.map +1 -0
  41. package/dist/stats/timeSeries.d.ts +34 -0
  42. package/dist/stats/timeSeries.d.ts.map +1 -0
  43. package/dist/stats/timeSeries.js +71 -0
  44. package/dist/stats/timeSeries.js.map +1 -0
  45. package/dist/working/fold.d.ts +51 -0
  46. package/dist/working/fold.d.ts.map +1 -0
  47. package/dist/working/fold.js +218 -0
  48. package/dist/working/fold.js.map +1 -0
  49. package/dist/working/index.d.ts +1 -0
  50. package/dist/working/index.d.ts.map +1 -1
  51. package/dist/working/index.js +1 -0
  52. package/dist/working/index.js.map +1 -1
  53. package/package.json +5 -1
  54. package/src/contract/exports.snapshot.json +41 -0
  55. package/src/stats/distributions.ts +180 -0
  56. package/src/stats/estimators.ts +101 -0
  57. package/src/stats/fitting.ts +252 -0
  58. package/src/stats/index.ts +59 -0
  59. package/src/stats/information.ts +20 -0
  60. package/src/stats/multivariate.ts +93 -0
  61. package/src/stats/policies.ts +84 -0
  62. package/src/stats/prng.ts +45 -0
  63. package/src/stats/scores.ts +135 -0
  64. package/src/stats/stats.test.ts +294 -0
  65. package/src/stats/tests.ts +164 -0
  66. package/src/stats/timeSeries.ts +92 -0
  67. package/src/working/fold.test.ts +196 -0
  68. package/src/working/fold.ts +241 -0
  69. package/src/working/index.ts +1 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Statistical tests for the stats module (PRD 41 Part D / D13): Wilcoxon signed-rank
3
+ * with the paired Hodges–Lehmann estimator, a seeded paired bootstrap CI, and the
4
+ * sign-test SPRT. All deterministic under their seeds.
5
+ */
6
+
7
+ import { createRng, type Rng } from "./prng.js";
8
+
9
+ const WILCOXON_P: number[] = (() => {
10
+ // Exact null distribution of W+ for n <= 60 via DP over subset sums.
11
+ const n = 60;
12
+ const total = (n * (n + 1)) / 2;
13
+ const dp: number[] = new Array(total + 1).fill(0);
14
+ dp[0] = 1;
15
+ for (let rank = 1; rank <= n; rank++) {
16
+ for (let s = total; s >= rank; s--) dp[s] = (dp[s] ?? 0) + (dp[s - rank] ?? 0);
17
+ }
18
+ const cum: number[] = new Array(total + 1).fill(0);
19
+ let running = 0;
20
+ for (let s = 0; s <= total; s++) {
21
+ running += dp[s]!;
22
+ cum[s] = running / 2 ** n;
23
+ }
24
+ return cum;
25
+ })();
26
+
27
+ function wilcoxonPValue(wPlus: number, n: number): number {
28
+ if (n > 60) {
29
+ // Normal approximation with continuity correction.
30
+ const mean = (n * (n + 1)) / 4;
31
+ const sd = Math.sqrt((n * (n + 1) * (2 * n + 1)) / 24);
32
+ const z = (wPlus - mean + 0.5) / sd;
33
+ return Math.min(1, Math.exp(-0.5 * z * z) * 0.5 * 2); // two-sided via |z|
34
+ }
35
+ const total = (n * (n + 1)) / 2;
36
+ const lo = Math.max(0, Math.floor(wPlus));
37
+ const hi = Math.min(total, Math.ceil(wPlus));
38
+ const pLo = WILCOXON_P[lo] ?? 0;
39
+ const pHi = 1 - (WILCOXON_P[hi - 1] ?? 0);
40
+ return Math.min(1, 2 * Math.min(pLo, pHi));
41
+ }
42
+
43
+ export interface WilcoxonResult {
44
+ n: number;
45
+ wPlus: number;
46
+ pValue: number;
47
+ /** Paired Hodges–Lehmann estimator: median of pairwise averages (after > 0 filter). */
48
+ hodgesLehmann: number;
49
+ }
50
+
51
+ /**
52
+ * Wilcoxon signed-rank test on the nonzero paired differences of `before` and
53
+ * `after`, plus the paired Hodges–Lehmann location estimator.
54
+ */
55
+ export function wilcoxonSignedRank(before: readonly number[], after: readonly number[]): WilcoxonResult {
56
+ const diffs: number[] = [];
57
+ const n0 = Math.min(before.length, after.length);
58
+ for (let i = 0; i < n0; i++) {
59
+ const d = after[i]! - before[i]!;
60
+ if (d !== 0) diffs.push(d);
61
+ }
62
+ const n = diffs.length;
63
+ if (n === 0) return { n: 0, wPlus: 0, pValue: 1, hodgesLehmann: 0 };
64
+ const abs = diffs.map((d) => Math.abs(d));
65
+ const order = abs.map((_, i) => i).sort((p, q) => abs[p]! - abs[q]!);
66
+ const ranks = new Array<number>(n).fill(0);
67
+ let i = 0;
68
+ while (i < n) {
69
+ let j = i;
70
+ while (j + 1 < n && abs[order[j + 1]!] === abs[order[i]!]) j++;
71
+ const avg = (i + j) / 2 + 1;
72
+ for (let k = i; k <= j; k++) ranks[order[k]!] = avg;
73
+ i = j + 1;
74
+ }
75
+ let wPlus = 0;
76
+ for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!;
77
+ // Hodges–Lehmann: median of Walsh averages over positive-magnitude pairs.
78
+ const walsh: number[] = [];
79
+ for (let p = 0; p < n; p++) {
80
+ for (let q = p; q < n; q++) walsh.push((diffs[p]! + diffs[q]!) / 2);
81
+ }
82
+ walsh.sort((a, b) => a - b);
83
+ const hl =
84
+ walsh.length % 2 === 1
85
+ ? walsh[(walsh.length - 1) / 2]!
86
+ : (walsh[walsh.length / 2 - 1]! + walsh[walsh.length / 2]!) / 2;
87
+ return { n, wPlus, pValue: wilcoxonPValue(wPlus, n), hodgesLehmann: hl };
88
+ }
89
+
90
+ /**
91
+ * Paired bootstrap confidence interval for the mean difference `after − before`,
92
+ * resampling PAIRS so the pairing is preserved. Deterministic under `seed`.
93
+ */
94
+ export function pairedBootstrapCi(
95
+ before: readonly number[],
96
+ after: readonly number[],
97
+ options: { iterations?: number; confidence?: number; seed?: number } = {},
98
+ ): { low: number; high: number; estimate: number } {
99
+ const iterations = options.iterations ?? 2000;
100
+ const confidence = options.confidence ?? 0.95;
101
+ const rng: Rng = createRng(options.seed ?? 1);
102
+ const n = Math.min(before.length, after.length);
103
+ const diffs: number[] = [];
104
+ for (let i = 0; i < n; i++) diffs.push(after[i]! - before[i]!);
105
+ const estimate = diffs.reduce((a, b) => a + b, 0) / Math.max(diffs.length, 1);
106
+ if (n === 0) return { low: 0, high: 0, estimate: 0 };
107
+ const means: number[] = [];
108
+ for (let b = 0; b < iterations; b++) {
109
+ let s = 0;
110
+ for (let i = 0; i < n; i++) s += diffs[Math.floor(rng() * n)]!;
111
+ means.push(s / n);
112
+ }
113
+ means.sort((a, b) => a - b);
114
+ const alpha = 1 - confidence;
115
+ return {
116
+ low: means[Math.floor((alpha / 2) * iterations)] ?? estimate,
117
+ high: means[Math.floor((1 - alpha / 2) * iterations) - 1] ?? estimate,
118
+ estimate,
119
+ };
120
+ }
121
+
122
+ export interface SprtResult {
123
+ decision: "reject-null" | "accept-null" | "continue";
124
+ likelihoodRatio: number;
125
+ observations: number;
126
+ }
127
+
128
+ /**
129
+ * Sequential probability ratio test on paired signs. H0: P(after > before) = p0,
130
+ * H1: = p1. Decides as soon as the likelihood ratio crosses a boundary, else reports
131
+ * `continue` at `maxObservations`. Deterministic — the observations are supplied.
132
+ */
133
+ export function signTestSprt(
134
+ pairs: ReadonlyArray<readonly [number, number]>,
135
+ options: {
136
+ p0?: number;
137
+ p1?: number;
138
+ alpha?: number;
139
+ beta?: number;
140
+ alternative?: "greater" | "less";
141
+ } = {},
142
+ ): SprtResult {
143
+ const p0 = options.p0 ?? 0.5;
144
+ const p1 = options.p1 ?? 0.7;
145
+ const alpha = options.alpha ?? 0.05;
146
+ const beta = options.beta ?? 0.1;
147
+ const aBound = Math.log((1 - beta) / alpha);
148
+ const bBound = Math.log(beta / (1 - alpha));
149
+ let llr = 0;
150
+ let observations = 0;
151
+ for (const [beforeV, afterV] of pairs) {
152
+ const plus = afterV > beforeV;
153
+ const inc = Math.log((plus ? p1 : 1 - p1) / (plus ? p0 : 1 - p0));
154
+ const incAlt =
155
+ options.alternative === "less"
156
+ ? Math.log((plus ? 1 - p1 : p1) / (plus ? 1 - p0 : p0))
157
+ : inc;
158
+ llr += incAlt;
159
+ observations++;
160
+ if (llr >= aBound) return { decision: "reject-null", likelihoodRatio: llr, observations };
161
+ if (llr <= bBound) return { decision: "accept-null", likelihoodRatio: llr, observations };
162
+ }
163
+ return { decision: "continue", likelihoodRatio: llr, observations };
164
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Time-series change detection for the stats module (PRD 41 Part D / D13): CUSUM
3
+ * and Bayesian online change-point detection. Both are deterministic (fixed hazard,
4
+ * bounded run length); EWMA itself is reused from ml/classical, not copied here.
5
+ */
6
+
7
+ export interface CusumResult {
8
+ /** First index where |cumulative sum| exceeds `threshold`, or -1. */
9
+ alarmIndex: number;
10
+ cumulative: number[];
11
+ }
12
+
13
+ /** Cumulative-sum detector on standardized deviations from `target`. */
14
+ export function cusum(
15
+ values: readonly number[],
16
+ target: number,
17
+ options: { threshold?: number; sigma?: number; drift?: number } = {},
18
+ ): CusumResult {
19
+ const sigma = options.sigma ?? 1;
20
+ const h = options.threshold ?? 5;
21
+ const k = options.drift ?? 0.5;
22
+ const cumulative: number[] = [];
23
+ let cPlus = 0;
24
+ let cMinus = 0;
25
+ let alarmIndex = -1;
26
+ for (let i = 0; i < values.length; i++) {
27
+ const z = (values[i]! - target) / sigma;
28
+ cPlus = Math.max(0, cPlus + z - k);
29
+ cMinus = Math.min(0, cMinus + z + k);
30
+ cumulative.push(cPlus + cMinus);
31
+ if (alarmIndex === -1 && (cPlus > h || -cMinus > h)) alarmIndex = i;
32
+ }
33
+ return { alarmIndex, cumulative };
34
+ }
35
+
36
+ export interface ChangePointResult {
37
+ /** MAP run length at the last observation; -1 when the series is empty. */
38
+ currentRunLength: number;
39
+ /** Posterior probability of a change point at each index (run length 0 mass). */
40
+ changePointProbabilities: number[];
41
+ }
42
+
43
+ /**
44
+ * Bayesian online change-point detection (Adams & MacKay, 2007), Gaussian with
45
+ * unknown mean and known variance 1, conjugate N(0, 1) prior on the mean per run.
46
+ * Each run length carries its own sufficient statistics (sum of observations), so a
47
+ * level shift accumulates evidence for a young run. Run-length mass is truncated at
48
+ * `maxRunLength` and renormalized; identical inputs give identical outputs.
49
+ */
50
+ export function bayesianOnlineChangePoint(
51
+ values: readonly number[],
52
+ options: { hazard?: number; maxRunLength?: number } = {},
53
+ ): ChangePointResult {
54
+ const hazard = options.hazard ?? 1 / 250;
55
+ const maxRunLength = options.maxRunLength ?? 500;
56
+ let growth: number[] = [1];
57
+ let sums: number[] = [0]; // sums[r] = Σ of observations inside a run of length r
58
+ const changePointProbabilities: number[] = [];
59
+ let currentRunLength = -1;
60
+ for (let t = 0; t < values.length; t++) {
61
+ const x = values[t]!;
62
+ const predProbs = growth.map((g, r) => g * gaussianPredictive(x, sums[r]!, r));
63
+ const evidence = predProbs.reduce((a, b) => a + b, 0) || 1e-300;
64
+ const next = new Array<number>(maxRunLength).fill(0);
65
+ const nextSums = new Array<number>(maxRunLength).fill(0);
66
+ next[0] = hazard;
67
+ nextSums[0] = 0;
68
+ for (let r = 0; r < growth.length && r + 1 < maxRunLength; r++) {
69
+ next[r + 1] = ((1 - hazard) * predProbs[r]!) / evidence;
70
+ nextSums[r + 1] = sums[r]! + x;
71
+ }
72
+ growth = next;
73
+ sums = nextSums;
74
+ const norm = growth.reduce((a, b) => a + b, 0) || 1e-300;
75
+ growth = growth.map((g) => g / norm);
76
+ changePointProbabilities.push(growth[0]!);
77
+ currentRunLength = growth.indexOf(Math.max(...growth));
78
+ }
79
+ return { currentRunLength, changePointProbabilities };
80
+ }
81
+
82
+ /**
83
+ * Predictive N(x; sum/(r+1), 1 + 1/(r+1)) for a run of length r: the posterior mean
84
+ * of the run's mean under the N(0, 1) prior is sum/(r+1), and the posterior variance
85
+ * adds 1 to the observation variance 1.
86
+ */
87
+ function gaussianPredictive(x: number, sum: number, runLength: number): number {
88
+ const mean = sum / (runLength + 1);
89
+ const variance = 1 + 1 / (runLength + 1);
90
+ const z = (x - mean) / Math.sqrt(variance);
91
+ return Math.exp(-0.5 * z * z) / Math.sqrt(2 * Math.PI * variance);
92
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * src/working/fold.test.ts — PRD 45 §4.7 B6 and B7.
3
+ *
4
+ * B6: a read of path P followed by a successful edit/write of P at step N folds the
5
+ * earlier read result to "(read of P superseded by the edit at step N — re-read if
6
+ * needed)". The trace (the caller's transcript) keeps full fidelity.
7
+ *
8
+ * B7: assistant narration preceding tool calls whose word-set overlap with the previous
9
+ * such narration is ≥ 0.8 becomes "(progress note)". A final answer and a turn without
10
+ * tool calls are NEVER folded.
11
+ */
12
+
13
+ import {
14
+ foldRepeatedNarration,
15
+ foldSupersededReads,
16
+ foldWorkingTranscript,
17
+ NARRATION_OVERLAP,
18
+ PROGRESS_NOTE,
19
+ supersededReadMarker,
20
+ } from './fold.js';
21
+ import type { TranscriptMessage } from './transcript.js';
22
+
23
+ const readCall = (id: string, path: string) => ({
24
+ id,
25
+ function: { name: 'read_file', arguments: JSON.stringify({ path }) },
26
+ });
27
+ const editCall = (id: string, path: string) => ({
28
+ id,
29
+ function: { name: 'edit_file', arguments: JSON.stringify({ path, old_string: 'a', new_string: 'b' }) },
30
+ });
31
+
32
+ describe('B6 — fold superseded reads', () => {
33
+ it('regression: a read of P followed by an edit of P at step N folds the earlier read with the right step', () => {
34
+ const msgs: TranscriptMessage[] = [
35
+ { role: 'system', content: 'sys' },
36
+ { role: 'user', content: 'fix src/a.ts' },
37
+ { role: 'assistant', content: 'Reading the file first.', tool_calls: [readCall('r1', 'src/a.ts')] },
38
+ { role: 'tool', tool_call_id: 'r1', content: 'the whole file text' },
39
+ // step 4: the successful edit of the same path.
40
+ { role: 'assistant', content: 'Applying the fix.', tool_calls: [editCall('e1', 'src/a.ts')] },
41
+ { role: 'tool', tool_call_id: 'e1', content: JSON.stringify({ ok: true }) },
42
+ { role: 'assistant', content: 'Done.' },
43
+ ];
44
+ const out = foldSupersededReads(msgs);
45
+ expect(out[3]).toEqual({ role: 'tool', tool_call_id: 'r1', content: supersededReadMarker('src/a.ts', 4) });
46
+ expect(out[3]!.content).toBe('(read of src/a.ts superseded by the edit at step 4 — re-read if needed)');
47
+ // The successful edit's own result, and everything else, pass through untouched.
48
+ expect(out[5]).toBe(msgs[5]);
49
+ expect(out).toHaveLength(msgs.length);
50
+ // Full fidelity in the trace: the caller's transcript is NOT mutated.
51
+ expect(msgs[3]!.content).toBe('the whole file text');
52
+ });
53
+
54
+ it('regression: a read re-made after the edit is not superseded by that edit', () => {
55
+ const msgs: TranscriptMessage[] = [
56
+ { role: 'assistant', content: '', tool_calls: [readCall('r1', 'p.ts')] },
57
+ { role: 'tool', tool_call_id: 'r1', content: 'v1' },
58
+ { role: 'assistant', content: '', tool_calls: [editCall('e1', 'p.ts')] },
59
+ { role: 'tool', tool_call_id: 'e1', content: { ok: true } },
60
+ { role: 'assistant', content: '', tool_calls: [readCall('r2', 'p.ts')] },
61
+ { role: 'tool', tool_call_id: 'r2', content: 'v2 after edit' },
62
+ ];
63
+ const out = foldSupersededReads(msgs);
64
+ expect(out[1]!.content).toBe(supersededReadMarker('p.ts', 2));
65
+ expect(out[5]!.content).toBe('v2 after edit'); // read AFTER the edit: current, kept verbatim
66
+ });
67
+
68
+ it('a failed edit supersedes nothing', () => {
69
+ const msgs: TranscriptMessage[] = [
70
+ { role: 'assistant', content: '', tool_calls: [readCall('r1', 'p.ts')] },
71
+ { role: 'tool', tool_call_id: 'r1', content: 'text' },
72
+ { role: 'assistant', content: '', tool_calls: [editCall('e1', 'p.ts')] },
73
+ { role: 'tool', tool_call_id: 'e1', content: { ok: false, error: 'no match' } },
74
+ ];
75
+ const out = foldSupersededReads(msgs);
76
+ expect(out[1]).toBe(msgs[1]); // same reference: nothing folded
77
+ expect(out[1]!.content).toBe('text');
78
+ });
79
+
80
+ it('an edit of a different path supersedes nothing', () => {
81
+ const msgs: TranscriptMessage[] = [
82
+ { role: 'assistant', content: '', tool_calls: [readCall('r1', 'a.ts')] },
83
+ { role: 'tool', tool_call_id: 'r1', content: 'text of a' },
84
+ { role: 'assistant', content: '', tool_calls: [editCall('e1', 'b.ts')] },
85
+ { role: 'tool', tool_call_id: 'e1', content: { ok: true } },
86
+ ];
87
+ const out = foldSupersededReads(msgs);
88
+ expect(out[1]!.content).toBe('text of a');
89
+ });
90
+ });
91
+
92
+ describe('B7 — fold repeated narration', () => {
93
+ it('regression (chat #216): two assistant texts before tool calls with ≥0.8 word overlap → the later is a progress note', () => {
94
+ const msgs: TranscriptMessage[] = [
95
+ { role: 'user', content: 'wire the folds in' },
96
+ {
97
+ role: 'assistant',
98
+ content: 'Now reading the transcript builder to find where the fold should run.',
99
+ tool_calls: [readCall('r1', 'src/working/transcript.ts')],
100
+ },
101
+ { role: 'tool', tool_call_id: 'r1', content: 'export async function buildWorkingTranscript…' },
102
+ {
103
+ role: 'assistant',
104
+ content: 'Now reading the transcript builder again to find where the fold should run next.',
105
+ tool_calls: [readCall('r2', 'src/working/fold.ts')],
106
+ },
107
+ { role: 'tool', tool_call_id: 'r2', content: 'export function foldWorkingTranscript…' },
108
+ ];
109
+ const out = foldRepeatedNarration(msgs);
110
+ expect(out[1]).toBe(msgs[1]); // first narration is kept verbatim
111
+ expect(out[3]!.content).toBe(PROGRESS_NOTE);
112
+ expect(wordOverlapWouldFold(msgs[3]!.content as string, msgs[1]!.content as string)).toBe(true);
113
+ });
114
+
115
+ it('a final answer is NEVER folded', () => {
116
+ const msgs: TranscriptMessage[] = [
117
+ {
118
+ role: 'assistant',
119
+ content: 'Now reading the transcript builder to find where the fold should run.',
120
+ tool_calls: [readCall('r1', 'src/working/transcript.ts')],
121
+ },
122
+ { role: 'tool', tool_call_id: 'r1', content: 'text' },
123
+ // The FINAL answer: same words as the earlier narration, but no tool calls.
124
+ { role: 'assistant', content: 'Now reading the transcript builder to find where the fold should run.' },
125
+ ];
126
+ const out = foldRepeatedNarration(msgs);
127
+ expect(out[2]).toBe(msgs[2]);
128
+ expect(out[2]!.content).not.toBe(PROGRESS_NOTE);
129
+ });
130
+
131
+ it('a turn without tool calls is NEVER folded, even mid-run', () => {
132
+ const msgs: TranscriptMessage[] = [
133
+ {
134
+ role: 'assistant',
135
+ content: 'Reading the file to find where the fold should run in the builder.',
136
+ tool_calls: [readCall('r1', 'a.ts')],
137
+ },
138
+ { role: 'tool', tool_call_id: 'r1', content: 'text' },
139
+ { role: 'assistant', content: 'Reading the file to find where the fold should run in the builder.' }, // no tool_calls
140
+ ];
141
+ const out = foldRepeatedNarration(msgs);
142
+ expect(out[2]!.content).not.toBe(PROGRESS_NOTE);
143
+ });
144
+
145
+ it('narration below the 0.8 overlap threshold is kept', () => {
146
+ const msgs: TranscriptMessage[] = [
147
+ { role: 'assistant', content: 'Reading the auth middleware to see how tokens verify.', tool_calls: [readCall('r1', 'auth.ts')] },
148
+ { role: 'tool', tool_call_id: 'r1', content: 'text' },
149
+ { role: 'assistant', content: 'Editing the auth middleware so expired tokens refresh.', tool_calls: [editCall('e1', 'auth.ts')] },
150
+ ];
151
+ const out = foldRepeatedNarration(msgs);
152
+ expect(out[2]!.content).toBe('Editing the auth middleware so expired tokens refresh.');
153
+ });
154
+
155
+ it('a folded note does not become the comparison text', () => {
156
+ const msgs: TranscriptMessage[] = [
157
+ { role: 'assistant', content: 'Reading the builder to locate the fold hook now.', tool_calls: [readCall('r1', 'a.ts')] },
158
+ { role: 'tool', tool_call_id: 'r1', content: 'text' },
159
+ { role: 'assistant', content: 'Reading the builder to locate the fold hook now, again.', tool_calls: [readCall('r2', 'b.ts')] },
160
+ { role: 'tool', tool_call_id: 'r2', content: 'text' },
161
+ // Different words from the FIRST narration: must NOT fold just because it differs from the folded one.
162
+ { role: 'assistant', content: 'Searching the repo for other callers of the fold hook.', tool_calls: [readCall('r3', 'c.ts')] },
163
+ ];
164
+ const out = foldRepeatedNarration(msgs);
165
+ expect(out[2]!.content).toBe(PROGRESS_NOTE);
166
+ expect(out[4]!.content).toBe('Searching the repo for other callers of the fold hook.');
167
+ });
168
+ });
169
+
170
+ describe('foldWorkingTranscript — B6 then B7 together', () => {
171
+ it('applies both folds over the model transcript without mutating the input', () => {
172
+ const msgs: TranscriptMessage[] = [
173
+ { role: 'assistant', content: 'Reading the config to find the lever wiring.', tool_calls: [readCall('r1', 'cfg.ts')] },
174
+ { role: 'tool', tool_call_id: 'r1', content: 'lever config text' },
175
+ { role: 'assistant', content: 'Reading the config to find the lever wiring once more.', tool_calls: [editCall('e1', 'cfg.ts')] },
176
+ { role: 'tool', tool_call_id: 'e1', content: { ok: true } },
177
+ ];
178
+ const out = foldWorkingTranscript(msgs);
179
+ expect(out[1]!.content).toBe(supersededReadMarker('cfg.ts', 2));
180
+ expect(out[2]!.content).toBe(PROGRESS_NOTE);
181
+ expect(msgs[1]!.content).toBe('lever config text'); // trace intact
182
+ expect(msgs[2]!.content).toContain('once more');
183
+ });
184
+ });
185
+
186
+ /** Local re-derivation for the assertion above: the two narrations must actually meet the
187
+ * exported threshold (kept honest if NARRATION_OVERLAP ever changes). */
188
+ function wordOverlapWouldFold(a: string, b: string): boolean {
189
+ const words = (t: string) => new Set(t.toLowerCase().split(/[^a-z0-9_]+/).filter((w) => w.length > 0));
190
+ const sa = words(a);
191
+ const sb = words(b);
192
+ let intersection = 0;
193
+ for (const w of sa) if (sb.has(w)) intersection += 1;
194
+ const union = sa.size + sb.size - intersection;
195
+ return union > 0 && intersection / union >= NARRATION_OVERLAP;
196
+ }