1 +import assert from "node:assert/strict";
2 +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import { dirname, join } from "node:path";
5 +import { spawnSync } from "node:child_process";
6 +import { fileURLToPath } from "node:url";
7 +import test from "node:test";
8 +import { inspect } from "./inspect.mjs";
10 +const script = fileURLToPath(new URL("./inspect.mjs", import.meta.url));
11 +const stamp = "2026-09-01T12:00:00.000Z";
12 +const entry = (id, parentId, type, rest = {}) => ({ id, parentId, type, timestamp: stamp, ...rest });
13 +const message = (id, parentId, role, rest = {}) =>
14 + entry(id, parentId, "message", {
15 + message: { role, content: [{ type: "text", text: `${role} text` }], ...rest },
18 +function fixture(t) {
19 + const root = mkdtempSync(join(tmpdir(), "pi-sessions-test-"));
20 + t.after(() => rmSync(root, { recursive: true, force: true }));
21 + const cwd = join(root, "project");
22 + const home = join(root, "home");
23 + const agent = join(home, ".pi/agent");
24 + const store = join(home, ".local/state/pi/sessions");
25 + for (const dir of [cwd, agent, store]) mkdirSync(dir, { recursive: true });
26 + const ctx = { cwd, home, env: {} };
27 + function json(file, value) {
28 + mkdirSync(dirname(file), { recursive: true });
29 + writeFileSync(file, JSON.stringify(value));
31 + function add(id, name = "task", entries = [message("u", null, "user")], options = {}) {
32 + const file = join(options.dir ?? store, `${id}.jsonl`);
37 + cwd: options.cwd ?? cwd,
38 + timestamp: options.timestamp ?? stamp,
40 + const records = [header, ...entries];
41 + if (name !== null) records.push(entry("name", entries.at(-1)?.id ?? null, "session_info", { name }));
42 + mkdirSync(dirname(file), { recursive: true });
43 + writeFileSync(file, `${records.map((e) => JSON.stringify(e)).join("\n")}\n`);
46 + return { root, cwd, home, agent, store, ctx, json, add };
49 +test("storage precedence: CLI, environment, project, global, then ordered fallbacks", async (t) => {
50 + const f = fixture(t);
51 + for (const id of ["cli", "env", "project", "global"]) f.add(id, id, [], { dir: join(f.cwd, id) });
52 + f.json(join(f.agent, "settings.json"), { sessionDir: "global" });
53 + f.json(join(f.cwd, ".pi/settings.json"), { sessionDir: "project" });
54 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "project");
55 + f.ctx.env.PI_CODING_AGENT_SESSION_DIR = "env";
56 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "env");
57 + assert.equal((await inspect(["list", "--session-dir", "cli"], f.ctx)).sessions[0].id, "cli");
58 + delete f.ctx.env.PI_CODING_AGENT_SESSION_DIR;
59 + rmSync(join(f.cwd, ".pi/settings.json"));
60 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "global");
61 + f.json(join(f.agent, "settings.json"), { sessionDir: "missing" });
63 + assert.equal((await inspect(["list"], f.ctx)).total, 0, "configured empty roots never fall through");
64 + rmSync(join(f.agent, "settings.json"));
65 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "fallback");
66 + rmSync(f.store, { recursive: true });
67 + f.add("agent", "agent", [], { dir: join(f.agent, "sessions/nested") });
68 + f.add("local", "local", [], { dir: join(f.cwd, ".pi/sessions") });
69 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "agent");
70 + rmSync(join(f.agent, "sessions"), { recursive: true });
71 + assert.equal((await inspect(["list"], f.ctx)).sessions[0].id, "local");
74 +test("agent directory and tilde settings resolve without loading other settings fields", async (t) => {
75 + const f = fixture(t);
76 + const agent = join(f.root, "agent override");
77 + f.json(join(agent, "settings.json"), { sessionDir: "~/sessions", irrelevant: "NEVER_EMIT_SETTINGS_CONTENT" });
78 + f.ctx.env.PI_CODING_AGENT_DIR = agent;
79 + f.add("custom", "custom", [], { dir: join(f.home, "sessions") });
80 + const result = await inspect(["list"], f.ctx);
81 + assert.equal(result.sessions[0].id, "custom");
82 + assert.doesNotMatch(JSON.stringify(result), /NEVER_EMIT_SETTINGS_CONTENT/);
85 +test("list filters literal names, exact cwd, UTC dates and pages with stable ordering", async (t) => {
86 + const f = fixture(t);
87 + f.add("bbb", "same [literal]", [], { timestamp: "2026-09-02T12:00:00Z" });
88 + f.add("aaa", "same [literal]", [], { timestamp: "2026-09-02T12:00:00Z" });
89 + f.add("old", "same [literal]", [], { timestamp: "2026-08-31T12:00:00Z" });
90 + f.add("other", "another", [], { cwd: join(f.cwd, "other") });
91 + const r = await inspect(
108 + assert.equal(r.total, 2);
109 + assert.equal(r.sessions.length, 1);
110 + assert.equal(r.sessions[0].id, "bbb");
111 + f.add("utc", "offset date", [], { timestamp: "2026-09-01T01:00:00+02:00" });
112 + const utc = await inspect(["list", "offset date", "--until", "2026-08-31"], f.ctx);
113 + assert.equal(utc.total, 1);
114 + assert.equal(utc.sessions[0].started, "2026-08-31T23:00:00.000Z");
115 + await assert.rejects(inspect(["list", "--since", "2026-02-30"], f.ctx), /date/i);
116 + await assert.rejects(inspect(["list", "--limit", "101"], f.ctx), /limit/i);
117 + await assert.rejects(inspect(["list", "--offset", "-1"], f.ctx), /offset/i);
120 +test("duplicate names and ID prefixes require disambiguation; discovered paths work", async (t) => {
121 + const f = fixture(t);
122 + const file = f.add("abc-1", "duplicate");
123 + f.add("abc-2", "duplicate");
124 + await assert.rejects(inspect(["show", "duplicate"], f.ctx), /ambiguous/i);
125 + await assert.rejects(inspect(["show", "abc"], f.ctx), /ambiguous/i);
126 + assert.equal((await inspect(["show", "abc-1"], f.ctx)).id, "abc-1");
127 + assert.equal((await inspect(["show", file], f.ctx)).file, file);
128 + await assert.rejects(inspect(["show", "missing"], f.ctx), /not found/i);
131 +test("persisted branch excludes abandoned errors; explicit leaf recovers them", async (t) => {
132 + const f = fixture(t);
133 + f.add("branches", null, [
134 + message("u", null, "user"),
135 + message("old", "u", "assistant", { stopReason: "error" }),
136 + message("new", "u", "assistant", {
137 + stopReason: "stop",
138 + content: [{ type: "toolCall", id: "call1", name: "read", arguments: { path: "ARGUMENT_MUST_NOT_APPEAR" } }],
140 + message("result", "new", "toolResult", { toolName: "read", isError: true }),
141 + message("abort", "result", "assistant", { stopReason: "aborted" }),
142 + entry("exec", "abort", "message", {
143 + message: { role: "bashExecution", exitCode: 1, output: "OUTPUT_MUST_NOT_APPEAR" },
146 + const r = await inspect(["show", "branches"], f.ctx);
147 + assert.equal(r.leafId, "exec");
148 + assert.equal(r.heads.total, 2);
149 + assert.equal(r.branch.counts.assistantErrors, 0);
150 + assert.equal(r.branch.counts.toolErrors, 1);
151 + assert.equal(r.branch.counts.toolCalls, 1);
152 + assert.equal(r.branch.counts.aborts, 1);
153 + assert.equal(r.branch.counts.bashErrors, 1);
155 + r.timeline.map((e) => e.id),
156 + ["u", "new", "result", "abort", "exec"],
158 + assert.equal(r.timeline[1].line, 4);
159 + const old = await inspect(["show", "branches", "--leaf", "old"], f.ctx);
160 + assert.equal(old.branch.counts.assistantErrors, 1);
161 + assert.equal(old.counts.assistantErrors, 1);
162 + assert.doesNotMatch(JSON.stringify(r), /ARGUMENT_MUST_NOT_APPEAR|OUTPUT_MUST_NOT_APPEAR|user text/);
163 + await assert.rejects(inspect(["show", "branches", "--leaf", "unknown"], f.ctx), /leaf/i);
166 +test("retained-tail compaction supplies context once, without inflating branch turns", async (t) => {
167 + const f = fixture(t);
168 + f.add("tail", null, [
169 + message("u1", null, "user"),
170 + message("u2", "u1", "user"),
171 + entry("c", "u2", "compaction", {
172 + summary: "SUMMARY_TEXT",
173 + tokensBefore: 9000,
175 + { role: "user", content: "retained user" },
176 + { role: "assistant", content: [{ type: "text", text: "retained answer" }] },
179 + message("a", "c", "assistant"),
181 + const r = await inspect(["show", "tail", "--view", "context", "--text"], f.ctx);
182 + assert.equal(r.branch.counts.users, 2);
183 + assert.equal(r.context.counts.users, 1);
184 + assert.equal(r.context.counts.assistants, 2);
186 + r.timeline.map((e) => e.id),
187 + ["c", "c:tail:0", "c:tail:1", "a"],
189 + assert.equal(r.timeline[0].text, "SUMMARY_TEXT");
190 + assert.equal(r.timeline[1].line, 4);
191 + assert.equal(r.timeline[1].text, "retained user");
194 +test("firstKeptEntryId and branch summaries reconstruct the documented context order", async (t) => {
195 + const f = fixture(t);
196 + f.add("kept", null, [
197 + message("u1", null, "user"),
198 + message("u2", "u1", "user"),
199 + entry("c", "u2", "compaction", { summary: "summary", tokensBefore: 5000, firstKeptEntryId: "u2" }),
200 + entry("b", "c", "branch_summary", { summary: "branch text", fromId: "u1" }),
201 + message("a", "b", "assistant"),
203 + const r = await inspect(["show", "kept", "--view", "context"], f.ctx);
205 + r.timeline.map((e) => e.id),
206 + ["c", "u2", "b", "a"],
208 + assert.equal(r.context.counts.users, 1);
209 + assert.equal(r.context.counts.compactions, 1);
212 +test("text is opt-in, bounded, and never includes thinking, tool payloads, images or custom state", async (t) => {
213 + const f = fixture(t);
214 + f.add("bounded", null, [
215 + message("u", null, "user", { content: "x".repeat(10000) }),
216 + message("a", "u", "assistant", {
218 + { type: "thinking", thinking: "HIDDEN_THINKING" },
219 + { type: "image", data: "HIDDEN_IMAGE" },
220 + { type: "text", text: "visible answer" },
221 + { type: "toolCall", name: "bash", id: "t", arguments: { command: "HIDDEN_ARGUMENTS" } },
224 + message("r", "a", "toolResult", { content: [{ type: "text", text: "HIDDEN_RESULT" }] }),
225 + entry("custom", "r", "custom", { customType: "state", data: "HIDDEN_STATE" }),
227 + const r = await inspect(["show", "bounded", "--text", "--limit", "1"], f.ctx);
228 + assert.equal(r.total, 4);
229 + assert.equal(r.timeline.length, 1);
230 + assert.ok(r.timeline[0].text.length <= 500);
231 + assert.equal(r.timeline[0].textTruncated, true);
232 + const full = await inspect(["show", "bounded", "--text"], f.ctx);
233 + assert.doesNotMatch(JSON.stringify(full), /HIDDEN_/);
234 + assert.equal(full.timeline[1].text, "visible answer");
235 + const page = await inspect(["show", "bounded", "--offset", "1", "--limit", "1"], f.ctx);
236 + assert.equal(page.timeline[0].id, "a");
237 + assert.equal(page.timeline[0].text, undefined);
240 +test("malformed lines and partial tails report locations, never parser content; listing is explicitly partial", async (t) => {
241 + const f = fixture(t);
243 + const broken = f.add("broken", null, []);
244 + writeFileSync(broken, `${readFileSync(broken, "utf8")}{"NEVER_ECHO_BAD_JSON":`);
245 + const r = await inspect(["list"], f.ctx);
246 + assert.equal(r.complete, false);
247 + assert.equal(r.errorCount, 1);
248 + assert.equal(r.sessions[0].id, "valid");
249 + assert.match(r.errors[0].error, /line 2/);
250 + assert.doesNotMatch(JSON.stringify(r), /NEVER_ECHO_BAD_JSON/);
251 + await assert.rejects(inspect(["show", broken], f.ctx), /line 2/);
252 + const settings = join(f.agent, "settings.json");
253 + writeFileSync(settings, '{"NEVER_ECHO_SETTINGS":');
254 + await assert.rejects(
255 + inspect(["list"], f.ctx),
256 + (error) => /settings/.test(error.message) && !error.message.includes("NEVER_ECHO_SETTINGS"),
260 +test("unsupported versions, duplicate IDs and missing parents fail, rather than guessing", async (t) => {
261 + const f = fixture(t);
262 + const file = f.add("invalid", null, [message("u", "absent", "user")]);
263 + await assert.rejects(inspect(["show", file], f.ctx), /parent/i);
264 + f.add("invalid", null, [message("u", null, "user"), message("u", null, "user")]);
265 + await assert.rejects(inspect(["show", file], f.ctx), /duplicate/i);
266 + f.json(file, { type: "session", version: 99, id: "invalid", cwd: f.cwd, timestamp: stamp });
267 + await assert.rejects(inspect(["show", file], f.ctx), /version/i);
270 +test("latest compaction wins, including an empty retained tail", async (t) => {
271 + const f = fixture(t);
272 + f.add("latest", null, [
273 + message("u", null, "user"),
274 + entry("c1", "u", "compaction", { summary: "old", retainedTail: [{ role: "user", content: "old user" }] }),
275 + entry("c2", "c1", "compaction", { summary: "new", retainedTail: [], firstKeptEntryId: "u" }),
277 + const r = await inspect(["show", "latest", "--view", "context"], f.ctx);
279 + r.timeline.map((e) => e.id),
282 + assert.equal(r.context.counts.users, 0);
283 + assert.equal(r.branch.counts.compactions, 2);
286 +test("invalid compaction metadata is rejected without serializing its payload", async (t) => {
287 + const f = fixture(t);
288 + const file = f.add("bad-compaction", null, [
289 + entry("c", null, "compaction", { retainedTail: [], firstKeptEntryId: { value: "HIDDEN_METADATA" } }),
291 + await assert.rejects(
292 + inspect(["show", file], f.ctx),
293 + (e) => /line 2/.test(e.message) && !e.message.includes("HIDDEN_METADATA"),
295 + f.add("bad-compaction", null, [entry("c", null, "compaction", { firstKeptEntryId: "absent" })]);
296 + await assert.rejects(inspect(["show", file], f.ctx), (e) => e.message.includes(file) && /line 2/.test(e.message));
299 +test("empty stores, header-only sessions and valid unterminated final lines are read-only", async (t) => {
300 + const f = fixture(t);
301 + assert.equal((await inspect(["list"], f.ctx)).total, 0);
302 + const file = f.add("header", null, []);
303 + const text = readFileSync(file, "utf8").trimEnd();
304 + writeFileSync(file, text);
305 + const result = await inspect(["show", file], f.ctx);
306 + assert.equal(result.total, 0);
307 + assert.equal(result.leafId, null);
308 + assert.equal(result.scanned, 1);
309 + assert.equal(readFileSync(file, "utf8"), text);
310 + writeFileSync(file, "");
311 + await assert.rejects(inspect(["show", file], f.ctx), /empty session/);
314 +test("file symlinks are not followed and the input file is unchanged", async (t) => {
315 + const f = fixture(t);
316 + const file = f.add("real");
317 + const before = readFileSync(file);
318 + const time = statSync(file).mtimeMs;
319 + if (process.platform !== "win32") symlinkSync(file, join(f.store, "alias.jsonl"));
320 + const r = await inspect(["list"], f.ctx);
321 + assert.equal(r.total, 1);
322 + await inspect(["show", file, "--view", "context", "--text"], f.ctx);
323 + assert.deepEqual(readFileSync(file), before);
324 + assert.equal(statSync(file).mtimeMs, time);
327 +test("CLI prints JSON, reports partial failures through exit status, and rejects unsupported options", (t) => {
328 + const f = fixture(t);
330 + const args = [script, "list", "--session-dir", f.store];
331 + const env = { ...process.env, PI_CODING_AGENT_DIR: f.agent, PI_CODING_AGENT_SESSION_DIR: "" };
332 + const good = spawnSync(process.execPath, args, { cwd: f.cwd, env, encoding: "utf8" });
333 + assert.equal(good.status, 0, good.stderr);
334 + assert.equal(JSON.parse(good.stdout).sessions[0].id, "cli");
335 + writeFileSync(join(f.store, "broken.jsonl"), "bad");
336 + const partial = spawnSync(process.execPath, args, { cwd: f.cwd, env, encoding: "utf8" });
337 + assert.equal(partial.status, 1);
338 + assert.equal(JSON.parse(partial.stdout).complete, false);
339 + const invalid = spawnSync(process.execPath, [script, "--unsupported"], { encoding: "utf8" });
340 + assert.equal(invalid.status, 1);
341 + assert.ok(JSON.parse(invalid.stderr).error);
342 + const help = spawnSync(process.execPath, [script, "--help"], { encoding: "utf8" });
343 + assert.equal(help.status, 0);
344 + assert.match(help.stdout, /show/);
345 + if (process.platform !== "win32") {
346 + const linkedScript = join(f.cwd, "inspect-link.mjs");
347 + symlinkSync(script, linkedScript);
348 + const linked = spawnSync(process.execPath, [linkedScript, "--help"], { encoding: "utf8" });
349 + assert.equal(linked.status, 0);
350 + assert.match(linked.stdout, /show/);