fix(compact): move force tier to agent_settled
Manual compaction (ctx.compact) aborts the active run and never resumes the interrupted turn (Pi 1.5.2 agent-session.js:2321-2327), so triggering it from turn_end destroyed in-progress agent work. The force tier now fires at agent_settled, where ctx.isIdle() is guaranteed and compaction aborts nothing; Pi's built-in mid-run threshold check stays the actor and preserves runs. Also: the settled handler awaits compaction completion so prompts deferred from settled handlers cannot race an in-flight compaction; per-field config validation falls back to defaults (null token values previously zeroed thresholds via Math.min, strings silently NaN-disabled them); the cached token count is cleared on session_compact so stale pre-compaction counts cannot re-trigger. Adds harness.ts: 15-test mock harness (node --test, type stripping, zero deps) covering both regressions, locks, cooldown, validation, and cycle resets. README corrected accordingly.
This commit is contained in:
1 parent
2c6d98995a
commit
a6cfb51626
3 files changed
+332
-71
No files matched your search
+223
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* smart-compact mock-harness — run with: node --test harness.ts
|
||||
* (Node ≥ 22.18 with built-in TypeScript type stripping.)
|
||||
*
|
||||
* Drives the extension against a mock Pi: turn_end / agent_settled /
|
||||
* session_compact events, controllable getContextUsage(), and a ctx.compact
|
||||
* recorder. Config is injected per scenario via a temp project
|
||||
* .pi/settings.json (all fields set, so the user's global file cannot leak
|
||||
* into assertions).
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import smartCompact from "./index.ts";
|
||||
|
||||
interface CtxOverrides {
|
||||
tokens: number | null;
|
||||
window: number;
|
||||
onCompact?: (opts: any) => void;
|
||||
idle?: boolean;
|
||||
}
|
||||
|
||||
function load(settings: Record<string, unknown>) {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "smart-compact-test-"));
|
||||
mkdirSync(path.join(dir, ".pi"));
|
||||
writeFileSync(
|
||||
path.join(dir, ".pi", "settings.json"),
|
||||
JSON.stringify({ smartCompact: settings }),
|
||||
);
|
||||
const prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
const pi: any = {
|
||||
handlers: {} as Record<string, any>,
|
||||
commands: {} as Record<string, any>,
|
||||
on(name: string, fn: any) {
|
||||
this.handlers[name] = fn;
|
||||
},
|
||||
registerCommand(name: string, def: any) {
|
||||
this.commands[name] = def;
|
||||
},
|
||||
};
|
||||
try {
|
||||
smartCompact(pi);
|
||||
} finally {
|
||||
process.chdir(prevCwd);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
return pi;
|
||||
}
|
||||
|
||||
function makeCtx({ tokens, window, onCompact, idle = true }: CtxOverrides) {
|
||||
const calls: { compact: number; notified: string[] } = { compact: 0, notified: [] };
|
||||
return {
|
||||
calls,
|
||||
ctx: {
|
||||
isIdle: () => idle,
|
||||
getContextUsage: () => ({ tokens, contextWindow: window }),
|
||||
ui: { notify: (msg: string) => calls.notified.push(msg) },
|
||||
compact: (opts: any) => {
|
||||
calls.compact++;
|
||||
(onCompact ?? ((o: any) => o?.onComplete?.({})))(opts);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const fire = async (pi: any, name: string, ctx: any, event: any = { entries: [] }) =>
|
||||
await pi.handlers[name](event, ctx);
|
||||
|
||||
const FULL = { enabled: true, warnTokens: 60_000, forceTokens: 90_000, warnFraction: 0.55, forceFraction: 0.8 };
|
||||
// With window 100k: warnAt = min(60k, 55k) = 55k, forceAt = min(90k, 80k) = 80k.
|
||||
|
||||
test("warn fires once per cycle at the effective threshold", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 });
|
||||
const first = await fire(pi, "turn_end", ctx);
|
||||
assert.equal(first.entries.at(-1).customType, "smart-compact-notice");
|
||||
assert.equal(first.entries.at(-1).display, false);
|
||||
assert.equal(first.continue, true);
|
||||
assert.match(first.entries.at(-1).content, /56k tokens/);
|
||||
const second = await fire(pi, "turn_end", ctx);
|
||||
assert.equal(second, undefined);
|
||||
});
|
||||
|
||||
test("below warn threshold: no message", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx } = makeCtx({ tokens: 40_000, window: 100_000 });
|
||||
assert.equal(await fire(pi, "turn_end", ctx), undefined);
|
||||
});
|
||||
|
||||
test("force tier never triggers from turn_end (mid-run compaction aborts work)", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 95_000, window: 100_000 }); // above forceAt
|
||||
await fire(pi, "turn_end", ctx);
|
||||
assert.equal(calls.compact, 0);
|
||||
});
|
||||
|
||||
test("force fires at agent_settled above the effective threshold", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 });
|
||||
const result = await fire(pi, "agent_settled", ctx, {});
|
||||
assert.equal(result, undefined); // notification event — no entries returned
|
||||
assert.equal(calls.compact, 1);
|
||||
assert.match(calls.notified.join("\n"), /85k/);
|
||||
});
|
||||
|
||||
test("force does not fire at agent_settled below the threshold", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 60_000, window: 100_000 }); // above warn, below force
|
||||
await fire(pi, "agent_settled", ctx, {});
|
||||
assert.equal(calls.compact, 0);
|
||||
});
|
||||
|
||||
test("in-flight lock prevents a second compaction before onComplete", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: () => {} }); // never completes
|
||||
const first = fire(pi, "agent_settled", ctx, {}); // handler pends until a callback fires
|
||||
await fire(pi, "agent_settled", ctx, {}); // blocked by the in-flight lock
|
||||
assert.equal(calls.compact, 1);
|
||||
});
|
||||
|
||||
test("failed compaction starts the cooldown; no immediate retry", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: (o) => o?.onError?.(new Error("x")) });
|
||||
await fire(pi, "agent_settled", ctx, {});
|
||||
await fire(pi, "agent_settled", ctx, {});
|
||||
assert.equal(calls.compact, 1);
|
||||
});
|
||||
|
||||
test("stale pre-compaction token count does not re-trigger force", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 });
|
||||
await fire(pi, "agent_settled", ctx, {}); // compacts, onComplete releases lock
|
||||
await fire(pi, "session_compact", { getContextUsage: () => ({ tokens: null, contextWindow: 100_000 }) });
|
||||
// Usage still null right after compaction (no assistant response yet):
|
||||
const { ctx: nullCtx, calls: nullCalls } = makeCtx({ tokens: null, window: 100_000 });
|
||||
await fire(pi, "agent_settled", nullCtx, {});
|
||||
assert.equal(nullCalls.compact, 0); // cache was cleared, not stale
|
||||
assert.equal(calls.compact, 1);
|
||||
});
|
||||
|
||||
test("warn re-arms after session_compact starts a new cycle", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 });
|
||||
assert.notEqual(await fire(pi, "turn_end", ctx), undefined);
|
||||
await fire(pi, "session_compact", {});
|
||||
assert.notEqual(await fire(pi, "turn_end", ctx), undefined);
|
||||
});
|
||||
|
||||
test("invalid config values fall back per field (null ≠ 0, strings ≠ NaN)", async () => {
|
||||
const pi = load({ enabled: true, warnTokens: null, forceTokens: "big", warnFraction: 0, forceFraction: 1.5 } as any);
|
||||
// Defaults: warnAt = min(100k, .55×100k) = 55k, forceAt = min(200k, .8×100k) = 80k.
|
||||
const below = makeCtx({ tokens: 79_999, window: 100_000 });
|
||||
await fire(pi, "agent_settled", below.ctx, {});
|
||||
assert.equal(below.calls.compact, 0);
|
||||
const above = makeCtx({ tokens: 80_000, window: 100_000 });
|
||||
await fire(pi, "agent_settled", above.ctx, {});
|
||||
assert.equal(above.calls.compact, 1);
|
||||
// The old Math.min(null, …) → 0 bug would compact on ANY token count:
|
||||
const tiny = makeCtx({ tokens: 1, window: 100_000 });
|
||||
await fire(pi, "agent_settled", tiny.ctx, {});
|
||||
assert.equal(tiny.calls.compact, 0);
|
||||
});
|
||||
|
||||
test("invalid warn-side config falls back per field, verified via turn_end", async () => {
|
||||
const pi = load({ enabled: true, warnTokens: null, forceTokens: 90_000, warnFraction: "high", forceFraction: 0.8 } as any);
|
||||
// Defaults: warnAt = min(100k, 0.55 × window).
|
||||
const fracLimited = makeCtx({ tokens: 54_999, window: 100_000 }); // 0.55×100k = 55k < 100k absolute
|
||||
assert.equal(await fire(pi, "turn_end", fracLimited.ctx), undefined);
|
||||
const atFractional = makeCtx({ tokens: 55_000, window: 100_000 });
|
||||
assert.notEqual(await fire(pi, "turn_end", atFractional.ctx), undefined);
|
||||
// New cycle + absolute-limited window: 0.55×400k = 220k > 100k absolute floor.
|
||||
await fire(pi, "session_compact", {});
|
||||
const absLimited = makeCtx({ tokens: 99_999, window: 400_000 });
|
||||
assert.equal(await fire(pi, "turn_end", absLimited.ctx), undefined);
|
||||
const atAbsolute = makeCtx({ tokens: 100_000, window: 400_000 });
|
||||
assert.notEqual(await fire(pi, "turn_end", atAbsolute.ctx), undefined);
|
||||
});
|
||||
|
||||
test("enabled: false registers nothing", () => {
|
||||
const pi = load({ ...FULL, enabled: false });
|
||||
assert.equal(Object.keys(pi.handlers).length, 0);
|
||||
assert.equal(Object.keys(pi.commands).length, 0);
|
||||
});
|
||||
|
||||
test("status command reports thresholds and crossed indicators", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 });
|
||||
await pi.commands["smart-compact"].handler(undefined, ctx);
|
||||
const text = calls.notified.join("\n");
|
||||
assert.match(text, /smart-compact enabled/);
|
||||
assert.match(text, /warn threshold:\s+55k \(crossed\)/);
|
||||
assert.match(text, /force threshold:\s+80k/);
|
||||
assert.doesNotMatch(text, /force threshold:.*crossed/);
|
||||
});
|
||||
|
||||
test("force does not fire when settled reports not idle", async () => {
|
||||
const pi = load(FULL);
|
||||
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, idle: false });
|
||||
await fire(pi, "agent_settled", ctx, {});
|
||||
assert.equal(calls.compact, 0);
|
||||
});
|
||||
|
||||
test("settled handler awaits compaction completion before finishing", async () => {
|
||||
const pi = load(FULL);
|
||||
let finish!: (cb: "onComplete" | "onError") => void;
|
||||
const { ctx, calls } = makeCtx({
|
||||
tokens: 85_000,
|
||||
window: 100_000,
|
||||
onCompact: (o) => { finish = (cb) => o[cb]?.({}); },
|
||||
});
|
||||
const pending = fire(pi, "agent_settled", ctx, {});
|
||||
let handlerDone = false;
|
||||
pending.then(() => { handlerDone = true; });
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.equal(handlerDone, false); // handler still awaiting the compaction
|
||||
assert.equal(calls.compact, 1);
|
||||
finish("onComplete");
|
||||
await pending;
|
||||
assert.equal(handlerDone, true);
|
||||
});
|
||||
Reference in new issue
Block a user