import assert from "node:assert/strict";
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
COVER_FILE_NAME,
deploySystemPromptCover,
resolveAgentDir,
} from "../scripts/deploy-system-prompt-cover.mjs";
import {
readCoverFile,
resolveCoverPath,
spliceCover,
} from "../extensions/system-prompt-cover-config.ts";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bundledCoverPath = join(repositoryRoot, "config", "system-prompt-cover.md");
const DEFAULT_PREAMBLE =
"You are an expert coding assistant operating inside pi, a coding agent harness. " +
"You help users by reading files, executing commands, editing code, and writing new files.";
/** A rendered prompt shaped like Pi's: preamble, then tag-wrapped top-level sections. */
function renderedPrompt(preamble = DEFAULT_PREAMBLE) {
return [
preamble,
"",
"- read: reads files",
"",
"",
"- Be concise",
"",
"",
"",
" ",
" s",
" ",
"",
"",
"",
'',
"Nested content with a -looking line is not a tag.",
"",
"",
"",
"/work",
"",
].join("\n");
}
function tagsOf(text: string): string[] {
return [...text.matchAll(/^<([a-z][a-z0-9_-]*)>$/gm)].map((match) => match[1]);
}
async function makeTempDir() {
return mkdtemp(join(tmpdir(), "my-pi-cover-"));
}
test("bundled cover holds Pi's default preamble text", async () => {
const content = await readFile(bundledCoverPath, "utf8");
assert.equal(content.replace(/\s+$/, ""), DEFAULT_PREAMBLE);
});
test("spliceCover replaces only the preamble and preserves the remaining bytes", () => {
const rendered = renderedPrompt();
const spliced = spliceCover(rendered, "MY CUSTOM COVER");
assert.ok(spliced.startsWith("MY CUSTOM COVER\n"));
// Everything after the preamble's terminating newline is untouched.
const originalTail = rendered.slice(rendered.indexOf("\n"));
assert.ok(spliced.endsWith(originalTail));
// Section order — including nested tags — is identical to the unmodified prompt.
assert.deepEqual(tagsOf(spliced), tagsOf(rendered));
assert.deepEqual(tagsOf(spliced), [
"tools",
"rules",
"skills",
"available_skills",
"project_context",
"cwd",
]);
});
test("spliceCover keeps section order rather than appending recovered sections", () => {
const rendered = renderedPrompt("ORIGINAL COVER");
const spliced = spliceCover(rendered, "NEW COVER");
const order = tagsOf(spliced).join(",");
assert.equal(order, "tools,rules,skills,available_skills,project_context,cwd");
assert.ok(
order.indexOf("tools") < order.indexOf("cwd"),
"tools must still precede cwd; a re-appended section list would invert this",
);
assert.ok(
order.indexOf("project_context") < order.indexOf("cwd"),
"project_context must keep its original position",
);
});
test("spliceCover tolerates a trailing newline from the editor and a blank cover", () => {
const rendered = renderedPrompt();
assert.equal(spliceCover(rendered, "COVER\n\n"), spliceCover(rendered, "COVER"));
// A whitespace-only cover leaves an empty preamble but still keeps every section.
const blank = spliceCover(rendered, " \n");
assert.equal(blank, rendered.slice(rendered.indexOf("\n")));
assert.deepEqual(tagsOf(blank), tagsOf(rendered));
});
test("spliceCover degenerates to the cover when the prompt has no sections", () => {
assert.equal(spliceCover("just a preamble", "NEW"), "NEW");
assert.equal(spliceCover("", "NEW"), "NEW");
});
test("spliceCover keeps an attribute-bearing nested tag inside its parent section", () => {
// Pi nests inside the bare tag, so the
// boundary must be the first *bare* tag line and the nested markup must survive verbatim.
const rendered = [
"ORIGINAL COVER",
"",
"- read: reads files",
"",
"",
'',
"nested instructions",
"",
"",
"",
"/work",
"",
].join("\n");
const spliced = spliceCover(rendered, "NEW");
assert.equal(tagsOf(spliced).join(","), "tools,project_context,cwd");
assert.ok(spliced.startsWith("NEW\n"));
assert.ok(
spliced.includes('\nnested instructions\n'),
"nested project instructions must be preserved byte-for-byte",
);
});
test("readCoverFile returns undefined when the file is absent or blank", async () => {
const dir = await makeTempDir();
try {
const coverPath = resolveCoverPath(dir);
assert.equal(readCoverFile(coverPath), undefined);
await writeFile(coverPath, " \n\n", "utf8");
assert.equal(readCoverFile(coverPath), undefined);
await writeFile(coverPath, " REAL COVER \n", "utf8");
assert.equal(readCoverFile(coverPath), " REAL COVER");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("resolveAgentDir honours PI_CODING_AGENT_DIR and defaults to ~/.pi/agent", () => {
assert.equal(resolveAgentDir({}, "/home/u"), "/home/u/.pi/agent");
assert.equal(resolveAgentDir({ PI_CODING_AGENT_DIR: "/custom/agent" }, "/home/u"), "/custom/agent");
assert.equal(resolveAgentDir({ PI_CODING_AGENT_DIR: "~/other" }, "/home/u"), "/home/u/other");
});
test("deploySystemPromptCover creates, is idempotent, and overwrites without a backup", async () => {
const dir = await makeTempDir();
try {
const target = join(dir, COVER_FILE_NAME);
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "created");
assert.equal(await readFile(target, "utf8"), await readFile(bundledCoverPath, "utf8"));
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "current");
await writeFile(target, "USER EDITED COVER\n", "utf8");
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "updated");
assert.equal(await readFile(target, "utf8"), await readFile(bundledCoverPath, "utf8"));
// No backup and no temporary file may survive an overwrite.
assert.deepEqual(await readdir(dir), [COVER_FILE_NAME]);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("deploySystemPromptCover fails loudly when the bundled cover is unreadable", async () => {
const dir = await makeTempDir();
try {
await assert.rejects(
deploySystemPromptCover({ agentDir: dir, bundledCoverPath: join(dir, "missing.md") }),
/cannot read bundled system prompt cover/,
);
// The failure must not leave a partial file behind.
assert.deepEqual(await readdir(dir), []);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("deploy-system-prompt-cover.mjs prints a status line and exits zero", async () => {
const dir = await makeTempDir();
try {
const helper = join(repositoryRoot, "scripts", "deploy-system-prompt-cover.mjs");
const first = execFileSync(process.execPath, [helper, dir], { encoding: "utf8" }).trim();
const second = execFileSync(process.execPath, [helper, dir], { encoding: "utf8" }).trim();
assert.equal(first, "created");
assert.equal(second, "current");
} finally {
await rm(dir, { recursive: true, force: true });
}
});