@monotykamary/pi-vcc 0.3.16
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/README.md +688 -0
- package/__tests__/helpers.ts +135 -0
- package/__tests__/root-causes.test.ts +858 -0
- package/demo.gif +0 -0
- package/index.ts +21 -0
- package/knip.json +4 -0
- package/npm-shrinkwrap.json +3001 -0
- package/package.json +36 -0
- package/scripts/audit-sessions.ts +88 -0
- package/scripts/benchmark-real-sessions.ts +25 -0
- package/scripts/compare-before-after.ts +36 -0
- package/scripts/dump-branch-output.ts +20 -0
- package/src/commands/pi-vcc.ts +36 -0
- package/src/commands/vcc-recall.ts +65 -0
- package/src/core/brief.ts +497 -0
- package/src/core/build-sections.ts +431 -0
- package/src/core/content.ts +71 -0
- package/src/core/filter-noise.ts +42 -0
- package/src/core/format-recall.ts +177 -0
- package/src/core/format.ts +98 -0
- package/src/core/invisible-continue.ts +172 -0
- package/src/core/lineage.ts +26 -0
- package/src/core/load-messages.ts +40 -0
- package/src/core/normalize.ts +73 -0
- package/src/core/recall-scope.ts +49 -0
- package/src/core/render-entries.ts +58 -0
- package/src/core/report.ts +237 -0
- package/src/core/sanitize.ts +5 -0
- package/src/core/search-entries.ts +375 -0
- package/src/core/settings.ts +190 -0
- package/src/core/skill-collapse.ts +35 -0
- package/src/core/summarize.ts +179 -0
- package/src/core/tool-args.ts +14 -0
- package/src/details.ts +19 -0
- package/src/extract/commits.ts +69 -0
- package/src/extract/goals.ts +79 -0
- package/src/extract/preferences.ts +55 -0
- package/src/extract/shared-symbols.ts +357 -0
- package/src/hooks/before-compact.ts +564 -0
- package/src/hooks/proactive-threshold.ts +131 -0
- package/src/sections.ts +23 -0
- package/src/tools/recall.ts +204 -0
- package/src/types.ts +20 -0
- package/tests/australian-government.test.ts +479 -0
- package/tests/before-compact-hook.test.ts +185 -0
- package/tests/before-compact.test.ts +227 -0
- package/tests/brief.test.ts +215 -0
- package/tests/build-sections.test.ts +59 -0
- package/tests/compile.test.ts +89 -0
- package/tests/content.test.ts +66 -0
- package/tests/deep-extraction.test.ts +313 -0
- package/tests/extract-goals.test.ts +86 -0
- package/tests/extract-preferences.test.ts +30 -0
- package/tests/filter-noise.test.ts +61 -0
- package/tests/fixtures.ts +61 -0
- package/tests/format-recall.test.ts +87 -0
- package/tests/format.test.ts +73 -0
- package/tests/government-domain.test.ts +542 -0
- package/tests/lineage.test.ts +33 -0
- package/tests/load-messages.test.ts +49 -0
- package/tests/model-threshold-hook.test.ts +377 -0
- package/tests/model-threshold.test.ts +223 -0
- package/tests/normalize.test.ts +104 -0
- package/tests/proactive-threshold.test.ts +490 -0
- package/tests/real-sessions.test.ts +38 -0
- package/tests/recall-expand.test.ts +15 -0
- package/tests/recall-scope.test.ts +32 -0
- package/tests/recall-tool-scope.test.ts +67 -0
- package/tests/render-entries.test.ts +92 -0
- package/tests/report.test.ts +58 -0
- package/tests/sanitize.test.ts +24 -0
- package/tests/search-entries.test.ts +233 -0
- package/tests/support/load-session.ts +23 -0
- package/tests/support/real-sessions.ts +51 -0
- package/tests/threshold-integration.test.ts +359 -0
- package/tsconfig.json +20 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import type { NormalizedBlock } from "../types";
|
|
2
|
+
import { clip, firstLine } from "./content";
|
|
3
|
+
import { extractPath } from "./tool-args";
|
|
4
|
+
import { collapseSkillText } from "./skill-collapse";
|
|
5
|
+
|
|
6
|
+
const TRUNCATE_USER = 256;
|
|
7
|
+
const TRUNCATE_ASSISTANT = 200;
|
|
8
|
+
|
|
9
|
+
// Strip common self-reflective assistant prefixes that carry no semantic info.
|
|
10
|
+
// Conservative list: only removes the leading filler, preserves the actual content.
|
|
11
|
+
const SELF_TALK_PREFIX_RE =
|
|
12
|
+
/^\s*(?:hmm|wait|actually|oh|okay|ok|well|so)[,.!\s-]+/i;
|
|
13
|
+
|
|
14
|
+
// ── noise filtering ──
|
|
15
|
+
|
|
16
|
+
const isNoiseUser = (text: string): boolean => {
|
|
17
|
+
return !text.trim();
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// ── truncation ──
|
|
21
|
+
|
|
22
|
+
// Common stop words — don't count toward budget
|
|
23
|
+
const STOP_WORDS = new Set([
|
|
24
|
+
"a", "an", "the", "is", "are", "was", "were", "be", "been", "being",
|
|
25
|
+
"have", "has", "had", "do", "does", "did", "will", "would", "could",
|
|
26
|
+
"should", "may", "might", "shall", "can", "need", "must",
|
|
27
|
+
"to", "of", "in", "for", "on", "with", "at", "by", "from", "as",
|
|
28
|
+
"into", "through", "during", "before", "after", "above", "below",
|
|
29
|
+
"between", "under", "over",
|
|
30
|
+
"and", "but", "or", "nor", "not", "so", "yet", "both", "either",
|
|
31
|
+
"neither", "each", "every", "all", "any", "few", "more", "most",
|
|
32
|
+
"other", "some", "such", "no",
|
|
33
|
+
"that", "this", "these", "those", "it", "its",
|
|
34
|
+
"i", "me", "my", "we", "our", "you", "your", "he", "him", "his",
|
|
35
|
+
"she", "her", "they", "them", "their", "who", "which", "what",
|
|
36
|
+
"if", "then", "than", "when", "where", "how", "just", "also",
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
// Fast word-aware truncation: regex word split with stopword budget.
|
|
40
|
+
// Replaces Intl.Segmenter which was ~2× slower with identical output.
|
|
41
|
+
// Content words = consecutive letters (optionally followed by alphanumerics)
|
|
42
|
+
// or digit sequences. Stopwords don't count toward the budget.
|
|
43
|
+
const CONTENT_WORD_RE = /\p{L}[\p{L}\p{N}]*|\p{N}+/gu;
|
|
44
|
+
|
|
45
|
+
const truncateTokens = (text: string, limit: number): string => {
|
|
46
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
47
|
+
let count = 0;
|
|
48
|
+
let cutIdx = flat.length;
|
|
49
|
+
CONTENT_WORD_RE.lastIndex = 0;
|
|
50
|
+
let match: RegExpExecArray | null;
|
|
51
|
+
while ((match = CONTENT_WORD_RE.exec(flat)) !== null) {
|
|
52
|
+
if (!STOP_WORDS.has(match[0].toLowerCase())) {
|
|
53
|
+
count++;
|
|
54
|
+
if (count > limit) {
|
|
55
|
+
cutIdx = match.index;
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
cutIdx = match.index + match[0].length;
|
|
60
|
+
}
|
|
61
|
+
if (count <= limit) return flat;
|
|
62
|
+
return flat.slice(0, cutIdx).trimEnd() + "...(truncated)";
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// ── bash command compression ──
|
|
66
|
+
|
|
67
|
+
const BASH_CAP = 120;
|
|
68
|
+
const PIPE_TAIL_RE = /\s*\|\s*(?:head|tail|sort|wc|column|tr|cut|awk|uniq|python3|node|bun)(?:\s[^|]*)?$/;
|
|
69
|
+
|
|
70
|
+
/** Semantic compression: strip cd prefix, pipe tail formatting, cap length */
|
|
71
|
+
const compressBash = (raw: string): string => {
|
|
72
|
+
// Flatten multi-line: take first meaningful line
|
|
73
|
+
let cmd = raw.split("\n").map(l => l.trim()).filter(Boolean)[0] ?? raw;
|
|
74
|
+
// Strip cd <path> && prefix
|
|
75
|
+
cmd = cmd.replace(/^cd\s+\S+\s*&&\s*/, "");
|
|
76
|
+
// Strip pipe tail formatting commands (up to 3 times)
|
|
77
|
+
for (let i = 0; i < 3; i++) {
|
|
78
|
+
const stripped = cmd.replace(PIPE_TAIL_RE, "");
|
|
79
|
+
if (stripped === cmd) break;
|
|
80
|
+
cmd = stripped;
|
|
81
|
+
}
|
|
82
|
+
if (cmd.length > BASH_CAP) {
|
|
83
|
+
return cmd.slice(0, BASH_CAP - 3) + "...";
|
|
84
|
+
}
|
|
85
|
+
return cmd;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// ── tool summary ──
|
|
89
|
+
|
|
90
|
+
const TOOL_SUMMARY_FIELDS: Record<string, string> = {
|
|
91
|
+
Read: "file_path", Edit: "file_path", Write: "file_path",
|
|
92
|
+
read: "file_path", edit: "file_path", write: "file_path",
|
|
93
|
+
Glob: "pattern", Grep: "pattern",
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const toolOneLiner = (name: string, args: Record<string, unknown>): string => {
|
|
97
|
+
const field = TOOL_SUMMARY_FIELDS[name];
|
|
98
|
+
if (field && typeof args[field] === "string") {
|
|
99
|
+
return `* ${name} "${args[field] as string}"`;
|
|
100
|
+
}
|
|
101
|
+
const path = extractPath(args);
|
|
102
|
+
if (path) return `* ${name} "${path}"`;
|
|
103
|
+
if (name === "bash" || name === "Bash") {
|
|
104
|
+
const raw = (args.command ?? args.description ?? "") as string;
|
|
105
|
+
const cmd = compressBash(raw);
|
|
106
|
+
return `* ${name} "${cmd}"`;
|
|
107
|
+
}
|
|
108
|
+
if (typeof args.query === "string") {
|
|
109
|
+
return `* ${name} "${clip(args.query as string, 60)}"`;
|
|
110
|
+
}
|
|
111
|
+
return `* ${name}`;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
interface BriefLine {
|
|
115
|
+
/** Section header like "[user]", "[assistant]", "[tool_error] bash" */
|
|
116
|
+
header: string;
|
|
117
|
+
/** Content lines for this section */
|
|
118
|
+
lines: string[];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Structured transcript entry for JSON output */
|
|
122
|
+
export interface TranscriptEntry {
|
|
123
|
+
role: "user" | "assistant" | "tool_error";
|
|
124
|
+
text?: string;
|
|
125
|
+
tool?: string;
|
|
126
|
+
cmd?: string;
|
|
127
|
+
ref?: string;
|
|
128
|
+
/** Collapse count when identical tool calls are grouped */
|
|
129
|
+
count?: number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Build BriefLine sections from NormalizedBlocks.
|
|
134
|
+
*/
|
|
135
|
+
export const buildBriefSections = (blocks: NormalizedBlock[]): BriefLine[] => {
|
|
136
|
+
const sections: BriefLine[] = [];
|
|
137
|
+
let lastHeader = "";
|
|
138
|
+
|
|
139
|
+
const push = (header: string, line: string) => {
|
|
140
|
+
if (header === lastHeader && sections.length > 0) {
|
|
141
|
+
sections[sections.length - 1].lines.push(line);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
sections.push({ header, lines: [line] });
|
|
145
|
+
lastHeader = header;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
for (const b of blocks) {
|
|
149
|
+
switch (b.kind) {
|
|
150
|
+
case "user": {
|
|
151
|
+
if (isNoiseUser(b.text)) break;
|
|
152
|
+
const text = truncateTokens(collapseSkillText(b.text), TRUNCATE_USER);
|
|
153
|
+
if (text) {
|
|
154
|
+
const ref = b.sourceIndex != null ? ` (#${b.sourceIndex})` : "";
|
|
155
|
+
push("[user]", text + ref);
|
|
156
|
+
}
|
|
157
|
+
lastHeader = "[user]";
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
case "bash": {
|
|
161
|
+
const cmd = compressBash(b.command);
|
|
162
|
+
const ref = b.sourceIndex != null ? ` (#${b.sourceIndex})` : "";
|
|
163
|
+
if (cmd) {
|
|
164
|
+
push("[user]", `$ ${cmd}${ref}`);
|
|
165
|
+
}
|
|
166
|
+
lastHeader = "[user]";
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case "assistant": {
|
|
170
|
+
let raw = b.text;
|
|
171
|
+
// Strip leading self-talk prefix (up to 2x; assistants sometimes chain "Hmm, actually, ...")
|
|
172
|
+
for (let i = 0; i < 2; i++) {
|
|
173
|
+
const stripped = raw.replace(SELF_TALK_PREFIX_RE, "");
|
|
174
|
+
if (stripped === raw) break;
|
|
175
|
+
raw = stripped;
|
|
176
|
+
}
|
|
177
|
+
const text = truncateTokens(raw, TRUNCATE_ASSISTANT);
|
|
178
|
+
if (text) {
|
|
179
|
+
const ref = b.sourceIndex != null ? ` (#${b.sourceIndex})` : "";
|
|
180
|
+
push("[assistant]", text + ref);
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
case "tool_call": {
|
|
185
|
+
// Skip malformed tool calls from streaming providers (empty name / fragmented args).
|
|
186
|
+
if (!b.name || b.name.trim() === "") break;
|
|
187
|
+
const ref = b.sourceIndex != null ? ` (#${b.sourceIndex})` : "";
|
|
188
|
+
const summary = toolOneLiner(b.name, b.args) + ref;
|
|
189
|
+
push("[assistant]", summary);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
case "tool_result": {
|
|
193
|
+
if (b.isError) {
|
|
194
|
+
const body = firstLine(b.text, 150);
|
|
195
|
+
// Drop empty/placeholder error bodies — keep the line only if it carries info.
|
|
196
|
+
if (!body || body === "(no output)") break;
|
|
197
|
+
const ref = b.sourceIndex != null ? ` (#${b.sourceIndex})` : "";
|
|
198
|
+
const header = `[tool_error] ${b.name}${ref}`;
|
|
199
|
+
push(header, body);
|
|
200
|
+
lastHeader = header;
|
|
201
|
+
}
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
case "thinking":
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Collapse consecutive identical tool lines (same text, different #ref)
|
|
210
|
+
for (const sec of sections) {
|
|
211
|
+
if (sec.header !== "[assistant]") continue;
|
|
212
|
+
const out: string[] = [];
|
|
213
|
+
for (const line of sec.lines) {
|
|
214
|
+
if (!line.startsWith("* ")) { out.push(line); continue; }
|
|
215
|
+
const ref = line.match(/\(#(\d+)\)$/)?.[1] ?? "";
|
|
216
|
+
const base = ref ? line.slice(0, -(ref.length + 3)).trimEnd() : line;
|
|
217
|
+
const last = out.length > 0 ? out[out.length - 1] : "";
|
|
218
|
+
const m = last.match(/^(.*) \((#[\d, #]+)\) x(\d+)$/);
|
|
219
|
+
if (m && m[1] === base) {
|
|
220
|
+
out[out.length - 1] = `${base} (${m[2]}, #${ref}) x${parseInt(m[3]) + 1}`;
|
|
221
|
+
} else if (last.match(/\(#\d+\)$/) && last.replace(/\s*\(#\d+\)$/, "") === base) {
|
|
222
|
+
const prevRef = last.match(/\(#(\d+)\)$/)?.[1];
|
|
223
|
+
out[out.length - 1] = `${base} (#${prevRef}, #${ref}) x2`;
|
|
224
|
+
} else {
|
|
225
|
+
out.push(line);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
sec.lines = out;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Cap tool calls per [assistant] turn — keep tail (latest actions tend to
|
|
232
|
+
// be the deciding edits/writes; head is usually exploration noise).
|
|
233
|
+
const TOOL_CALLS_PER_TURN = 8;
|
|
234
|
+
for (const sec of sections) {
|
|
235
|
+
if (sec.header !== "[assistant]") continue;
|
|
236
|
+
const toolIdxs = sec.lines
|
|
237
|
+
.map((l, i) => (l.startsWith("* ") ? i : -1))
|
|
238
|
+
.filter((i) => i >= 0);
|
|
239
|
+
if (toolIdxs.length <= TOOL_CALLS_PER_TURN) continue;
|
|
240
|
+
const dropCount = toolIdxs.length - TOOL_CALLS_PER_TURN;
|
|
241
|
+
const dropSet = new Set(toolIdxs.slice(0, dropCount));
|
|
242
|
+
const firstKeptToolIdx = toolIdxs[dropCount];
|
|
243
|
+
const next: string[] = [];
|
|
244
|
+
let inserted = false;
|
|
245
|
+
for (let i = 0; i < sec.lines.length; i++) {
|
|
246
|
+
if (dropSet.has(i)) continue;
|
|
247
|
+
if (!inserted && i === firstKeptToolIdx) {
|
|
248
|
+
next.push(`* (${dropCount} earlier tool-call entries omitted)`);
|
|
249
|
+
inserted = true;
|
|
250
|
+
}
|
|
251
|
+
next.push(sec.lines[i]);
|
|
252
|
+
}
|
|
253
|
+
sec.lines = next;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Collapse consecutive identical [tool_error] sections (same tool, same body).
|
|
257
|
+
// E.g. 20 back-to-back `[tool_error] bash (#N) ... Command aborted` become one
|
|
258
|
+
// `[tool_error] bash (#refs...) x20` entry.
|
|
259
|
+
const collapsedErrors: BriefLine[] = [];
|
|
260
|
+
for (const sec of sections) {
|
|
261
|
+
const m = sec.header.match(/^\[tool_error\]\s+(\S+?)(?:\s*\(#(\d+)\))?$/);
|
|
262
|
+
if (!m || sec.lines.length !== 1) {
|
|
263
|
+
collapsedErrors.push(sec);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const tool = m[1];
|
|
267
|
+
const ref = m[2];
|
|
268
|
+
const body = sec.lines[0];
|
|
269
|
+
const prev = collapsedErrors[collapsedErrors.length - 1];
|
|
270
|
+
const prevMatch = prev?.header.match(
|
|
271
|
+
/^\[tool_error\]\s+(\S+?)\s*\(((?:#\d+(?:,\s*)?)+)\)(?:\s*x(\d+))?$/,
|
|
272
|
+
);
|
|
273
|
+
if (prev && prevMatch && prevMatch[1] === tool && prev.lines.length === 1 && prev.lines[0] === body) {
|
|
274
|
+
const refs = prevMatch[2] + (ref ? `, #${ref}` : "");
|
|
275
|
+
const count = prevMatch[3] ? parseInt(prevMatch[3]) + 1 : 2;
|
|
276
|
+
prev.header = `[tool_error] ${tool} (${refs}) x${count}`;
|
|
277
|
+
} else {
|
|
278
|
+
collapsedErrors.push(sec);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
sections.length = 0;
|
|
282
|
+
sections.push(...collapsedErrors);
|
|
283
|
+
|
|
284
|
+
return sections;
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Stringify BriefLine sections into text format.
|
|
289
|
+
*/
|
|
290
|
+
export const stringifyBrief = (sections: BriefLine[]): string => {
|
|
291
|
+
|
|
292
|
+
// Emit sections -- suppress blank lines between consecutive tool summaries
|
|
293
|
+
const out: string[] = [];
|
|
294
|
+
for (let i = 0; i < sections.length; i++) {
|
|
295
|
+
const sec = sections[i];
|
|
296
|
+
if (i > 0) {
|
|
297
|
+
const prev = sections[i - 1];
|
|
298
|
+
const prevIsTools = prev.header === "[assistant]" &&
|
|
299
|
+
prev.lines.every((l) => l.startsWith("* "));
|
|
300
|
+
const curIsTools = sec.header === "[assistant]" &&
|
|
301
|
+
sec.lines.every((l) => l.startsWith("* "));
|
|
302
|
+
if (!(prevIsTools && curIsTools)) {
|
|
303
|
+
out.push("");
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
out.push(sec.header);
|
|
307
|
+
for (const line of sec.lines) {
|
|
308
|
+
out.push(line);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return out.join("\n");
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
/** Parse a text line into a structured TranscriptEntry */
|
|
316
|
+
const parseToolLine = (line: string): { tool: string; cmd?: string; ref?: string; count?: number } | null => {
|
|
317
|
+
// * bash "cmd" (#5)
|
|
318
|
+
// * bash "cmd" (#1, #3) x2
|
|
319
|
+
// * tilth "query" (#7)
|
|
320
|
+
const m = line.match(/^\* (\S+)\s*(?:"([^"]*)")?\s*(?:\((#[\d, #]+)\))?\s*(?:x(\d+))?$/);
|
|
321
|
+
if (!m) return null;
|
|
322
|
+
return {
|
|
323
|
+
tool: m[1],
|
|
324
|
+
cmd: m[2] || undefined,
|
|
325
|
+
ref: m[3] || undefined,
|
|
326
|
+
count: m[4] ? parseInt(m[4]) : undefined,
|
|
327
|
+
};
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const extractRef = (text: string): { clean: string; ref?: string } => {
|
|
331
|
+
const m = text.match(/\s*\(#(\d+)\)$/);
|
|
332
|
+
if (!m) return { clean: text };
|
|
333
|
+
return { clean: text.slice(0, m.index).trimEnd(), ref: `#${m[1]}` };
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Convert BriefLine sections to structured TranscriptEntry array for JSON output.
|
|
338
|
+
*/
|
|
339
|
+
export const sectionsToTranscript = (sections: BriefLine[]): TranscriptEntry[] => {
|
|
340
|
+
const entries: TranscriptEntry[] = [];
|
|
341
|
+
|
|
342
|
+
for (const sec of sections) {
|
|
343
|
+
if (sec.header === "[user]") {
|
|
344
|
+
for (const line of sec.lines) {
|
|
345
|
+
const { clean, ref } = extractRef(line);
|
|
346
|
+
entries.push({ role: "user", text: clean, ...(ref && { ref }) });
|
|
347
|
+
}
|
|
348
|
+
} else if (sec.header === "[assistant]") {
|
|
349
|
+
for (const line of sec.lines) {
|
|
350
|
+
if (line.startsWith("* ")) {
|
|
351
|
+
const parsed = parseToolLine(line);
|
|
352
|
+
if (parsed) {
|
|
353
|
+
entries.push({
|
|
354
|
+
role: "assistant",
|
|
355
|
+
tool: parsed.tool,
|
|
356
|
+
...(parsed.cmd && { cmd: parsed.cmd }),
|
|
357
|
+
...(parsed.ref && { ref: parsed.ref }),
|
|
358
|
+
...(parsed.count && { count: parsed.count }),
|
|
359
|
+
});
|
|
360
|
+
} else {
|
|
361
|
+
// Fallback: unparseable tool line
|
|
362
|
+
const { clean, ref } = extractRef(line.slice(2));
|
|
363
|
+
entries.push({ role: "assistant", text: clean, ...(ref && { ref }) });
|
|
364
|
+
}
|
|
365
|
+
} else {
|
|
366
|
+
const { clean, ref } = extractRef(line);
|
|
367
|
+
entries.push({ role: "assistant", text: clean, ...(ref && { ref }) });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
} else if (sec.header.startsWith("[tool_error]")) {
|
|
371
|
+
// [tool_error] bash (#5)
|
|
372
|
+
const headerMatch = sec.header.match(/^\[tool_error\]\s+(\S+)\s*(?:\(#(\d+)\))?/);
|
|
373
|
+
const tool = headerMatch?.[1] ?? "unknown";
|
|
374
|
+
const ref = headerMatch?.[2] ? `#${headerMatch[2]}` : undefined;
|
|
375
|
+
for (const line of sec.lines) {
|
|
376
|
+
entries.push({
|
|
377
|
+
role: "tool_error",
|
|
378
|
+
tool,
|
|
379
|
+
text: line,
|
|
380
|
+
...(ref && { ref }),
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
return entries;
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
// ── convenience ──
|
|
390
|
+
|
|
391
|
+
/** Build and stringify the brief transcript in one call. */
|
|
392
|
+
export const compileBrief = (blocks: NormalizedBlock[]): string =>
|
|
393
|
+
stringifyBrief(buildBriefSections(blocks));
|
|
394
|
+
|
|
395
|
+
// ── turn identification (HCA zone) ──
|
|
396
|
+
|
|
397
|
+
const WRITE_TOOLS = new Set([
|
|
398
|
+
"Edit", "Write", "edit", "write", "MultiEdit",
|
|
399
|
+
]);
|
|
400
|
+
|
|
401
|
+
export interface TurnInfo {
|
|
402
|
+
/** Per-turn one-line summary */
|
|
403
|
+
summary: string;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Shorten a file path by taking the last 2 segments. */
|
|
407
|
+
const shortenPath = (p: string): string => {
|
|
408
|
+
const parts = p.split("/");
|
|
409
|
+
return parts.length > 2 ? parts.slice(-2).join("/") : p;
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Synthesize a one-line summary for a conversational turn.
|
|
414
|
+
* No LLM — purely algorithmic compression.
|
|
415
|
+
*/
|
|
416
|
+
const synthesizeTurnSummary = (
|
|
417
|
+
userText: string | null,
|
|
418
|
+
toolActions: string[],
|
|
419
|
+
): string => {
|
|
420
|
+
const parts: string[] = [];
|
|
421
|
+
|
|
422
|
+
// What was asked (truncated aggressively for HCA zone)
|
|
423
|
+
if (userText && userText.length > 3) {
|
|
424
|
+
parts.push(clip(userText, 50));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Key actions — dedup and cap
|
|
428
|
+
const uniqueActions = [...new Set(toolActions)].slice(0, 5);
|
|
429
|
+
if (uniqueActions.length > 0) {
|
|
430
|
+
const edits = uniqueActions.filter(a => a.startsWith("edited"));
|
|
431
|
+
const others = uniqueActions.filter(a => !a.startsWith("edited"));
|
|
432
|
+
if (edits.length > 0 && others.length <= 2) {
|
|
433
|
+
parts.push(uniqueActions.join(", "));
|
|
434
|
+
} else if (edits.length > 0) {
|
|
435
|
+
parts.push(edits.join(", "));
|
|
436
|
+
if (others.length > 0) parts.push(`+${others.length} more`);
|
|
437
|
+
} else {
|
|
438
|
+
parts.push(uniqueActions.join(", "));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return parts.join(" \u2192 ") || "(no actions)";
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Identify conversational turns and produce one-liner summaries.
|
|
447
|
+
*
|
|
448
|
+
* Each turn starts at a user/bash block and continues through assistant
|
|
449
|
+
* responses, tool calls, and tool results until the next user/bash block.
|
|
450
|
+
* This is the HCA zone — the heaviest compression layer that covers turns
|
|
451
|
+
* that would otherwise fall off the brief transcript's capBrief cutoff.
|
|
452
|
+
*/
|
|
453
|
+
export const identifyTurns = (blocks: NormalizedBlock[]): TurnInfo[] => {
|
|
454
|
+
const turns: TurnInfo[] = [];
|
|
455
|
+
let currentUserText: string | null = null;
|
|
456
|
+
const toolActions: string[] = [];
|
|
457
|
+
|
|
458
|
+
const flush = () => {
|
|
459
|
+
if (currentUserText === null && toolActions.length === 0) return;
|
|
460
|
+
turns.push({
|
|
461
|
+
summary: synthesizeTurnSummary(currentUserText, toolActions),
|
|
462
|
+
});
|
|
463
|
+
currentUserText = null;
|
|
464
|
+
toolActions.length = 0;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
for (const b of blocks) {
|
|
468
|
+
if (b.kind === "user" || b.kind === "bash") {
|
|
469
|
+
flush();
|
|
470
|
+
currentUserText = b.kind === "user"
|
|
471
|
+
? truncateTokens(collapseSkillText(b.text), 12)
|
|
472
|
+
: `$ ${compressBash(b.command)}`;
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
if (b.kind === "tool_call") {
|
|
476
|
+
if (!b.name || b.name.trim() === "") continue;
|
|
477
|
+
const path = extractPath(b.args);
|
|
478
|
+
const isWrite = WRITE_TOOLS.has(b.name);
|
|
479
|
+
if (isWrite && path) {
|
|
480
|
+
toolActions.push(`edited ${shortenPath(path)}`);
|
|
481
|
+
} else if (path) {
|
|
482
|
+
toolActions.push(`${b.name.toLowerCase()} ${shortenPath(path)}`);
|
|
483
|
+
} else if (b.name === "bash" || b.name === "Bash") {
|
|
484
|
+
const raw = (b.args.command ?? "") as string;
|
|
485
|
+
const cmd = compressBash(raw);
|
|
486
|
+
if (cmd) toolActions.push(`ran ${cmd}`);
|
|
487
|
+
} else {
|
|
488
|
+
toolActions.push(b.name.toLowerCase());
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
flush();
|
|
493
|
+
|
|
494
|
+
return turns;
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
|