pi-mega-compact 0.4.5 → 0.4.6
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/extensions/dashboard-server.js +450 -0
- package/dist/extensions/dashboard-server.test.js +111 -0
- package/dist/extensions/error-patterns.js +115 -0
- package/dist/extensions/mega-compact.js +782 -0
- package/dist/extensions/mega-compact.test.js +328 -0
- package/dist/extensions/openclaw-mega-compact.js +291 -0
- package/dist/src/adapt.js +106 -0
- package/dist/src/boundary.js +88 -0
- package/dist/src/boundary.test.js +53 -0
- package/dist/src/canary.js +118 -0
- package/dist/src/compact.js +250 -0
- package/dist/src/compact.test.js +78 -0
- package/dist/src/config/dedup.js +81 -0
- package/dist/src/config.js +12 -0
- package/dist/src/dedup/dedup.test.js +41 -0
- package/dist/src/dedup/digest.js +30 -0
- package/dist/src/dedup/l1-lsh.js +52 -0
- package/dist/src/dedup/l1-minhash.js +91 -0
- package/dist/src/dedup/l1-verify.js +54 -0
- package/dist/src/dedup/l1.test.js +50 -0
- package/dist/src/dedup/mmr.js +45 -0
- package/dist/src/dedup/normalize.js +39 -0
- package/dist/src/dedup/raptor/guardrails.js +83 -0
- package/dist/src/dedup/raptor/index.js +94 -0
- package/dist/src/dedup/raptor/kmeans.js +152 -0
- package/dist/src/dedup/raptor/raptor.test.js +205 -0
- package/dist/src/dedup/raptor/retrieval.js +81 -0
- package/dist/src/dedup/raptor/summarizer.js +85 -0
- package/dist/src/dedup/raptor/tree.js +177 -0
- package/dist/src/dedup/sprint12.test.js +219 -0
- package/dist/src/dedup/topk.js +60 -0
- package/dist/src/dedup-engine.test.js +447 -0
- package/dist/src/e2e.test.js +698 -0
- package/dist/src/embedder.js +102 -0
- package/dist/src/engine.js +137 -0
- package/dist/src/engine.test.js +111 -0
- package/dist/src/extractive.js +209 -0
- package/dist/src/extractive.test.js +130 -0
- package/dist/src/httpEmbedder.js +143 -0
- package/dist/src/log.js +47 -0
- package/dist/src/log.test.js +42 -0
- package/dist/src/minilm.js +92 -0
- package/dist/src/monitoring.js +131 -0
- package/dist/src/ratio.bench.test.js +897 -0
- package/dist/src/recall.integration.test.js +77 -0
- package/dist/src/recall.js +60 -0
- package/dist/src/recall.test.js +50 -0
- package/dist/src/sprint14.test.js +219 -0
- package/dist/src/store/backfill.js +189 -0
- package/dist/src/store/bloom.js +114 -0
- package/dist/src/store/compression.js +177 -0
- package/dist/src/store/compression.test.js +67 -0
- package/dist/src/store/integrity.js +44 -0
- package/dist/src/store/migrate.js +79 -0
- package/dist/src/store/migrate.test.js +139 -0
- package/dist/src/store/sprint10.test.js +186 -0
- package/dist/src/store/sqlite.js +574 -0
- package/dist/src/store.js +115 -0
- package/dist/src/store.test.js +142 -0
- package/dist/src/supersede.js +68 -0
- package/dist/src/supersede.test.js +36 -0
- package/dist/src/tokens.js +31 -0
- package/dist/src/types.js +8 -0
- package/dist/src/types.test.js +9 -0
- package/dist/src/vectorStore.js +465 -0
- package/dist/src/vectorStore.test.js +479 -0
- package/dist/src/wordpiece.js +129 -0
- package/package.json +4 -2
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* embedder.ts — pluggable text embedding for the local vector store.
|
|
3
|
+
*
|
|
4
|
+
* Default embedder is a zero-dependency, deterministic hashed n-gram bag
|
|
5
|
+
* encoder — no native build, no network, no external library, works offline.
|
|
6
|
+
* It is heuristic-strength (good enough to rank "which checkpoint is relevant
|
|
7
|
+
* to this query?"), not RAG-grade. A stronger LOCAL embedding backend (your own
|
|
8
|
+
* localhost ONNX/TEI/Ollama server) can be plugged in via MEGACOMPACT_EMBEDDING_URL
|
|
9
|
+
* — see httpEmbedder.ts. The `Embedder` interface is the seam both implement;
|
|
10
|
+
* this extension ships no model and makes no remote call (PREVENT-PI-004).
|
|
11
|
+
*/
|
|
12
|
+
import { HttpEmbedder, embeddingConfigFromEnv } from "./httpEmbedder.js";
|
|
13
|
+
/** Normalize a vector to unit length (cosine-sim safe). Returns a new array. */
|
|
14
|
+
export function l2Normalize(v) {
|
|
15
|
+
let sumSq = 0;
|
|
16
|
+
for (const x of v)
|
|
17
|
+
sumSq += x * x;
|
|
18
|
+
const norm = Math.sqrt(sumSq);
|
|
19
|
+
if (norm === 0)
|
|
20
|
+
return v.map(() => 0);
|
|
21
|
+
return v.map((x) => x / norm);
|
|
22
|
+
}
|
|
23
|
+
/** Cosine similarity in [-1, 1]. Assumes inputs are same dim. */
|
|
24
|
+
export function cosineSimilarity(a, b) {
|
|
25
|
+
if (a.length !== b.length)
|
|
26
|
+
return 0;
|
|
27
|
+
let dot = 0;
|
|
28
|
+
let na = 0;
|
|
29
|
+
let nb = 0;
|
|
30
|
+
for (let i = 0; i < a.length; i++) {
|
|
31
|
+
dot += a[i] * b[i];
|
|
32
|
+
na += a[i] * a[i];
|
|
33
|
+
nb += b[i] * b[i];
|
|
34
|
+
}
|
|
35
|
+
if (na === 0 || nb === 0)
|
|
36
|
+
return 0;
|
|
37
|
+
return dot / (Math.sqrt(na) * Math.sqrt(nb));
|
|
38
|
+
}
|
|
39
|
+
/** Stable 32-bit string hash (FNV-1a). */
|
|
40
|
+
function fnv1a(str) {
|
|
41
|
+
let h = 0x811c9dc5;
|
|
42
|
+
for (let i = 0; i < str.length; i++) {
|
|
43
|
+
h ^= str.charCodeAt(i);
|
|
44
|
+
h = Math.imul(h, 0x01000193);
|
|
45
|
+
}
|
|
46
|
+
return h >>> 0;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Default embedder: character 3-gram bag-of-counts, hashed into a fixed-dim
|
|
50
|
+
* vector, L2-normalized. Captures local lexical/structure overlap well enough
|
|
51
|
+
* for checkpoint relevance ranking.
|
|
52
|
+
*/
|
|
53
|
+
export class TrigramEmbedder {
|
|
54
|
+
dim;
|
|
55
|
+
seed;
|
|
56
|
+
constructor(dim = 512, seed = 0x9e3779b9) {
|
|
57
|
+
this.dim = dim;
|
|
58
|
+
this.seed = seed >>> 0;
|
|
59
|
+
}
|
|
60
|
+
embed(text) {
|
|
61
|
+
const vec = new Array(this.dim).fill(0);
|
|
62
|
+
const norm = text.toLowerCase().replace(/\s+/g, " ");
|
|
63
|
+
if (norm.length === 0)
|
|
64
|
+
return l2Normalize(vec);
|
|
65
|
+
// Whole-string + word + char-trigram signals.
|
|
66
|
+
vec[fnv1a(norm) % this.dim] += 1;
|
|
67
|
+
for (const word of norm.split(" ")) {
|
|
68
|
+
if (word.length === 0)
|
|
69
|
+
continue;
|
|
70
|
+
vec[fnv1a(word) % this.dim] += 1;
|
|
71
|
+
for (let i = 0; i + 3 <= word.length; i++) {
|
|
72
|
+
const gram = word.slice(i, i + 3);
|
|
73
|
+
const idx = (fnv1a(gram) ^ this.seed) % this.dim;
|
|
74
|
+
vec[idx] += 1;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Edge: very short tokens still get a slot.
|
|
78
|
+
if (norm.length < 3)
|
|
79
|
+
vec[fnv1a(norm) % this.dim] += 1;
|
|
80
|
+
return l2Normalize(vec);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Select the default embedder used by VectorStore.
|
|
85
|
+
*
|
|
86
|
+
* - If MEGACOMPACT_EMBEDDING_URL points at a localhost server, use HttpEmbedder
|
|
87
|
+
* (your own local embedding backend — ONNX/TEI/Ollama/etc). This is the
|
|
88
|
+
* PREVENT-PI-004-sanctioned "bring your own" path: the endpoint is a
|
|
89
|
+
* user-spawned loopback server, so conversation content never leaves the box.
|
|
90
|
+
* - Otherwise the TrigramEmbedder is the shipped default: zero-dependency,
|
|
91
|
+
* deterministic, GPU-free, cross-platform, fully offline.
|
|
92
|
+
*
|
|
93
|
+
* The `Embedder` interface is the seam for any LOCAL embedder. Never point it
|
|
94
|
+
* at a remote provider — that would violate PREVENT-PI-004. A user wanting
|
|
95
|
+
* semantic-grade dedup should run a local embedding server and set the URL.
|
|
96
|
+
*/
|
|
97
|
+
export function defaultEmbedder() {
|
|
98
|
+
const cfg = embeddingConfigFromEnv();
|
|
99
|
+
if (cfg)
|
|
100
|
+
return new HttpEmbedder(cfg);
|
|
101
|
+
return new TrigramEmbedder();
|
|
102
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* engine.ts — Layer 4 (PERSIST / checkpoint) orchestration.
|
|
3
|
+
*
|
|
4
|
+
* Ties the Sprint 1–2 primitives into the compaction pipeline the extension
|
|
5
|
+
* calls. Pure of any pi runtime type: it consumes EngineMessage[] and talks to
|
|
6
|
+
* the on-disk VectorStore. The extension adapts pi messages -> EngineMessage
|
|
7
|
+
* (see adapt.ts) and reports status.
|
|
8
|
+
*
|
|
9
|
+
* Pipeline (mirrors the PLAN Trident stack):
|
|
10
|
+
* SUPERSEDE (drop obsolete file reads)
|
|
11
|
+
* -> COLLAPSE (summarize the compacted slice)
|
|
12
|
+
* -> CLUSTER (embed + persist a checkpoint to the vector store)
|
|
13
|
+
*/
|
|
14
|
+
import { findSuperseded, supersede } from "./supersede.js";
|
|
15
|
+
import { summarizeMessages, mergeCompactSummaries, formatCompactSummary } from "./compact.js";
|
|
16
|
+
import { extractiveSummarize } from "./extractive.js";
|
|
17
|
+
import { estimateSessionTokens, estimateBlockTokens } from "./tokens.js";
|
|
18
|
+
import { computeRegionHash, VectorStore } from "./vectorStore.js";
|
|
19
|
+
/** Default store used by the convenience `compactSession`. */
|
|
20
|
+
let defaultStore;
|
|
21
|
+
export function getDefaultStore(stateDir) {
|
|
22
|
+
if (!defaultStore)
|
|
23
|
+
defaultStore = new VectorStore({ stateDir });
|
|
24
|
+
return defaultStore;
|
|
25
|
+
}
|
|
26
|
+
/** Replace the default store (used by tests to inject a temp dir). */
|
|
27
|
+
export function setDefaultStore(store) {
|
|
28
|
+
defaultStore = store;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Run the Trident pipeline over a message slice and persist a checkpoint.
|
|
32
|
+
*
|
|
33
|
+
* `messages` is the FULL session view; `keepFrom` marks where the verbatim tail
|
|
34
|
+
* starts, so indices stay absolute and the caller can map the drop range back
|
|
35
|
+
* onto the real (pi) message array via adapt.ts. Returns a `skipped` result
|
|
36
|
+
* when the compactable slice is empty.
|
|
37
|
+
*/
|
|
38
|
+
export function compactSession(input, store = getDefaultStore()) {
|
|
39
|
+
const keepFrom = input.keepFrom ?? input.messages.length;
|
|
40
|
+
const compactable = input.messages.slice(0, keepFrom);
|
|
41
|
+
const compactedFrom = keepFrom;
|
|
42
|
+
if (compactable.length === 0) {
|
|
43
|
+
return {
|
|
44
|
+
skipped: true,
|
|
45
|
+
deduped: false,
|
|
46
|
+
summary: "",
|
|
47
|
+
regionHash: "",
|
|
48
|
+
tokenEstimate: 0,
|
|
49
|
+
originalTokenEstimate: 0,
|
|
50
|
+
compactedFrom,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// LAYER 1 — SUPERSEDE: zero-cost factual pruning of obsolete file reads.
|
|
54
|
+
const supersededIdx = new Set(findSuperseded(compactable));
|
|
55
|
+
const keep = compactable.filter((_m, i) => !supersededIdx.has(i));
|
|
56
|
+
// LAYER 2 — COLLAPSE: build (or accept) the summary.
|
|
57
|
+
// When useExtractiveSummary is enabled (default), use the deterministic
|
|
58
|
+
// extractive engine that compresses ~70K tokens → ~2K tokens with structured
|
|
59
|
+
// fields populated. Falls back to legacy concatenation when disabled.
|
|
60
|
+
const useExtractive = input.useExtractiveSummary !== false;
|
|
61
|
+
let summary;
|
|
62
|
+
let topicSummary;
|
|
63
|
+
let keyDecisions;
|
|
64
|
+
let nextSteps;
|
|
65
|
+
let filesModified;
|
|
66
|
+
if (useExtractive && !input.summary) {
|
|
67
|
+
const ext = extractiveSummarize(keep);
|
|
68
|
+
summary = ext.topicSummary;
|
|
69
|
+
topicSummary = ext.topicSummary;
|
|
70
|
+
keyDecisions = input.keyDecisions ?? ext.keyDecisions;
|
|
71
|
+
nextSteps = input.nextSteps ?? ext.nextSteps;
|
|
72
|
+
filesModified = input.filesModified ?? ext.filesModified;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
const collapsed = input.summary ?? summarizeMessages(keep);
|
|
76
|
+
summary = formatCompactSummary(collapsed);
|
|
77
|
+
topicSummary = undefined;
|
|
78
|
+
keyDecisions = input.keyDecisions ?? [];
|
|
79
|
+
nextSteps = input.nextSteps ?? [];
|
|
80
|
+
filesModified = input.filesModified ?? [];
|
|
81
|
+
}
|
|
82
|
+
// Honest "tokens saved" accounting:
|
|
83
|
+
// - originalTokenEstimate = the dropped region's token count (what context
|
|
84
|
+
// held before compaction) = the compacted slice's tokens.
|
|
85
|
+
// - storedTokens = the persisted summary's token count, computed from the
|
|
86
|
+
// actual summary string so it's honest for BOTH the extractive and legacy
|
|
87
|
+
// COLLAPSE paths (the legacy path's fallback estimateSessionTokens is the
|
|
88
|
+
// *original* size, not the stored size).
|
|
89
|
+
const originalTokenEstimate = estimateSessionTokens(compactable);
|
|
90
|
+
const storedTokens = estimateBlockTokens(summary);
|
|
91
|
+
// Region text = the compacted slice, used for dedup + embedding.
|
|
92
|
+
const regionText = input.regionText ?? keep.map((m) => m.text).join("\n");
|
|
93
|
+
const regionHash = computeRegionHash(regionText);
|
|
94
|
+
const add = store.add({
|
|
95
|
+
sessionId: input.sessionId,
|
|
96
|
+
summary,
|
|
97
|
+
topicSummary,
|
|
98
|
+
keyDecisions,
|
|
99
|
+
nextSteps,
|
|
100
|
+
filesModified,
|
|
101
|
+
regionText,
|
|
102
|
+
tokenEstimate: storedTokens,
|
|
103
|
+
originalTokenEstimate,
|
|
104
|
+
timestamp: input.timestamp ?? 0,
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
skipped: false,
|
|
108
|
+
deduped: add.deduped,
|
|
109
|
+
dedupReason: add.reason,
|
|
110
|
+
checkpointId: add.checkpoint.checkpointId,
|
|
111
|
+
summary,
|
|
112
|
+
regionHash,
|
|
113
|
+
tokenEstimate: storedTokens,
|
|
114
|
+
originalTokenEstimate,
|
|
115
|
+
compactedFrom,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Layer 5 (query side, shared by auto-inline + on-demand): search the store and
|
|
120
|
+
* drop any checkpoint already injected this session. The caller decides how to
|
|
121
|
+
* inject (Sprint 4 wires injection); this module only does the deduped search.
|
|
122
|
+
*/
|
|
123
|
+
export function recall(input, store = getDefaultStore()) {
|
|
124
|
+
const hits = store.search(input.sessionId, input.query, input.limit ?? 3);
|
|
125
|
+
const newHits = input.skipInjected === false ? hits : hits.filter((h) => !store.wasInjected(input.sessionId, h.checkpoint.checkpointId));
|
|
126
|
+
return { hits, newHits };
|
|
127
|
+
}
|
|
128
|
+
/** Merge a freshly compacted summary into the prior persisted summary text. */
|
|
129
|
+
export function mergeSummary(existing, next) {
|
|
130
|
+
return mergeCompactSummaries(existing, next);
|
|
131
|
+
}
|
|
132
|
+
/** Exposed for callers that want raw supersede stats (status reporting). */
|
|
133
|
+
export function supersededCount(messages) {
|
|
134
|
+
return new Set(findSuperseded(messages)).size;
|
|
135
|
+
}
|
|
136
|
+
/** Re-export so the extension has one import surface. */
|
|
137
|
+
export { supersede, summarizeMessages, formatCompactSummary };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { VectorStore } from "./vectorStore.js";
|
|
7
|
+
import { compactSession, recall, mergeSummary, supersededCount } from "./engine.js";
|
|
8
|
+
const baseTmp = mkdtempSync(join(tmpdir(), "mc-engine-"));
|
|
9
|
+
let counter = 0;
|
|
10
|
+
function store() {
|
|
11
|
+
return new VectorStore({ dedupSim: 0.9, stateDir: join(baseTmp, `run-${counter++}`) });
|
|
12
|
+
}
|
|
13
|
+
const SESS = "sess_engine";
|
|
14
|
+
function msg(role, text, toolName) {
|
|
15
|
+
return toolName ? { role, text, toolName, input: text, output: text } : { role, text };
|
|
16
|
+
}
|
|
17
|
+
test("compactSession supersedes then persists a checkpoint", () => {
|
|
18
|
+
const s = store();
|
|
19
|
+
const messages = [
|
|
20
|
+
msg("user", "read src/server.ts"),
|
|
21
|
+
msg("assistant", "ok", "Read"),
|
|
22
|
+
msg("user", "edit src/server.ts"),
|
|
23
|
+
msg("assistant", "ok", "Edit"),
|
|
24
|
+
msg("user", "now fix the bug in src/server.ts"),
|
|
25
|
+
msg("assistant", "done", "Edit"),
|
|
26
|
+
];
|
|
27
|
+
const r = compactSession({ sessionId: SESS, messages, keepFrom: 4, timestamp: 1 }, s);
|
|
28
|
+
assert.equal(r.skipped, false);
|
|
29
|
+
assert.equal(r.deduped, false);
|
|
30
|
+
assert.match(r.checkpointId ?? "", /^chkpt_001$/);
|
|
31
|
+
assert.ok(r.summary.length > 0, "summary produced by COLLAPSE");
|
|
32
|
+
assert.ok(r.regionHash.length > 0);
|
|
33
|
+
// SUPERSEDE dropped the obsolete first read turn (user read @0 superseded by
|
|
34
|
+
// the edit @2) — so exactly one superseded message in the compacted slice.
|
|
35
|
+
assert.equal(supersededCount(messages.slice(0, 4)), 1);
|
|
36
|
+
assert.equal(r.compactedFrom, 4);
|
|
37
|
+
// The persisted checkpoint is searchable.
|
|
38
|
+
assert.equal(s.search(SESS, "bug src/server.ts", 5).length, 1);
|
|
39
|
+
});
|
|
40
|
+
test("compactSession is idempotent on identical region (dedup sentinel)", () => {
|
|
41
|
+
const s = store();
|
|
42
|
+
const messages = [
|
|
43
|
+
msg("user", "alpha work on the parser"),
|
|
44
|
+
msg("assistant", "did it", "Edit"),
|
|
45
|
+
msg("user", "beta work on the renderer"),
|
|
46
|
+
msg("assistant", "done", "Edit"),
|
|
47
|
+
];
|
|
48
|
+
const r1 = compactSession({ sessionId: SESS, messages, keepFrom: 4, timestamp: 1 }, s);
|
|
49
|
+
const r2 = compactSession({ sessionId: SESS, messages, keepFrom: 4, timestamp: 2 }, s);
|
|
50
|
+
assert.equal(r1.deduped, false);
|
|
51
|
+
assert.equal(r2.deduped, true);
|
|
52
|
+
assert.equal(r1.checkpointId, r2.checkpointId);
|
|
53
|
+
assert.equal(s.search(SESS, "parser", 10).length, 1);
|
|
54
|
+
});
|
|
55
|
+
test("compactSession skipped when slice is empty", () => {
|
|
56
|
+
const s = store();
|
|
57
|
+
const r = compactSession({ sessionId: SESS, messages: [msg("user", "only tail")], keepFrom: 0 }, s);
|
|
58
|
+
assert.equal(r.skipped, true);
|
|
59
|
+
assert.equal(s.search(SESS, "x", 5).length, 0);
|
|
60
|
+
});
|
|
61
|
+
test("recall drops already-injected checkpoints", () => {
|
|
62
|
+
const s = store();
|
|
63
|
+
compactSession({ sessionId: SESS, messages: [msg("user", "investigated src/vectorStore.ts"), msg("assistant", "ok", "Edit")], keepFrom: 2, timestamp: 1 }, s);
|
|
64
|
+
const first = recall({ sessionId: SESS, query: "vectorStore", limit: 5, skipInjected: true }, s);
|
|
65
|
+
assert.equal(first.newHits.length, 1);
|
|
66
|
+
s.markInjected(SESS, first.hits[0].checkpoint.checkpointId);
|
|
67
|
+
const second = recall({ sessionId: SESS, query: "vectorStore", limit: 5, skipInjected: true }, s);
|
|
68
|
+
assert.equal(second.newHits.length, 0);
|
|
69
|
+
// Without the skip flag, both hits still surface.
|
|
70
|
+
assert.equal(second.hits.length, 1);
|
|
71
|
+
});
|
|
72
|
+
test("mergeSummary accumulates prior + new context", () => {
|
|
73
|
+
const prior = "<summary>Conversation summary:\n- Key files referenced: src/a.ts.\n</summary>";
|
|
74
|
+
const next = "<summary>Conversation summary:\n- Key files referenced: src/b.ts.\n</summary>";
|
|
75
|
+
const merged = mergeSummary(prior, next);
|
|
76
|
+
assert.ok(merged.includes("src/a.ts"));
|
|
77
|
+
assert.ok(merged.includes("src/b.ts"));
|
|
78
|
+
assert.ok(merged.includes("Newly compacted"));
|
|
79
|
+
});
|
|
80
|
+
test("supersededCount reports obsolete reads", () => {
|
|
81
|
+
const messages = [
|
|
82
|
+
msg("user", "read src/x.ts"),
|
|
83
|
+
msg("assistant", "ok", "Read"),
|
|
84
|
+
msg("user", "write src/x.ts"),
|
|
85
|
+
msg("assistant", "ok", "Edit"),
|
|
86
|
+
];
|
|
87
|
+
assert.equal(supersededCount(messages), 1);
|
|
88
|
+
});
|
|
89
|
+
test("compactSession with useExtractive produces topicSummary on checkpoint", () => {
|
|
90
|
+
const s = store();
|
|
91
|
+
const messages = [
|
|
92
|
+
msg("user", "let's refactor the auth module in src/auth.ts"),
|
|
93
|
+
msg("assistant", "I'll start by reading the current implementation", "Read"),
|
|
94
|
+
msg("user", "extract the login logic into a separate function"),
|
|
95
|
+
msg("assistant", "Extracted login() into src/auth.ts:45", "Edit"),
|
|
96
|
+
msg("user", "now add the session token generation"),
|
|
97
|
+
msg("assistant", "Added generateSessionToken in src/auth.ts:78", "Edit"),
|
|
98
|
+
];
|
|
99
|
+
const r = compactSession({ sessionId: "sess_extr", messages, keepFrom: 4, timestamp: 1, useExtractiveSummary: true }, s);
|
|
100
|
+
assert.equal(r.skipped, false);
|
|
101
|
+
assert.ok(r.checkpointId, "checkpoint created");
|
|
102
|
+
// The checkpoint should have topicSummary populated
|
|
103
|
+
const hits = s.search("sess_extr", "auth refactor", 5);
|
|
104
|
+
assert.ok(hits.length > 0);
|
|
105
|
+
// topicSummary should be present on the stored checkpoint (via extractive path)
|
|
106
|
+
assert.ok(hits[0].checkpoint.topicSummary, "topicSummary should be populated when useExtractive is true");
|
|
107
|
+
assert.ok(hits[0].checkpoint.topicSummary.length > 0);
|
|
108
|
+
});
|
|
109
|
+
test("cleanup", () => {
|
|
110
|
+
rmSync(baseTmp, { recursive: true, force: true });
|
|
111
|
+
});
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* extractive.ts — deterministic, LLM-free extractive summary engine.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the "Key timeline" dump in compact.ts with structured extraction:
|
|
5
|
+
* topicSummary (one paragraph), keyDecisions, nextSteps, filesModified.
|
|
6
|
+
*
|
|
7
|
+
* Target compression: 70K tokens → ~2K tokens (35:1).
|
|
8
|
+
* Deterministic: same messages → same output, every time.
|
|
9
|
+
*/
|
|
10
|
+
import { estimateBlockTokens } from "./tokens.js";
|
|
11
|
+
// ---- Limits ----------------------------------------------------------------
|
|
12
|
+
const MAX_RECENT_USER = 3;
|
|
13
|
+
const MAX_DECISIONS = 5;
|
|
14
|
+
const MAX_FILES = 10;
|
|
15
|
+
const MAX_PENDING = 5;
|
|
16
|
+
const MAX_TOPIC_LINES = 12;
|
|
17
|
+
// ---- Truncation helper -----------------------------------------------------
|
|
18
|
+
function truncate(s, maxLen) {
|
|
19
|
+
if (s.length <= maxLen)
|
|
20
|
+
return s;
|
|
21
|
+
return s.slice(0, maxLen - 1) + "…";
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Build a one-paragraph topic summary from the message slice.
|
|
25
|
+
*
|
|
26
|
+
* This is the compressed replacement for the raw "Key timeline" loop.
|
|
27
|
+
* Captures: tools used, recent user requests, current work, key files,
|
|
28
|
+
* pending work. Typically 12 lines / ~500 tokens instead of ~70K.
|
|
29
|
+
*/
|
|
30
|
+
function buildTopicSummary(messages, tools, recentUser, currentWork, keyFiles, pending) {
|
|
31
|
+
const lines = [];
|
|
32
|
+
// Scope line
|
|
33
|
+
const users = messages.filter((m) => m.role === "user");
|
|
34
|
+
const assistants = messages.filter((m) => m.role === "assistant");
|
|
35
|
+
const toolMsgs = messages.filter((m) => m.role === "tool");
|
|
36
|
+
lines.push(`Conversation: ${messages.length} messages (${users.length} user, ` +
|
|
37
|
+
`${assistants.length} assistant, ${toolMsgs.length} tool). ` +
|
|
38
|
+
(tools.length ? `Tools: ${tools.join(", ")}.` : "No tools used."));
|
|
39
|
+
// Recent user requests
|
|
40
|
+
if (recentUser.length) {
|
|
41
|
+
lines.push("User requests:");
|
|
42
|
+
for (const r of recentUser)
|
|
43
|
+
lines.push(` • ${r}`);
|
|
44
|
+
}
|
|
45
|
+
// Current work
|
|
46
|
+
if (currentWork)
|
|
47
|
+
lines.push(`Current work: ${currentWork}`);
|
|
48
|
+
// Key files
|
|
49
|
+
if (keyFiles.length)
|
|
50
|
+
lines.push(`Key files: ${keyFiles.join(", ")}.`);
|
|
51
|
+
// Pending work
|
|
52
|
+
if (pending.length) {
|
|
53
|
+
lines.push("Pending work:");
|
|
54
|
+
for (const p of pending)
|
|
55
|
+
lines.push(` • ${p}`);
|
|
56
|
+
}
|
|
57
|
+
// Cap total length
|
|
58
|
+
return lines.slice(0, MAX_TOPIC_LINES).join("\n");
|
|
59
|
+
}
|
|
60
|
+
// ---- File path extraction --------------------------------------------------
|
|
61
|
+
const INTERESTING_EXT = new Set(["rs", "ts", "tsx", "js", "json", "md"]);
|
|
62
|
+
const FILE_PATH_RE = /(?:^|\s)([^\s"`']+\.(rs|ts|tsx|js|json|md|py|sh|sql|toml|yaml|yml|css|html))\b/g;
|
|
63
|
+
function extractFilePaths(text) {
|
|
64
|
+
const paths = [];
|
|
65
|
+
for (const m of text.matchAll(FILE_PATH_RE)) {
|
|
66
|
+
const filePath = m[1];
|
|
67
|
+
const ext = m[2];
|
|
68
|
+
const basename = filePath.split("/").pop() ?? filePath;
|
|
69
|
+
if (basename === "node_modules" || filePath.includes("node_modules/"))
|
|
70
|
+
continue;
|
|
71
|
+
if (INTERESTING_EXT.has(ext))
|
|
72
|
+
paths.push(filePath);
|
|
73
|
+
}
|
|
74
|
+
return paths;
|
|
75
|
+
}
|
|
76
|
+
// ---- Recent user requests (existing logic, kept) ---------------------------
|
|
77
|
+
function collectRecentUserRequests(messages, limit) {
|
|
78
|
+
const requests = [];
|
|
79
|
+
for (let i = messages.length - 1; i >= 0 && requests.length < limit; i--) {
|
|
80
|
+
if (messages[i].role === "user") {
|
|
81
|
+
let snippet = messages[i].text.split("\n").slice(0, 3).join(" ");
|
|
82
|
+
snippet = snippet.replace(/^.+\nProcessed\$?\s*/i, "").replace(/\n/g, " ");
|
|
83
|
+
requests.push(truncate(snippet, 200));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return requests.reverse();
|
|
87
|
+
}
|
|
88
|
+
// ---- Pending work (existing logic, kept) -----------------------------------
|
|
89
|
+
const PENDING_WORDS = ["todo", "next", "pending", "follow up", "remaining"];
|
|
90
|
+
function inferPendingWork(messages) {
|
|
91
|
+
const pending = [];
|
|
92
|
+
const recent = messages.slice(-5);
|
|
93
|
+
for (const m of recent) {
|
|
94
|
+
const t = m.text.toLowerCase();
|
|
95
|
+
if (PENDING_WORDS.some((w) => t.includes(w))) {
|
|
96
|
+
const snippet = m.text.split("\n").find((l) => PENDING_WORDS.some((w) => l.toLowerCase().includes(w)));
|
|
97
|
+
if (snippet)
|
|
98
|
+
pending.push(truncate(snippet.trim(), 180));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return [...new Set(pending)].slice(0, MAX_PENDING);
|
|
102
|
+
}
|
|
103
|
+
// ---- Current work (existing logic, kept) -----------------------------------
|
|
104
|
+
function inferCurrentWork(messages) {
|
|
105
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
106
|
+
const m = messages[i];
|
|
107
|
+
if (m.role !== "assistant")
|
|
108
|
+
continue;
|
|
109
|
+
const path = m.text.match(/(?:^|\s)([^\s"`':]+\.(rs|ts|tsx|js|json|md|py|toml|yaml|yml|sql))\b/m);
|
|
110
|
+
if (path) {
|
|
111
|
+
const line = m.text.split("\n").slice(0, 2).join(" ");
|
|
112
|
+
return truncate(line, 200);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
// ---- Key decisions ---------------------------------------------------------
|
|
118
|
+
const DECISION_PATTERNS = [
|
|
119
|
+
/(?:I('ll| will| decided to| chose to| recommend| suggest))\s+(.{10,120})/i,
|
|
120
|
+
/(?:let's|we('ll| should| can| will))\s+(.{10,120})/i,
|
|
121
|
+
/(?:the (?:plan|approach|decision|strategy) is (?:to )?)\s*(.{10,120})/i,
|
|
122
|
+
/(?:going (?:with|forward))\s+(.{10,120})/i,
|
|
123
|
+
];
|
|
124
|
+
function extractDecisions(messages) {
|
|
125
|
+
const decisions = [];
|
|
126
|
+
// Only look at assistant messages (they make/receive decisions)
|
|
127
|
+
for (const m of messages) {
|
|
128
|
+
if (m.role !== "assistant")
|
|
129
|
+
continue;
|
|
130
|
+
const text = m.text;
|
|
131
|
+
if (!text || text.length < 20)
|
|
132
|
+
continue;
|
|
133
|
+
for (const pat of DECISION_PATTERNS) {
|
|
134
|
+
const match = text.match(pat);
|
|
135
|
+
if (match) {
|
|
136
|
+
const decision = match[2]?.trim();
|
|
137
|
+
if (decision && decision.length > 10) {
|
|
138
|
+
decisions.push(truncate(decision, 150));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (decisions.length >= MAX_DECISIONS)
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
return [...new Set(decisions)];
|
|
146
|
+
}
|
|
147
|
+
// ---- Files modified --------------------------------------------------------
|
|
148
|
+
function extractFilesModified(tools) {
|
|
149
|
+
const files = new Set();
|
|
150
|
+
for (const m of tools) {
|
|
151
|
+
if (!m.toolName)
|
|
152
|
+
continue;
|
|
153
|
+
const name = m.toolName.toLowerCase();
|
|
154
|
+
if (name === "write" || name === "edit" || name === "notebookedit") {
|
|
155
|
+
// Extract file path from input payload
|
|
156
|
+
const input = m.input ?? m.text;
|
|
157
|
+
const pathMatch = input.match(/["']?(\/[^\s"']+\.\w+)["']?/);
|
|
158
|
+
if (pathMatch)
|
|
159
|
+
files.add(pathMatch[1]);
|
|
160
|
+
}
|
|
161
|
+
if (name === "bash") {
|
|
162
|
+
const cmd = m.input ?? m.text;
|
|
163
|
+
if (cmd.includes("git add") || cmd.includes("git commit") || cmd.includes("git diff")) {
|
|
164
|
+
for (const p of extractFilePaths(cmd))
|
|
165
|
+
files.add(p);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return [...files].slice(0, MAX_FILES);
|
|
170
|
+
}
|
|
171
|
+
// ---- Public API ------------------------------------------------------------
|
|
172
|
+
/**
|
|
173
|
+
* Deterministic extractive summary. Same messages → same output, every time.
|
|
174
|
+
*
|
|
175
|
+
* Returns structured data + a pre-formatted topicSummary string.
|
|
176
|
+
* Compression target: 70K tokens → ~2K tokens.
|
|
177
|
+
*/
|
|
178
|
+
export function extractiveSummarize(messages) {
|
|
179
|
+
if (messages.length === 0) {
|
|
180
|
+
return { topicSummary: "(empty)", keyDecisions: [], nextSteps: [], filesModified: [], tokenEstimate: 0 };
|
|
181
|
+
}
|
|
182
|
+
const toolMsgs = messages.filter((m) => m.role === "tool");
|
|
183
|
+
const tools = [...new Set(messages.flatMap((m) => (m.toolName ? [m.toolName] : [])))].sort();
|
|
184
|
+
const recentUser = collectRecentUserRequests(messages, MAX_RECENT_USER);
|
|
185
|
+
const currentWork = inferCurrentWork(messages);
|
|
186
|
+
const keyFiles = collectKeyFiles(messages);
|
|
187
|
+
const pending = inferPendingWork(messages);
|
|
188
|
+
const keyDecisions = extractDecisions(messages);
|
|
189
|
+
const filesModified = extractFilesModified(toolMsgs);
|
|
190
|
+
const topicSummary = buildTopicSummary(messages, tools, recentUser, currentWork, keyFiles, pending);
|
|
191
|
+
const tokenEstimate = estimateBlockTokens(topicSummary);
|
|
192
|
+
return { topicSummary, keyDecisions, nextSteps: pending, filesModified, tokenEstimate };
|
|
193
|
+
}
|
|
194
|
+
// ---- Key files (existing logic from compact.ts, moved here) ----------------
|
|
195
|
+
const MAX_KEY_FILES = 5;
|
|
196
|
+
const FRESHNESS_WINDOW = 10;
|
|
197
|
+
function collectKeyFiles(messages) {
|
|
198
|
+
const recent = messages.slice(-FRESHNESS_WINDOW);
|
|
199
|
+
const pathFreq = new Map();
|
|
200
|
+
for (const m of recent) {
|
|
201
|
+
for (const p of extractFilePaths(m.text)) {
|
|
202
|
+
pathFreq.set(p, (pathFreq.get(p) ?? 0) + 1);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return [...pathFreq.entries()]
|
|
206
|
+
.sort((a, b) => b[1] - a[1])
|
|
207
|
+
.slice(0, MAX_KEY_FILES)
|
|
208
|
+
.map(([p]) => p);
|
|
209
|
+
}
|