@seanhogg/builderforce-memory 2026.10.62 → 2026.10.66

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 (177) hide show
  1. package/dist/knowledge/pack/frame.d.ts +12 -3
  2. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  3. package/dist/knowledge/pack/frame.js +18 -4
  4. package/dist/knowledge/pack/frame.js.map +1 -1
  5. package/dist/knowledge/pack/manifest.d.ts +11 -3
  6. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  7. package/dist/knowledge/pack/manifest.js +26 -12
  8. package/dist/knowledge/pack/manifest.js.map +1 -1
  9. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
  10. package/dist/knowledge/pack/sections/extr.js +16 -4
  11. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  12. package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
  13. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  14. package/dist/knowledge/pack/sections/extrLists.js +5 -6
  15. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  16. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  17. package/dist/knowledge/pack/sections/facts.js +3 -2
  18. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  19. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  20. package/dist/knowledge/pack/sections/rows.js +11 -2
  21. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  22. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  23. package/dist/knowledge/pack/strings.js +6 -1
  24. package/dist/knowledge/pack/strings.js.map +1 -1
  25. package/dist/knowledge/pack/varint.d.ts +14 -0
  26. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  27. package/dist/knowledge/pack/varint.js +32 -1
  28. package/dist/knowledge/pack/varint.js.map +1 -1
  29. package/dist/knowledge/review.d.ts +6 -6
  30. package/dist/knowledge/review.d.ts.map +1 -1
  31. package/dist/knowledge/review.js +56 -329
  32. package/dist/knowledge/review.js.map +1 -1
  33. package/dist/knowledge/reviewAnalyse.d.ts +17 -0
  34. package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
  35. package/dist/knowledge/reviewAnalyse.js +61 -0
  36. package/dist/knowledge/reviewAnalyse.js.map +1 -0
  37. package/dist/knowledge/reviewApply.d.ts +33 -0
  38. package/dist/knowledge/reviewApply.d.ts.map +1 -0
  39. package/dist/knowledge/reviewApply.js +121 -0
  40. package/dist/knowledge/reviewApply.js.map +1 -0
  41. package/dist/knowledge/reviewContext.d.ts +77 -0
  42. package/dist/knowledge/reviewContext.d.ts.map +1 -0
  43. package/dist/knowledge/reviewContext.js +111 -0
  44. package/dist/knowledge/reviewContext.js.map +1 -0
  45. package/dist/knowledge/reviewFinish.d.ts +9 -0
  46. package/dist/knowledge/reviewFinish.d.ts.map +1 -0
  47. package/dist/knowledge/reviewFinish.js +62 -0
  48. package/dist/knowledge/reviewFinish.js.map +1 -0
  49. package/dist/knowledge/reviewRunModel.d.ts +3 -0
  50. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  51. package/dist/knowledge/reviewRunModel.js.map +1 -1
  52. package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
  53. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
  54. package/dist/knowledge/stores/extractLogWriter.js +38 -13
  55. package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
  56. package/dist/knowledge/stores/extractRefs.d.ts +68 -0
  57. package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
  58. package/dist/knowledge/stores/extractRefs.js +168 -0
  59. package/dist/knowledge/stores/extractRefs.js.map +1 -0
  60. package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
  61. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  62. package/dist/knowledge/stores/localSnapshotStore.js +25 -5
  63. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  64. package/dist/knowledge/stores/rowDelta.d.ts +6 -0
  65. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
  66. package/dist/knowledge/stores/rowDelta.js.map +1 -1
  67. package/dist/knowledge/stores/rowMemory.d.ts +30 -0
  68. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
  69. package/dist/knowledge/stores/rowMemory.js +46 -1
  70. package/dist/knowledge/stores/rowMemory.js.map +1 -1
  71. package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
  72. package/dist/knowledge/stores/rowSync.js +2 -1
  73. package/dist/knowledge/stores/rowSync.js.map +1 -1
  74. package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
  75. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  76. package/dist/knowledge/stores/snapshotFormat.js +22 -9
  77. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  78. package/dist/stats/distributions.d.ts +34 -0
  79. package/dist/stats/distributions.d.ts.map +1 -0
  80. package/dist/stats/distributions.js +180 -0
  81. package/dist/stats/distributions.js.map +1 -0
  82. package/dist/stats/estimators.d.ts +53 -0
  83. package/dist/stats/estimators.d.ts.map +1 -0
  84. package/dist/stats/estimators.js +79 -0
  85. package/dist/stats/estimators.js.map +1 -0
  86. package/dist/stats/fitting.d.ts +48 -0
  87. package/dist/stats/fitting.d.ts.map +1 -0
  88. package/dist/stats/fitting.js +209 -0
  89. package/dist/stats/fitting.js.map +1 -0
  90. package/dist/stats/index.d.ts +26 -0
  91. package/dist/stats/index.d.ts.map +1 -0
  92. package/dist/stats/index.js +18 -0
  93. package/dist/stats/index.js.map +1 -0
  94. package/dist/stats/information.d.ts +9 -0
  95. package/dist/stats/information.d.ts.map +1 -0
  96. package/dist/stats/information.js +21 -0
  97. package/dist/stats/information.js.map +1 -0
  98. package/dist/stats/multivariate.d.ts +25 -0
  99. package/dist/stats/multivariate.d.ts.map +1 -0
  100. package/dist/stats/multivariate.js +89 -0
  101. package/dist/stats/multivariate.js.map +1 -0
  102. package/dist/stats/policies.d.ts +19 -0
  103. package/dist/stats/policies.d.ts.map +1 -0
  104. package/dist/stats/policies.js +75 -0
  105. package/dist/stats/policies.js.map +1 -0
  106. package/dist/stats/prng.d.ts +11 -0
  107. package/dist/stats/prng.d.ts.map +1 -0
  108. package/dist/stats/prng.js +41 -0
  109. package/dist/stats/prng.js.map +1 -0
  110. package/dist/stats/scores.d.ts +33 -0
  111. package/dist/stats/scores.d.ts.map +1 -0
  112. package/dist/stats/scores.js +134 -0
  113. package/dist/stats/scores.js.map +1 -0
  114. package/dist/stats/tests.d.ts +48 -0
  115. package/dist/stats/tests.d.ts.map +1 -0
  116. package/dist/stats/tests.js +143 -0
  117. package/dist/stats/tests.js.map +1 -0
  118. package/dist/stats/timeSeries.d.ts +34 -0
  119. package/dist/stats/timeSeries.d.ts.map +1 -0
  120. package/dist/stats/timeSeries.js +71 -0
  121. package/dist/stats/timeSeries.js.map +1 -0
  122. package/dist/working/fold.d.ts +65 -0
  123. package/dist/working/fold.d.ts.map +1 -0
  124. package/dist/working/fold.js +228 -0
  125. package/dist/working/fold.js.map +1 -0
  126. package/dist/working/index.d.ts +3 -0
  127. package/dist/working/index.d.ts.map +1 -1
  128. package/dist/working/index.js +2 -0
  129. package/dist/working/index.js.map +1 -1
  130. package/dist/working/textSummary.d.ts +46 -0
  131. package/dist/working/textSummary.d.ts.map +1 -0
  132. package/dist/working/textSummary.js +142 -0
  133. package/dist/working/textSummary.js.map +1 -0
  134. package/package.json +5 -1
  135. package/src/contract/exports.snapshot.json +48 -1
  136. package/src/contract/regression.extractEviction.test.ts +162 -0
  137. package/src/contract/regression.fixCommits.test.ts +112 -0
  138. package/src/contract/regression.packWire.test.ts +174 -0
  139. package/src/contract/types.contract.test.ts +2 -1
  140. package/src/knowledge/pack/frame.ts +21 -5
  141. package/src/knowledge/pack/manifest.ts +26 -11
  142. package/src/knowledge/pack/sections/extr.ts +14 -4
  143. package/src/knowledge/pack/sections/extrLists.ts +4 -6
  144. package/src/knowledge/pack/sections/facts.ts +3 -2
  145. package/src/knowledge/pack/sections/rows.ts +11 -2
  146. package/src/knowledge/pack/strings.ts +5 -1
  147. package/src/knowledge/pack/varint.ts +33 -1
  148. package/src/knowledge/review.ts +58 -311
  149. package/src/knowledge/reviewAnalyse.ts +59 -0
  150. package/src/knowledge/reviewApply.ts +128 -0
  151. package/src/knowledge/reviewContext.ts +158 -0
  152. package/src/knowledge/reviewFinish.ts +63 -0
  153. package/src/knowledge/reviewRunModel.ts +3 -0
  154. package/src/knowledge/stores/extractLogWriter.ts +36 -12
  155. package/src/knowledge/stores/extractRefs.ts +161 -0
  156. package/src/knowledge/stores/localSnapshotStore.ts +22 -5
  157. package/src/knowledge/stores/rowDelta.ts +6 -0
  158. package/src/knowledge/stores/rowMemory.ts +50 -1
  159. package/src/knowledge/stores/rowSync.ts +2 -1
  160. package/src/knowledge/stores/snapshotFormat.ts +27 -10
  161. package/src/stats/distributions.ts +180 -0
  162. package/src/stats/estimators.ts +101 -0
  163. package/src/stats/fitting.ts +252 -0
  164. package/src/stats/index.ts +59 -0
  165. package/src/stats/information.ts +20 -0
  166. package/src/stats/multivariate.ts +93 -0
  167. package/src/stats/policies.ts +84 -0
  168. package/src/stats/prng.ts +45 -0
  169. package/src/stats/scores.ts +135 -0
  170. package/src/stats/stats.test.ts +294 -0
  171. package/src/stats/tests.ts +164 -0
  172. package/src/stats/timeSeries.ts +92 -0
  173. package/src/working/fold.test.ts +196 -0
  174. package/src/working/fold.ts +252 -0
  175. package/src/working/index.ts +13 -0
  176. package/src/working/textSummary.test.ts +113 -0
  177. package/src/working/textSummary.ts +156 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Advisory folds of the working transcript (PRD 45 §4.7 B6/B7) — pure post-processing
3
+ * over the messages {@link buildWorkingTranscript} returns, before a host sends them to
4
+ * the model. The folds are COMPRESSION ONLY: the run's own transcript (`state.transcript`)
5
+ * and its trace keep every message at full fidelity; only what the MODEL sees is folded.
6
+ *
7
+ * B6 — fold superseded reads: when an edit/write to path P succeeds at step N, every
8
+ * earlier `read_file` result for P in the model transcript becomes a one-line marker.
9
+ * The stale content leaves the model's window (the edit changed those bytes — anything
10
+ * the model still needs it re-reads), and stays in the trace at full fidelity.
11
+ *
12
+ * B7 — fold repeated narration: assistant text PRECEDING tool calls whose word-set
13
+ * overlaps the previous such text by ≥ {@link NARRATION_OVERLAP} becomes
14
+ * `"(progress note)"`. A final answer and a turn without tool calls are NEVER folded —
15
+ * those carry the run's actual output.
16
+ *
17
+ * A "step" is the index of the assistant message carrying the tool call, in the message
18
+ * list the fold runs over (the model transcript, system prompt included).
19
+ *
20
+ * Pure: no `node:*`, no I/O — runs wherever the `./working` subpath runs.
21
+ */
22
+
23
+ import type { TranscriptMessage } from './transcript.js';
24
+
25
+ /** B7's fold threshold: |intersection| / |union| of the two texts' word sets (Jaccard). */
26
+ export const NARRATION_OVERLAP = 0.8;
27
+
28
+ /** B6's replacement for a read result whose file a later successful edit superseded. */
29
+ export function supersededReadMarker(path: string, step: number): string {
30
+ return `(read of ${path} superseded by the edit at step ${step} — re-read if needed)`;
31
+ }
32
+
33
+ /** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
34
+ export const PROGRESS_NOTE = '(progress note)';
35
+
36
+ interface NamedToolCall {
37
+ id?: unknown;
38
+ function?: { name?: unknown; arguments?: unknown };
39
+ }
40
+
41
+ interface ToolResult {
42
+ ok?: unknown;
43
+ error?: unknown;
44
+ }
45
+
46
+ function callsOf(m: TranscriptMessage): NamedToolCall[] {
47
+ return Array.isArray(m.tool_calls) ? (m.tool_calls as NamedToolCall[]) : [];
48
+ }
49
+
50
+ function nameOf(call: NamedToolCall): string | null {
51
+ const name = call.function?.name;
52
+ return typeof name === 'string' && name.length > 0 ? name : null;
53
+ }
54
+
55
+ /** The `path` argument of a tool call — from the object form or parsed out of a JSON string. */
56
+ function pathOf(call: NamedToolCall): string | null {
57
+ const raw = call.function?.arguments;
58
+ let parsed: unknown = raw;
59
+ if (typeof raw === 'string') {
60
+ try {
61
+ parsed = JSON.parse(raw);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ if (!parsed || typeof parsed !== 'object') return null;
67
+ const path = (parsed as { path?: unknown }).path;
68
+ return typeof path === 'string' && path.length > 0 ? path : null;
69
+ }
70
+
71
+ /** The tool result answering `call`: by `tool_call_id` when present, else positionally. */
72
+ function resultFor(convo: readonly TranscriptMessage[], call: NamedToolCall, callIndex: number): TranscriptMessage | undefined {
73
+ const id = typeof call.id === 'string' && call.id.length > 0 ? call.id : null;
74
+ if (id) {
75
+ const byId = convo.find((m) => m.role === 'tool' && m.tool_call_id === id);
76
+ if (byId) return byId;
77
+ }
78
+ // No ids (or an unmatched one): the nth tool result answers the nth call.
79
+ const results = convo.filter((m) => m.role === 'tool');
80
+ return results[callIndex];
81
+ }
82
+
83
+ /** Did the tool call SUCCEED? An explicit `{ok:false}` / `error` fails; anything else —
84
+ * including a textual error, which is still informative — passes. Absent result fails
85
+ * (a write nobody confirmed changed nothing). */
86
+ function succeeded(m: TranscriptMessage | undefined): boolean {
87
+ if (!m) return false;
88
+ const content: unknown = m.content;
89
+ if (typeof content === 'string') return content.trim().length > 0;
90
+ if (!content || typeof content !== 'object') return false;
91
+ const r = content as ToolResult;
92
+ if (typeof r.ok === 'boolean') return r.ok;
93
+ return r.error == null;
94
+ }
95
+
96
+ const EDIT_OR_WRITE = /^(edit|write)/i;
97
+ const READ = /^read/i;
98
+
99
+ function wordSet(text: string): Set<string> {
100
+ return new Set(
101
+ text
102
+ .toLowerCase()
103
+ .split(/[^a-z0-9_]+/)
104
+ .filter((w) => w.length > 0),
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Jaccard similarity of two texts' word sets (lower-cased `[a-z0-9_]` words): |A ∩ B| / |A ∪ B|, 0 when either has no word.
110
+ * The measure B7 folds repeated narration by (see {@link isRepeatedNarration}).
111
+ */
112
+ export function wordOverlap(a: string, b: string): number {
113
+ const sa = wordSet(a);
114
+ const sb = wordSet(b);
115
+ if (sa.size === 0 || sb.size === 0) return 0;
116
+ let intersection = 0;
117
+ for (const w of sa) if (sb.has(w)) intersection += 1;
118
+ return intersection / (sa.size + sb.size - intersection);
119
+ }
120
+
121
+ /** Containment: is every word of the smaller set present in the larger? True when one
122
+ * narration is the other plus a trailing qualifier ("…once more", "…again", "…now") —
123
+ * a repeat Jaccard under-counts because the union grows with the qualifier's words. */
124
+ export function wordContained(a: string, b: string): boolean {
125
+ const sa = wordSet(a);
126
+ const sb = wordSet(b);
127
+ if (sa.size === 0 || sb.size === 0) return false;
128
+ const [small, large] = sa.size <= sb.size ? [sa, sb] : [sb, sa];
129
+ for (const w of small) if (!large.has(w)) return false;
130
+ return true;
131
+ }
132
+
133
+ /**
134
+ * B7's detector: `text` merely repeats `previous` — their {@link wordOverlap} is at least `overlap`
135
+ * (default {@link NARRATION_OVERLAP}), or one's words are all in the other ({@link wordContained}).
136
+ */
137
+ export function isRepeatedNarration(text: string, previous: string, overlap = NARRATION_OVERLAP): boolean {
138
+ return wordOverlap(text, previous) >= overlap || wordContained(text, previous);
139
+ }
140
+
141
+ /** The narration an assistant turn carries before its tool calls — null when it carries
142
+ * none (an empty-content tool-call turn, or any turn without tool calls). */
143
+ function narrationOf(m: TranscriptMessage): string | null {
144
+ const content = m.content;
145
+ const text = typeof content === 'string' ? content : content == null ? '' : JSON.stringify(content);
146
+ const t = text.trim();
147
+ return callsOf(m).length > 0 && t.length > 0 ? t : null;
148
+ }
149
+
150
+ interface ReadRow {
151
+ /** The assistant step that issued the read. */
152
+ step: number;
153
+ path: string;
154
+ /** The message carrying the read's result — what the marker replaces. */
155
+ result: TranscriptMessage;
156
+ /** The read call itself — B7 skips a narration that narrated a now-folded read. */
157
+ call: NamedToolCall;
158
+ }
159
+
160
+ /** Tracks which read CALLS were superseded, so `foldWorkingTranscript`'s B7 pass can
161
+ * skip the narration that introduced a read whose content B6 just replaced. */
162
+ const SUPERSEDED_CALL = new WeakSet<object>();
163
+
164
+ /**
165
+ * B6 — fold reads a later successful edit/write superseded. Returns the input unchanged
166
+ * (same reference, no copy) when nothing is superseded; otherwise a new list whose
167
+ * replaced messages are shallow copies with only `content` changed. The caller's
168
+ * transcript is never touched.
169
+ */
170
+ export function foldSupersededReads<M extends TranscriptMessage>(msgs: readonly M[]): M[] {
171
+ interface Edit {
172
+ path: string;
173
+ step: number;
174
+ }
175
+ const edits: Edit[] = [];
176
+ const reads: ReadRow[] = [];
177
+ let callIndex = 0;
178
+ for (let i = 0; i < msgs.length; i++) {
179
+ const m = msgs[i]!;
180
+ for (const call of callsOf(m)) {
181
+ const name = nameOf(call);
182
+ if (!name) continue;
183
+ const path = pathOf(call);
184
+ const result = resultFor(msgs, call, callIndex);
185
+ if (path && EDIT_OR_WRITE.test(name)) {
186
+ if (succeeded(result)) edits.push({ path, step: i });
187
+ } else if (path && READ.test(name) && result) {
188
+ reads.push({ step: i, path, result, call });
189
+ }
190
+ callIndex += 1;
191
+ }
192
+ }
193
+ if (edits.length === 0 || reads.length === 0) return msgs as M[];
194
+ const superseded = new Map<TranscriptMessage, string>();
195
+ for (const read of reads) {
196
+ // The LATEST successful edit of the same path after the read wins — an earlier read
197
+ // re-made after an edit is not superseded by that edit.
198
+ let step = -1;
199
+ for (const e of edits) {
200
+ if (e.path === read.path && e.step > read.step && e.step > step) step = e.step;
201
+ }
202
+ if (step >= 0) {
203
+ superseded.set(read.result, supersededReadMarker(read.path, step));
204
+ SUPERSEDED_CALL.add(read.call);
205
+ }
206
+ }
207
+ if (superseded.size === 0) return msgs as M[];
208
+ return msgs.map((m) => {
209
+ const marker = superseded.get(m);
210
+ return marker == null ? m : ({ ...m, content: marker } as M);
211
+ });
212
+ }
213
+
214
+ /**
215
+ * B7 — fold a tool-call turn's narration when it merely repeats the previous one.
216
+ * Only assistant messages WITH tool calls are candidates: a final answer and a turn
217
+ * without tool calls are never folded. The FIRST narration is kept verbatim (it has no
218
+ * predecessor to repeat); each later one folds when its word-set overlap with the most
219
+ * recent kept narration is ≥ {@link NARRATION_OVERLAP}. Once folded, it does not become
220
+ * the comparison text — the model keeps the last thing actually said.
221
+ */
222
+ export function foldRepeatedNarration<M extends TranscriptMessage>(msgs: readonly M[], overlap = NARRATION_OVERLAP): M[] {
223
+ let lastKept: string | null = null;
224
+ let changed = false;
225
+ const out = msgs.map((m) => {
226
+ if (m.role !== 'assistant') return m;
227
+ const narration = narrationOf(m);
228
+ if (narration == null) return m; // no tool calls, or no narration: never folded
229
+ // A narration that introduced a read B6 folded is the model's only record of why it
230
+ // read — it never folds itself, but it IS what a later repeat is compared against.
231
+ if (callsOf(m).some((call) => SUPERSEDED_CALL.has(call))) {
232
+ lastKept = narration;
233
+ return m;
234
+ }
235
+ if (lastKept != null && isRepeatedNarration(narration, lastKept, overlap)) {
236
+ changed = true;
237
+ return { ...m, content: PROGRESS_NOTE } as M;
238
+ }
239
+ lastKept = narration;
240
+ return m;
241
+ });
242
+ return changed ? out : (msgs as M[]);
243
+ }
244
+
245
+ /**
246
+ * Both folds, B6 then B7, over the working transcript a host is about to send to the
247
+ * model. Pure and advisory: `msgs` is not mutated, and the run's own transcript/trace
248
+ * keep every message at full fidelity.
249
+ */
250
+ export function foldWorkingTranscript<M extends TranscriptMessage>(msgs: readonly M[]): M[] {
251
+ return foldRepeatedNarration(foldSupersededReads(msgs));
252
+ }
@@ -54,6 +54,19 @@ export {
54
54
  buildWorkingTranscript,
55
55
  } from './transcript.js';
56
56
  export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
57
+ export {
58
+ NARRATION_OVERLAP,
59
+ PROGRESS_NOTE,
60
+ supersededReadMarker,
61
+ foldSupersededReads,
62
+ foldRepeatedNarration,
63
+ foldWorkingTranscript,
64
+ wordOverlap,
65
+ wordContained,
66
+ isRepeatedNarration,
67
+ } from './fold.js';
68
+ export { DEFAULT_MAX_MERGE_DEPTH, chunkText, chunkedTextSummary } from './textSummary.js';
69
+ export type { ChunkedTextSummaryOptions } from './textSummary.js';
57
70
  export { TRANSCRIPT_SUMMARY_PROMPT, TRANSCRIPT_SUMMARY_MAX_TOKENS, TRANSCRIPT_SUMMARY_INPUT_TOKENS, renderForSummary, summaryChunks, summarizeTranscript } from './summary.js';
58
71
  export type { SummaryCompletion } from './summary.js';
59
72
  export {
@@ -0,0 +1,113 @@
1
+ /**
2
+ * src/working/textSummary.test.ts — chunkText / chunkedTextSummary, the text-level summarizer brain-embedded's on-device
3
+ * `chunkedSummary` binds to. The cases are that module's own (its reference tests), run against this port with its constants
4
+ * (an 80% chunk share, at most 8 leaf chunks), plus the surrogate-pair rule and the B7 detector export.
5
+ */
6
+
7
+ import { jest } from '@jest/globals';
8
+ import { chunkedTextSummary, chunkText, isRepeatedNarration, wordContained, wordOverlap, type ChunkedTextSummaryOptions } from './index.js';
9
+
10
+ const MAX_CHUNKS = 8;
11
+ /** 1 char = 1 token, a 100-token window: chunks must stay under 80. */
12
+ const base = { limit: 100, measure: async (t: string) => t.length, maxChunks: MAX_CHUNKS, budgetShare: 0.8 };
13
+ const paragraphs = (n: number, size = 20) => Array.from({ length: n }, (_, i) => `${i}`.padEnd(size, 'x')).join('\n\n');
14
+ const summarize = (o: Partial<ChunkedTextSummaryOptions> & Pick<ChunkedTextSummaryOptions, 'text' | 'summarizeChunk'>) => chunkedTextSummary({ ...base, ...o });
15
+
16
+ describe('chunkedTextSummary', () => {
17
+ it('summarizes an in-window text in one call', async () => {
18
+ const summarizeChunk = jest.fn(async (_c: string) => 'S');
19
+ expect(await summarize({ text: 'short', summarizeChunk })).toBe('S');
20
+ expect(summarizeChunk).toHaveBeenCalledTimes(1);
21
+ });
22
+
23
+ it('splits a 5x-window text on paragraph boundaries, then merges', async () => {
24
+ const seen: string[] = [];
25
+ const text = paragraphs(20, 22);
26
+ expect(await summarize({ text, summarizeChunk: async (c) => { seen.push(c); return 'sum'; } })).toBe('sum');
27
+ const leaves = seen.filter((c) => /^\d/.test(c));
28
+ expect(leaves.length).toBeGreaterThan(1);
29
+ for (const chunk of seen) expect(chunk.length).toBeLessThanOrEqual(80);
30
+ expect(leaves.every((c) => c.split('\n\n').every((p) => p.trim().length === 22 || p.trim() === ''))).toBe(true);
31
+ });
32
+
33
+ it('recurses while the merged summaries are still over budget', async () => {
34
+ const out = await summarize({ text: paragraphs(20, 22), summarizeChunk: async (c) => c.slice(0, Math.ceil(c.length / 2)) });
35
+ expect(out).not.toBeNull();
36
+ expect(out!.length).toBeLessThanOrEqual(80);
37
+ });
38
+
39
+ it('returns null past maxChunks leaf chunks without summarizing any', async () => {
40
+ const summarizeChunk = jest.fn(async (_c: string) => 'S');
41
+ expect(await summarize({ text: paragraphs(MAX_CHUNKS * 4 + 4, 40), summarizeChunk })).toBeNull();
42
+ expect(summarizeChunk).not.toHaveBeenCalled();
43
+ });
44
+
45
+ it('is null when a chunk is declined', async () => {
46
+ expect(await summarize({ text: paragraphs(6, 40), summarizeChunk: async () => null })).toBeNull();
47
+ });
48
+
49
+ it('is null when a merge does not shrink the text', async () => {
50
+ expect(await summarize({ text: paragraphs(6, 40), summarizeChunk: async (c) => c })).toBeNull();
51
+ });
52
+
53
+ it('is null past maxMergeDepth', async () => {
54
+ expect(await summarize({ text: paragraphs(20, 22), maxMergeDepth: 0, summarizeChunk: async () => 'S' })).toBeNull();
55
+ });
56
+
57
+ it('terminates on a paragraph longer than the window followed by a short one, preserving content', async () => {
58
+ const seen: string[] = [];
59
+ const text = `${'a'.repeat(300)}\n\nshort`;
60
+ expect(await summarize({ text, summarizeChunk: async (c) => { seen.push(c); return 'S'; } })).toBe('S');
61
+ const leaves = seen.slice(0, -1);
62
+ expect(leaves.length).toBeGreaterThan(1);
63
+ for (const c of leaves) expect(c.length).toBeLessThanOrEqual(80);
64
+ expect(leaves.join('')).toBe(text);
65
+ });
66
+
67
+ it('reserves output tokens out of the window', async () => {
68
+ const seen: string[] = [];
69
+ await summarize({ text: paragraphs(10, 22), reserveTokens: 50, summarizeChunk: async (c) => { seen.push(c); return 's'; } });
70
+ for (const c of seen.filter((c) => /^\d/.test(c))) expect(c.length).toBeLessThanOrEqual(40);
71
+ });
72
+
73
+ it('re-measures a chunk and splits again when the estimate under-cut', async () => {
74
+ const seen: string[] = [];
75
+ const measure = async (t: string) => (t.includes('9') ? t.length * 2 : t.length);
76
+ await summarize({ text: paragraphs(12, 22), measure, summarizeChunk: async (c) => { seen.push(c); return 's'; } });
77
+ for (const c of seen.filter((c) => /^\d/.test(c))) expect(await measure(c)).toBeLessThanOrEqual(80);
78
+ });
79
+
80
+ it('throws only AbortError', async () => {
81
+ const controller = new AbortController();
82
+ controller.abort();
83
+ await expect(summarize({ text: 'x', summarizeChunk: async () => 'S', signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError' });
84
+ });
85
+ });
86
+
87
+ describe('chunkText', () => {
88
+ it('cuts on paragraphs, then lines, then hard; joined, the chunks are the text', () => {
89
+ const text = `${'p'.repeat(5)}\n\n${'l'.repeat(4)}\n${'m'.repeat(4)}\n\n${'h'.repeat(12)}`;
90
+ const chunks = chunkText(text, 8);
91
+ for (const c of chunks) expect(c.length).toBeLessThanOrEqual(8);
92
+ expect(chunks.join('')).toBe(text);
93
+ });
94
+
95
+ it('regression: a hard cut never splits a surrogate pair', () => {
96
+ const text = '😀'.repeat(9); // 18 code units
97
+ for (const max of [1, 2, 3, 5, 7]) {
98
+ const chunks = chunkText(text, max);
99
+ expect(chunks.join('')).toBe(text);
100
+ for (const c of chunks) expect(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/.test(c)).toBe(false);
101
+ }
102
+ });
103
+ });
104
+
105
+ describe('B7 narration detector exports', () => {
106
+ it('regression: wordOverlap / wordContained / isRepeatedNarration are the detector foldRepeatedNarration uses', () => {
107
+ expect(wordOverlap('read the file', 'read the file')).toBe(1);
108
+ expect(wordOverlap('', 'x')).toBe(0);
109
+ expect(wordContained('read the file again', 'read the file')).toBe(true);
110
+ expect(isRepeatedNarration('Now I will read the file.', 'Now I will read the file again.')).toBe(true);
111
+ expect(isRepeatedNarration('Now edit the parser.', 'Read the docs first.')).toBe(false);
112
+ });
113
+ });
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Chunked text summaries — the TEXT-level primitive beside the message-level {@link summaryChunks} /
3
+ * {@link summarizeTranscript} (summary.ts): a small window (an on-device model) takes a long text.
4
+ *
5
+ * 1. the text fits the chunk limit → ONE `summarizeChunk(text)` call;
6
+ * 2. otherwise split on paragraph, then line boundaries (then a hard cut) into chunks under the limit,
7
+ * re-measured with the caller's own `measure` and split again when the char estimate under-cut;
8
+ * 3. summarize each chunk; any chunk declined (`null`) → `null`;
9
+ * 4. summarize the joined summaries, recursing while still over the limit, up to `maxMergeDepth`;
10
+ * 5. past `maxChunks` leaf chunks, past the depth, or a merge that did not shrink the text → `null`
11
+ * (the caller's existing path takes it).
12
+ *
13
+ * Pure over an injected `measure` and an injected one-chunk summarizer: it knows no model API. An aborted
14
+ * `signal` rejects with an `AbortError` (and only an abort throws). Ported from brain-embedded's
15
+ * `onDevice/chunkedSummary.ts`, behaviour for behaviour; the one change is that a hard cut never splits a
16
+ * UTF-16 surrogate pair.
17
+ */
18
+
19
+ /** Separators from the coarsest boundary to the finest; past the last, a hard cut. */
20
+ const SEPARATORS = ['\n\n', '\n'] as const;
21
+ /** Bounds the re-measure/re-split of a chunk the first estimate under-cut. */
22
+ const MAX_REFIT_ATTEMPTS = 3;
23
+ /** Merging summaries must shrink the text; this bounds a pathological recursion. */
24
+ export const DEFAULT_MAX_MERGE_DEPTH = 3;
25
+
26
+ export interface ChunkedTextSummaryOptions {
27
+ text: string;
28
+ /** The window, in the units `measure` counts (tokens). */
29
+ limit: number;
30
+ /** The size of `text` in the window's units. */
31
+ measure(text: string, signal?: AbortSignal): number | Promise<number>;
32
+ /** Summarizes one in-window piece; `null` = declined (the whole summary is then `null`). */
33
+ summarizeChunk(chunk: string, signal?: AbortSignal): Promise<string | null>;
34
+ /** More leaf chunks than this → `null` without summarizing any. */
35
+ maxChunks: number;
36
+ /** Merge rounds before giving up (default {@link DEFAULT_MAX_MERGE_DEPTH}). */
37
+ maxMergeDepth?: number;
38
+ /** Units each call spends outside the chunk (instruction + expected reply); never more than half the window. Default 0. */
39
+ reserveTokens?: number;
40
+ /** Share of the remaining window a chunk may fill (default 1; an on-device host uses 0.8 for headroom). */
41
+ budgetShare?: number;
42
+ signal?: AbortSignal;
43
+ }
44
+
45
+ function abortError(): Error {
46
+ const e = new Error('Aborted');
47
+ e.name = 'AbortError';
48
+ return e;
49
+ }
50
+
51
+ function throwIfAborted(signal?: AbortSignal): void {
52
+ if (signal?.aborted) throw abortError();
53
+ }
54
+
55
+ /** A hard cut of `text` into slices of at most `maxChars`, never between the halves of a surrogate pair. */
56
+ function hardCut(text: string, maxChars: number): string[] {
57
+ const out: string[] = [];
58
+ let at = 0;
59
+ while (at < text.length) {
60
+ let end = Math.min(text.length, at + maxChars);
61
+ const last = text.charCodeAt(end - 1);
62
+ // A high surrogate at the cut belongs with the low one after it: cut before it (or keep the pair whole when it is the slice).
63
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff) end = end - 1 > at ? end - 1 : end + 1;
64
+ out.push(text.slice(at, end));
65
+ at = end;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /**
71
+ * Cut `text` into pieces of at most `maxChars`: paragraphs first, then lines, then a hard cut. A piece still
72
+ * over `maxChars` moves to the NEXT level only, so every recursion strictly descends and the split terminates;
73
+ * the separator stays on its piece, so joining the pieces gives back `text`.
74
+ */
75
+ function pieces(text: string, maxChars: number, level = 0): string[] {
76
+ if (text.length <= maxChars) return [text];
77
+ const separator = SEPARATORS[level];
78
+ if (separator === undefined) return hardCut(text, maxChars);
79
+ const parts = text.split(separator);
80
+ if (parts.length === 1) return pieces(text, maxChars, level + 1);
81
+ return parts.flatMap((p, i) => pieces(i < parts.length - 1 ? p + separator : p, maxChars, level + 1));
82
+ }
83
+
84
+ /**
85
+ * `text` as chunks of at most `maxChars` (a lone surrogate pair at `maxChars` 1 is the one exception): pieces cut on
86
+ * paragraph, then line, then hard boundaries, packed greedily. Joined, the chunks give back `text`, except that a
87
+ * trailing whitespace-only remainder is dropped.
88
+ */
89
+ export function chunkText(text: string, maxChars: number): string[] {
90
+ const max = Math.max(1, Math.floor(maxChars));
91
+ const chunks: string[] = [];
92
+ let current = '';
93
+ for (const piece of pieces(text, max)) {
94
+ if (current && current.length + piece.length > max) {
95
+ chunks.push(current);
96
+ current = '';
97
+ }
98
+ current += piece;
99
+ }
100
+ if (current.trim()) chunks.push(current);
101
+ return chunks;
102
+ }
103
+
104
+ /** Re-measure each chunk with the real measure; a chunk still over `limit` is split again (bounded). */
105
+ async function fitChunks(chunks: readonly string[], limit: number, o: ChunkedTextSummaryOptions): Promise<string[]> {
106
+ const out: string[] = [];
107
+ for (const chunk of chunks) {
108
+ let parts = [chunk];
109
+ for (let attempt = 0; attempt < MAX_REFIT_ATTEMPTS; attempt++) {
110
+ const next: string[] = [];
111
+ let over = false;
112
+ for (const part of parts) {
113
+ throwIfAborted(o.signal);
114
+ const tokens = await o.measure(part, o.signal);
115
+ if (tokens <= limit || part.length <= 1) { next.push(part); continue; }
116
+ over = true;
117
+ next.push(...chunkText(part, Math.max(1, Math.floor(((part.length / tokens) * limit) * 0.9))));
118
+ }
119
+ parts = next;
120
+ if (!over) break;
121
+ }
122
+ out.push(...parts);
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /** See the module comment. Resolves to the summary, or `null` when it cannot be made within the bounds. */
128
+ export async function chunkedTextSummary(o: ChunkedTextSummaryOptions): Promise<string | null> {
129
+ return summarizeAt(o, 0);
130
+ }
131
+
132
+ async function summarizeAt(o: ChunkedTextSummaryOptions, depth: number): Promise<string | null> {
133
+ const { text, signal } = o;
134
+ throwIfAborted(signal);
135
+ // The reserve never takes more than half the window, so a tiny window still holds a chunk.
136
+ const room = Math.max(Math.floor(o.limit / 2), o.limit - (o.reserveTokens ?? 0));
137
+ const limit = Math.max(1, Math.floor(room * (o.budgetShare ?? 1)));
138
+ const tokens = await o.measure(text, signal);
139
+ if (tokens <= limit) return o.summarizeChunk(text, signal);
140
+ if (depth >= (o.maxMergeDepth ?? DEFAULT_MAX_MERGE_DEPTH)) return null;
141
+
142
+ const chunks = await fitChunks(chunkText(text, Math.max(1, Math.floor((text.length / tokens) * limit))), limit, o);
143
+ if (chunks.length > o.maxChunks) return null;
144
+
145
+ const summaries: string[] = [];
146
+ for (const chunk of chunks) {
147
+ throwIfAborted(signal);
148
+ const summary = await o.summarizeChunk(chunk, signal);
149
+ if (summary === null) return null;
150
+ summaries.push(summary);
151
+ }
152
+ const merged = summaries.join('\n\n');
153
+ // A merge that did not shrink the text will not converge.
154
+ if (merged.length >= text.length) return null;
155
+ return summarizeAt({ ...o, text: merged }, depth + 1);
156
+ }