Files
wonder 922e1c3be2 Initial commit: pi-lens session observability for pi
- collector, classify, prompt-parser, server (TypeScript)
- web panel (app.js, index.html, style.css)
- smoke and load-test scripts
- DESIGN.md and README.md
2026-10-04 19:54:34 +08:00

158 lines
7.5 KiB
TypeScript

/**
* smoke.ts — standalone test of pi-lens internals (no pi runtime needed).
* Run: node --experimental-strip-types smoke.ts
*/
import { TraceStore } from "./collector.ts";
import { parseSystemPrompt, coverageRatio } from "./prompt-parser.ts";
import { startServer } from "./server.ts";
import type { PromptSourceOptions } from "./types.ts";
function assert(cond: unknown, msg: string): void {
if (!cond) {
console.error("FAIL:", msg);
process.exitCode = 1;
} else {
console.log("ok:", msg);
}
}
// ── 1. prompt parser: every byte lands in a colored segment ─────────────────
const rendered = [
"You are an expert coding assistant operating inside pi.",
"",
"<tools>",
"- read: Read a file.",
"- bash: Run a command.",
"</tools>",
"",
"<rules>",
"- Be concise in your responses",
"</rules>",
"<project_context>\nProject-specific instructions and guidelines:",
'<project_instructions path="AGENTS.md">\nAlways use pnpm.\n</project_instructions>',
"</project_context>",
"",
"<skills>\nThe following skills provide specialized instructions.",
"<available_skills>",
" <skill>",
" <name>pdf-tools</name>",
" <description>Extract text from PDFs.</description>",
" <location>/home/u/skills/pdf-tools/SKILL.md</location>",
" </skill>",
"</available_skills>",
"</skills>",
"<cwd>\n/home/wonder/project\n</cwd>",
].join("\n");
const segments = parseSystemPrompt(rendered, []);
const names = segments.map((s) => s.name);
assert(names.includes("preamble"), "preamble segment found");
assert(names.includes("tools:read") && names.includes("tools:bash"), "tool children found: " + names.join(","));
assert(names.includes("rules"), "rules segment found");
assert(names.includes("project_context:AGENTS.md"), "context file child found");
assert(names.includes("skills:pdf-tools"), "skill child found");
assert(names.includes("cwd"), "cwd segment found");
assert(coverageRatio(rendered, segments) >= 0.99, "segments cover the rendered prompt");
const byName = new Map(segments.map((s) => [s.name, s]));
assert(byName.get("project_context:AGENTS.md")?.kind === "context-file", "context file colored as context-file");
assert(byName.get("skills:pdf-tools")?.kind === "skill-list", "skill list colored as skill-list");
assert(byName.get("rules")?.kind === "tool-rules", "rules colored as tool-rules");
assert(byName.get("skills:pdf-tools")?.source.includes("pdf-tools/SKILL.md"), "skill segment source is its location");
// ── 2. collector: builds, diff, skill traces ────────────────────────────────
const store = new TraceStore();
const options: PromptSourceOptions = {
selectedTools: ["read", "bash"],
toolSnippets: { read: "Read a file.", bash: "Run a command." },
toolGuidelines: {},
promptGuidelines: [],
appendSystemPrompt: "",
sections: {},
cwd: "/home/wonder/project",
contextFiles: [{ path: "AGENTS.md", content: "Always use pnpm." }],
skills: [
{
name: "pdf-tools",
description: "Extract text from PDFs.",
filePath: "/home/u/skills/pdf-tools/SKILL.md",
baseDir: "/home/u/skills/pdf-tools",
disableModelInvocation: false,
},
],
};
store.recordInput("/skill:pdf-tools extract report.pdf", "interactive");
let spans = store.getSkills().spans;
assert(spans.length === 1 && spans[0].trigger === "explicit", "explicit /skill: opens a span");
// Real path: the <skill …> block arrives in the expanded USER prompt, not the system prompt.
const userPrompt =
'extract report.pdf\n<skill name="pdf-tools" location="/home/u/skills/pdf-tools/SKILL.md">\n# pdf-tools\nfull instructions here\n</skill>';
const build1 = store.capturePromptBuild(options, rendered, "command", userPrompt);
assert(build1.sections.some((s) => s.name === "skills:pdf-tools"), "prompt build carries skill-list section");
spans = store.getSkills().spans;
assert(spans[0].status === "loaded" && spans[0].loadedAt !== undefined, "explicit span marked loaded after expansion");
const loadStep = spans[0].steps.find((s) => s.kind === "load");
assert(
!!loadStep?.contentId && (store.getContent(loadStep.contentId) ?? "").includes("full instructions here"),
"injected skill body stored on demand for the detail card",
);
// second build with one changed section → diff
const build2 = store.capturePromptBuild(options, rendered.replace("Always use pnpm.", "Always use pnpm, never npm."), "user");
const changed = build2.sections.find((s) => s.name === "project_context:AGENTS.md");
assert(changed?.status === "changed", "changed section detected in diff");
assert(build2.sections.filter((s) => s.status === "added").length > 0 || build2.sections.some((s) => s.status === "same"), "diff statuses populated");
// model-driven skill load via read tool
store.recordToolCall({
toolCallId: "call-1",
toolName: "read",
input: { path: "/home/u/skills/pdf-tools/SKILL.md" },
});
spans = store.getSkills().spans;
const modelSpan = spans.find((s) => s.trigger === "model");
assert(modelSpan && modelSpan.status === "loaded", "model read of SKILL.md opens a loaded model span");
store.recordToolResult({ toolCallId: "call-1", toolName: "read", isError: false, content: [{ type: "text", text: "# pdf-tools" }] });
assert(modelSpan!.steps.some((s) => s.kind === "load" && s.status === "ok"), "load step completed with ok status");
store.recordToolCall({ toolCallId: "call-2", toolName: "bash", input: { command: "ls" } });
store.recordToolResult({ toolCallId: "call-2", toolName: "bash", isError: true, content: [{ type: "text", text: "boom" }] });
store.recordAgentEnd();
const tail = store.getTimeline(undefined, 500);
assert(tail.events.some((e) => e.type === "tool_call"), "timeline has tool_call");
assert(tail.events.some((e) => e.type === "skill_load"), "timeline has skill_load");
assert(store.getState().totals.toolErrors === 1, "tool errors counted");
// ── 3. server: REST + content on demand ─────────────────────────────────────
const server = await startServer(store, 7890);
assert(/^http:\/\/127\.0\.0\.1:\d+\/$/.test(server.url), "server url: " + server.url);
const stateRes = await fetch(server.url + "api/state");
const stateJson = (await stateRes.json()) as { totals: { toolCalls: number } };
assert(stateJson.totals.toolCalls === 2, "GET /api/state reports tool calls");
const buildsRes = await fetch(server.url + "api/prompt-builds");
const buildsJson = (await buildsRes.json()) as Array<{ sections: Array<{ contentId: string }> }>;
const anyContentId = buildsJson[0].sections[0].contentId;
const contentRes = await fetch(server.url + "api/content/" + anyContentId);
const contentJson = (await contentRes.json()) as { text: string };
assert(typeof contentJson.text === "string" && contentJson.text.length > 0, "GET /api/content/:id returns full text on demand");
const tlRes = await fetch(server.url + "api/timeline?limit=5");
const tlJson = (await tlRes.json()) as { events: unknown[]; total: number };
assert(tlJson.events.length === 5 && tlJson.total > 5, "GET /api/timeline paginates (5 of " + tlJson.total + ")");
const indexRes = await fetch(server.url);
const html = await indexRes.text();
assert(html.includes("pi-lens") && html.includes("detail-card"), "GET / serves the panel shell");
const sseRes = await fetch(server.url + "api/events");
assert(sseRes.headers.get("content-type")?.includes("text/event-stream"), "GET /api/events is an SSE stream");
await sseRes.body?.cancel();
await server.stop();
console.log(process.exitCode ? "\nSMOKE TEST FAILED" : "\nSMOKE TEST PASSED");