@seanhogg/builderforce-memory 2026.10.24 → 2026.10.25

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.
@@ -0,0 +1,243 @@
1
+ /**
2
+ * The working transcript — what of a run the model is SHOWN each turn.
3
+ *
4
+ * A run's full transcript grows without bound; the request sent to the model must not.
5
+ * This module owns the two ways it is kept in bounds: the message-count + token WINDOW
6
+ * (drop-oldest, anchored on a user turn) and AUTO-COMPACTION (fold the older part into a
7
+ * memory note, keep every later message verbatim). A host supplies only what is
8
+ * run-specific: the summarizer it calls (see `summary.ts`) and what a fold records.
9
+ *
10
+ * Pure except for {@link buildWorkingTranscript}, which awaits the injected summarizer and
11
+ * updates the caller's `compactMemo`. Generic over the host's message shape: anything with
12
+ * the OpenAI-style `role` / `content` / `tool_calls` fields (`HandoffMessage`).
13
+ */
14
+ import { defaultEstimateTokens, messageTokens as handoffMessageTokens, tokensOf as handoffTokensOf } from '../handoff/budget.js';
15
+ /** How much history we send to the model (message-count ceiling). */
16
+ export const HISTORY_WINDOW = 80;
17
+ /**
18
+ * Token budget for the working transcript sent to the model each turn — how much of this
19
+ * run the model can SEE: the file windows it read, the searches it ran, what it decided.
20
+ *
21
+ * It bounds context, which message-count windowing (HISTORY_WINDOW) alone does not: one
22
+ * `tasks.list` result can be tens of thousands of tokens. It is NOT what keeps a request
23
+ * inside the serving model's window — the gateway fits every request to a model that can
24
+ * hold it.
25
+ *
26
+ * It was 24k, "sized under the smallest pool model's window". That protected nothing — the
27
+ * ~16k-token system prompt + tool catalog in front of it already put a full turn at ~40k,
28
+ * past any 32k window — and it cost every coding run its memory. Six 4k-token file windows
29
+ * filled it, compaction folded them into a 1.2k-token note, and the model went back for the
30
+ * files it had just read (chat #105: 55 turns, 63% of calls revisiting, zero edits, prompt
31
+ * peak 40,351). 64k holds a coding task's working set — a dozen-plus file windows —
32
+ * verbatim, while a full turn stays well inside the 128k window every coding-capable pool
33
+ * model has. See {@link windowed} and {@link buildWorkingTranscript}.
34
+ */
35
+ export const HISTORY_TOKEN_BUDGET = 64_000;
36
+ /**
37
+ * How much of {@link HISTORY_TOKEN_BUDGET} the verbatim TAIL may keep when the older part
38
+ * of the transcript is compacted. The rest is headroom new work fills before the next
39
+ * fold, so the memo is re-folded once per ~20k tokens of progress, not on every turn.
40
+ */
41
+ export const COMPACT_TAIL_TOKEN_BUDGET = 40_000;
42
+ /** Estimated tokens for one message (content + tool-call payload + framing) — THE
43
+ * hand-off packer's estimate, so the working transcript and a hand-off to a smaller
44
+ * model count a message the same way. */
45
+ function messageTokens(m) {
46
+ return handoffMessageTokens(m, defaultEstimateTokens);
47
+ }
48
+ /**
49
+ * Trim the in-memory transcript to the history window before sending it to the
50
+ * model. Slicing the last N can leave the window starting on an `assistant`
51
+ * tool-call turn or an orphaned `tool` result (whose owning call fell off the
52
+ * front). That payload is invalid for strict vendors: Gemini rejects a request
53
+ * whose conversation does not begin with a user turn — surfaced as the cascade
54
+ * `[googleai] 400 INVALID_ARGUMENT` after a long tool-loop crossed the window
55
+ * boundary. So anchor the window at a user turn.
56
+ *
57
+ * If the last-N slice contains no user turn (a tool loop longer than the
58
+ * window), fall back to the most recent user turn in the FULL transcript and
59
+ * keep everything after it — correctness over the size cap.
60
+ */
61
+ export function windowed(convo) {
62
+ let w = convo.slice(-HISTORY_WINDOW);
63
+ while (w.length > 0 && w[0].role !== 'user')
64
+ w = w.slice(1);
65
+ if (w.length === 0) {
66
+ const lastUser = convo.map((m) => m.role).lastIndexOf('user');
67
+ w = lastUser >= 0 ? convo.slice(lastUser) : convo.slice();
68
+ }
69
+ return tokenBounded(w);
70
+ }
71
+ /**
72
+ * Enforce the token budget on an already message-count-windowed slice. Drops the
73
+ * OLDEST turns first, then re-anchors on a user turn (a strict vendor rejects a window
74
+ * that doesn't start on `user`, and dropping a turn can orphan a `tool` result whose
75
+ * `assistant` tool-call fell off the front). The most recent user turn is never
76
+ * dropped: correctness over the budget when a single turn is itself oversized.
77
+ */
78
+ function tokenBounded(w) {
79
+ let total = transcriptTokens(w);
80
+ if (total <= HISTORY_TOKEN_BUDGET)
81
+ return w;
82
+ const lastUser = w.map((m) => m.role).lastIndexOf('user');
83
+ let start = 0;
84
+ while (total > HISTORY_TOKEN_BUDGET && start < lastUser) {
85
+ total -= messageTokens(w[start]);
86
+ start += 1;
87
+ }
88
+ let trimmed = w.slice(start);
89
+ while (trimmed.length > 1 && trimmed[0].role !== 'user')
90
+ trimmed = trimmed.slice(1);
91
+ return trimmed;
92
+ }
93
+ /**
94
+ * Is a transcript message still part of what the model sees? False once auto-compaction
95
+ * has folded it into the memory note, or the drop-oldest window has let it fall off the
96
+ * front. Deliberately conservative: it judges against the CURRENT transcript (which has
97
+ * grown since the last working set was built), so it can only ever call a message gone a
98
+ * turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
99
+ */
100
+ export function stillInWorkingContext(state, anchor) {
101
+ const convo = state.transcript;
102
+ const idx = convo.indexOf(anchor);
103
+ if (idx < 0)
104
+ return false;
105
+ if (state.compactMemo)
106
+ return idx >= verbatimStart(convo, state.compactMemo.coveredEnd);
107
+ return windowed(convo).includes(convo[idx]);
108
+ }
109
+ // ---------------------------------------------------------------------------
110
+ // Auto-compaction — summarize the bulky MIDDLE instead of dropping it.
111
+ //
112
+ // `tokenBounded` keeps the request inside the window by DROPPING the oldest turns. That
113
+ // never 413s, but it silently LOSES context — which made a weak model re-read files and
114
+ // thrash ("LOOP EXHAUSTED", chat #50). When a summarizer is available the older turns are
115
+ // compressed into ONE memory note instead, so the model keeps working from a distilled
116
+ // memory. Falls back to `tokenBounded` when no summarizer is reachable.
117
+ //
118
+ // Why this fold is NOT `packHandoff` (`../handoff`): the packer is stateless and gives the
119
+ // verbatim tail priority, handing the note whatever room the tail leaves. The working
120
+ // transcript needs the opposite on both counts — an INCREMENTAL memo reused across turns
121
+ // (one summarizer call per ~20k tokens of progress), a tail capped at
122
+ // COMPACT_TAIL_TOKEN_BUDGET so the note and the next turns have headroom, and a
123
+ // message-count window. What the two share — the token estimate — is the packer's.
124
+ // ---------------------------------------------------------------------------
125
+ /** The fewest recent messages the verbatim tail keeps, however large they are. */
126
+ export const COMPACT_TAIL_TURNS = 8;
127
+ /** The most recent messages the verbatim tail may hold — half the message window, so a
128
+ * compacted transcript stays inside {@link HISTORY_WINDOW} with room to grow. */
129
+ const COMPACT_TAIL_MAX_MESSAGES = HISTORY_WINDOW / 2;
130
+ /** The first index at or after `from` that is not a `tool` result: a tool row whose
131
+ * assistant call was folded into the memo would be orphaned (strict vendors 400 on it). */
132
+ export function verbatimStart(convo, from) {
133
+ let start = Math.max(0, Math.min(from, convo.length));
134
+ while (start < convo.length && convo[start].role === 'tool')
135
+ start += 1;
136
+ return start;
137
+ }
138
+ /** Start index of the last `tailTurns` messages, walked off a leading `tool` result. */
139
+ export function compactTailStart(convo, tailTurns) {
140
+ return verbatimStart(convo, convo.length - tailTurns);
141
+ }
142
+ /**
143
+ * Where the verbatim tail begins when the transcript is compacted: as many of the most
144
+ * recent messages as fit in `budgetTokens` — never fewer than {@link COMPACT_TAIL_TURNS},
145
+ * never more than {@link COMPACT_TAIL_MAX_MESSAGES} — walked off a leading tool result.
146
+ *
147
+ * Sized by TOKENS, not a message count: a fixed eight messages is four tool results, so
148
+ * after a fold the fifth file the model needed was always the one it had to read again.
149
+ */
150
+ export function compactTailStartForBudget(convo, budgetTokens) {
151
+ let start = convo.length;
152
+ let tokens = 0;
153
+ while (start > 0) {
154
+ const kept = convo.length - start;
155
+ if (kept >= COMPACT_TAIL_MAX_MESSAGES)
156
+ break;
157
+ const next = messageTokens(convo[start - 1]);
158
+ if (kept >= COMPACT_TAIL_TURNS && tokens + next > budgetTokens)
159
+ break;
160
+ tokens += next;
161
+ start -= 1;
162
+ }
163
+ return verbatimStart(convo, start);
164
+ }
165
+ /**
166
+ * Index of the MOST RECENT user turn to re-inject verbatim ahead of the tail — the
167
+ * ACTIVE directive — or -1 when the latest user turn is already inside the tail. Pinning
168
+ * the FIRST user turn (the old behaviour) made a multi-instruction chat revert to its
169
+ * opening request (chat #55); the current instruction is always the LATEST user turn.
170
+ */
171
+ export function pinnedDirectiveIndex(convo, tailStart) {
172
+ const lastUser = convo.map((m) => m.role).lastIndexOf('user');
173
+ return lastUser >= 0 && lastUser < tailStart ? lastUser : -1;
174
+ }
175
+ /**
176
+ * Assemble the working transcript from a compressed-memory `note` that covers
177
+ * `convo[0, coveredEnd)`: system + the memory note + the ACTIVE user directive re-injected
178
+ * verbatim (when the note covers it) + EVERY message from `coveredEnd` on (tool-pairing
179
+ * safe via {@link verbatimStart}). Nothing is in neither the note nor the tail. The
180
+ * directive sits immediately before the tail so the model reads it as the CURRENT
181
+ * instruction.
182
+ */
183
+ export function assembleCompacted(systemPrompt, convo, note, coveredEnd) {
184
+ const tailStart = verbatimStart(convo, coveredEnd);
185
+ const out = [{ role: 'system', content: systemPrompt }];
186
+ out.push({ role: 'assistant', content: note });
187
+ const directiveIdx = pinnedDirectiveIndex(convo, tailStart);
188
+ if (directiveIdx >= 0)
189
+ out.push(convo[directiveIdx]);
190
+ out.push(...convo.slice(tailStart));
191
+ return out;
192
+ }
193
+ /** Estimated tokens of a message list — the ONE count compaction budgets by, exported so
194
+ * a run measures what compaction kept out of a call with the same rule. */
195
+ export function transcriptTokens(msgs) {
196
+ return handoffTokensOf(msgs, defaultEstimateTokens);
197
+ }
198
+ /** Can these messages (plus `extraTokens` in front of them) go to the model verbatim —
199
+ * inside both the token budget and the message window? */
200
+ function fitsVerbatim(msgs, extraTokens = 0) {
201
+ return msgs.length <= HISTORY_WINDOW && extraTokens + transcriptTokens(msgs) <= HISTORY_TOKEN_BUDGET;
202
+ }
203
+ /**
204
+ * Build the working transcript for a turn. When the whole transcript fits → all of it,
205
+ * verbatim. Otherwise → a memory note of the older part plus EVERY message after it,
206
+ * verbatim; `onFolded` is told about each NEW fold, so the caller can record it (a
207
+ * visible step, a durable consolidation marker).
208
+ *
209
+ * The note is folded INCREMENTALLY, and only when it has to be. A note whose verbatim
210
+ * remainder still fits is reused as-is; once it no longer fits, the previous note plus
211
+ * exactly the messages since it are folded into a new one, up to a token-sized tail
212
+ * ({@link compactTailStartForBudget}). Falls back to drop-oldest when the summarizer is
213
+ * unavailable (`summarize` resolves null). A message-count overflow folds too.
214
+ */
215
+ export async function buildWorkingTranscript(state, systemPrompt, summarize, onFolded) {
216
+ const convo = state.transcript;
217
+ if (fitsVerbatim(convo)) {
218
+ state.compactMemo = null; // back under budget — a later overflow summarizes afresh
219
+ return [{ role: 'system', content: systemPrompt }, ...windowed(convo)];
220
+ }
221
+ // A note written against a transcript that has since been replaced covers nothing here.
222
+ const memo = state.compactMemo && state.compactMemo.coveredEnd <= convo.length ? state.compactMemo : null;
223
+ if (memo && fitsVerbatim(convo.slice(verbatimStart(convo, memo.coveredEnd)), defaultEstimateTokens(memo.note))) {
224
+ return assembleCompacted(systemPrompt, convo, memo.note, memo.coveredEnd);
225
+ }
226
+ const from = memo?.coveredEnd ?? 0;
227
+ const to = Math.max(from, compactTailStartForBudget(convo, COMPACT_TAIL_TOKEN_BUDGET));
228
+ const fold = memo
229
+ ? [{ role: 'assistant', content: memo.note }, ...convo.slice(from, to)]
230
+ : convo.slice(from, to);
231
+ const summary = to > from ? await summarize(fold) : null;
232
+ if (summary == null) {
233
+ // Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest.
234
+ return memo
235
+ ? assembleCompacted(systemPrompt, convo, memo.note, memo.coveredEnd)
236
+ : [{ role: 'system', content: systemPrompt }, ...windowed(convo)];
237
+ }
238
+ const note = `Compressed memory of the first ${to} message(s) of this conversation:\n${summary}`;
239
+ state.compactMemo = { note, coveredEnd: to };
240
+ onFolded({ droppedMessages: to - from, note, coveredEnd: to });
241
+ return assembleCompacted(systemPrompt, convo, note, to);
242
+ }
243
+ //# sourceMappingURL=transcript.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AA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ilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, and persistent agent memory for BuilderForce.ai agents.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -103,7 +103,7 @@
103
103
  },
104
104
  "homepage": "https://github.com/SeanHogg/builderforce-memory/tree/main/packages/memory#readme",
105
105
  "peerDependencies": {
106
- "@seanhogg/builderforce-memory-engine": "^2026.10.24"
106
+ "@seanhogg/builderforce-memory-engine": "^2026.10.25"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@jest/globals": "^29.7.0",
@@ -117,7 +117,7 @@
117
117
  "ts-jest": "^29.2.0",
118
118
  "typescript": "^6.0.3",
119
119
  "@typescript/native-preview": "7.0.0-dev.20260627.2",
120
- "@seanhogg/builderforce-memory-engine": "2026.10.24"
120
+ "@seanhogg/builderforce-memory-engine": "2026.10.25"
121
121
  },
122
122
  "jest": {
123
123
  "preset": "ts-jest/presets/default-esm",
@@ -0,0 +1,95 @@
1
+ /**
2
+ * src/working/consolidationMarker.test.ts
3
+ * Consolidation markers (moved unchanged from brain-embedded) + the auto-fold coverage rule.
4
+ */
5
+ import {
6
+ consolidationMetadata,
7
+ consolidationMarkerContent,
8
+ isConsolidationMarker,
9
+ lastConsolidationIndex,
10
+ scopeToConsolidation,
11
+ CONSOLIDATION_MARKER_PREFIX,
12
+ consolidationMarkerOf,
13
+ foldKeepFromId,
14
+ } from './consolidationMarker.js';
15
+
16
+ const msg = (content: string, metadata: string | null = null) => ({ content, metadata });
17
+
18
+ describe('consolidation markers', () => {
19
+ it('flags a message tagged in metadata', () => {
20
+ expect(isConsolidationMarker(msg('x', consolidationMetadata()))).toBe(true);
21
+ expect(isConsolidationMarker(msg('x', null))).toBe(false);
22
+ expect(isConsolidationMarker(msg('x', '{"feedback":"up"}'))).toBe(false);
23
+ expect(isConsolidationMarker(msg('x', 'not json'))).toBe(false);
24
+ });
25
+
26
+ it('finds the LAST marker index', () => {
27
+ const list = [
28
+ msg('a'),
29
+ msg('sum1', consolidationMetadata()),
30
+ msg('b'),
31
+ msg('sum2', consolidationMetadata()),
32
+ msg('c'),
33
+ ];
34
+ expect(lastConsolidationIndex(list)).toBe(3);
35
+ expect(lastConsolidationIndex([msg('a'), msg('b')])).toBe(-1);
36
+ });
37
+
38
+ it('scopes the seed from the last marker (inclusive)', () => {
39
+ const list = [msg('a'), msg('b'), msg('sum', consolidationMetadata()), msg('c')];
40
+ expect(scopeToConsolidation(list).map((m) => m.content)).toEqual(['sum', 'c']);
41
+ });
42
+
43
+ it('returns the full list unchanged when there is no marker', () => {
44
+ const list = [msg('a'), msg('b')];
45
+ expect(scopeToConsolidation(list)).toBe(list);
46
+ });
47
+
48
+ it('wraps a summary with the visible marker prefix', () => {
49
+ const content = consolidationMarkerContent(' hello ');
50
+ expect(content).toBe(`${CONSOLIDATION_MARKER_PREFIX}hello`);
51
+ });
52
+ });
53
+
54
+ describe('auto consolidation markers (a persisted fold)', () => {
55
+ const row = (id: number, content: string, metadata: string | null = null) => ({ id, content, metadata });
56
+
57
+ it('keeps every message from keepFromId on, after the marker, and drops older notes', () => {
58
+ const list = [
59
+ row(1, 'old user'), row(2, 'old reply'),
60
+ row(3, 'superseded note', consolidationMetadata({ keepFromId: 2 })),
61
+ row(4, 'user turn'), row(5, 'narration'),
62
+ row(6, 'note', consolidationMetadata({ keepFromId: 4, folded: 12 })),
63
+ row(7, 'final reply'),
64
+ ];
65
+ expect(scopeToConsolidation(list).map((m) => m.content)).toEqual(['note', 'user turn', 'narration', 'final reply']);
66
+ });
67
+
68
+ it('reads as manual when keepFromId is gone or after the marker', () => {
69
+ const gone = [row(1, 'a'), row(2, 'note', consolidationMetadata({ keepFromId: 99 })), row(3, 'b')];
70
+ expect(scopeToConsolidation(gone).map((m) => m.content)).toEqual(['note', 'b']);
71
+ });
72
+
73
+ it('round-trips the auto metadata', () => {
74
+ expect(consolidationMarkerOf(row(1, 'x', consolidationMetadata({ keepFromId: 4, folded: 3 })))).toEqual({ consolidation: true, auto: true, keepFromId: 4, folded: 3 });
75
+ expect(consolidationMarkerOf(row(1, 'x', consolidationMetadata()))).toEqual({ consolidation: true });
76
+ expect(consolidationMarkerOf(row(1, 'x', null))).toBeNull();
77
+ });
78
+ });
79
+
80
+ describe('foldKeepFromId', () => {
81
+ const anchors = [{ index: 0, id: 10 }, { index: 1, id: 11 }, { index: 2, id: 12 }, { index: 7, id: 20 }];
82
+
83
+ it('is exact when a persisted message sits at the cut', () => {
84
+ expect(foldKeepFromId(anchors, 2)).toBe(12);
85
+ });
86
+
87
+ it('falls back to the nearest persisted message before the cut (covered twice, never lost)', () => {
88
+ expect(foldKeepFromId(anchors, 5)).toBe(12);
89
+ expect(foldKeepFromId(anchors, 30)).toBe(20);
90
+ });
91
+
92
+ it('is undefined with nothing persisted before the cut', () => {
93
+ expect(foldKeepFromId([{ index: 4, id: 1 }], 2)).toBeUndefined();
94
+ });
95
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Chat consolidation markers — the durable form of a compressed conversation.
3
+ *
4
+ * A long conversation is compressed into ONE summary that becomes the new base context:
5
+ * everything before the marker stays visible in the transcript, but the next run's model
6
+ * seed starts from the marker instead of the full history. The marker is a normal
7
+ * assistant message (so a reader SEES the summary) tagged in its metadata.
8
+ *
9
+ * Two writers:
10
+ * - MANUAL — "Consolidate" / "Fork": the summary covers everything before the marker.
11
+ * - AUTO — a run's working-transcript fold (`transcript.ts`), persisted so the next run
12
+ * (after a reload, on another surface) starts from the note instead of summarizing the
13
+ * whole history again. A fold covers only the OLDER part of the transcript; its
14
+ * `keepFromId` names the first persisted message it did NOT cover, and every message
15
+ * from there on stays verbatim in the seed. Nothing is in neither.
16
+ */
17
+
18
+ /** The marker's metadata. `auto` / `keepFromId` / `folded` are set only by a run's fold. */
19
+ export interface ConsolidationMarkerMeta {
20
+ consolidation: true;
21
+ /** Written by auto-compaction, not by a person. */
22
+ auto?: true;
23
+ /** The first persisted message the note does NOT cover (kept verbatim after the marker). */
24
+ keepFromId?: number;
25
+ /** How many transcript messages the fold newly compressed. */
26
+ folded?: number;
27
+ }
28
+
29
+ /** The metadata of a manual marker. */
30
+ export const CONSOLIDATION_META: ConsolidationMarkerMeta = { consolidation: true };
31
+
32
+ /** Serialized metadata for a marker message (ready to persist). Manual when no `auto`. */
33
+ export function consolidationMetadata(auto?: { keepFromId?: number; folded?: number }): string {
34
+ if (!auto) return JSON.stringify(CONSOLIDATION_META);
35
+ const meta: ConsolidationMarkerMeta = {
36
+ consolidation: true,
37
+ auto: true,
38
+ ...(auto.keepFromId !== undefined ? { keepFromId: auto.keepFromId } : {}),
39
+ ...(auto.folded !== undefined ? { folded: auto.folded } : {}),
40
+ };
41
+ return JSON.stringify(meta);
42
+ }
43
+
44
+ /** The marker metadata a persisted message carries, or null when it is not a marker. */
45
+ export function consolidationMarkerOf(msg: { metadata?: string | null }): ConsolidationMarkerMeta | null {
46
+ if (!msg.metadata) return null;
47
+ try {
48
+ const m = JSON.parse(msg.metadata) as Partial<ConsolidationMarkerMeta> | null;
49
+ if (m?.consolidation !== true) return null;
50
+ return {
51
+ consolidation: true,
52
+ ...(m.auto === true ? { auto: true as const } : {}),
53
+ ...(typeof m.keepFromId === 'number' && Number.isFinite(m.keepFromId) ? { keepFromId: m.keepFromId } : {}),
54
+ ...(typeof m.folded === 'number' && Number.isFinite(m.folded) && m.folded > 0 ? { folded: m.folded } : {}),
55
+ };
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /** True when a persisted message is a consolidation marker (by its metadata flag). */
62
+ export function isConsolidationMarker(msg: { metadata?: string | null }): boolean {
63
+ return consolidationMarkerOf(msg) !== null;
64
+ }
65
+
66
+ /** The index of the LAST consolidation marker in a message list, or -1 if none. */
67
+ export function lastConsolidationIndex(messages: ReadonlyArray<{ metadata?: string | null }>): number {
68
+ for (let i = messages.length - 1; i >= 0; i--) {
69
+ if (isConsolidationMarker(messages[i]!)) return i;
70
+ }
71
+ return -1;
72
+ }
73
+
74
+ /**
75
+ * Trim a message list to the compressed context: the last marker, then what it does not
76
+ * cover. A manual marker covers everything before it (the list from the marker on). An
77
+ * auto marker covers up to its `keepFromId`: the marker, then every message from that id
78
+ * on (other markers dropped — an older note is superseded by the newer one). Unchanged
79
+ * when there is no marker; a `keepFromId` no longer in the list reads as manual.
80
+ */
81
+ export function scopeToConsolidation<T extends { id?: number; metadata?: string | null }>(messages: T[]): T[] {
82
+ const idx = lastConsolidationIndex(messages);
83
+ if (idx < 0) return messages;
84
+ const marker = messages[idx]!;
85
+ const keepFromId = consolidationMarkerOf(marker)?.keepFromId;
86
+ const from = keepFromId === undefined ? -1 : messages.findIndex((m) => m.id === keepFromId);
87
+ if (from < 0 || from > idx) return messages.slice(idx);
88
+ return [marker, ...messages.slice(from).filter((m) => m !== marker && !isConsolidationMarker(m))];
89
+ }
90
+
91
+ /**
92
+ * Where an auto marker's verbatim part begins: given the persisted messages the run's
93
+ * transcript holds (`anchors`: transcript index → message id) and the index the fold now
94
+ * covers up to (exclusive), the id of the persisted message the next seed must keep from.
95
+ *
96
+ * Exact when a persisted message sits AT `coveredEnd` (the fold ended inside seeded
97
+ * history). Otherwise the nearest persisted message BEFORE it — conservative: the span
98
+ * between it and `coveredEnd` is then both in the note and verbatim, never in neither.
99
+ * Undefined when no persisted message precedes the cut (nothing to keep from).
100
+ */
101
+ export function foldKeepFromId(anchors: ReadonlyArray<{ index: number; id: number }>, coveredEnd: number): number | undefined {
102
+ let best: { index: number; id: number } | undefined;
103
+ for (const a of anchors) {
104
+ if (a.index <= coveredEnd && (!best || a.index > best.index)) best = a;
105
+ }
106
+ return best?.id;
107
+ }
108
+
109
+ /** The visible header prefixed onto a consolidation summary so a reader recognizes it. */
110
+ export const CONSOLIDATION_MARKER_PREFIX = '📌 **Consolidated summary** — context continues from here.\n\n';
111
+
112
+ /** Wrap a raw summary as the marker's visible content (prefix + summary). */
113
+ export function consolidationMarkerContent(summary: string): string {
114
+ return `${CONSOLIDATION_MARKER_PREFIX}${summary.trim()}`;
115
+ }
@@ -15,6 +15,11 @@
15
15
  * The memory knows observations ("read this file", "changed that one"), never tool
16
16
  * names — a host maps its own tool vocabulary onto {@link Observation}.
17
17
  *
18
+ * And what the MODEL sees of a run each turn — the working TRANSCRIPT (`transcript.ts`):
19
+ * the drop-oldest window and the incremental auto-compaction fold, the ONE summarizer
20
+ * prompt it folds with (`summary.ts`), and the consolidation markers a fold or a
21
+ * "Consolidate" persists so the next run starts from the note (`consolidationMarker.ts`).
22
+ *
18
23
  * Pure: no `node:*`, no I/O — runs in a Cloudflare Worker, a browser page and Node alike.
19
24
  */
20
25
 
@@ -22,3 +27,33 @@ export { WorkingMemory } from './workingMemory.js';
22
27
  export { consolidate, mergeConsolidated, consolidatedKey, CONSOLIDATED_KEY_PREFIX, MIN_CONSOLIDATED_FILES } from './consolidate.js';
23
28
  export { rankByCount } from './rank.js';
24
29
  export type { Observation, WorkingMemorySnapshot, ConsolidatedMemory, ConsolidateOptions } from './types.js';
30
+ export {
31
+ HISTORY_WINDOW,
32
+ HISTORY_TOKEN_BUDGET,
33
+ COMPACT_TAIL_TOKEN_BUDGET,
34
+ COMPACT_TAIL_TURNS,
35
+ windowed,
36
+ stillInWorkingContext,
37
+ verbatimStart,
38
+ compactTailStart,
39
+ compactTailStartForBudget,
40
+ pinnedDirectiveIndex,
41
+ assembleCompacted,
42
+ transcriptTokens,
43
+ buildWorkingTranscript,
44
+ } from './transcript.js';
45
+ export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
46
+ export { TRANSCRIPT_SUMMARY_PROMPT, TRANSCRIPT_SUMMARY_MAX_TOKENS, renderForSummary, summarizeTranscript } from './summary.js';
47
+ export type { SummaryCompletion } from './summary.js';
48
+ export {
49
+ CONSOLIDATION_META,
50
+ CONSOLIDATION_MARKER_PREFIX,
51
+ consolidationMetadata,
52
+ consolidationMarkerOf,
53
+ consolidationMarkerContent,
54
+ isConsolidationMarker,
55
+ lastConsolidationIndex,
56
+ scopeToConsolidation,
57
+ foldKeepFromId,
58
+ } from './consolidationMarker.js';
59
+ export type { ConsolidationMarkerMeta } from './consolidationMarker.js';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * src/working/summary.test.ts
3
+ * The ONE transcript summarizer: what it asks, how it renders tool calls, and that a
4
+ * failing or empty completion reads as "no summary" (the caller falls back).
5
+ */
6
+
7
+ import { renderForSummary, summarizeTranscript, TRANSCRIPT_SUMMARY_MAX_TOKENS, TRANSCRIPT_SUMMARY_PROMPT } from './summary.js';
8
+ import { buildWorkingTranscript, HISTORY_TOKEN_BUDGET, type TranscriptFold, type TranscriptMessage, type WorkingTranscriptState } from './transcript.js';
9
+
10
+ describe('renderForSummary', () => {
11
+ it('names the tools an assistant turn called', () => {
12
+ const text = renderForSummary([
13
+ { role: 'user', content: 'fix it' },
14
+ { role: 'assistant', content: '', tool_calls: [{ function: { name: 'read_file' } }, { function: { name: 'edit' } }] },
15
+ { role: 'tool', content: { ok: true } },
16
+ ]);
17
+ expect(text).toBe('user: fix it\n\nassistant [called: read_file, edit]: \n\ntool: {"ok":true}');
18
+ });
19
+ });
20
+
21
+ describe('summarizeTranscript', () => {
22
+ it('asks the shared prompt with the bounded budget and trims the answer', async () => {
23
+ const seen: Array<{ system: string; maxTokens: number }> = [];
24
+ const out = await summarizeTranscript(async (req) => { seen.push(req); return ' the note '; }, [{ role: 'user', content: 'x' }]);
25
+ expect(out).toBe('the note');
26
+ expect(seen[0]).toMatchObject({ system: TRANSCRIPT_SUMMARY_PROMPT, maxTokens: TRANSCRIPT_SUMMARY_MAX_TOKENS });
27
+ });
28
+
29
+ it('is null for nothing to summarize, an empty answer, or a failure', async () => {
30
+ expect(await summarizeTranscript(async () => 'x', [])).toBeNull();
31
+ expect(await summarizeTranscript(async () => ' ', [{ role: 'user', content: 'x' }])).toBeNull();
32
+ expect(await summarizeTranscript(async () => { throw new Error('down'); }, [{ role: 'user', content: 'x' }])).toBeNull();
33
+ });
34
+ });
35
+
36
+ describe('buildWorkingTranscript fold report', () => {
37
+ it('reports the note and the index it covers up to', async () => {
38
+ const big = 'x'.repeat(HISTORY_TOKEN_BUDGET); // ~16k tokens each
39
+ const state: WorkingTranscriptState = {
40
+ transcript: Array.from({ length: 12 }, (_, i): TranscriptMessage => ({ role: i % 2 ? 'assistant' : 'user', content: big })),
41
+ compactMemo: null,
42
+ };
43
+ const folds: TranscriptFold[] = [];
44
+ const out = await buildWorkingTranscript(state, 'sys', async () => 'summary', (f) => folds.push(f));
45
+ expect(folds).toHaveLength(1);
46
+ expect(folds[0]!.droppedMessages).toBe(folds[0]!.coveredEnd);
47
+ expect(folds[0]!.note).toContain('summary');
48
+ expect(state.compactMemo).toEqual({ note: folds[0]!.note, coveredEnd: folds[0]!.coveredEnd });
49
+ expect(out[1]).toEqual({ role: 'assistant', content: folds[0]!.note });
50
+ });
51
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The transcript summarizer — the ONE prompt every fold, hand-off note and chat
3
+ * consolidation compresses a conversation with. The model call is the host's
4
+ * ({@link SummaryCompletion}); this module owns what is asked and how the transcript is
5
+ * rendered for it, so a compaction note, a hand-off note and a "Consolidate" summary read
6
+ * the same everywhere.
7
+ */
8
+
9
+ import type { TranscriptMessage } from './transcript.js';
10
+
11
+ /** The summarizer's instructions. */
12
+ export const TRANSCRIPT_SUMMARY_PROMPT =
13
+ 'You compress an in-progress AI agent transcript into a concise MEMORY the agent keeps working from. Capture: the CURRENT outstanding instruction from the user (the most recent user message is authoritative — earlier requests it supersedes are history, not the active task), concrete facts/answers discovered, tool results that matter (ids, paths, values), decisions made, and what still remains to do. Keep every file path, symbol name and line number the remaining work depends on, with the specific facts learned from each file — the agent no longer sees those results, so what you leave out it must read again. Be information-dense; drop pleasantries. No preamble.';
14
+
15
+ /**
16
+ * The note's output ceiling. A compaction note is a UTILITY completion: a bounded answer
17
+ * with no thinking. ~2.5k tokens: the note is the agent's only record of every file it
18
+ * folds (paths, symbols, line numbers), and 1.2k was too little to carry them.
19
+ */
20
+ export const TRANSCRIPT_SUMMARY_MAX_TOKENS = 2_500;
21
+
22
+ /** One no-tools, no-reasoning completion — the host's model call. Resolves the text. */
23
+ export type SummaryCompletion = (request: {
24
+ system: string;
25
+ user: string;
26
+ maxTokens: number;
27
+ signal?: AbortSignal;
28
+ }) => Promise<string | null | undefined>;
29
+
30
+ interface NamedToolCall {
31
+ function?: { name?: unknown };
32
+ }
33
+
34
+ /** Render a slice of the transcript to the compact text the summarizer compresses. */
35
+ export function renderForSummary(msgs: readonly TranscriptMessage[]): string {
36
+ return msgs
37
+ .map((m) => {
38
+ const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '');
39
+ const calls = Array.isArray(m.tool_calls) && m.tool_calls.length > 0
40
+ ? ` [called: ${(m.tool_calls as NamedToolCall[]).map((t) => t.function?.name).filter((n): n is string => typeof n === 'string' && n.length > 0).join(', ')}]`
41
+ : '';
42
+ return `${m.role}${calls}: ${content}`;
43
+ })
44
+ .join('\n\n');
45
+ }
46
+
47
+ /**
48
+ * Compress `msgs` into a memory note. Null on any failure or an empty answer, so the
49
+ * caller falls back (drop-oldest, elision, "nothing to consolidate").
50
+ */
51
+ export async function summarizeTranscript(
52
+ complete: SummaryCompletion,
53
+ msgs: readonly TranscriptMessage[],
54
+ signal?: AbortSignal,
55
+ ): Promise<string | null> {
56
+ if (msgs.length === 0) return null;
57
+ try {
58
+ const out = ((await complete({
59
+ system: TRANSCRIPT_SUMMARY_PROMPT,
60
+ user: renderForSummary(msgs),
61
+ maxTokens: TRANSCRIPT_SUMMARY_MAX_TOKENS,
62
+ ...(signal ? { signal } : {}),
63
+ })) ?? '').trim();
64
+ return out.length > 0 ? out : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }