import { SessionManager } from "@earendil-works/pi-coding-agent"; import { describe, expect, it } from "vitest"; import { historyQuerySchema, queryHistory, safeHistoryText, } from "../src/history-query.ts"; function fixture() { const voice = SessionManager.inMemory(); const scope = { sessionId: "main", voice, executor: [ { id: "result", timestamp: "2026-10-21T12:00:00.000Z", role: "assistant" as const, text: "Fixed caption queue.", outcome: "completed" as const, }, { id: "tool", timestamp: "2026-10-21T11:59:00.000Z", role: "tool" as const, text: "Checked two files.", outcome: "completed" as const, tool: "read", }, ], }; const add = (id: string, text: string, extra = {}) => voice.appendCustomEntry("voice.native-history", { id, role: "assistant", text, playedText: "", playback: "not-played", interrupted: false, ...extra, }); return { scope, add }; } describe("bounded history queries", () => { it("declares bounded schema-driven filters and no arbitrary paths", () => { expect(Reflect.get(historyQuerySchema, "additionalProperties")).toBe(false); expect(Reflect.get(historyQuerySchema.properties.limit, "maximum")).toBe( 20, ); expect(Reflect.get(historyQuerySchema.properties.search, "maxLength")).toBe( 256, ); expect(Object.keys(historyQuerySchema.properties)).not.toContain("path"); }); it("deduplicates persisted playback revisions, preserving generated versus heard evidence", async () => { const { scope, add } = fixture(); add("reply", "Generated complete answer."); add("reply", "Generated complete answer.", { playedText: "Generated", playback: "partial", interrupted: true, }); const result = await queryHistory({ source: "voice" }, scope); expect(result.entries).toMatchObject([ { id: "reply", excerpt: "Generated complete answer.", playedExcerpt: "Generated", playback: "partial", interrupted: true, }, ]); expect(result.entries).toHaveLength(1); }); it("filters roles, session identity and literal case-insensitive search", async () => { const { scope, add } = fixture(); add("user", "I asked about CAPTION queues.", { role: "user" }); add("reply", "Other answer"); expect( ( await queryHistory( { search: "caption", role: "user", sessionId: "main" }, scope, ) ).entries.map((entry) => entry.id), ).toEqual(["user"]); expect( (await queryHistory({ sessionId: "different" }, scope)).entries, ).toEqual([]); expect( ( await queryHistory({ source: "executor", role: "tool" }, scope) ).entries.map((entry) => entry.id), ).toEqual(["tool"]); expect((await queryHistory({ search: ".*" }, scope)).entries).toEqual([]); }); it("filters time ranges inclusively and rejects malformed or reversed ranges", async () => { const { scope } = fixture(); expect( ( await queryHistory( { source: "executor", since: "2026-10-21T12:00:00.000Z", until: "2026-10-21T12:00:00.000Z", }, scope, ) ).entries.map((entry) => entry.id), ).toEqual(["result"]); await expect(queryHistory({ since: "yesterday" }, scope)).rejects.toThrow( "ISO 8601", ); await expect( queryHistory( { since: "2026-10-22T00:00:00Z", until: "2026-10-21T00:00:00Z" }, scope, ), ).rejects.toThrow("must not follow"); await expect(queryHistory({ limit: 21 }, scope)).rejects.toThrow("1–20"); }); it("never searches SDK raw messages, tool logs, or obsolete playback snapshots", async () => { const { scope, add } = fixture(); scope.voice.appendMessage({ role: "user", content: "raw SDK needle", timestamp: 1, }); scope.voice.appendCustomEntry("tool-log", { text: "raw tool needle" }); add("corrected", "obsolete needle"); add("corrected", "corrected transcription"); expect( (await queryHistory({ source: "voice", search: "needle" }, scope)) .entries, ).toEqual([]); }); it("includes automatic commentary only when explicitly requested", async () => { const { scope, add } = fixture(); add("status", "I am checking files.", { kind: "status" }); expect((await queryHistory({ source: "voice" }, scope)).entries).toEqual( [], ); expect( (await queryHistory({ source: "voice", includeStatus: true }, scope)) .entries, ).toHaveLength(1); }); it("centres bounded excerpts around a match", async () => { const { scope, add } = fixture(); add("long", `${"a".repeat(5_000)}needle${"b".repeat(5_000)}`); const result = await queryHistory( { source: "voice", search: "needle" }, scope, ); expect(result.entries[0]?.excerpt).toContain("needle"); expect(result.entries[0]?.excerpt.length).toBeLessThanOrEqual(482); }); it("caps UTF-8 response bytes and resumes at the first omitted voice entry", async () => { const { scope, add } = fixture(); for (let index = 0; index < 25; index++) add(`reply-${index}`, "界".repeat(1_000)); const first = await queryHistory({ source: "voice", limit: 20 }, scope); expect(first.truncated).toBe(true); expect( Buffer.byteLength(JSON.stringify(first), "utf8"), ).toBeLessThanOrEqual(12_000); expect(first.entries.length).toBeLessThan(20); const cursor = first.nextVoiceCursor; if (!cursor) throw new Error("Missing continuation cursor"); const second = await queryHistory( { source: "voice", limit: 20, cursor }, scope, ); expect(second.entries[0]?.id).toBe(`reply-${24 - first.entries.length}`); }); it("bounds archive scanning and provides continuation without mutating history", async () => { const { scope, add } = fixture(); add("older", "older match"); for (let index = 0; index < 4_100; index++) scope.voice.appendCustomEntry("ignored", { index }); const count = scope.voice.getEntryCount(); const first = await queryHistory( { source: "voice", search: "match" }, scope, ); expect(first).toMatchObject({ entries: [], scanned: 4_096, truncated: true, }); const cursor = first.nextVoiceCursor; if (!cursor) throw new Error("Missing continuation cursor"); const next = await queryHistory( { source: "voice", search: "match", cursor }, scope, ); expect(next.entries[0]?.id).toBe("older"); expect(scope.voice.getEntryCount()).toBe(count); await expect(queryHistory({ cursor }, scope)).rejects.toThrow( "requires source voice", ); }); it.each(["short", "界".repeat(1_000)])( "continues executor results across count/byte caps even with equal timestamps (%s)", async (text) => { const { scope } = fixture(); scope.executor = Array.from({ length: 24 }, (_, index) => ({ id: `executor-${index}`, timestamp: "2026-10-21T12:00:00Z", role: "assistant" as const, text, outcome: "completed" as const, })); const seen: string[] = []; let cursor: string | undefined; for (let page = 0; page < 24; page++) { const result = await queryHistory( { source: "executor", limit: 20, ...(cursor ? { cursor } : {}) }, scope, ); expect( Buffer.byteLength(JSON.stringify(result), "utf8"), ).toBeLessThanOrEqual(12_000); seen.push(...result.entries.map((entry) => entry.id)); cursor = result.nextExecutorCursor; if (!cursor) break; } expect(seen).toHaveLength(24); expect(new Set(seen).size).toBe(24); }, ); it("redacts credential-bearing text before search or excerpts", async () => { const { scope, add } = fixture(); add("private", 'TOKEN="fake-value"'); expect( (await queryHistory({ source: "voice", search: "fake-value" }, scope)) .entries, ).toEqual([]); expect(safeHistoryText("https://name:fake-value@example.org/path")).toBe( "https://[redacted]@example.org/path", ); }); });