ceulen 0.29.2 → 0.30.0

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.
@@ -0,0 +1,297 @@
1
+ // Spill recovery must be UTF-8 clean AND terminate.
2
+ //
3
+ // Two independent failure modes are pinned here, both found by live panes:
4
+ //
5
+ // 1. RE-SPILL: a recovery page over the active budget spills again and the
6
+ // model loops. Every page must estimate under the budget.
7
+ // 2. UTF-8 SPLIT: a raw `head -c N` cuts a multibyte character at the page
8
+ // boundary, and bash decodes each page INDEPENDENTLY — so the character is
9
+ // lost in BOTH pages (measured: a 3-byte `日` straddling byte 996 decoded
10
+ // to U+FFFD at page 1's end AND page 2's start). The fix is `iconv -c` plus
11
+ // a page that reports its OWN next offset, so paging never guesses.
12
+ //
13
+ // These tests RUN the command the notice emits, verbatim, and reassemble the
14
+ // whole payload — a text assertion cannot catch either bug.
15
+ import assert from "node:assert/strict";
16
+ import { execFileSync } from "node:child_process";
17
+ import { statSync } from "node:fs";
18
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
19
+ import { tmpdir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { after, describe, it } from "node:test";
22
+ import {
23
+ PAGE_BYTE_LIMIT,
24
+ PAGE_LINE_LIMIT,
25
+ PI_BASH_BYTE_LIMIT,
26
+ PI_BASH_LINE_LIMIT,
27
+ estimateTokens,
28
+ formatSpillNotice,
29
+ maxRecoveryBytes,
30
+ maxRecoveryPageBytes,
31
+ shortestLineLength,
32
+ } from "../lib/spill.js";
33
+
34
+ const dirs: string[] = [];
35
+ after(async () => {
36
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
37
+ });
38
+
39
+ async function fixture(text: string): Promise<string> {
40
+ const dir = await mkdtemp(join(tmpdir(), "spill-utf8-"));
41
+ dirs.push(dir);
42
+ const file = join(dir, "payload.txt");
43
+ await writeFile(file, text, "utf8");
44
+ return file;
45
+ }
46
+
47
+ /** The bash template the notice emits, with the offset argument filled in. */
48
+ function pageTemplate(file: string, budget: number): string {
49
+ const notice = formatSpillNotice(1, file, 80, budget);
50
+ const start = notice.indexOf("bash -c ");
51
+ assert.ok(start >= 0, "notice must emit a bash page command");
52
+ return notice.slice(start).trim();
53
+ }
54
+
55
+ /** Reassemble the whole file by running the emitted command page by page. */
56
+ function recover(file: string, budget: number): { text: string; pages: number; sizes: number[] } {
57
+ const template = pageTemplate(file, budget);
58
+ const size = statSync(file).size;
59
+ let offset = 1;
60
+ let text = "";
61
+ let pages = 0;
62
+ const sizes: number[] = [];
63
+ while (offset <= size && pages < 4000) {
64
+ const out = execFileSync("/bin/sh", ["-c", template.replace("_ OFFSET", `_ ${offset}`)], {
65
+ encoding: "utf8",
66
+ maxBuffer: 64 << 20,
67
+ });
68
+ const marker = /\[next OFFSET = (\d+)\]\n$/.exec(out);
69
+ assert.ok(marker, `page at ${offset} printed no next-offset marker`);
70
+ const page = out.slice(0, marker.index);
71
+ text += page;
72
+ sizes.push(page.length);
73
+ const next = Number(marker[1]);
74
+ assert.ok(next > offset, `offset must advance (was ${offset}, page reported ${next})`);
75
+ assert.equal(next, offset + Buffer.byteLength(page, "utf8"), "reported offset must equal offset + bytes printed");
76
+ offset = next;
77
+ pages++;
78
+ }
79
+ return { text, pages, sizes };
80
+ }
81
+
82
+ describe("recovery round trip", () => {
83
+ const fixtures: Array<[string, string]> = [
84
+ ["ascii", "x".repeat(5_000)],
85
+ ["multibyte wide", `${"日本語テキスト😀 héllo wörld\n".repeat(400)}`],
86
+ ["split at the boundary", `${"a".repeat(995)}日${"b".repeat(5_000)}`],
87
+ ["emoji-dense", "😀🎉🚀".repeat(1_500)],
88
+ ];
89
+
90
+ for (const [label, payload] of fixtures) {
91
+ it(`recovers ${label} byte-for-byte at the default budget`, async () => {
92
+ const file = await fixture(payload);
93
+ const { text, pages } = recover(file, 12_500);
94
+ assert.equal(text, payload, "reassembled text must equal the original");
95
+ assert.ok(!text.includes("\uFFFD"), "no replacement characters");
96
+ assert.ok(pages >= 1);
97
+ });
98
+ }
99
+
100
+ it("recovers a multibyte payload at a LOWERED budget", async () => {
101
+ const payload = "日本語😀abc\n".repeat(300);
102
+ const file = await fixture(payload);
103
+ const { text, sizes } = recover(file, 2_000);
104
+ assert.equal(text, payload);
105
+ assert.ok(!text.includes("\uFFFD"));
106
+ // And no page may re-spill.
107
+ for (const size of sizes) {
108
+ assert.ok(estimateTokens([{ type: "text", text: "x".repeat(size) }]) <= 2_000);
109
+ }
110
+ });
111
+
112
+ it("strips only the incomplete trailing sequence, never a whole character", async () => {
113
+ // 995 ASCII + a 3-byte char straddling the 996-byte boundary: page 1 must
114
+ // drop exactly the 1 dangling byte and keep all 995 ASCII characters.
115
+ const payload = `${"a".repeat(995)}日${"b".repeat(500)}`;
116
+ const file = await fixture(payload);
117
+ const budget = 2_000; // chunk 996
118
+ assert.equal(maxRecoveryBytes(budget), 996);
119
+
120
+ const template = pageTemplate(file, budget);
121
+ const first = execFileSync("/bin/sh", ["-c", template.replace("_ OFFSET", "_ 1")], { encoding: "utf8" });
122
+ const page = first.slice(0, first.lastIndexOf("[next OFFSET"));
123
+ assert.equal(page, "a".repeat(995), "page 1 keeps 995 ASCII chars and drops only the dangling byte");
124
+ assert.match(first, /\[next OFFSET = 996\]\n$/);
125
+ });
126
+ });
127
+
128
+ describe("page line cap (pi's bash truncates the HEAD past 2000 lines)", () => {
129
+ it("bounds the byte window by the shortest line, not just the budget", () => {
130
+ // 1-byte lines are the worst case: 6,246 bytes would be 6,246 lines, and
131
+ // pi's bash keeps only the LAST 2000 — dropping the head our offset has
132
+ // already advanced past.
133
+ const wide = maxRecoveryPageBytes(12_500, 1);
134
+ assert.ok(wide <= PAGE_LINE_LIMIT, `${wide} must fit ${PAGE_LINE_LIMIT} one-byte lines`);
135
+ assert.ok(wide < maxRecoveryBytes(12_500), "the line cap narrows the byte window");
136
+ // A long minimum line cannot exceed the token budget either.
137
+ assert.equal(maxRecoveryPageBytes(12_500, 100), maxRecoveryBytes(12_500));
138
+ });
139
+
140
+ it("shrinks the advertised window for short-line payloads", () => {
141
+ const short = formatSpillNotice(1, "/tmp/x.txt", 2, 12_500, 2);
142
+ const long = formatSpillNotice(1, "/tmp/x.txt", 2, 12_500, 100);
143
+ const shortChunk = Number(short.match(/~(\d+)-byte/)?.[1]);
144
+ const longChunk = Number(long.match(/~(\d+)-byte/)?.[1]);
145
+ assert.ok(shortChunk < longChunk, `short lines must page smaller (${shortChunk} vs ${longChunk})`);
146
+ assert.ok(shortChunk <= 2 * PAGE_LINE_LIMIT, "two-byte lines must fit the line cap");
147
+ });
148
+
149
+ it("caps the page with head -n so it can never overflow pi's line limit", () => {
150
+ const notice = formatSpillNotice(1, "/tmp/x.txt", 2, 12_500, 1);
151
+ assert.match(notice, new RegExp(`head -n ${PAGE_LINE_LIMIT}`));
152
+ assert.ok(PAGE_LINE_LIMIT < PI_BASH_LINE_LIMIT, "headroom under pi's cap");
153
+ });
154
+
155
+ it("shortestLineLength ignores empty lines and defaults to 1", () => {
156
+ assert.equal(shortestLineLength(""), 1);
157
+ assert.equal(shortestLineLength("\n\n\n"), 1);
158
+ assert.equal(shortestLineLength("a\nbbbb\n\ncc"), 1);
159
+ assert.equal(shortestLineLength("abc\nde\nfghij"), 2);
160
+ });
161
+
162
+ // End-to-end: every page must survive pi's REAL truncation path and the
163
+ // reassembly must equal the file. /bin/sh alone cannot see this cap.
164
+ it("every emitted page survives pi's bash truncateTail and reassembles exactly", async () => {
165
+ const { truncateTail } = await import(
166
+ // Pi exposes no subpath export for this module; import it by path.
167
+ "../../../../node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.js"
168
+ );
169
+ for (const payload of ["ab\n".repeat(6_000), "a\n".repeat(9_000), "\n".repeat(9_000)]) {
170
+ const file = await fixture(payload);
171
+ const budget = 12_500;
172
+ const notice = formatSpillNotice(1, file, 80, budget, shortestLineLength(payload));
173
+ const template = notice.slice(notice.indexOf("bash -c ")).trim();
174
+ const size = statSync(file).size;
175
+ let offset = 1;
176
+ let out = "";
177
+ let pages = 0;
178
+ while (offset <= size && pages < 4_000) {
179
+ const raw = execFileSync("/bin/sh", ["-c", template.replace("_ OFFSET", `_ ${offset}`)], {
180
+ encoding: "utf8", maxBuffer: 64 << 20,
181
+ });
182
+ const marker = /\[next OFFSET = (\d+)\]\n$/.exec(raw);
183
+ assert.ok(marker, `page at ${offset} printed no marker`);
184
+ const page = raw.slice(0, marker.index);
185
+ const t = truncateTail(page);
186
+ assert.equal(t.truncated, false, `page at ${offset} was truncated by pi (${t.truncatedBy}) — data would be lost`);
187
+ out += page;
188
+ offset = Number(marker[1]);
189
+ pages++;
190
+ }
191
+ assert.equal(out, payload, "reassembly must be byte-exact");
192
+ }
193
+ });
194
+ });
195
+
196
+ describe("page byte cap (pi's bash truncates past 50 KiB)", () => {
197
+ it("clamps the window under pi's byte cap even at a raised budget", () => {
198
+ // The budget alone does not bound bytes: spillMaxTokens 200,000 asks for a
199
+ // 99,996-byte page — nearly 2x pi's 50 KiB cap, so bash drops the HEAD.
200
+ for (const budget of [12_500, 50_000, 100_000, 200_000, 1_000_000]) {
201
+ for (const minLine of [1, 80, 10_000, 40_000]) {
202
+ const windowBytes = maxRecoveryPageBytes(budget, minLine);
203
+ assert.ok(
204
+ windowBytes <= PAGE_BYTE_LIMIT,
205
+ `budget=${budget} minLine=${minLine} → ${windowBytes} exceeds PAGE_BYTE_LIMIT ${PAGE_BYTE_LIMIT}`,
206
+ );
207
+ assert.ok(windowBytes <= PI_BASH_BYTE_LIMIT, "must stay under pi's bash cap");
208
+ }
209
+ }
210
+ assert.ok(PAGE_BYTE_LIMIT < PI_BASH_BYTE_LIMIT, "headroom under pi's cap");
211
+ });
212
+
213
+ it("advertises the clamped window in the notice at a high budget", () => {
214
+ const notice = formatSpillNotice(1, "/tmp/big.txt", 40_000, 200_000, 40_000);
215
+ const chunk = Number(notice.match(/head -c (\d+)/)?.[1]);
216
+ assert.ok(chunk > 0 && chunk <= PAGE_BYTE_LIMIT, `advertised ${chunk} must be clamped`);
217
+ });
218
+
219
+ // The advisor's case, end to end: high budget + long lines, and the check
220
+ // passes the page's RAW output INCLUDING the offset marker to pi's
221
+ // truncateTail — because the marker is part of what bash evaluates against
222
+ // its byte/line caps, not something appended after the fact.
223
+ it("high-budget long-line pages survive truncateTail with the marker included", async () => {
224
+ const { truncateTail } = await import(
225
+ "../../../../node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.js"
226
+ );
227
+ // 400-char lines: long enough that the LINE window never binds, so only
228
+ // the byte cap can protect the page.
229
+ const payload = `${"x".repeat(399)}\n`.repeat(2_000);
230
+ const file = await fixture(payload);
231
+ const size = statSync(file).size;
232
+
233
+ for (const budget of [12_500, 50_000, 200_000]) {
234
+ const notice = formatSpillNotice(1, file, 399, budget, 400);
235
+ const template = notice.slice(notice.indexOf("bash -c ")).trim();
236
+
237
+ let offset = 1;
238
+ let out = "";
239
+ let pages = 0;
240
+ while (offset <= size && pages < 2_000) {
241
+ const raw = execFileSync("/bin/sh", ["-c", template.replace("_ OFFSET", `_ ${offset}`)], {
242
+ encoding: "utf8", maxBuffer: 64 << 20,
243
+ });
244
+ // RAW output, marker included — the marker is part of the tool result.
245
+ const t = truncateTail(raw);
246
+ assert.equal(
247
+ t.truncated, false,
248
+ `budget=${budget} page at ${offset}: pi truncated RAW output (${t.truncatedBy}, ` +
249
+ `${Buffer.byteLength(raw)} bytes / ${raw.split("\n").length} lines) — head would be lost`,
250
+ );
251
+ assert.ok(Buffer.byteLength(raw) <= PI_BASH_BYTE_LIMIT);
252
+
253
+ const marker = /\[next OFFSET = (\d+)\]\n$/.exec(raw);
254
+ assert.ok(marker, `budget=${budget} page at ${offset} lost its marker`);
255
+ out += raw.slice(0, marker.index);
256
+ offset = Number(marker[1]);
257
+ pages++;
258
+ }
259
+ assert.equal(out, payload, `budget=${budget}: reassembly must be byte-exact`);
260
+ }
261
+ });
262
+ });
263
+
264
+ describe("byte-cap risk region is qualified by the line window", () => {
265
+ // The byte clamp protects a region the LINE window does not: `byLines =
266
+ // minLine * PAGE_LINE_LIMIT` binds first for short lines, so the old
267
+ // over-cap window only exists once minLine is large enough. Pinning the
268
+ // boundaries keeps the documentation's numbers honest.
269
+ const budget = 200_000;
270
+ const byBudget = maxRecoveryBytes(budget);
271
+ const oldWindow = (minLine: number) => Math.min(byBudget, minLine * PAGE_LINE_LIMIT);
272
+
273
+ it("the old formula only exceeds pi's byte cap from minLine 27 up", () => {
274
+ assert.ok(oldWindow(26) <= PI_BASH_BYTE_LIMIT, `minLine=26 → ${oldWindow(26)} must already be under the cap`);
275
+ assert.ok(oldWindow(27) > PI_BASH_BYTE_LIMIT, `minLine=27 → ${oldWindow(27)} must be the first over-cap value`);
276
+ // Below the byte clamp the LINE window was the only protection.
277
+ assert.equal(oldWindow(1), PAGE_LINE_LIMIT);
278
+ });
279
+
280
+ it("the full 99,996-byte window needs minLine >= 53", () => {
281
+ assert.equal(Math.ceil(byBudget / PAGE_LINE_LIMIT), 53);
282
+ assert.equal(oldWindow(52), 98_800);
283
+ assert.equal(oldWindow(53), byBudget);
284
+ assert.equal(oldWindow(40_000), byBudget);
285
+ });
286
+
287
+ it("the shipped formula clamps at every minLine", () => {
288
+ for (const minLine of [1, 26, 27, 52, 53, 80, 1_000, 40_000]) {
289
+ for (const b of [12_500, 50_000, 200_000, 1_000_000]) {
290
+ assert.ok(
291
+ maxRecoveryPageBytes(b, minLine) <= PAGE_BYTE_LIMIT,
292
+ `budget=${b} minLine=${minLine} must be clamped`,
293
+ );
294
+ }
295
+ }
296
+ });
297
+ });
@@ -0,0 +1,208 @@
1
+ // Spill policy: estimation, retention geometry, store escaping, and the
2
+ // handler's exclusion contract.
3
+ //
4
+ // The exclusions are the load-bearing part: stock read/bash truncate INSIDE the
5
+ // tool before `tool_result` fires, so spilling them would bound an
6
+ // already-bounded result and point at a file that cannot restore the dropped
7
+ // bytes. The discriminator is METADATA (details.truncation / details.fullOutputPath),
8
+ // never notice text — a wrapped read of a file CONTAINING "Use offset=" must
9
+ // still spill.
10
+ import assert from "node:assert/strict";
11
+ import { after, describe, it } from "node:test";
12
+ import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ CHARS_PER_TOKEN,
17
+ DEFAULT_SPILL_MAX_TOKENS,
18
+ PI_READ_LINE_LIMIT,
19
+ estimateTextTokens,
20
+ estimateTokens,
21
+ fitText,
22
+ formatSpillNotice,
23
+ longestLineLength,
24
+ maxRecoveryBytes,
25
+ retainContent,
26
+ textSlice,
27
+ } from "../lib/spill.js";
28
+ import { encodeSegment, privateRoot, saveSpill } from "../lib/spill-store.js";
29
+
30
+ const dirs: string[] = [];
31
+ after(async () => {
32
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
33
+ });
34
+
35
+ describe("estimate", () => {
36
+ it("prices text at the fixed density plus per-block overhead", () => {
37
+ assert.equal(estimateTextTokens(""), 4);
38
+ assert.equal(estimateTextTokens("a".repeat(CHARS_PER_TOKEN * 10)), 4 + 10);
39
+ assert.equal(estimateTokens([{ type: "text", text: "a".repeat(40) }, { type: "image" }]), 4 + 10);
40
+ });
41
+
42
+ it("default budget matches DSH's base preset", () => {
43
+ assert.equal(DEFAULT_SPILL_MAX_TOKENS, 12_500);
44
+ });
45
+
46
+ it("a stock-truncated read (50KB) exceeds the default budget — why metadata, not budget, discriminates", () => {
47
+ // pi's read caps at 50KB; that is ~12,800 estimated tokens, ABOVE 12,500.
48
+ assert.ok(estimateTextTokens("a".repeat(50 * 1024)) > DEFAULT_SPILL_MAX_TOKENS);
49
+ });
50
+ });
51
+
52
+ describe("retention geometry", () => {
53
+ it("never splits a surrogate pair", () => {
54
+ // "😀" is one code point, two UTF-16 units. A cut between them must move.
55
+ const text = `a${"😀".repeat(20)}`;
56
+ for (let length = 1; length < text.length; length++) {
57
+ const head = textSlice(text, length, false);
58
+ const tail = textSlice(text, length, true);
59
+ assert.ok(!/[\ud800-\udbff]$/.test(head), `head ${length} ends on a lone surrogate`);
60
+ assert.ok(!/^[\udc00-\udfff]/.test(tail), `tail ${length} starts on a lone surrogate`);
61
+ }
62
+ });
63
+
64
+ it("fitText keeps the largest end under budget", () => {
65
+ const text = "x".repeat(1000);
66
+ const head = fitText(text, 100, false);
67
+ assert.ok(head.length > 0 && head.length < text.length);
68
+ assert.ok(estimateTextTokens(head) <= 100);
69
+ assert.ok(estimateTextTokens("x".repeat(head.length + 1)) > 100);
70
+ });
71
+
72
+ it("splits head and tail with no overlap and reports the omitted bytes", () => {
73
+ const texts = ["A".repeat(2000), "B".repeat(2000)];
74
+ const retained = retainContent(texts, 200);
75
+ const headText = retained.head.map((b) => b.text).join("");
76
+ const tailText = retained.tail.map((b) => b.text).join("");
77
+ assert.ok(headText.length > 0, "head retained");
78
+ assert.ok(tailText.length > 0, "tail retained");
79
+ const original = 4000;
80
+ assert.equal(retained.omittedBytes, original - headText.length - tailText.length);
81
+ assert.ok(retained.omittedBytes > 0);
82
+ // The retained ends must not re-emit the same characters.
83
+ assert.ok(headText.length + tailText.length <= original);
84
+ });
85
+
86
+ it("does not duplicate a single oversized block across both ends", () => {
87
+ const retained = retainContent(["0123456789".repeat(100)], 100);
88
+ const headText = retained.head.map((b) => b.text).join("");
89
+ const tailText = retained.tail.map((b) => b.text).join("");
90
+ assert.ok(headText.length + tailText.length <= 1000);
91
+ });
92
+
93
+ it("notice names the recovery file", () => {
94
+ const notice = formatSpillNotice(1234, "/tmp/ceulen-spill-x/tool-1.txt");
95
+ assert.match(notice, /1234 bytes omitted/);
96
+ assert.match(notice, /Full output saved to: \/tmp\/ceulen-spill-x\/tool-1\.txt/);
97
+ // Every branch pages by bytes now — see the "NEVER recommends read" test.
98
+ assert.match(notice, /Retrieve it in <=1900-line, ~\d+-byte UTF-8-safe pages with bash/);
99
+ assert.match(notice, /cat \/tmp\/ceulen-spill-x\/tool-1\.txt \| tail -c \+\$OFFSET \| head -c \d+/);
100
+ });
101
+
102
+ it("tells the model to page with bash when the payload is one over-limit line", () => {
103
+ // pi's read REFUSES a single line over 50KB, so "use read" would be dead
104
+ // advice for minified JSON / a single long log line (live finding, herdr).
105
+ const notice = formatSpillNotice(1234, "/tmp/x/tool-1.txt", longestLineLength("a".repeat(150_000)));
106
+ assert.match(notice, /Retrieve it in <=1900-line, ~6246-byte UTF-8-safe pages with bash/);
107
+ assert.match(notice, /cat \/tmp\/x\/tool-1\.txt \| tail -c \+\$OFFSET \| head -c 6246/);
108
+ assert.doesNotMatch(notice, /Use read with that path/);
109
+ });
110
+
111
+ it("emits a UTF-8-safe page command with a self-reporting offset", () => {
112
+ // A raw `head -c` splits a multibyte char at the boundary, and bash decodes
113
+ // each page independently — the char is lost in BOTH pages. `iconv -c`
114
+ // drops the incomplete tail and the page prints the ACTUAL next offset.
115
+ const notice = formatSpillNotice(1234, "/tmp/x/a b.txt", 80, 2_000);
116
+ assert.match(notice, /iconv -f UTF-8 -t UTF-8 -c/);
117
+ assert.match(notice, /\[next OFFSET = %d\]/);
118
+ assert.match(notice, /OFFSET=\$1/, "OFFSET is a shell variable, not a pasted literal");
119
+ });
120
+
121
+ it("sizes the recovery chunk UNDER the active budget so it cannot re-spill", () => {
122
+ // The advisor finding, as arithmetic: `head -c 50000` of ASCII estimates to
123
+ // 12,504 tokens with block overhead — over the 12,500 default — so the
124
+ // recovery would itself spill and loop the model.
125
+ const fiftyK = estimateTokens([{ type: "text", text: "x".repeat(50_000) }]);
126
+ assert.ok(fiftyK > DEFAULT_SPILL_MAX_TOKENS, `50KB must exceed the budget (got ${fiftyK})`);
127
+
128
+ for (const budget of [2_000, 12_500, 40_000]) {
129
+ const chunk = maxRecoveryBytes(budget);
130
+ assert.ok(chunk > 0, `budget ${budget} must still leave a usable chunk`);
131
+ const cost = estimateTokens([{ type: "text", text: "x".repeat(chunk) }]);
132
+ assert.ok(cost <= budget, `budget ${budget}: chunk ${chunk} costs ${cost} — must not re-spill`);
133
+ }
134
+ });
135
+
136
+ it("shrinks the chunk when the user lowers the budget", () => {
137
+ assert.ok(maxRecoveryBytes(2_000) < maxRecoveryBytes(12_500));
138
+ assert.ok(maxRecoveryBytes(12_500) < maxRecoveryBytes(40_000));
139
+ });
140
+
141
+ it("NEVER recommends read, even for short-line payloads", () => {
142
+ // read is never safe here: the spill file exceeds the budget by definition.
143
+ // pi's read caps at 50KB/2000 lines with no byte-budget parameter, and
144
+ // 50KB alone estimates to 12,804 tokens — over the 12,500 default.
145
+ const multiline = "line of text\n".repeat(10_000);
146
+ const notice = formatSpillNotice(1234, "/tmp/x/tool-1.txt", longestLineLength(multiline), 12_500);
147
+ assert.doesNotMatch(notice, /Use read with that path/);
148
+ assert.match(notice, /Retrieve it in <=1900-line, ~\d+-byte UTF-8-safe pages with bash/);
149
+ assert.match(notice, /read would return more than this result's budget and spill again/);
150
+ });
151
+
152
+ it("pages under a LOWERED budget instead of suggesting read (advisor case)", () => {
153
+ // 9,000 ASCII chars over 100 lines fits pi's read caps but costs 2,254
154
+ // estimated tokens — over a 2,000 budget, so an untruncated read re-spills.
155
+ const payload = ("x".repeat(89) + "\n").repeat(100);
156
+ assert.equal(payload.length, 9_000);
157
+ assert.ok(estimateTextTokens(payload) > 2_000);
158
+
159
+ const notice = formatSpillNotice(payload.length, "/tmp/x/short.txt", longestLineLength(payload), 2_000);
160
+ assert.doesNotMatch(notice, /Use read with that path/);
161
+ const chunk = Number(notice.match(/~(\d+)-byte UTF-8-safe pages/)?.[1]);
162
+ assert.ok(chunk > 0, "a usable chunk survives a small budget");
163
+ assert.ok(estimateTextTokens("x".repeat(chunk)) <= 2_000, `chunk ${chunk} must fit the 2,000 budget`);
164
+ });
165
+
166
+ it("measures the longest line, not the whole text", () => {
167
+ assert.equal(longestLineLength(""), 0);
168
+ assert.equal(longestLineLength("abc"), 3);
169
+ assert.equal(longestLineLength("a\nbbbb\ncc"), 4);
170
+ assert.equal(longestLineLength("trailing\n"), 8);
171
+ assert.equal(longestLineLength(PI_READ_LINE_LIMIT > 0 ? "a".repeat(PI_READ_LINE_LIMIT) : ""), PI_READ_LINE_LIMIT);
172
+ });
173
+ });
174
+
175
+ describe("store", () => {
176
+ it("encodes untrusted segments injectively and never traverses", () => {
177
+ assert.equal(encodeSegment(""), "~");
178
+ assert.equal(encodeSegment("."), "~002E");
179
+ assert.equal(encodeSegment(".."), "~002E~002E");
180
+ const traversal = encodeSegment("../../etc/passwd");
181
+ assert.ok(!traversal.includes("/"), "no separator survives");
182
+ // `.` is a safe character (it appears in every filename), so dot PAIRS may
183
+ // remain as a substring — what must never survive is a separator or a
184
+ // whole-segment `..`, and the latter is escaped above.
185
+ assert.ok(!/^\.\.$/.test(traversal), "no whole-segment dot-dot survives");
186
+ assert.notEqual(encodeSegment("a~b"), encodeSegment("a/b"));
187
+ assert.equal(encodeSegment("plain-name_1.txt"), "plain-name_1.txt");
188
+ });
189
+
190
+ it("writes the full text and returns a readable path", async () => {
191
+ const dir = await mkdtemp(join(tmpdir(), "spill-store-"));
192
+ dirs.push(dir);
193
+ process.env.TMPDIR = dir;
194
+ const full = "payload ".repeat(5000);
195
+ const file = await saveSpill("web_extract", "call/1", full);
196
+ assert.ok(file.startsWith(privateRoot()));
197
+ await stat(file);
198
+ assert.equal(await readFile(file, "utf8"), full);
199
+ });
200
+
201
+ it("never overwrites an earlier spill when a call id repeats", async () => {
202
+ const first = await saveSpill("read", "same-id", "first payload");
203
+ const second = await saveSpill("read", "same-id", "second payload");
204
+ assert.notEqual(first, second, "each spill is immutable");
205
+ assert.equal(await readFile(first, "utf8"), "first payload", "the earlier path still recovers its own text");
206
+ assert.equal(await readFile(second, "utf8"), "second payload");
207
+ });
208
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.29.2",
3
+ "version": "0.30.0",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -10,6 +10,13 @@
10
10
  #
11
11
  # Usage: scripts/check-provenance-fixtures.sh [path-to-AGENTS.md]
12
12
  # Exit: 0 = every row reproduced; 1 = a row disagreed or the table changed shape.
13
+ #
14
+ # NOTE: this checks the REPO's documentation, so it needs AGENTS.md — which is
15
+ # deliberately not in package.json `files` (npm ships extensions/skills/themes/
16
+ # scripts + README/LICENSE/CHANGELOG). In an npm-installed copy there is no
17
+ # table to check and the script fails with "no such file"; run it from a
18
+ # checkout. `verify-provenance.sh` and `audit-attestations.sh` have no such
19
+ # dependency and work from an installed package.
13
20
  set -eu
14
21
 
15
22
  DOC="${1:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)/AGENTS.md}"
@@ -0,0 +1,90 @@
1
+ #!/bin/sh
2
+ # Smoke-test the npm-installable tarball: install into a throwaway directory and
3
+ # assert the payload, with a non-zero exit for EVERY kind of wrong answer.
4
+ #
5
+ # Exists because AGENTS.md tells you to "install it from a clean directory and
6
+ # assert the payload" before calling a release shipped, and hand-rolling that
7
+ # check has repeatedly produced exit codes that meant nothing — capturing $?
8
+ # after a pipeline, or a node -e that only printed results without calling
9
+ # process.exit. Every assertion here is fatal.
10
+ #
11
+ # Checks, each independently fatal:
12
+ # - npm install's own exit status (captured without a pipe)
13
+ # - installed package.json version == the requested version
14
+ # - every --require path exists in the installed package
15
+ # - every --forbid path is ABSENT (deleted files must stay deleted)
16
+ #
17
+ # Usage: scripts/smoke-install.sh <version> [package]
18
+ # [--require <path-in-package>]...
19
+ # [--forbid <path-in-package>]...
20
+ # Exit: 0 = installed and every assertion held; 1 = a check failed; 2 = bad usage.
21
+ set -eu
22
+
23
+ VERSION=""
24
+ PACKAGE="ceulen"
25
+ REQUIRE=""
26
+ FORBID=""
27
+ # Version the installed package.json must report. Defaults to the version we
28
+ # install; --expect-version exists so the mismatch guard is testable through the
29
+ # real CLI instead of by poking at internals.
30
+ EXPECT_VERSION=""
31
+ while [ $# -gt 0 ]; do
32
+ case "$1" in
33
+ --require) REQUIRE="$REQUIRE $2"; shift 2 ;;
34
+ --forbid) FORBID="$FORBID $2"; shift 2 ;;
35
+ --package) PACKAGE="$2"; shift 2 ;;
36
+ --expect-version) EXPECT_VERSION="$2"; shift 2 ;;
37
+ -*) echo "unknown option: $1" >&2; exit 2 ;;
38
+ *) [ -z "$VERSION" ] && VERSION="$1" || { echo "unexpected argument: $1" >&2; exit 2; }; shift ;;
39
+ esac
40
+ done
41
+ [ -n "$VERSION" ] || { echo "usage: smoke-install.sh <version> [package] [--require p]... [--forbid p]... [--expect-version v]" >&2; exit 2; }
42
+ [ -n "$EXPECT_VERSION" ] || EXPECT_VERSION="$VERSION"
43
+
44
+ WORK=$(mktemp -d)
45
+ trap 'rm -rf "$WORK"' EXIT INT TERM
46
+ cd "$WORK"
47
+
48
+ # npm's OWN exit status — no pipeline, so nothing can mask it.
49
+ if ! npm install "$PACKAGE@$VERSION" --no-save --loglevel=error > install.log 2>&1; then
50
+ echo "FAIL: npm install $PACKAGE@$VERSION exited non-zero" >&2
51
+ tail -20 install.log >&2
52
+ exit 1
53
+ fi
54
+ echo "ok npm install $PACKAGE@$VERSION — exit 0"
55
+
56
+ BASE="node_modules/$PACKAGE"
57
+ SMOKE_BASE="$BASE" SMOKE_VERSION="$EXPECT_VERSION" SMOKE_REQUIRE="$REQUIRE" SMOKE_FORBID="$FORBID" node -e '
58
+ const fs = require("fs");
59
+ const path = require("path");
60
+ const base = process.env.SMOKE_BASE;
61
+ const want = process.env.SMOKE_VERSION;
62
+ const split = (s) => (s || "").trim().split(/\s+/).filter(Boolean);
63
+ const require_ = split(process.env.SMOKE_REQUIRE);
64
+ const forbid = split(process.env.SMOKE_FORBID);
65
+
66
+ let bad = 0;
67
+ const fail = (m) => { console.error("FAIL: " + m); bad = 1; };
68
+
69
+ let pkg;
70
+ try {
71
+ pkg = JSON.parse(fs.readFileSync(path.join(base, "package.json"), "utf8"));
72
+ } catch (e) {
73
+ console.error("FAIL: cannot read the installed package.json — extraction failed");
74
+ process.exit(1);
75
+ }
76
+
77
+ if (pkg.version !== want) fail("installed version " + pkg.version + " != requested " + want);
78
+ else console.log("ok version " + pkg.version);
79
+
80
+ for (const f of require_) {
81
+ if (fs.existsSync(path.join(base, f))) console.log("ok present " + f);
82
+ else fail("missing " + f);
83
+ }
84
+ for (const f of forbid) {
85
+ if (fs.existsSync(path.join(base, f))) fail("unexpected " + f + " (should not ship)");
86
+ else console.log("ok absent " + f);
87
+ }
88
+
89
+ process.exit(bad ? 1 : 0);
90
+ '