@seanhogg/builderforce-memory 2026.10.63 → 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.
- package/dist/knowledge/pack/frame.d.ts +12 -3
- package/dist/knowledge/pack/frame.d.ts.map +1 -1
- package/dist/knowledge/pack/frame.js +18 -4
- package/dist/knowledge/pack/frame.js.map +1 -1
- package/dist/knowledge/pack/manifest.d.ts +11 -3
- package/dist/knowledge/pack/manifest.d.ts.map +1 -1
- package/dist/knowledge/pack/manifest.js +26 -12
- package/dist/knowledge/pack/manifest.js.map +1 -1
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extr.js +16 -4
- package/dist/knowledge/pack/sections/extr.js.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.js +5 -6
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/facts.js +3 -2
- package/dist/knowledge/pack/sections/facts.js.map +1 -1
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/rows.js +11 -2
- package/dist/knowledge/pack/sections/rows.js.map +1 -1
- package/dist/knowledge/pack/strings.d.ts.map +1 -1
- package/dist/knowledge/pack/strings.js +6 -1
- package/dist/knowledge/pack/strings.js.map +1 -1
- package/dist/knowledge/pack/varint.d.ts +14 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -1
- package/dist/knowledge/pack/varint.js +32 -1
- package/dist/knowledge/pack/varint.js.map +1 -1
- package/dist/knowledge/review.d.ts +6 -6
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +56 -329
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewAnalyse.d.ts +17 -0
- package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
- package/dist/knowledge/reviewAnalyse.js +61 -0
- package/dist/knowledge/reviewAnalyse.js.map +1 -0
- package/dist/knowledge/reviewApply.d.ts +33 -0
- package/dist/knowledge/reviewApply.d.ts.map +1 -0
- package/dist/knowledge/reviewApply.js +121 -0
- package/dist/knowledge/reviewApply.js.map +1 -0
- package/dist/knowledge/reviewContext.d.ts +77 -0
- package/dist/knowledge/reviewContext.d.ts.map +1 -0
- package/dist/knowledge/reviewContext.js +111 -0
- package/dist/knowledge/reviewContext.js.map +1 -0
- package/dist/knowledge/reviewFinish.d.ts +9 -0
- package/dist/knowledge/reviewFinish.d.ts.map +1 -0
- package/dist/knowledge/reviewFinish.js +62 -0
- package/dist/knowledge/reviewFinish.js.map +1 -0
- package/dist/knowledge/reviewRunModel.d.ts +3 -0
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.js +38 -13
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
- package/dist/knowledge/stores/extractRefs.d.ts +68 -0
- package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
- package/dist/knowledge/stores/extractRefs.js +168 -0
- package/dist/knowledge/stores/extractRefs.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +25 -5
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +6 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
- package/dist/knowledge/stores/rowDelta.js.map +1 -1
- package/dist/knowledge/stores/rowMemory.d.ts +30 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
- package/dist/knowledge/stores/rowMemory.js +46 -1
- package/dist/knowledge/stores/rowMemory.js.map +1 -1
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
- package/dist/knowledge/stores/rowSync.js +2 -1
- package/dist/knowledge/stores/rowSync.js.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +22 -9
- package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
- package/dist/working/fold.d.ts +14 -0
- package/dist/working/fold.d.ts.map +1 -1
- package/dist/working/fold.js +14 -4
- package/dist/working/fold.js.map +1 -1
- package/dist/working/index.d.ts +3 -1
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +2 -1
- package/dist/working/index.js.map +1 -1
- package/dist/working/textSummary.d.ts +46 -0
- package/dist/working/textSummary.d.ts.map +1 -0
- package/dist/working/textSummary.js +142 -0
- package/dist/working/textSummary.js.map +1 -0
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +7 -1
- package/src/contract/regression.extractEviction.test.ts +162 -0
- package/src/contract/regression.fixCommits.test.ts +112 -0
- package/src/contract/regression.packWire.test.ts +174 -0
- package/src/contract/types.contract.test.ts +2 -1
- package/src/knowledge/pack/frame.ts +21 -5
- package/src/knowledge/pack/manifest.ts +26 -11
- package/src/knowledge/pack/sections/extr.ts +14 -4
- package/src/knowledge/pack/sections/extrLists.ts +4 -6
- package/src/knowledge/pack/sections/facts.ts +3 -2
- package/src/knowledge/pack/sections/rows.ts +11 -2
- package/src/knowledge/pack/strings.ts +5 -1
- package/src/knowledge/pack/varint.ts +33 -1
- package/src/knowledge/review.ts +58 -311
- package/src/knowledge/reviewAnalyse.ts +59 -0
- package/src/knowledge/reviewApply.ts +128 -0
- package/src/knowledge/reviewContext.ts +158 -0
- package/src/knowledge/reviewFinish.ts +63 -0
- package/src/knowledge/reviewRunModel.ts +3 -0
- package/src/knowledge/stores/extractLogWriter.ts +36 -12
- package/src/knowledge/stores/extractRefs.ts +161 -0
- package/src/knowledge/stores/localSnapshotStore.ts +22 -5
- package/src/knowledge/stores/rowDelta.ts +6 -0
- package/src/knowledge/stores/rowMemory.ts +50 -1
- package/src/knowledge/stores/rowSync.ts +2 -1
- package/src/knowledge/stores/snapshotFormat.ts +27 -10
- package/src/working/fold.ts +15 -4
- package/src/working/index.ts +13 -1
- package/src/working/textSummary.test.ts +113 -0
- package/src/working/textSummary.ts +156 -0
|
@@ -66,6 +66,22 @@ export function stripUndefined<T extends object>(o: T): Partial<T> {
|
|
|
66
66
|
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* What a COMPACTED log line records beside its body: `c` the source refs it is current for, `p` those it is the previous body of
|
|
71
|
+
* (extractRefs.ts). An appended line has neither: its replay derives them from the put sequence. Older readers ignore both.
|
|
72
|
+
*/
|
|
73
|
+
export interface LoggedRefState { current: string[]; previous: string[] }
|
|
74
|
+
|
|
75
|
+
const strings = (v: unknown): string[] | undefined => (Array.isArray(v) && v.every((x) => typeof x === 'string') ? v as string[] : undefined);
|
|
76
|
+
|
|
77
|
+
function refStateOf(row: { c?: unknown; p?: unknown }): LoggedRefState | undefined {
|
|
78
|
+
const current = strings(row.c), previous = strings(row.p);
|
|
79
|
+
return current || previous ? { current: current ?? [], previous: previous ?? [] } : undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One compacted log line (newline-terminated) for a body and its reference state. */
|
|
83
|
+
export const compactedLogLine = (h: string, e: Extracted[], s: LoggedRefState): string => `${JSON.stringify({ h, e, c: s.current, p: s.previous })}\n`;
|
|
84
|
+
|
|
69
85
|
export interface ParsedLog {
|
|
70
86
|
entries: Map<string, Extracted[]>;
|
|
71
87
|
/** The live (last) line of each hash, newline-terminated, in log order. */
|
|
@@ -77,21 +93,22 @@ export interface ParsedLog {
|
|
|
77
93
|
|
|
78
94
|
/**
|
|
79
95
|
* The log's entries, last line per hash winning. A line that does not parse (torn by a crash or a failed
|
|
80
|
-
* append) is skipped on its own: it never costs the other lines.
|
|
96
|
+
* append) is skipped on its own: it never costs the other lines. `onLine` sees EVERY parsed line in log order (superseded
|
|
97
|
+
* ones too), for a reader that replays the puts.
|
|
81
98
|
*/
|
|
82
|
-
export function parseLog(text: string | undefined): ParsedLog {
|
|
99
|
+
export function parseLog(text: string | undefined, onLine?: (hash: string, entries: Extracted[], state?: LoggedRefState) => void): ParsedLog {
|
|
83
100
|
const out: ParsedLog = { entries: new Map(), liveLines: new Map(), liveBytes: 0, deadBytes: 0 };
|
|
84
101
|
if (!text) return out;
|
|
85
102
|
for (const line of text.split('\n')) {
|
|
86
103
|
if (!line.trim()) continue;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
104
|
+
let row: { h?: unknown; e?: unknown; c?: unknown; p?: unknown };
|
|
105
|
+
// Only a line that does not parse is torn; a failure of the replay below is the caller's and surfaces.
|
|
106
|
+
try { row = JSON.parse(line) as typeof row; } catch { continue; /* torn line */ }
|
|
107
|
+
if (!row || typeof row.h !== 'string' || !Array.isArray(row.e)) continue;
|
|
108
|
+
out.entries.set(row.h, row.e as Extracted[]);
|
|
109
|
+
out.liveLines.delete(row.h); // re-set below so the map stays in log order of last occurrence
|
|
110
|
+
out.liveLines.set(row.h, `${line}\n`);
|
|
111
|
+
onLine?.(row.h, row.e as Extracted[], refStateOf(row));
|
|
95
112
|
}
|
|
96
113
|
for (const l of out.liveLines.values()) out.liveBytes += l.length;
|
|
97
114
|
out.deadBytes = Math.max(0, text.length - out.liveBytes);
|
package/src/working/fold.ts
CHANGED
|
@@ -105,8 +105,11 @@ function wordSet(text: string): Set<string> {
|
|
|
105
105
|
);
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
/**
|
|
109
|
-
|
|
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 {
|
|
110
113
|
const sa = wordSet(a);
|
|
111
114
|
const sb = wordSet(b);
|
|
112
115
|
if (sa.size === 0 || sb.size === 0) return 0;
|
|
@@ -118,7 +121,7 @@ function wordOverlap(a: string, b: string): number {
|
|
|
118
121
|
/** Containment: is every word of the smaller set present in the larger? True when one
|
|
119
122
|
* narration is the other plus a trailing qualifier ("…once more", "…again", "…now") —
|
|
120
123
|
* a repeat Jaccard under-counts because the union grows with the qualifier's words. */
|
|
121
|
-
function wordContained(a: string, b: string): boolean {
|
|
124
|
+
export function wordContained(a: string, b: string): boolean {
|
|
122
125
|
const sa = wordSet(a);
|
|
123
126
|
const sb = wordSet(b);
|
|
124
127
|
if (sa.size === 0 || sb.size === 0) return false;
|
|
@@ -127,6 +130,14 @@ function wordContained(a: string, b: string): boolean {
|
|
|
127
130
|
return true;
|
|
128
131
|
}
|
|
129
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
|
+
|
|
130
141
|
/** The narration an assistant turn carries before its tool calls — null when it carries
|
|
131
142
|
* none (an empty-content tool-call turn, or any turn without tool calls). */
|
|
132
143
|
function narrationOf(m: TranscriptMessage): string | null {
|
|
@@ -221,7 +232,7 @@ export function foldRepeatedNarration<M extends TranscriptMessage>(msgs: readonl
|
|
|
221
232
|
lastKept = narration;
|
|
222
233
|
return m;
|
|
223
234
|
}
|
|
224
|
-
if (lastKept != null && (
|
|
235
|
+
if (lastKept != null && isRepeatedNarration(narration, lastKept, overlap)) {
|
|
225
236
|
changed = true;
|
|
226
237
|
return { ...m, content: PROGRESS_NOTE } as M;
|
|
227
238
|
}
|
package/src/working/index.ts
CHANGED
|
@@ -54,7 +54,19 @@ export {
|
|
|
54
54
|
buildWorkingTranscript,
|
|
55
55
|
} from './transcript.js';
|
|
56
56
|
export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
|
|
57
|
-
export {
|
|
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';
|
|
58
70
|
export { TRANSCRIPT_SUMMARY_PROMPT, TRANSCRIPT_SUMMARY_MAX_TOKENS, TRANSCRIPT_SUMMARY_INPUT_TOKENS, renderForSummary, summaryChunks, summarizeTranscript } from './summary.js';
|
|
59
71
|
export type { SummaryCompletion } from './summary.js';
|
|
60
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
|
+
}
|