repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/ctx/__tests__/harness.test.ts
RawFile outline
- CTX_COMMIT line 7
- root line 9
- sessionDir line 10
- t line 11
- ctxPath line 13
- ctxTool line 17
- ctxExec line 21
- textOf line 31
- text line 32
- dbFiles line 35
- beforeEach line 41
- afterEach line 49
- ctx harness integration line 57
- loads from git pi-test-harness fork pinned to source-export commit line 58
- registers exactly one ctx tool and one ctx command line 65
- runs JS off-context, stores oversized output, and retrieves exact needles later line 71
- analyzes a huge file without returning the file body or indexing small findings line 94
- collapses huge bash tool_result using fullOutputPath before it reaches the transcript line 117
- extracts searchable failure context for huge failing bash output and keeps isError line 147
- search returns the matching region when a hit is buried deep inside a chunk line 168
- collapses actual built-in bash execution output using Pi fullOutputPath metadata line 182
- falls back to visible bash content when fullOutputPath is absent line 210
- handles concurrent ctx writes without lock errors or lost sources line 228
- keeps unicode output valid while using byte thresholds conservatively line 246
- closes ctx resources so session directory can be removed after dispose line 259
- does not touch small bash output, then /ctx reports, searches, and purges stored data line 268
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path, { join } from "node:path";
import { createTestSession, type TestSession } from "@marcfargas/pi-test-harness";
const CTX_COMMIT = "0cb5ce5f10fb18c9a80e904e2e3310cc98a28e29";
let root: string;
let sessionDir: string;
let t: TestSession | undefined;
function ctxPath(): string {
return path.resolve(import.meta.dir, "../index.ts");
}
function ctxTool() {
return t!.session.extensionRunner.getToolDefinition("ctx");
}
function ctxExec(params: Record<string, unknown>) {
return ctxTool().execute(
`call-${crypto.randomUUID()}`,
params,
undefined,
undefined,
t!.session.extensionRunner.createContext(),
);
}
function textOf(result: any): string {
return result.content.map((part: { text?: string }) => part.text ?? "").join("\n");
}
function dbFiles(): string[] {
const dir = join(sessionDir, "ctx");
if (!existsSync(dir)) return [];
return readdirSync(dir).filter((name) => name.endsWith(".db"));
}
beforeEach(async () => {
root = mkdtempSync(join(tmpdir(), "pi-ctx-harness-"));
sessionDir = join(root, "session");
process.env.PI_CODING_AGENT_SESSION_DIR = sessionDir;
delete process.env.PI_CTX_DB_PATH;
t = await createTestSession({ extensions: [ctxPath()] });
});
afterEach(() => {
t?.dispose();
t = undefined;
delete process.env.PI_CODING_AGENT_SESSION_DIR;
delete process.env.PI_CTX_DB_PATH;
rmSync(root, { recursive: true, force: true });
});
describe("ctx harness integration", () => {
it("loads from git pi-test-harness fork pinned to source-export commit", async () => {
const pkg = await import("@marcfargas/pi-test-harness");
expect(typeof pkg.createTestSession).toBe("function");
const lock = readFileSync(path.resolve(import.meta.dir, "../bun.lock"), "utf8");
expect(lock).toContain(CTX_COMMIT);
});
it("registers exactly one ctx tool and one ctx command", () => {
const [extension] = t!.session.extensionRunner.extensions;
expect([...extension.tools.keys()]).toEqual(["ctx"]);
expect([...extension.commands.keys()]).toEqual(["ctx"]);
});
it("runs JS off-context, stores oversized output, and retrieves exact needles later", async () => {
const result = await ctxExec({
op: "run-js",
query: "ctxneedle12345",
code: `
for (let i = 0; i < 9000; i++) console.log('noise line ' + i + ' ' + 'x'.repeat(20));
console.log('ctxneedle12345 fatal failure in generated report');
for (let i = 0; i < 9000; i++) console.log('tail noise ' + i + ' ' + 'y'.repeat(20));
`,
});
const text = textOf(result);
expect(text).toContain("ctx:stored");
expect(text).toContain("matched");
expect(text.length).toBeLessThan(2_000);
expect(text).not.toContain("tail noise 8999");
expect(dbFiles()).toHaveLength(1);
const search = await ctxExec({ op: "search", query: "ctxneedle12345", limit: 1 });
const searchText = textOf(search);
expect(searchText).toContain("ctxneedle12345 fatal failure");
});
it("analyzes a huge file without returning the file body or indexing small findings", async () => {
const file = join(root, "huge.log");
const lines = Array.from({ length: 25_000 }, (_, i) => `row ${i} boring payload ${"z".repeat(40)}`);
lines[19_876] = "ctxfilemarker67890 ERROR customer=42 shard=west";
writeFileSync(file, `${lines.join("\n")}\n`, "utf8");
const result = await ctxExec({
op: "file-js",
path: file,
code: `
const hit = text.split(/\\n/).find(line => line.includes('ctxfilemarker67890'));
console.log(hit);
`,
});
const out = textOf(result);
expect(out.trim()).toBe("ctxfilemarker67890 ERROR customer=42 shard=west");
expect(out).not.toContain("row 0 boring payload");
const [extension] = t!.session.extensionRunner.extensions;
const stats = await extension.commands.get("ctx").handler("", t!.session.extensionRunner.createContext());
expect(stats.text).toContain("ctx: 0 sources");
});
it("collapses huge bash tool_result using fullOutputPath before it reaches the transcript", async () => {
const raw = [
"header",
...Array.from({ length: 5 }, (_, i) => `bash noise ${i} ${"a".repeat(30)}`),
"bashneedle24680 terminal fact hidden in full log",
...Array.from({ length: 7_500 }, (_, i) => `bash tail ${i} ${"a".repeat(30)}`),
].join("\n");
const full = join(root, "bash-full.log");
writeFileSync(full, raw, "utf8");
const patched = await t!.session.extensionRunner.emitToolResult({
type: "tool_result",
toolName: "bash",
input: { command: "generate massive report" },
content: [{ type: "text", text: "[pi truncated visible output]" }],
details: { fullOutputPath: full, truncation: { truncated: true } },
isError: false,
});
const text = textOf(patched);
expect(text).toContain("ctx:stored");
expect(text).toContain("Use ctx search");
expect(text).not.toContain("bashneedle24680");
expect(patched.details.ctxStored).toBe(true);
expect(statSync(join(sessionDir, "ctx", dbFiles()[0])).size).toBeGreaterThan(0);
const search = await ctxExec({ op: "search", query: "bashneedle24680", limit: 1 });
expect(textOf(search)).toContain("bashneedle24680 terminal fact");
});
it("extracts searchable failure context for huge failing bash output and keeps isError", async () => {
const full = join(root, "bash-error.log");
writeFileSync(full, `${"boring\n".repeat(5_000)}panic ctxboom999 exploded\nstack trace line\n`, "utf8");
const patched = await t!.session.extensionRunner.emitToolResult({
type: "tool_result",
toolName: "bash",
input: { command: "run failing suite" },
content: [{ type: "text", text: "[truncated]" }],
details: { fullOutputPath: full },
isError: true,
});
expect(patched.isError).toBe(true);
expect(textOf(patched)).toContain("ctx:stored");
expect(textOf(patched)).toContain("matched");
const search = await ctxExec({ op: "search", query: "ctxboom999", limit: 1 });
expect(textOf(search)).toContain("panic ctxboom999 exploded");
});
it("search returns the matching region when a hit is buried deep inside a chunk", async () => {
const filler = Array.from({ length: 180 }, (_, i) => `preface ${i} ${"p".repeat(80)}`).join("\n");
await ctxExec({
op: "run-js",
query: "buriedneedle424242",
code: `console.log(${JSON.stringify(`${filler}\nburiedneedle424242 exact match near end of chunk\n${"tail ".repeat(5_000)}`)})`,
});
const search = await ctxExec({ op: "search", query: "buriedneedle424242", limit: 1 });
const out = textOf(search);
expect(out).toContain("buriedneedle424242 exact match");
expect(out.length).toBeLessThan(3_000);
});
it("collapses actual built-in bash execution output using Pi fullOutputPath metadata", async () => {
const bash = (t!.session.agent as any).state.tools.find((tool: any) => tool.name === "bash");
expect(bash).toBeDefined();
const command = `python3 - <<'PY'\nfor i in range(7000): print(f'realbashneedle777 line {i}')\nPY`;
const raw = await bash.execute("bash-real-1", { command }, undefined, undefined, t!.session.extensionRunner.createContext());
expect(typeof raw.details?.fullOutputPath).toBe("string");
expect(raw.details?.truncation?.truncated).toBe(true);
try {
const patched = await t!.session.extensionRunner.emitToolResult({
type: "tool_result",
toolCallId: "bash-real-1",
toolName: "bash",
input: { command },
content: raw.content,
details: raw.details,
isError: raw.isError,
});
expect(textOf(patched)).toContain("ctx:stored");
expect(textOf(patched)).not.toContain("realbashneedle777 line 6999");
const search = await ctxExec({ op: "search", query: "realbashneedle777", limit: 1 });
expect(textOf(search)).toContain("realbashneedle777 line");
} finally {
rmSync(raw.details?.fullOutputPath, { force: true });
}
});
it("falls back to visible bash content when fullOutputPath is absent", async () => {
const visible = `${"visible filler\n".repeat(9_000)}visibleonly333 final line`;
const patched = await t!.session.extensionRunner.emitToolResult({
type: "tool_result",
toolCallId: "bash-visible-1",
toolName: "bash",
input: { command: "already truncated elsewhere" },
content: [{ type: "text", text: visible }],
details: { truncation: { truncated: true } },
isError: false,
});
expect(textOf(patched)).toContain("ctx:stored");
expect(textOf(patched)).not.toContain("visibleonly333");
const search = await ctxExec({ op: "search", query: "visibleonly333", limit: 1 });
expect(textOf(search)).toContain("visibleonly333 final line");
});
it("handles concurrent ctx writes without lock errors or lost sources", async () => {
const count = 8;
const results = await Promise.all(Array.from({ length: count }, (_, i) => ctxExec({
op: "run-js",
code: `console.log('concurrentneedle${i} ' + '${"x".repeat(130_000)}')`,
})));
for (const result of results) expect(textOf(result)).toContain("ctx:stored");
const [extension] = t!.session.extensionRunner.extensions;
const stats = await extension.commands.get("ctx").handler("", t!.session.extensionRunner.createContext());
expect(stats.text).toContain(`ctx: ${count} sources`);
for (let i = 0; i < count; i++) {
const search = await ctxExec({ op: "search", query: `concurrentneedle${i}`, limit: 1 });
expect(textOf(search)).toContain(`concurrentneedle${i}`);
}
});
it("keeps unicode output valid while using byte thresholds conservatively", async () => {
const marker = "unicodeNeedle555 測試 ✅";
const result = await ctxExec({
op: "run-js",
code: `console.log('${"😀".repeat(40_000)} ${marker}')`,
});
expect(textOf(result)).toContain("ctx:stored");
const search = await ctxExec({ op: "search", query: "unicodeNeedle555", limit: 1 });
expect(textOf(search)).toContain(marker);
expect(textOf(search)).not.toContain("�");
});
it("closes ctx resources so session directory can be removed after dispose", async () => {
await ctxExec({ op: "run-js", code: "console.log('cleanupneedle ' + 'x'.repeat(120_000))" });
expect(dbFiles()).toHaveLength(1);
t!.dispose();
t = undefined;
rmSync(root, { recursive: true, force: true });
expect(existsSync(root)).toBe(false);
});
it("does not touch small bash output, then /ctx reports, searches, and purges stored data", async () => {
const unchanged = await t!.session.extensionRunner.emitToolResult({
type: "tool_result",
toolName: "bash",
input: { command: "echo small" },
content: [{ type: "text", text: "small output" }],
details: {},
isError: false,
});
expect(unchanged).toBeUndefined();
await ctxExec({ op: "run-js", code: "console.log('cmdneedle13579 ' + 'q'.repeat(120_000))" });
const [extension] = t!.session.extensionRunner.extensions;
const command = extension.commands.get("ctx");
const stats = await command.handler("", t!.session.extensionRunner.createContext());
expect(stats.text).toContain("ctx: 1 sources");
expect(stats.text).toContain("recent:");
const found = await command.handler("cmdneedle13579", t!.session.extensionRunner.createContext());
expect(found.text).toContain("cmdneedle13579");
const purged = await command.handler("--purge", t!.session.extensionRunner.createContext());
expect(purged.text).toBe("ctx purged");
const empty = await command.handler("", t!.session.extensionRunner.createContext());
expect(empty.text).toContain("ctx: 0 sources");
});
});