Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(goal): include pre-compaction usage in round budgets (#1355)

lmliheng148688395a45
diff --git a/changelog/unreleased/2026-10-28-goal-compaction-budget.md b/changelog/unreleased/2026-10-28-goal-compaction-budget.md
new file mode 100644
index 00000000..64b1bec8
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-goal-compaction-budget.md
@@ -0,0 +1,51 @@
+# Goal budgets count usage from before a mid-round compaction
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `plugins`
+- **Breaking:** no
+
+[中文](2026-10-28-goal-compaction-budget.zh.md)
+
+Ported from PenguinHarness `eb3edfec` (`#1355`).
+
+Goal mode's stop hook added up a round's token usage from the newest Trace file only. When a
+context compaction rotated the log mid-round, everything the round had already spent went with
+the older file: a round that used 110 uncached tokens against a budget of 100 was recorded as 20
+and stayed `active`, so the wrap-up round never started and the goal kept working past the budget
+it was given.
+
+The hook now reads the Session's preceding Trace shards back to the round's own injected input
+before counting. Earlier rounds are not charged twice — the window still starts right after the
+last round input, it just no longer starts at the beginning of a shard. A shard that is missing,
+unreadable or belongs to another Session ends the lookup and keeps the usage that is available:
+an incomplete count is a better answer than counting an unrelated run's tokens.
+
+## Details
+
+- `plugins/goal/hooks/lib.mjs`: new `readRoundRecords(file, sessionId, records)`. It parses the
+ shard index off the Trace file name (`<sessionId>_<NNN>.jsonl`), then walks back one shard at a
+ time — pad-starting the index to the writer's three digits — until a shard contains a round
+ input or the walk reaches `_001`. Each predecessor must announce the same `session_id` in its
+ `session_meta`, otherwise the walk stops. The collected shards are flattened and handed to the
+ unchanged `lastRoundRecords()`, which keeps the "start after the last round input" rule in one
+ place. Trace names the hook does not recognize fall back to single-file accounting.
+- `plugins/goal/hooks/stop.mjs`: uses `readRoundRecords(tracePath, sessionId, records)` instead of
+ `lastRoundRecords(records)`.
+- `plugins/goal/plugin.json`: version `2026.09.29.1` → `2026.10.28.1`, so an Agent that already
+ has the plugin installed refreshes its hooks. Upstream bumps `hooks.version` in
+ `package.json`; this tree keeps the plugin version in `plugin.json` and has no such block, so
+ the bump lives there.
+- `packages/core/test/goal-hooks.test.ts`: the fixture writer takes a target file; the old
+ "counts the whole file when a compaction rotated the input away" case becomes a four-name table
+ (current shard, a legacy name, another Session's shard, an out-of-range index) asserting the
+ same fallback, plus three new cases — a budget spread over three shards wrapping up at
+ `tokens_used: 110` and then stopping at `115`; a later round whose input sits in a previous
+ shard counting only what follows that input; and a missing or foreign predecessor shard keeping
+ the current shard's 20 tokens.
+
+## Compatibility
+
+- No on-disk change: Trace and `GOAL.json` formats, the budget semantics and the single final
+ wrap-up round are exactly as before. Only the usage a round is charged with changes — for a
+ round that spanned a compaction it is now the usage that actually happened.
diff --git a/changelog/unreleased/2026-10-28-goal-compaction-budget.zh.md b/changelog/unreleased/2026-10-28-goal-compaction-budget.zh.md
new file mode 100644
index 00000000..0c881952
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-goal-compaction-budget.zh.md
@@ -0,0 +1,38 @@
+# 目标模式预算计入轮中压缩之前的用量
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `plugins`
+- **Breaking:** no
+
+[English](2026-10-28-goal-compaction-budget.md)
+
+移植自 PenguinHarness `eb3edfec`(`#1355`)。
+
+目标模式的 stop hook 只从最新的那个 Trace 文件里加总一轮的 token 用量。如果一轮进行到一半时上下文压缩把日志
+换成了新的一份,这一轮已经花掉的部分就留在旧文件里了:一轮对着 100 的预算用掉 110 个未命中缓存的 token,
+会被记成 20 并继续保持 `active`,于是收尾那一轮根本不开始、目标越过给定的预算继续跑。
+
+现在 hook 在计数之前会沿该 Session 之前的 Trace 分片回溯到本轮自己那条注入输入。已完成的轮次不会被重复计入 ——
+统计窗口仍然从最后一条轮次输入之后开始,只是不再从「这一片的开头」开始。分片缺失、读不出、或属于另一个 Session
+时,回溯就此停下、保留已经能读到的那部分用量:数不全,也好过把另一轮会话的 token 算进来。
+
+## 细节
+
+- `plugins/goal/hooks/lib.mjs`:新增 `readRoundRecords(file, sessionId, records)`。它从 Trace 文件名
+ (`<sessionId>_<NNN>.jsonl`)解析出分片序号,然后一片一片往回走 —— 序号按写入方的三位补零回填 ——
+ 直到某一片里出现轮次输入,或者走到 `_001`。每一片的前驱都必须在自己的 `session_meta` 里报着同一个
+ `session_id`,否则停下。收集到的分片展平后交给未改动的 `lastRoundRecords()`,「从最后一条轮次输入之后开始」
+ 这条规则因此仍然只写在一个地方。hook 认不出的 Trace 文件名退回单文件计数。
+- `plugins/goal/hooks/stop.mjs`:改用 `readRoundRecords(tracePath, sessionId, records)`。
+- `plugins/goal/plugin.json`:版本 `2026.09.29.1` → `2026.10.28.1`,已装过该插件的 Agent 因此会刷新钩子。
+ 上游改的是 `package.json` 里的 `hooks.version`;本仓把插件版本放在 `plugin.json`、没有那个块,所以版本号落在那里。
+- `packages/core/test/goal-hooks.test.ts`:夹具的写入函数多一个目标文件参数;原来那条「压缩把轮次输入转走时
+ 数整个文件」变成四个文件名的表驱动用例(当前分片、旧式名字、另一个 Session 的分片、超出安全整数范围的序号),
+ 断言同一条回退;另加三条 —— 预算摊在三个分片上的那一轮先以 `tokens_used: 110` 进入收尾、再以 `115` 停下;
+ 输入落在前一片里的后一轮只数那条输入之后的用量;前驱分片缺失或属于别人时只保留当前那一片的 20 个 token。
+
+## 兼容性
+
+- 落盘格式一个没变:Trace 与 `GOAL.json` 的格式、预算语义、最后那一轮收尾都照旧。变的只有「一轮被记多少用量」——
+ 跨了压缩的那一轮,记下的现在是真实发生过的量。
diff --git a/packages/core/test/goal-hooks.test.ts b/packages/core/test/goal-hooks.test.ts
index 51e21b1b..3da001b6 100644
--- a/packages/core/test/goal-hooks.test.ts
+++ b/packages/core/test/goal-hooks.test.ts
@@ -2,6 +2,11 @@
* The goal plugin's scripts, run the way the harness runs them — as Node subprocesses with
* JSON on stdin — against a fake Trace and scratchpad: start.mjs writes GOAL.json and prints
* the round-1 message; stop.mjs reads the round's usage off the Trace and decides.
+ *
+ * - A round spanning several Trace shards includes all uncached usage when checking its budget.
+ * - A later round starts at its own injected input, without recounting the preceding round.
+ * - Missing or foreign preceding shards preserve the available current-round usage.
+ * - Unrecognized Trace names retain single-file accounting.
*/
import { spawnSync } from "node:child_process";
import fs from "node:fs/promises";
@@ -82,8 +87,8 @@ const requestEnd = (status: string) => ({
});
const abort = () => ({ type: "event_msg", payload: { type: "abort", error_code: "user_abort" } });
-async function writeTrace(records: unknown[]): Promise<void> {
- await fs.writeFile(tracePath, records.map((r) => `${JSON.stringify(r)}\n`).join(""), "utf8");
+async function writeTrace(records: unknown[], file = tracePath): Promise<void> {
+ await fs.writeFile(file, records.map((r) => `${JSON.stringify(r)}\n`).join(""), "utf8");
}
async function readGoal(): Promise<Record<string, unknown>> {
@@ -275,15 +280,77 @@ describe("stop.mjs", () => {
});
});
- it("counts the whole file when a compaction rotated the round's input away", async () => {
- start("obj");
- await writeTrace([meta(), assistant("after compaction"), usage(30), usage(20)]);
+ it.each(["s1_001.jsonl", "legacy.jsonl", "other_002.jsonl", "s1_9007199254740992.jsonl"])(
+ "counts available usage without a round input in %s",
+ async (name) => {
+ start("obj");
+ tracePath = path.join(path.dirname(tracePath), name);
+ await writeTrace([meta(), assistant("after compaction"), usage(30), usage(20)]);
+ expect(stop().out).toMatchObject({
+ decision: "continue",
+ output: { round: 2, tokens_used: 50 },
+ });
+ },
+ );
+
+ it("counts usage across compaction shards and wraps up at the budget", async () => {
+ const { out: started } = start("obj", 100);
+ const dir = path.dirname(tracePath);
+ await writeTrace(
+ [meta(), usage(999), harness((started as { context: string }).context), usage(80, 20)],
+ path.join(dir, "s1_998.jsonl"),
+ );
+ await writeTrace([meta(), usage(30)], path.join(dir, "s1_999.jsonl"));
+ tracePath = path.join(dir, "s1_1000.jsonl");
+ await writeTrace([meta(), usage(20), requestEnd("completed")]);
+ const wrap = stop().out as { input: string };
+ expect(wrap).toMatchObject({
+ decision: "continue",
+ output: { status: "wrapping_up", round: 2, tokens_used: 110 },
+ });
+ expect(await readGoal()).toMatchObject({ status: "wrapping_up", tokens_used: 110 });
+
+ await writeTrace([meta(), usage(20), harness(wrap.input), usage(5)]);
+ expect(stop().out).toMatchObject({
+ decision: "stop",
+ output: { status: "budget_limited", tokens_used: 115 },
+ });
+ });
+
+ it("stops at the latest round input in a previous shard without recounting earlier usage", async () => {
+ const { out: started } = start("obj", 1000);
+ const firstRound = [meta(), harness((started as { context: string }).context), usage(90)];
+ await writeTrace(firstRound);
+ const next = stop().out as { input: string };
+ await writeTrace([...firstRound, harness(next.input), usage(10)]);
+ tracePath = path.join(path.dirname(tracePath), "s1_002.jsonl");
+ await writeTrace([meta(), usage(20)]);
expect(stop().out).toMatchObject({
decision: "continue",
- output: { round: 2, tokens_used: 50 },
+ output: { status: "active", round: 3, tokens_used: 120 },
});
});
+ it.each(["missing", "foreign"])(
+ "keeps available usage when the preceding shard is %s",
+ async (kind) => {
+ const { out: started } = start("obj", 100);
+ await writeTrace([meta(), harness((started as { context: string }).context), usage(90)]);
+ if (kind === "foreign") {
+ await writeTrace(
+ [{ type: "session_meta", payload: { session_id: "other" } }, usage(500)],
+ path.join(path.dirname(tracePath), "s1_002.jsonl"),
+ );
+ }
+ tracePath = path.join(path.dirname(tracePath), "s1_003.jsonl");
+ await writeTrace([meta(), usage(20)]);
+ expect(stop().out).toMatchObject({
+ decision: "continue",
+ output: { status: "active", tokens_used: 20 },
+ });
+ },
+ );
+
it("stops at the round cap", async () => {
start("obj");
await fs.writeFile(goalFile, JSON.stringify({ ...(await readGoal()), round: 100 }), "utf8");
diff --git a/plugins/goal/hooks/lib.mjs b/plugins/goal/hooks/lib.mjs
index fc2552ce..0eb766ad 100644
--- a/plugins/goal/hooks/lib.mjs
+++ b/plugins/goal/hooks/lib.mjs
@@ -94,8 +94,7 @@ export function uncachedTokens(record) {
}
/**
- * The records of the round that just ended: everything after the last round input, or the
- * whole file when there is none in it (a compaction rotated the file mid-round).
+ * Everything after the last round input, or all available records if it is missing.
*/
export function lastRoundRecords(records) {
let start = 0;
@@ -105,6 +104,28 @@ export function lastRoundRecords(records) {
return records.slice(start);
}
+/** Read preceding compaction shards only as far as this round's input. */
+export function readRoundRecords(file, sessionId, records) {
+ const match = /^(.*)_(\d+)\.jsonl$/.exec(path.basename(file));
+ if (!match || match[1] !== sessionId) return lastRoundRecords(records);
+ let index = Number(match[2]);
+ if (!Number.isSafeInteger(index)) return lastRoundRecords(records);
+ const chunks = [records];
+ let chunk = records;
+ while (!chunk.some(isRoundInput) && index > 1) {
+ index -= 1;
+ const previous = readTrace(
+ path.join(path.dirname(file), `${sessionId}_${String(index).padStart(3, "0")}.jsonl`),
+ );
+ const meta = previous.find((r) => r && r.type === "session_meta");
+ // Missing/unreadable shards or another session are not a reason to count older rounds.
+ if (meta?.payload?.session_id !== sessionId) break;
+ chunks.unshift(previous);
+ chunk = previous;
+ }
+ return lastRoundRecords(chunks.flat());
+}
+
/**
* How the round's Task ended, read off its records: an `abort` event is the user's
* interruption; a last `request_end` that is not completed is a failure the run gave up on;
diff --git a/plugins/goal/hooks/stop.mjs b/plugins/goal/hooks/stop.mjs
index a6bc676c..c68d758e 100644
--- a/plugins/goal/hooks/stop.mjs
+++ b/plugins/goal/hooks/stop.mjs
@@ -21,7 +21,7 @@ import path from "node:path";
import {
GOAL_FILE,
MAX_ROUNDS,
- lastRoundRecords,
+ readRoundRecords,
readGoal,
readInput,
readTrace,
@@ -76,7 +76,7 @@ if (goal === "broken") {
// A goal that already ended on this Session (an earlier run) is not this run's business.
if (goal.ended) process.exit(0);
-const round = lastRoundRecords(records);
+const round = readRoundRecords(tracePath, sessionId, records);
goal.tokens_used += round.reduce((n, r) => n + uncachedTokens(r), 0);
if (goal.status === "complete" || goal.status === "blocked") {
diff --git a/plugins/goal/plugin.json b/plugins/goal/plugin.json
index f8e6fb1c..577196e0 100644
--- a/plugins/goal/plugin.json
+++ b/plugins/goal/plugin.json
@@ -3,7 +3,7 @@
"description_zh": "目标模式:一个 stop hook,让会话持续朝目标工作——每轮重新注入目标并检查目标文件——直到目标完成、受阻或 token 预算耗尽。",
"short_description": "Loop the session on an objective until it is done.",
"short_description_zh": "让会话循环推进一个目标直到完成。",
- "version": "2026.09.29.1",
+ "version": "2026.10.28.1",
"category": "office-productivity",
"hooks": {
"user_prompt": [