pi-mega-compact 0.4.13 → 0.4.14
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.
|
@@ -34,7 +34,9 @@ import { recallAndInline } from "../src/recall.js";
|
|
|
34
34
|
import { autoCompactCheck } from "../src/compact.js";
|
|
35
35
|
import { estimateSessionTokens } from "../src/tokens.js";
|
|
36
36
|
import { normalizeSessionId } from "../src/store.js";
|
|
37
|
-
import { touchSession, logDaily } from "../src/store/sqlite.js";
|
|
37
|
+
import { touchSession, logDaily, listCheckpoints } from "../src/store/sqlite.js";
|
|
38
|
+
import { decompressSmart } from "../src/store/compression.js";
|
|
39
|
+
import { loadMetrics, fpRate, p95 } from "../src/monitoring.js";
|
|
38
40
|
import { Logger } from "../src/log.js";
|
|
39
41
|
import { writeFileSync, appendFileSync, readFileSync } from "node:fs";
|
|
40
42
|
import { existsSync, mkdirSync, unlinkSync } from "node:fs";
|
|
@@ -732,9 +734,25 @@ export default function (pi) {
|
|
|
732
734
|
const tokens = usage?.tokens != null ? `${usage.tokens} tok` : "n/a";
|
|
733
735
|
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
734
736
|
const st = store.stats(sid);
|
|
737
|
+
const repo = store.repoStats();
|
|
735
738
|
const di = store.dataInvariant();
|
|
736
739
|
const fmtB = (b) => b >= 1_048_576 ? `${(b / 1_048_576).toFixed(1)} MiB` :
|
|
737
740
|
b >= 1024 ? `${(b / 1024).toFixed(1)} KiB` : `${b} B`;
|
|
741
|
+
// Tangible cost: turn "tokens saved" into a dollar figure + context-days
|
|
742
|
+
// extended, so the counter is concrete rather than opaque. ~$3 / 1M tok
|
|
743
|
+
// (rough blended rate); contextWindow ÷ savedRate = days of context bought.
|
|
744
|
+
const usd = (repo.tokensSaved / 1_000_000 * 3).toFixed(2);
|
|
745
|
+
const ctxWindow = usage?.contextWindow ?? 0;
|
|
746
|
+
const daysExtended = ctxWindow > 0 && repo.tokensSaved > 0
|
|
747
|
+
? (repo.tokensSaved / ctxWindow).toFixed(1)
|
|
748
|
+
: "0";
|
|
749
|
+
const costStr = `≈ $${usd} saved · ${daysExtended} context-windows extended`;
|
|
750
|
+
// Recall-quality badge (Phase 4): trust score from monitoring metrics.
|
|
751
|
+
const m = loadMetrics(currentStateDir);
|
|
752
|
+
const fp = fpRate(m, "L2");
|
|
753
|
+
const p95L2 = p95(m.latency.L2 ?? []);
|
|
754
|
+
const relPct = (st.dedupHitRate * 100).toFixed(0);
|
|
755
|
+
const qualityStr = `recall ${relPct}% relevant · FP ${(fp * 100).toFixed(1)}% · L2 p95 ${p95L2.toFixed(0)}ms`;
|
|
738
756
|
ctx.ui.notify(`[mega-compact] pct=${pct} tokens=${tokens} tier=${config.tier} fastGate=${config.fastGatePct}% ` +
|
|
739
757
|
`threshold=${config.thresholdTokens} auto=${config.auto} autoInline=${config.autoInline}\n` +
|
|
740
758
|
`[mega-compact] store: ${st.checkpointCount} chkpt · ` +
|
|
@@ -746,9 +764,86 @@ export default function (pi) {
|
|
|
746
764
|
`(${fmtB(di.compressedOriginalBytes)} compressed-original) · ` +
|
|
747
765
|
`${di.duplicatesCollapsed} dedup-duplicates collapsed · ` +
|
|
748
766
|
`${C.green}0 bytes permanently deleted${C.reset}\n` +
|
|
767
|
+
`[mega-compact] 💰 ${costStr}\n` +
|
|
768
|
+
`[mega-compact] 🎯 ${qualityStr}\n` +
|
|
749
769
|
`[mega-compact] stateDir=${currentStateDir}`);
|
|
750
770
|
},
|
|
751
771
|
});
|
|
772
|
+
// ---- Phase 4: cheap standout commands (data is already persisted) -------
|
|
773
|
+
/** Resolve a checkpoint by id (or "recent"/"last") from this session's store. */
|
|
774
|
+
function findCheckpoint(sid, ref) {
|
|
775
|
+
const all = listCheckpoints(sid, currentStateDir);
|
|
776
|
+
if (all.length === 0)
|
|
777
|
+
return undefined;
|
|
778
|
+
if (!ref || ref === "recent" || ref === "last")
|
|
779
|
+
return all[all.length - 1];
|
|
780
|
+
return all.find((c) => c.checkpointId === ref) ?? all.find((c) => c.checkpointId.endsWith(ref));
|
|
781
|
+
}
|
|
782
|
+
pi.registerCommand("mega-restore", {
|
|
783
|
+
description: "Re-inject a checkpoint's verbatim original region into context. Usage: /mega-restore <chkpt|recent>",
|
|
784
|
+
handler: async (args, ctx) => {
|
|
785
|
+
bindRepo(ctx.cwd);
|
|
786
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
787
|
+
const cp = findCheckpoint(sid, args.trim());
|
|
788
|
+
if (!cp) {
|
|
789
|
+
ctx.ui.notify(`[mega-compact] no checkpoint found${args.trim() ? ` for "${args.trim()}"` : ""} in this session. Try /mega-history.`);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (!cp.compressedOriginal) {
|
|
793
|
+
ctx.ui.notify(`[mega-compact] ${cp.checkpointId} has no recoverable original (pre-blob or direct add). Cannot restore verbatim.`);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const original = decompressSmart(cp.compressedOriginal).toString("utf-8");
|
|
797
|
+
// Re-inject verbatim via before_agent_start (PREVENT-PI-003) — never
|
|
798
|
+
// touches live messages, only prepends the restored region to systemPrompt.
|
|
799
|
+
pendingRecallBlock = `The following compacted context was RESTORED from checkpoint ${cp.checkpointId} (verbatim original region):\n\n${original}`;
|
|
800
|
+
const files = cp.filesModified?.length ? cp.filesModified.join(", ") : "(no files captured)";
|
|
801
|
+
ctx.ui.notify(`[mega-compact] ♻ restored ${cp.checkpointId} — ${original.length} chars re-injected on next turn.\n` +
|
|
802
|
+
`[mega-compact] files: ${files}`);
|
|
803
|
+
dashboard.event("restore", { checkpointId: cp.checkpointId, chars: original.length });
|
|
804
|
+
},
|
|
805
|
+
});
|
|
806
|
+
pi.registerCommand("mega-history", {
|
|
807
|
+
description: "List this session's checkpoints (id, date, files, tokens). Usage: /mega-history",
|
|
808
|
+
handler: async (_args, ctx) => {
|
|
809
|
+
bindRepo(ctx.cwd);
|
|
810
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
811
|
+
const all = listCheckpoints(sid, currentStateDir);
|
|
812
|
+
if (all.length === 0) {
|
|
813
|
+
ctx.ui.notify("[mega-compact] no checkpoints in this session yet.");
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const rows = all.map((c) => {
|
|
817
|
+
const when = c.timestamp ? new Date(c.timestamp).toISOString().slice(0, 16).replace("T", " ") : "—";
|
|
818
|
+
const files = c.filesModified?.length ? c.filesModified.map((f) => f.split("/").pop()).join(", ") : "—";
|
|
819
|
+
const orig = c.originalTokenEstimate ?? 0;
|
|
820
|
+
const stored = c.tokenEstimate ?? 0;
|
|
821
|
+
const saved = Math.max(0, orig - stored);
|
|
822
|
+
return ` ${c.checkpointId} ${when} ${C.cyan}${saved}t saved${C.reset} ${files}`;
|
|
823
|
+
});
|
|
824
|
+
ctx.ui.notify(`[mega-compact] ${all.length} checkpoint(s) in this session:\n` + rows.join("\n") +
|
|
825
|
+
`\n[mega-compact] /mega-view <chkpt> to see the original region · /mega-restore <chkpt> to re-inject it`);
|
|
826
|
+
},
|
|
827
|
+
});
|
|
828
|
+
pi.registerCommand("mega-view", {
|
|
829
|
+
description: "Show a checkpoint's verbatim original region. Usage: /mega-view <chkpt|recent>",
|
|
830
|
+
handler: async (args, ctx) => {
|
|
831
|
+
bindRepo(ctx.cwd);
|
|
832
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
833
|
+
const cp = findCheckpoint(sid, args.trim());
|
|
834
|
+
if (!cp) {
|
|
835
|
+
ctx.ui.notify(`[mega-compact] no checkpoint found${args.trim() ? ` for "${args.trim()}"` : ""}. Try /mega-history.`);
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (!cp.compressedOriginal) {
|
|
839
|
+
ctx.ui.notify(`[mega-compact] ${cp.checkpointId} summary:\n${cp.summary.slice(0, 500)}${cp.summary.length > 500 ? "…" : ""}\n(no verbatim original stored)`);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
const original = decompressSmart(cp.compressedOriginal).toString("utf-8");
|
|
843
|
+
ctx.ui.notify(`[mega-compact] ${cp.checkpointId} — original region (${original.length} chars):\n` +
|
|
844
|
+
`${original.slice(0, 1500)}${original.length > 1500 ? "\n…(truncated)" : ""}`);
|
|
845
|
+
},
|
|
846
|
+
});
|
|
752
847
|
pi.registerCommand("mega-tier", {
|
|
753
848
|
description: "Show or change the compaction tier at runtime. Usage: /mega-tier [low|medium|high|ultra|mega]",
|
|
754
849
|
handler: async (args, ctx) => {
|
|
@@ -0,0 +1,54 @@
|
|
|
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 { listCheckpoints, dataInvariantStats } from "./sqlite.js";
|
|
8
|
+
import { decompressSmart, compressSmart } from "./compression.js";
|
|
9
|
+
const baseTmp = mkdtempSync(join(tmpdir(), "mc-p04-"));
|
|
10
|
+
let counter = 0;
|
|
11
|
+
function store(opts = {}) {
|
|
12
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
13
|
+
return { s: new VectorStore({ dedupSim: opts.dedupSim ?? 0.9, stateDir: dir }), dir };
|
|
14
|
+
}
|
|
15
|
+
test("Phase 4: added checkpoint is listed and its compressed-original round-trips", () => {
|
|
16
|
+
const { s, dir } = store();
|
|
17
|
+
const original = "the original region text that gets compacted and must be restorable verbatim";
|
|
18
|
+
const r = s.add({ sessionId: "sess_a", summary: "s", regionText: original, tokenEstimate: 5, originalTokenEstimate: 60, timestamp: 1 });
|
|
19
|
+
const all = listCheckpoints("sess_a", dir);
|
|
20
|
+
assert.equal(all.length, 1, "one checkpoint listed");
|
|
21
|
+
const cp = all[0];
|
|
22
|
+
assert.ok(cp.compressedOriginal, "compressed-original blob present");
|
|
23
|
+
// The DR/restore path: decompressSmart must return the exact original.
|
|
24
|
+
const restored = decompressSmart(cp.compressedOriginal).toString("utf-8");
|
|
25
|
+
assert.equal(restored, original, "restored verbatim === original");
|
|
26
|
+
assert.equal(cp.checkpointId, r.checkpoint.checkpointId);
|
|
27
|
+
});
|
|
28
|
+
test("Phase 4: findCheckpoint-by-id resolves a listed checkpoint", () => {
|
|
29
|
+
const { s, dir } = store();
|
|
30
|
+
s.add({ sessionId: "sess_b", summary: "s1", regionText: "region one text content here", tokenEstimate: 4, originalTokenEstimate: 40, timestamp: 1 });
|
|
31
|
+
const r2 = s.add({ sessionId: "sess_b", summary: "s2", regionText: "region two text content here different", tokenEstimate: 4, originalTokenEstimate: 45, timestamp: 2 });
|
|
32
|
+
const all = listCheckpoints("sess_b", dir);
|
|
33
|
+
assert.equal(all.length, 2);
|
|
34
|
+
const wanted = all.find((c) => c.checkpointId === r2.checkpoint.checkpointId);
|
|
35
|
+
assert.ok(wanted, "checkpoint resolved by id");
|
|
36
|
+
assert.ok(wanted.compressedOriginal, "has restorable original");
|
|
37
|
+
});
|
|
38
|
+
test("Phase 4: dataInvariantStats sanity for restore trust (0 deleted)", () => {
|
|
39
|
+
const { s, dir } = store();
|
|
40
|
+
s.add({ sessionId: "sess_c", summary: "s", regionText: "retained region body text", tokenEstimate: 5, originalTokenEstimate: 50, timestamp: 1 });
|
|
41
|
+
const di = dataInvariantStats(dir);
|
|
42
|
+
assert.equal(di.regionsRetained, 1);
|
|
43
|
+
assert.ok(di.compressedOriginalBytes > 0);
|
|
44
|
+
assert.equal(di.bytesPermanentlyDeleted, 0);
|
|
45
|
+
});
|
|
46
|
+
test("Phase 4: compressSmart/decompressSmart round-trips arbitrary text", () => {
|
|
47
|
+
const text = "x".repeat(2000);
|
|
48
|
+
const back = decompressSmart(compressSmart(Buffer.from(text, "utf-8"))).toString("utf-8");
|
|
49
|
+
assert.equal(back, text);
|
|
50
|
+
});
|
|
51
|
+
process.on("exit", () => { try {
|
|
52
|
+
rmSync(baseTmp, { recursive: true, force: true });
|
|
53
|
+
}
|
|
54
|
+
catch { /* ignore */ } });
|
|
@@ -37,7 +37,9 @@ import { recallAndInline } from "../src/recall.js";
|
|
|
37
37
|
import { autoCompactCheck } from "../src/compact.js";
|
|
38
38
|
import { estimateSessionTokens } from "../src/tokens.js";
|
|
39
39
|
import { normalizeSessionId } from "../src/store.js";
|
|
40
|
-
import { touchSession, logDaily } from "../src/store/sqlite.js";
|
|
40
|
+
import { touchSession, logDaily, listCheckpoints } from "../src/store/sqlite.js";
|
|
41
|
+
import { decompressSmart } from "../src/store/compression.js";
|
|
42
|
+
import { loadMetrics, fpRate, p95 } from "../src/monitoring.js";
|
|
41
43
|
import { Logger } from "../src/log.js";
|
|
42
44
|
import type { EngineMessage } from "../src/types.js";
|
|
43
45
|
import { writeFileSync, appendFileSync, readFileSync } from "node:fs";
|
|
@@ -869,10 +871,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
869
871
|
const tokens = usage?.tokens != null ? `${usage.tokens} tok` : "n/a";
|
|
870
872
|
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
871
873
|
const st = store.stats(sid);
|
|
874
|
+
const repo = store.repoStats();
|
|
872
875
|
const di = store.dataInvariant();
|
|
873
876
|
const fmtB = (b: number) =>
|
|
874
877
|
b >= 1_048_576 ? `${(b / 1_048_576).toFixed(1)} MiB` :
|
|
875
878
|
b >= 1024 ? `${(b / 1024).toFixed(1)} KiB` : `${b} B`;
|
|
879
|
+
// Tangible cost: turn "tokens saved" into a dollar figure + context-days
|
|
880
|
+
// extended, so the counter is concrete rather than opaque. ~$3 / 1M tok
|
|
881
|
+
// (rough blended rate); contextWindow ÷ savedRate = days of context bought.
|
|
882
|
+
const usd = (repo.tokensSaved / 1_000_000 * 3).toFixed(2);
|
|
883
|
+
const ctxWindow = usage?.contextWindow ?? 0;
|
|
884
|
+
const daysExtended = ctxWindow > 0 && repo.tokensSaved > 0
|
|
885
|
+
? (repo.tokensSaved / ctxWindow).toFixed(1)
|
|
886
|
+
: "0";
|
|
887
|
+
const costStr = `≈ $${usd} saved · ${daysExtended} context-windows extended`;
|
|
888
|
+
// Recall-quality badge (Phase 4): trust score from monitoring metrics.
|
|
889
|
+
const m = loadMetrics(currentStateDir);
|
|
890
|
+
const fp = fpRate(m, "L2");
|
|
891
|
+
const p95L2 = p95(m.latency.L2 ?? []);
|
|
892
|
+
const relPct = (st.dedupHitRate * 100).toFixed(0);
|
|
893
|
+
const qualityStr = `recall ${relPct}% relevant · FP ${(fp * 100).toFixed(1)}% · L2 p95 ${p95L2.toFixed(0)}ms`;
|
|
876
894
|
ctx.ui.notify(
|
|
877
895
|
`[mega-compact] pct=${pct} tokens=${tokens} tier=${config.tier} fastGate=${config.fastGatePct}% ` +
|
|
878
896
|
`threshold=${config.thresholdTokens} auto=${config.auto} autoInline=${config.autoInline}\n` +
|
|
@@ -885,11 +903,97 @@ export default function (pi: ExtensionAPI) {
|
|
|
885
903
|
`(${fmtB(di.compressedOriginalBytes)} compressed-original) · ` +
|
|
886
904
|
`${di.duplicatesCollapsed} dedup-duplicates collapsed · ` +
|
|
887
905
|
`${C.green}0 bytes permanently deleted${C.reset}\n` +
|
|
906
|
+
`[mega-compact] 💰 ${costStr}\n` +
|
|
907
|
+
`[mega-compact] 🎯 ${qualityStr}\n` +
|
|
888
908
|
`[mega-compact] stateDir=${currentStateDir}`,
|
|
889
909
|
);
|
|
890
910
|
},
|
|
891
911
|
});
|
|
892
912
|
|
|
913
|
+
// ---- Phase 4: cheap standout commands (data is already persisted) -------
|
|
914
|
+
|
|
915
|
+
/** Resolve a checkpoint by id (or "recent"/"last") from this session's store. */
|
|
916
|
+
function findCheckpoint(sid: string, ref: string) {
|
|
917
|
+
const all = listCheckpoints(sid, currentStateDir);
|
|
918
|
+
if (all.length === 0) return undefined;
|
|
919
|
+
if (!ref || ref === "recent" || ref === "last") return all[all.length - 1];
|
|
920
|
+
return all.find((c) => c.checkpointId === ref) ?? all.find((c) => c.checkpointId.endsWith(ref));
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
pi.registerCommand("mega-restore", {
|
|
924
|
+
description: "Re-inject a checkpoint's verbatim original region into context. Usage: /mega-restore <chkpt|recent>",
|
|
925
|
+
handler: async (args: string, ctx: ExtensionContext) => {
|
|
926
|
+
bindRepo(ctx.cwd);
|
|
927
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
928
|
+
const cp = findCheckpoint(sid, args.trim());
|
|
929
|
+
if (!cp) {
|
|
930
|
+
ctx.ui.notify(`[mega-compact] no checkpoint found${args.trim() ? ` for "${args.trim()}"` : ""} in this session. Try /mega-history.`);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
if (!cp.compressedOriginal) {
|
|
934
|
+
ctx.ui.notify(`[mega-compact] ${cp.checkpointId} has no recoverable original (pre-blob or direct add). Cannot restore verbatim.`);
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
const original = decompressSmart(cp.compressedOriginal).toString("utf-8");
|
|
938
|
+
// Re-inject verbatim via before_agent_start (PREVENT-PI-003) — never
|
|
939
|
+
// touches live messages, only prepends the restored region to systemPrompt.
|
|
940
|
+
pendingRecallBlock = `The following compacted context was RESTORED from checkpoint ${cp.checkpointId} (verbatim original region):\n\n${original}`;
|
|
941
|
+
const files = cp.filesModified?.length ? cp.filesModified.join(", ") : "(no files captured)";
|
|
942
|
+
ctx.ui.notify(
|
|
943
|
+
`[mega-compact] ♻ restored ${cp.checkpointId} — ${original.length} chars re-injected on next turn.\n` +
|
|
944
|
+
`[mega-compact] files: ${files}`,
|
|
945
|
+
);
|
|
946
|
+
dashboard.event("restore", { checkpointId: cp.checkpointId, chars: original.length });
|
|
947
|
+
},
|
|
948
|
+
});
|
|
949
|
+
|
|
950
|
+
pi.registerCommand("mega-history", {
|
|
951
|
+
description: "List this session's checkpoints (id, date, files, tokens). Usage: /mega-history",
|
|
952
|
+
handler: async (_args: string, ctx: ExtensionContext) => {
|
|
953
|
+
bindRepo(ctx.cwd);
|
|
954
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
955
|
+
const all = listCheckpoints(sid, currentStateDir);
|
|
956
|
+
if (all.length === 0) {
|
|
957
|
+
ctx.ui.notify("[mega-compact] no checkpoints in this session yet.");
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
const rows = all.map((c) => {
|
|
961
|
+
const when = c.timestamp ? new Date(c.timestamp).toISOString().slice(0, 16).replace("T", " ") : "—";
|
|
962
|
+
const files = c.filesModified?.length ? c.filesModified.map((f) => f.split("/").pop()).join(", ") : "—";
|
|
963
|
+
const orig = c.originalTokenEstimate ?? 0;
|
|
964
|
+
const stored = c.tokenEstimate ?? 0;
|
|
965
|
+
const saved = Math.max(0, orig - stored);
|
|
966
|
+
return ` ${c.checkpointId} ${when} ${C.cyan}${saved}t saved${C.reset} ${files}`;
|
|
967
|
+
});
|
|
968
|
+
ctx.ui.notify(
|
|
969
|
+
`[mega-compact] ${all.length} checkpoint(s) in this session:\n` + rows.join("\n") +
|
|
970
|
+
`\n[mega-compact] /mega-view <chkpt> to see the original region · /mega-restore <chkpt> to re-inject it`,
|
|
971
|
+
);
|
|
972
|
+
},
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
pi.registerCommand("mega-view", {
|
|
976
|
+
description: "Show a checkpoint's verbatim original region. Usage: /mega-view <chkpt|recent>",
|
|
977
|
+
handler: async (args: string, ctx: ExtensionContext) => {
|
|
978
|
+
bindRepo(ctx.cwd);
|
|
979
|
+
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
980
|
+
const cp = findCheckpoint(sid, args.trim());
|
|
981
|
+
if (!cp) {
|
|
982
|
+
ctx.ui.notify(`[mega-compact] no checkpoint found${args.trim() ? ` for "${args.trim()}"` : ""}. Try /mega-history.`);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
if (!cp.compressedOriginal) {
|
|
986
|
+
ctx.ui.notify(`[mega-compact] ${cp.checkpointId} summary:\n${cp.summary.slice(0, 500)}${cp.summary.length > 500 ? "…" : ""}\n(no verbatim original stored)`);
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const original = decompressSmart(cp.compressedOriginal).toString("utf-8");
|
|
990
|
+
ctx.ui.notify(
|
|
991
|
+
`[mega-compact] ${cp.checkpointId} — original region (${original.length} chars):\n` +
|
|
992
|
+
`${original.slice(0, 1500)}${original.length > 1500 ? "\n…(truncated)" : ""}`,
|
|
993
|
+
);
|
|
994
|
+
},
|
|
995
|
+
});
|
|
996
|
+
|
|
893
997
|
pi.registerCommand("mega-tier", {
|
|
894
998
|
description: "Show or change the compaction tier at runtime. Usage: /mega-tier [low|medium|high|ultra|mega]",
|
|
895
999
|
handler: async (args: string, ctx: ExtensionContext) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mega-compact",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.14",
|
|
4
4
|
"description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "BSD-2-Clause",
|
|
@@ -0,0 +1,58 @@
|
|
|
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 { listCheckpoints, dataInvariantStats } from "./sqlite.js";
|
|
8
|
+
import { decompressSmart, compressSmart } from "./compression.js";
|
|
9
|
+
|
|
10
|
+
const baseTmp = mkdtempSync(join(tmpdir(), "mc-p04-"));
|
|
11
|
+
|
|
12
|
+
let counter = 0;
|
|
13
|
+
function store(opts: { dedupSim?: number } = {}) {
|
|
14
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
15
|
+
return { s: new VectorStore({ dedupSim: opts.dedupSim ?? 0.9, stateDir: dir }), dir };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
test("Phase 4: added checkpoint is listed and its compressed-original round-trips", () => {
|
|
19
|
+
const { s, dir } = store();
|
|
20
|
+
const original = "the original region text that gets compacted and must be restorable verbatim";
|
|
21
|
+
const r = s.add({ sessionId: "sess_a", summary: "s", regionText: original, tokenEstimate: 5, originalTokenEstimate: 60, timestamp: 1 });
|
|
22
|
+
const all = listCheckpoints("sess_a", dir);
|
|
23
|
+
assert.equal(all.length, 1, "one checkpoint listed");
|
|
24
|
+
const cp = all[0];
|
|
25
|
+
assert.ok(cp.compressedOriginal, "compressed-original blob present");
|
|
26
|
+
// The DR/restore path: decompressSmart must return the exact original.
|
|
27
|
+
const restored = decompressSmart(cp.compressedOriginal!).toString("utf-8");
|
|
28
|
+
assert.equal(restored, original, "restored verbatim === original");
|
|
29
|
+
assert.equal(cp.checkpointId, r.checkpoint.checkpointId);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("Phase 4: findCheckpoint-by-id resolves a listed checkpoint", () => {
|
|
33
|
+
const { s, dir } = store();
|
|
34
|
+
s.add({ sessionId: "sess_b", summary: "s1", regionText: "region one text content here", tokenEstimate: 4, originalTokenEstimate: 40, timestamp: 1 });
|
|
35
|
+
const r2 = s.add({ sessionId: "sess_b", summary: "s2", regionText: "region two text content here different", tokenEstimate: 4, originalTokenEstimate: 45, timestamp: 2 });
|
|
36
|
+
const all = listCheckpoints("sess_b", dir);
|
|
37
|
+
assert.equal(all.length, 2);
|
|
38
|
+
const wanted = all.find((c) => c.checkpointId === r2.checkpoint.checkpointId)!;
|
|
39
|
+
assert.ok(wanted, "checkpoint resolved by id");
|
|
40
|
+
assert.ok(wanted.compressedOriginal, "has restorable original");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("Phase 4: dataInvariantStats sanity for restore trust (0 deleted)", () => {
|
|
44
|
+
const { s, dir } = store();
|
|
45
|
+
s.add({ sessionId: "sess_c", summary: "s", regionText: "retained region body text", tokenEstimate: 5, originalTokenEstimate: 50, timestamp: 1 });
|
|
46
|
+
const di = dataInvariantStats(dir);
|
|
47
|
+
assert.equal(di.regionsRetained, 1);
|
|
48
|
+
assert.ok(di.compressedOriginalBytes > 0);
|
|
49
|
+
assert.equal(di.bytesPermanentlyDeleted, 0);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("Phase 4: compressSmart/decompressSmart round-trips arbitrary text", () => {
|
|
53
|
+
const text = "x".repeat(2000);
|
|
54
|
+
const back = decompressSmart(compressSmart(Buffer.from(text, "utf-8"))).toString("utf-8");
|
|
55
|
+
assert.equal(back, text);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
process.on("exit", () => { try { rmSync(baseTmp, { recursive: true, force: true }); } catch { /* ignore */ } });
|