@seanhogg/builderforce-memory 2026.10.24 → 2026.10.26

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,113 @@
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 { transcriptTokens, 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
+ /**
23
+ * The most transcript one summarizer call reads (~tokens). A longer input — a whole long
24
+ * chat on "Consolidate", a first fold over a big seeded history — is summarized in
25
+ * CHUNKS of this size, each folded onto the note so far, so no single call can overrun
26
+ * a model's window.
27
+ */
28
+ export const TRANSCRIPT_SUMMARY_INPUT_TOKENS = 48_000;
29
+
30
+ /** One no-tools, no-reasoning completion — the host's model call. Resolves the text. */
31
+ export type SummaryCompletion = (request: {
32
+ system: string;
33
+ user: string;
34
+ maxTokens: number;
35
+ signal?: AbortSignal;
36
+ }) => Promise<string | null | undefined>;
37
+
38
+ interface NamedToolCall {
39
+ function?: { name?: unknown };
40
+ }
41
+
42
+ /** Render a slice of the transcript to the compact text the summarizer compresses. */
43
+ export function renderForSummary(msgs: readonly TranscriptMessage[]): string {
44
+ return msgs
45
+ .map((m) => {
46
+ const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '');
47
+ const calls = Array.isArray(m.tool_calls) && m.tool_calls.length > 0
48
+ ? ` [called: ${(m.tool_calls as NamedToolCall[]).map((t) => t.function?.name).filter((n): n is string => typeof n === 'string' && n.length > 0).join(', ')}]`
49
+ : '';
50
+ return `${m.role}${calls}: ${content}`;
51
+ })
52
+ .join('\n\n');
53
+ }
54
+
55
+ /**
56
+ * Split a transcript into consecutive chunks of at most `budget` tokens. A single message
57
+ * larger than the budget is a chunk of its own (its text is clipped when rendered).
58
+ */
59
+ export function summaryChunks(msgs: readonly TranscriptMessage[], budget = TRANSCRIPT_SUMMARY_INPUT_TOKENS): TranscriptMessage[][] {
60
+ const chunks: TranscriptMessage[][] = [];
61
+ let chunk: TranscriptMessage[] = [];
62
+ let used = 0;
63
+ for (const m of msgs) {
64
+ const cost = transcriptTokens([m]);
65
+ if (chunk.length > 0 && used + cost > budget) {
66
+ chunks.push(chunk);
67
+ chunk = [];
68
+ used = 0;
69
+ }
70
+ chunk.push(m);
71
+ used += cost;
72
+ }
73
+ if (chunk.length > 0) chunks.push(chunk);
74
+ return chunks;
75
+ }
76
+
77
+ /** ~4 characters a token: the rendered text one call may carry. */
78
+ const clip = (text: string, budget: number) => {
79
+ const max = budget * 4;
80
+ return text.length > max ? `${text.slice(0, max)}\n[…clipped]` : text;
81
+ };
82
+
83
+ /**
84
+ * Compress `msgs` into a memory note — in one call, or chunk by chunk with each chunk
85
+ * folded onto the note so far when the transcript is longer than one call may read. Null
86
+ * on any failure or an empty answer, so the caller falls back (drop-oldest, elision,
87
+ * "nothing to consolidate").
88
+ */
89
+ export async function summarizeTranscript(
90
+ complete: SummaryCompletion,
91
+ msgs: readonly TranscriptMessage[],
92
+ signal?: AbortSignal,
93
+ budget = TRANSCRIPT_SUMMARY_INPUT_TOKENS,
94
+ ): Promise<string | null> {
95
+ if (msgs.length === 0) return null;
96
+ let note: string | null = null;
97
+ for (const chunk of summaryChunks(msgs, budget)) {
98
+ const input: TranscriptMessage[] = note ? [{ role: 'assistant', content: note } as TranscriptMessage, ...chunk] : chunk;
99
+ try {
100
+ const out: string = ((await complete({
101
+ system: TRANSCRIPT_SUMMARY_PROMPT,
102
+ user: clip(renderForSummary(input), budget),
103
+ maxTokens: TRANSCRIPT_SUMMARY_MAX_TOKENS,
104
+ ...(signal ? { signal } : {}),
105
+ })) ?? '').trim();
106
+ if (!out) return null;
107
+ note = out;
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+ return note;
113
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * src/working/transcript.test.ts
3
+ * The working-transcript window and fold partitioning (moved unchanged from brain-embedded).
4
+ */
5
+ import {
6
+ windowed,
7
+ compactTailStart,
8
+ compactTailStartForBudget,
9
+ verbatimStart,
10
+ assembleCompacted,
11
+ pinnedDirectiveIndex,
12
+ COMPACT_TAIL_TURNS,
13
+ } from './transcript.js';
14
+ import type { TranscriptMessage as ChatCompletionMessage } from './transcript.js';
15
+
16
+ describe('windowed history (must begin with a user turn)', () => {
17
+ const msg = (role: ChatCompletionMessage['role'], content = 'x'): ChatCompletionMessage => ({ role, content });
18
+
19
+ it('keeps a normal short conversation intact', () => {
20
+ const convo = [msg('user'), msg('assistant'), msg('user'), msg('assistant')];
21
+ expect(windowed(convo)).toEqual(convo);
22
+ });
23
+
24
+ it('drops a leading orphaned tool result', () => {
25
+ const convo = [msg('tool'), msg('user'), msg('assistant')];
26
+ expect(windowed(convo)[0].role).toBe('user');
27
+ });
28
+
29
+ it('drops a leading assistant turn so the payload starts at a user turn (the googleai 400)', () => {
30
+ // After a long tool-loop slid the user turn out of the last-N slice, the
31
+ // window would otherwise start on an assistant tool-call turn — which Gemini
32
+ // rejects with INVALID_ARGUMENT.
33
+ const convo = [msg('assistant'), msg('tool'), msg('user'), msg('assistant'), msg('tool')];
34
+ expect(windowed(convo)[0].role).toBe('user');
35
+ });
36
+
37
+ it('anchors to the last user turn when the window has none (tool loop > window)', () => {
38
+ // 90 assistant/tool messages after a single user turn: the last-80 slice has
39
+ // no user turn, so we fall back to the most recent user turn in the full
40
+ // transcript rather than emit a user-less (invalid) request.
41
+ const convo: ChatCompletionMessage[] = [msg('user', 'go')];
42
+ for (let i = 0; i < 90; i++) convo.push(msg(i % 2 === 0 ? 'assistant' : 'tool'));
43
+ const w = windowed(convo);
44
+ expect(w[0].role).toBe('user');
45
+ expect(w[0].content).toBe('go');
46
+ });
47
+ });
48
+
49
+ describe('auto-compaction partitioning (summarize the middle, never orphan a tool)', () => {
50
+ const msg = (role: ChatCompletionMessage['role'], content = 'x'): ChatCompletionMessage => ({ role, content });
51
+
52
+ it('walks the tail forward off a leading orphaned tool result', () => {
53
+ // A tail that would start on a `tool` message (its assistant call is in the
54
+ // summarized middle) must advance past it so nothing is orphaned.
55
+ const convo = [msg('user'), msg('assistant'), msg('tool'), msg('assistant'), msg('user')];
56
+ const start = compactTailStart(convo, 3); // last 3 = [tool, assistant, user]
57
+ expect(convo[start].role).not.toBe('tool');
58
+ });
59
+
60
+ it('assembled output is [system, memo, active directive, ...tail] and never orphans a tool', () => {
61
+ const convo: ChatCompletionMessage[] = [msg('user', 'task')];
62
+ for (let i = 0; i < 30; i++) convo.push(msg(i % 2 === 0 ? 'assistant' : 'tool', `s${i}`));
63
+ const out = assembleCompacted('SYS', convo, 'MEMO', compactTailStart(convo, COMPACT_TAIL_TURNS));
64
+ expect(out[0]).toEqual({ role: 'system', content: 'SYS' });
65
+ // Memo first (the compressed history), THEN the active directive verbatim — not the
66
+ // other way round, so the model reads the directive as the current instruction.
67
+ expect(out[1]).toEqual({ role: 'assistant', content: 'MEMO' });
68
+ expect(out[2].role).toBe('user');
69
+ expect(out[2].content).toBe('task');
70
+ // The first tail message after the directive is never an orphaned tool result.
71
+ expect(out[3].role).not.toBe('tool');
72
+ });
73
+
74
+ it('re-injects the MOST RECENT user directive, not the first, when several fell out of the tail', () => {
75
+ // The opening request, then a superseding instruction, then a long tool loop that
76
+ // pushes BOTH out of the verbatim tail. The active directive is the latest one.
77
+ const convo: ChatCompletionMessage[] = [msg('user', 'run a self-diagnostic'), msg('assistant', 'ok')];
78
+ convo.push(msg('user', 'now create the gap and fix the code'));
79
+ for (let i = 0; i < 30; i++) convo.push(msg(i % 2 === 0 ? 'assistant' : 'tool', `s${i}`));
80
+ const idx = pinnedDirectiveIndex(convo, compactTailStart(convo, COMPACT_TAIL_TURNS));
81
+ expect(convo[idx].content).toBe('now create the gap and fix the code');
82
+ const out = assembleCompacted('SYS', convo, 'MEMO', COMPACT_TAIL_TURNS);
83
+ const directive = out[2];
84
+ expect(directive.role).toBe('user');
85
+ expect(directive.content).toBe('now create the gap and fix the code');
86
+ // The stale opening request is NOT re-injected verbatim (it lives only in the memo).
87
+ expect(out.filter((m) => m.content === 'run a self-diagnostic')).toHaveLength(0);
88
+ });
89
+
90
+ it('keeps EVERY message from the covered end on — nothing falls between the memo and the tail', () => {
91
+ // The old fold summarised "all but the last eight" on a turn count, so messages that
92
+ // slid out of the tail between two folds were in neither the memo nor the tail.
93
+ const convo: ChatCompletionMessage[] = [msg('user', 'task')];
94
+ for (let i = 0; i < 30; i++) convo.push(msg('assistant', `a${i}`));
95
+ const out = assembleCompacted('SYS', convo, 'MEMO', 5);
96
+ // [system, memo, the covered directive 'task', ...convo[5..]]
97
+ expect(out[2]).toEqual({ role: 'user', content: 'task' });
98
+ expect(out.slice(3)).toEqual(convo.slice(5));
99
+ });
100
+
101
+ it('walks the verbatim start off tool results whose call the memo folded', () => {
102
+ const convo = [msg('user'), msg('assistant'), msg('tool'), msg('tool'), msg('assistant')];
103
+ expect(verbatimStart(convo, 2)).toBe(4);
104
+ expect(verbatimStart(convo, 99)).toBe(convo.length);
105
+ });
106
+
107
+ it('sizes the compacted tail by tokens, never below the minimum tail', () => {
108
+ // Small messages: far more than eight fit, so far more than eight are kept verbatim.
109
+ const small: ChatCompletionMessage[] = [msg('user', 'task')];
110
+ for (let i = 0; i < 30; i++) small.push(msg('assistant', 'short'));
111
+ expect(small.length - compactTailStartForBudget(small, 10_000)).toBeGreaterThan(COMPACT_TAIL_TURNS);
112
+ // Oversized messages: the minimum tail survives however large it is.
113
+ const big: ChatCompletionMessage[] = [msg('user', 'task')];
114
+ for (let i = 0; i < 30; i++) big.push(msg('assistant', 'x'.repeat(40_000)));
115
+ expect(big.length - compactTailStartForBudget(big, 10_000)).toBe(COMPACT_TAIL_TURNS);
116
+ });
117
+
118
+ it('does not re-inject the directive when the latest user turn already lives in the tail', () => {
119
+ const convo = [msg('user', 'task'), msg('assistant'), msg('user', 'later')];
120
+ // Latest user turn ('later') is inside the tail → nothing to re-inject.
121
+ expect(pinnedDirectiveIndex(convo, compactTailStart(convo, COMPACT_TAIL_TURNS))).toBe(-1);
122
+ const out = assembleCompacted('SYS', convo, 'MEMO', COMPACT_TAIL_TURNS);
123
+ expect(out.filter((m) => m.content === 'later')).toHaveLength(1);
124
+ });
125
+ });
@@ -0,0 +1,291 @@
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
+
15
+ import { defaultEstimateTokens, messageTokens as handoffMessageTokens, tokensOf as handoffTokensOf } from '../handoff/budget.js';
16
+ import type { HandoffMessage } from '../handoff/types.js';
17
+
18
+ /** A transcript message — the hand-off packer's shape, so both count a message alike. */
19
+ export type TranscriptMessage = HandoffMessage;
20
+
21
+ /** How much history we send to the model (message-count ceiling). */
22
+ export const HISTORY_WINDOW = 80;
23
+
24
+ /**
25
+ * Token budget for the working transcript sent to the model each turn — how much of this
26
+ * run the model can SEE: the file windows it read, the searches it ran, what it decided.
27
+ *
28
+ * It bounds context, which message-count windowing (HISTORY_WINDOW) alone does not: one
29
+ * `tasks.list` result can be tens of thousands of tokens. It is NOT what keeps a request
30
+ * inside the serving model's window — the gateway fits every request to a model that can
31
+ * hold it.
32
+ *
33
+ * It was 24k, "sized under the smallest pool model's window". That protected nothing — the
34
+ * ~16k-token system prompt + tool catalog in front of it already put a full turn at ~40k,
35
+ * past any 32k window — and it cost every coding run its memory. Six 4k-token file windows
36
+ * filled it, compaction folded them into a 1.2k-token note, and the model went back for the
37
+ * files it had just read (chat #105: 55 turns, 63% of calls revisiting, zero edits, prompt
38
+ * peak 40,351). 64k holds a coding task's working set — a dozen-plus file windows —
39
+ * verbatim, while a full turn stays well inside the 128k window every coding-capable pool
40
+ * model has. See {@link windowed} and {@link buildWorkingTranscript}.
41
+ */
42
+ export const HISTORY_TOKEN_BUDGET = 64_000;
43
+ /**
44
+ * How much of {@link HISTORY_TOKEN_BUDGET} the verbatim TAIL may keep when the older part
45
+ * of the transcript is compacted. The rest is headroom new work fills before the next
46
+ * fold, so the memo is re-folded once per ~20k tokens of progress, not on every turn.
47
+ */
48
+ export const COMPACT_TAIL_TOKEN_BUDGET = 40_000;
49
+
50
+ /** Estimated tokens for one message (content + tool-call payload + framing) — THE
51
+ * hand-off packer's estimate, so the working transcript and a hand-off to a smaller
52
+ * model count a message the same way. */
53
+ function messageTokens(m: TranscriptMessage): number {
54
+ return handoffMessageTokens(m, defaultEstimateTokens);
55
+ }
56
+
57
+ /**
58
+ * The compressed memory of a transcript's older part: `note` summarizes
59
+ * `transcript[0, coveredEnd)`; every message from `coveredEnd` on is sent verbatim.
60
+ */
61
+ export interface CompactMemo {
62
+ note: string;
63
+ coveredEnd: number;
64
+ }
65
+
66
+ /**
67
+ * What the working transcript is built from — the run's full transcript and its cached
68
+ * compressed memory. {@link buildWorkingTranscript} updates `compactMemo` in place.
69
+ */
70
+ export interface WorkingTranscriptState<M extends TranscriptMessage = TranscriptMessage> {
71
+ transcript: M[];
72
+ compactMemo: CompactMemo | null;
73
+ }
74
+
75
+ /**
76
+ * Trim the in-memory transcript to the history window before sending it to the
77
+ * model. Slicing the last N can leave the window starting on an `assistant`
78
+ * tool-call turn or an orphaned `tool` result (whose owning call fell off the
79
+ * front). That payload is invalid for strict vendors: Gemini rejects a request
80
+ * whose conversation does not begin with a user turn — surfaced as the cascade
81
+ * `[googleai] 400 INVALID_ARGUMENT` after a long tool-loop crossed the window
82
+ * boundary. So anchor the window at a user turn.
83
+ *
84
+ * If the last-N slice contains no user turn (a tool loop longer than the
85
+ * window), fall back to the most recent user turn in the FULL transcript and
86
+ * keep everything after it — correctness over the size cap.
87
+ */
88
+ export function windowed<M extends TranscriptMessage>(convo: M[]): M[] {
89
+ let w = convo.slice(-HISTORY_WINDOW);
90
+ while (w.length > 0 && w[0]!.role !== 'user') w = w.slice(1);
91
+ if (w.length === 0) {
92
+ const lastUser = convo.map((m) => m.role).lastIndexOf('user');
93
+ w = lastUser >= 0 ? convo.slice(lastUser) : convo.slice();
94
+ }
95
+ return tokenBounded(w);
96
+ }
97
+
98
+ /**
99
+ * Enforce the token budget on an already message-count-windowed slice. Drops the
100
+ * OLDEST turns first, then re-anchors on a user turn (a strict vendor rejects a window
101
+ * that doesn't start on `user`, and dropping a turn can orphan a `tool` result whose
102
+ * `assistant` tool-call fell off the front). The most recent user turn is never
103
+ * dropped: correctness over the budget when a single turn is itself oversized.
104
+ */
105
+ function tokenBounded<M extends TranscriptMessage>(w: M[]): M[] {
106
+ let total = transcriptTokens(w);
107
+ if (total <= HISTORY_TOKEN_BUDGET) return w;
108
+ const lastUser = w.map((m) => m.role).lastIndexOf('user');
109
+ let start = 0;
110
+ while (total > HISTORY_TOKEN_BUDGET && start < lastUser) {
111
+ total -= messageTokens(w[start]!);
112
+ start += 1;
113
+ }
114
+ let trimmed = w.slice(start);
115
+ while (trimmed.length > 1 && trimmed[0]!.role !== 'user') trimmed = trimmed.slice(1);
116
+ return trimmed;
117
+ }
118
+
119
+ /**
120
+ * Is a transcript message still part of what the model sees? False once auto-compaction
121
+ * has folded it into the memory note, or the drop-oldest window has let it fall off the
122
+ * front. Deliberately conservative: it judges against the CURRENT transcript (which has
123
+ * grown since the last working set was built), so it can only ever call a message gone a
124
+ * turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
125
+ */
126
+ export function stillInWorkingContext<M extends TranscriptMessage>(state: WorkingTranscriptState<M>, anchor: unknown): boolean {
127
+ const convo = state.transcript;
128
+ const idx = convo.indexOf(anchor as M);
129
+ if (idx < 0) return false;
130
+ if (state.compactMemo) return idx >= verbatimStart(convo, state.compactMemo.coveredEnd);
131
+ return windowed(convo).includes(convo[idx]!);
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Auto-compaction — summarize the bulky MIDDLE instead of dropping it.
136
+ //
137
+ // `tokenBounded` keeps the request inside the window by DROPPING the oldest turns. That
138
+ // never 413s, but it silently LOSES context — which made a weak model re-read files and
139
+ // thrash ("LOOP EXHAUSTED", chat #50). When a summarizer is available the older turns are
140
+ // compressed into ONE memory note instead, so the model keeps working from a distilled
141
+ // memory. Falls back to `tokenBounded` when no summarizer is reachable.
142
+ //
143
+ // Why this fold is NOT `packHandoff` (`../handoff`): the packer is stateless and gives the
144
+ // verbatim tail priority, handing the note whatever room the tail leaves. The working
145
+ // transcript needs the opposite on both counts — an INCREMENTAL memo reused across turns
146
+ // (one summarizer call per ~20k tokens of progress), a tail capped at
147
+ // COMPACT_TAIL_TOKEN_BUDGET so the note and the next turns have headroom, and a
148
+ // message-count window. What the two share — the token estimate — is the packer's.
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /** The fewest recent messages the verbatim tail keeps, however large they are. */
152
+ export const COMPACT_TAIL_TURNS = 8;
153
+
154
+ /** The most recent messages the verbatim tail may hold — half the message window, so a
155
+ * compacted transcript stays inside {@link HISTORY_WINDOW} with room to grow. */
156
+ const COMPACT_TAIL_MAX_MESSAGES = HISTORY_WINDOW / 2;
157
+
158
+ /** The first index at or after `from` that is not a `tool` result: a tool row whose
159
+ * assistant call was folded into the memo would be orphaned (strict vendors 400 on it). */
160
+ export function verbatimStart(convo: readonly TranscriptMessage[], from: number): number {
161
+ let start = Math.max(0, Math.min(from, convo.length));
162
+ while (start < convo.length && convo[start]!.role === 'tool') start += 1;
163
+ return start;
164
+ }
165
+
166
+ /** Start index of the last `tailTurns` messages, walked off a leading `tool` result. */
167
+ export function compactTailStart(convo: readonly TranscriptMessage[], tailTurns: number): number {
168
+ return verbatimStart(convo, convo.length - tailTurns);
169
+ }
170
+
171
+ /**
172
+ * Where the verbatim tail begins when the transcript is compacted: as many of the most
173
+ * recent messages as fit in `budgetTokens` — never fewer than {@link COMPACT_TAIL_TURNS},
174
+ * never more than {@link COMPACT_TAIL_MAX_MESSAGES} — walked off a leading tool result.
175
+ *
176
+ * Sized by TOKENS, not a message count: a fixed eight messages is four tool results, so
177
+ * after a fold the fifth file the model needed was always the one it had to read again.
178
+ */
179
+ export function compactTailStartForBudget(convo: readonly TranscriptMessage[], budgetTokens: number): number {
180
+ let start = convo.length;
181
+ let tokens = 0;
182
+ while (start > 0) {
183
+ const kept = convo.length - start;
184
+ if (kept >= COMPACT_TAIL_MAX_MESSAGES) break;
185
+ const next = messageTokens(convo[start - 1]!);
186
+ if (kept >= COMPACT_TAIL_TURNS && tokens + next > budgetTokens) break;
187
+ tokens += next;
188
+ start -= 1;
189
+ }
190
+ return verbatimStart(convo, start);
191
+ }
192
+
193
+ /**
194
+ * Index of the MOST RECENT user turn to re-inject verbatim ahead of the tail — the
195
+ * ACTIVE directive — or -1 when the latest user turn is already inside the tail. Pinning
196
+ * the FIRST user turn (the old behaviour) made a multi-instruction chat revert to its
197
+ * opening request (chat #55); the current instruction is always the LATEST user turn.
198
+ */
199
+ export function pinnedDirectiveIndex(convo: readonly TranscriptMessage[], tailStart: number): number {
200
+ const lastUser = convo.map((m) => m.role).lastIndexOf('user');
201
+ return lastUser >= 0 && lastUser < tailStart ? lastUser : -1;
202
+ }
203
+
204
+ /**
205
+ * Assemble the working transcript from a compressed-memory `note` that covers
206
+ * `convo[0, coveredEnd)`: system + the memory note + the ACTIVE user directive re-injected
207
+ * verbatim (when the note covers it) + EVERY message from `coveredEnd` on (tool-pairing
208
+ * safe via {@link verbatimStart}). Nothing is in neither the note nor the tail. The
209
+ * directive sits immediately before the tail so the model reads it as the CURRENT
210
+ * instruction.
211
+ */
212
+ export function assembleCompacted<M extends TranscriptMessage>(
213
+ systemPrompt: string,
214
+ convo: M[],
215
+ note: string,
216
+ coveredEnd: number,
217
+ ): M[] {
218
+ const tailStart = verbatimStart(convo, coveredEnd);
219
+ const out: M[] = [{ role: 'system', content: systemPrompt } as M];
220
+ out.push({ role: 'assistant', content: note } as M);
221
+ const directiveIdx = pinnedDirectiveIndex(convo, tailStart);
222
+ if (directiveIdx >= 0) out.push(convo[directiveIdx]!);
223
+ out.push(...convo.slice(tailStart));
224
+ return out;
225
+ }
226
+
227
+ /** Estimated tokens of a message list — the ONE count compaction budgets by, exported so
228
+ * a run measures what compaction kept out of a call with the same rule. */
229
+ export function transcriptTokens(msgs: readonly TranscriptMessage[]): number {
230
+ return handoffTokensOf(msgs, defaultEstimateTokens);
231
+ }
232
+
233
+ /** Can these messages (plus `extraTokens` in front of them) go to the model verbatim —
234
+ * inside both the token budget and the message window? */
235
+ function fitsVerbatim(msgs: readonly TranscriptMessage[], extraTokens = 0): boolean {
236
+ return msgs.length <= HISTORY_WINDOW && extraTokens + transcriptTokens(msgs) <= HISTORY_TOKEN_BUDGET;
237
+ }
238
+
239
+ /** What a fold reports: how many messages it newly compressed, the note it wrote, and
240
+ * the transcript index the note now covers up to (exclusive). */
241
+ export interface TranscriptFold {
242
+ droppedMessages: number;
243
+ note: string;
244
+ coveredEnd: number;
245
+ }
246
+
247
+ /**
248
+ * Build the working transcript for a turn. When the whole transcript fits → all of it,
249
+ * verbatim. Otherwise → a memory note of the older part plus EVERY message after it,
250
+ * verbatim; `onFolded` is told about each NEW fold, so the caller can record it (a
251
+ * visible step, a durable consolidation marker).
252
+ *
253
+ * The note is folded INCREMENTALLY, and only when it has to be. A note whose verbatim
254
+ * remainder still fits is reused as-is; once it no longer fits, the previous note plus
255
+ * exactly the messages since it are folded into a new one, up to a token-sized tail
256
+ * ({@link compactTailStartForBudget}). Falls back to drop-oldest when the summarizer is
257
+ * unavailable (`summarize` resolves null). A message-count overflow folds too.
258
+ */
259
+ export async function buildWorkingTranscript<M extends TranscriptMessage>(
260
+ state: WorkingTranscriptState<M>,
261
+ systemPrompt: string,
262
+ summarize: (msgs: M[]) => Promise<string | null>,
263
+ onFolded: (fold: TranscriptFold) => void,
264
+ ): Promise<M[]> {
265
+ const convo = state.transcript;
266
+ if (fitsVerbatim(convo)) {
267
+ state.compactMemo = null; // back under budget — a later overflow summarizes afresh
268
+ return [{ role: 'system', content: systemPrompt } as M, ...windowed(convo)];
269
+ }
270
+ // A note written against a transcript that has since been replaced covers nothing here.
271
+ const memo = state.compactMemo && state.compactMemo.coveredEnd <= convo.length ? state.compactMemo : null;
272
+ if (memo && fitsVerbatim(convo.slice(verbatimStart(convo, memo.coveredEnd)), defaultEstimateTokens(memo.note))) {
273
+ return assembleCompacted(systemPrompt, convo, memo.note, memo.coveredEnd);
274
+ }
275
+ const from = memo?.coveredEnd ?? 0;
276
+ const to = Math.max(from, compactTailStartForBudget(convo, COMPACT_TAIL_TOKEN_BUDGET));
277
+ const fold: M[] = memo
278
+ ? [{ role: 'assistant', content: memo.note } as M, ...convo.slice(from, to)]
279
+ : convo.slice(from, to);
280
+ const summary = to > from ? await summarize(fold) : null;
281
+ if (summary == null) {
282
+ // Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest.
283
+ return memo
284
+ ? assembleCompacted(systemPrompt, convo, memo.note, memo.coveredEnd)
285
+ : [{ role: 'system', content: systemPrompt } as M, ...windowed(convo)];
286
+ }
287
+ const note = `Compressed memory of the earlier part of this conversation:\n${summary}`;
288
+ state.compactMemo = { note, coveredEnd: to };
289
+ onFolded({ droppedMessages: to - from, note, coveredEnd: to });
290
+ return assembleCompacted(systemPrompt, convo, note, to);
291
+ }