310 lines
11 KiB
TypeScript
310 lines
11 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import * as fs from "node:fs";
|
|
import * as os from "node:os";
|
|
import * as path from "node:path";
|
|
import test from "node:test";
|
|
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
import fc from "fast-check";
|
|
import registerExtension from "../src/index.ts";
|
|
import {
|
|
stripUltraKeyword,
|
|
ULTRA_KEYWORD_MESSAGE_TYPE,
|
|
UltraKeywordTrigger,
|
|
} from "../src/ultra-keyword.ts";
|
|
import { FakeRunner } from "./helpers.ts";
|
|
|
|
interface Harness {
|
|
cwd: string;
|
|
commands: Map<string, (args: string, ctx: ExtensionToolContext) => Promise<void>>;
|
|
events: Map<string, (event: any, ctx: ExtensionToolContext) => unknown>;
|
|
notifications: string[];
|
|
ctx: ExtensionToolContext;
|
|
}
|
|
|
|
async function harness(): Promise<Harness> {
|
|
const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-keyword-"));
|
|
const commands = new Map<string, (args: string, ctx: ExtensionToolContext) => Promise<void>>();
|
|
const events = new Map<string, (event: any, ctx: ExtensionToolContext) => unknown>();
|
|
const notifications: string[] = [];
|
|
const pi = {
|
|
registerTool() {},
|
|
registerCommand(name: string, definition: { handler: (args: string, ctx: ExtensionToolContext) => Promise<void> }) {
|
|
commands.set(name, definition.handler);
|
|
},
|
|
registerEntryRenderer() {},
|
|
registerMessageRenderer() {},
|
|
on(name: string, handler: (event: any, ctx: ExtensionToolContext) => unknown) {
|
|
events.set(name, handler);
|
|
},
|
|
appendEntry() {},
|
|
};
|
|
registerExtension(pi as unknown as ExtensionAPI, new FakeRunner());
|
|
const ctx = {
|
|
cwd,
|
|
mode: "tui",
|
|
hasUI: true,
|
|
model: undefined,
|
|
thinkingLevel: undefined,
|
|
isProjectTrusted: () => true,
|
|
ui: {
|
|
confirm: async () => true,
|
|
notify: (text: string) => {
|
|
notifications.push(text);
|
|
},
|
|
setStatus: () => {},
|
|
},
|
|
sessionManager: {
|
|
getBranch: () => [],
|
|
getSessionId: () => "test-session",
|
|
},
|
|
} as unknown as ExtensionToolContext;
|
|
return { cwd, commands, events, notifications, ctx };
|
|
}
|
|
|
|
function promptEvent(sections: Record<string, string> = {}) {
|
|
return {
|
|
messageType: "user",
|
|
prompt: "a prompt",
|
|
images: [],
|
|
systemPrompt: "",
|
|
systemPromptOptions: { sections },
|
|
};
|
|
}
|
|
|
|
async function dispose(h: Harness): Promise<void> {
|
|
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
|
|
function withEnv<T>(name: string, value: string, fn: () => Promise<T>): Promise<T> {
|
|
const previous = process.env[name];
|
|
process.env[name] = value;
|
|
return fn().finally(() => {
|
|
if (previous === undefined) delete process.env[name];
|
|
else process.env[name] = previous;
|
|
});
|
|
}
|
|
|
|
test("the keyword matcher accepts only the standalone lowercase word at any position", () => {
|
|
for (const text of ["ultracode", "ultracode audit this", "please ultracode this", "audit this ultracode", "a (ultracode) b"]) {
|
|
assert.equal(stripUltraKeyword(text).occurrences, 1, text);
|
|
}
|
|
for (const text of ["ultracodes", "myultracode", "ultracodex", "ULTRAcode", "Ultracode", "ultra code"]) {
|
|
assert.equal(stripUltraKeyword(text).occurrences, 0, text);
|
|
}
|
|
});
|
|
|
|
test("stripping removes every keyword occurrence and leaves surrounding text verbatim", () => {
|
|
const cases: Array<[string, string, number]> = [
|
|
["please ultracode audit this", "please audit this", 1],
|
|
["ultracode audit this", "audit this", 1],
|
|
["audit this ultracode", "audit this", 1],
|
|
["a ultracode b", "a b", 1],
|
|
["please ultracode audit", "please audit", 1],
|
|
["keep double spaces ultracode", "keep double spaces", 1],
|
|
["a\nultracode\nb", "a\nb", 1],
|
|
["a-ultracode-b", "a--b", 1],
|
|
["ultracode ultracode audit", "audit", 2],
|
|
["a ultracode ultracode b", "a b", 2],
|
|
["ultracode", "", 1],
|
|
];
|
|
for (const [input, expected, occurrences] of cases) {
|
|
assert.deepEqual(stripUltraKeyword(input), { text: expected, occurrences }, input);
|
|
}
|
|
assert.deepEqual(stripUltraKeyword("no keyword here"), { text: "no keyword here", occurrences: 0 });
|
|
});
|
|
|
|
test("the trigger arms once, consumes once, and resets", () => {
|
|
const trigger = new UltraKeywordTrigger();
|
|
assert.equal(trigger.consume(), undefined);
|
|
assert.deepEqual(trigger.handleInput("please ultracode audit", "interactive"), { action: "transform", text: "please audit" });
|
|
|
|
const message = trigger.consume();
|
|
assert.equal(message?.customType, ULTRA_KEYWORD_MESSAGE_TYPE);
|
|
assert.equal(message?.display, true);
|
|
assert.match(message?.content ?? "", /inline `ultra` plan/);
|
|
assert.match(message?.content ?? "", /Do not ask whether to plan/);
|
|
assert.equal(trigger.consume(), undefined);
|
|
|
|
trigger.handleInput("ultracode audit", "interactive");
|
|
trigger.reset();
|
|
assert.equal(trigger.consume(), undefined);
|
|
});
|
|
|
|
test("property: stripping is idempotent, removes every standalone keyword, and never matches embedded words", () => {
|
|
const standalone = /\bultracode\b/g;
|
|
const countStandalone = (text: string): number => text.match(standalone)?.length ?? 0;
|
|
const printable = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()[]".split("");
|
|
const letterRun = fc
|
|
.array(fc.constantFrom(..."abcdefghijklmnopqrstuvwxyz".split("")), { minLength: 1, maxLength: 6 })
|
|
.map((letters) => letters.join(""));
|
|
const embeddedKeyword = fc.tuple(letterRun, letterRun).map(([before, after]) => `${before}ultracode${after}`);
|
|
const chunk = fc.oneof(
|
|
fc.constant("ultracode"),
|
|
fc.constant("ultracodes"),
|
|
fc.constant("myultracode"),
|
|
fc.constant("Ultracode"),
|
|
embeddedKeyword,
|
|
fc.array(fc.constantFrom(...printable), { maxLength: 10 }).map((chars) => chars.join("")),
|
|
);
|
|
|
|
fc.assert(
|
|
fc.property(fc.array(chunk, { maxLength: 8 }), embeddedKeyword, (chunks, embedded) => {
|
|
const text = [...chunks, embedded].join(" ");
|
|
|
|
// (a) A keyword inside a longer word never matches.
|
|
assert.equal(stripUltraKeyword(embedded).occurrences, 0);
|
|
|
|
const once = stripUltraKeyword(text);
|
|
const twice = stripUltraKeyword(once.text);
|
|
// (b) Stripping is idempotent.
|
|
assert.equal(twice.text, once.text);
|
|
// (c) No standalone keyword survives.
|
|
assert.equal(countStandalone(once.text), 0);
|
|
// (d) The count equals the standalone occurrences in the input.
|
|
assert.equal(once.occurrences, countStandalone(text));
|
|
}),
|
|
{ numRuns: 250 },
|
|
);
|
|
});
|
|
|
|
test("origin gating: interactive transforms and arms, while rpc and extension pass through", async () => {
|
|
for (const source of ["rpc", "extension"] as const) {
|
|
const h = await harness();
|
|
try {
|
|
const transformed = await h.events.get("input")!(
|
|
{ type: "input", text: "please ultracode audit", source },
|
|
h.ctx,
|
|
);
|
|
assert.deepEqual(transformed, { action: "continue" }, source);
|
|
const run = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal(run, undefined, `${source} must not inject a keyword message`);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
}
|
|
|
|
const h = await harness();
|
|
try {
|
|
const transformed = await h.events.get("input")!(
|
|
{ type: "input", text: "please ultracode audit", source: "interactive" },
|
|
h.ctx,
|
|
);
|
|
assert.deepEqual(transformed, { action: "transform", text: "please audit" });
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
|
|
test("the keyword message is injected into the next run only, then the flag is cleared", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await h.events.get("input")!({ type: "input", text: "audit src ultracode", source: "interactive" }, h.ctx);
|
|
|
|
const first = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
const message = (first as { message?: { customType?: string; content?: string; display?: boolean } } | undefined)?.message;
|
|
assert.equal(message?.customType, ULTRA_KEYWORD_MESSAGE_TYPE);
|
|
assert.equal(message?.display, true);
|
|
assert.match(message?.content ?? "", /inline `ultra` plan/);
|
|
|
|
const second = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal(second, undefined);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
|
|
test("the keyword forces plan-first handling whether ultra mode is on or off", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await h.events.get("input")!({ type: "input", text: "audit ultracode", source: "interactive" }, h.ctx);
|
|
const offRun = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal(
|
|
(offRun as { message?: { customType?: string } }).message?.customType,
|
|
ULTRA_KEYWORD_MESSAGE_TYPE,
|
|
);
|
|
|
|
await h.commands.get("ultra")!("on", h.ctx);
|
|
await h.events.get("input")!({ type: "input", text: "audit ultracode", source: "interactive" }, h.ctx);
|
|
const onEvent = promptEvent();
|
|
const onRun = await h.events.get("before_agent_start")!(onEvent, h.ctx);
|
|
assert.equal(
|
|
(onRun as { message?: { customType?: string } }).message?.customType,
|
|
ULTRA_KEYWORD_MESSAGE_TYPE,
|
|
);
|
|
assert.match(onEvent.systemPromptOptions.sections.ultracode ?? "", /Ultra mode is on/);
|
|
|
|
const noKeyword = await h.events.get("input")!(
|
|
{ type: "input", text: "audit without the trigger", source: "interactive" },
|
|
h.ctx,
|
|
);
|
|
assert.deepEqual(noKeyword, { action: "continue" });
|
|
assert.equal(await h.events.get("before_agent_start")!(promptEvent(), h.ctx), undefined);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
|
|
test("multiple keyword occurrences strip all of them but inject one message", async () => {
|
|
const h = await harness();
|
|
try {
|
|
const transformed = await h.events.get("input")!(
|
|
{ type: "input", text: "ultracode audit ultracode src ultracode", source: "interactive" },
|
|
h.ctx,
|
|
);
|
|
assert.deepEqual(transformed, { action: "transform", text: "audit src" });
|
|
|
|
const first = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal((first as { message?: { customType?: string } }).message?.customType, ULTRA_KEYWORD_MESSAGE_TYPE);
|
|
const second = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal(second, undefined);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
|
|
test("PI_SUBAGENT_ULTRA_KEYWORD=off removes the input hook and injects nothing", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA_KEYWORD", "off", async () => {
|
|
const h = await harness();
|
|
try {
|
|
assert.equal(h.events.has("input"), false);
|
|
const run = await h.events.get("before_agent_start")!(promptEvent(), h.ctx);
|
|
assert.equal(run, undefined);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
});
|
|
|
|
test("PI_SUBAGENT_ULTRA=off removes the keyword hook and consumption with the rest of the layer", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA", "off", async () => {
|
|
const h = await harness();
|
|
try {
|
|
assert.equal(h.events.has("input"), false);
|
|
assert.equal(h.events.has("before_agent_start"), false);
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
});
|
|
|
|
test("an invalid PI_SUBAGENT_ULTRA_KEYWORD value warns and keeps the trigger on", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA_KEYWORD", "sometimes", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await h.events.get("session_start")!({ type: "session_start", reason: "startup" }, h.ctx);
|
|
assert.equal(h.notifications.length, 1);
|
|
assert.match(h.notifications[0], /PI_SUBAGENT_ULTRA_KEYWORD="sometimes"/);
|
|
assert.match(h.notifications[0], /using on/);
|
|
|
|
const transformed = await h.events.get("input")!(
|
|
{ type: "input", text: "please ultracode audit", source: "interactive" },
|
|
h.ctx,
|
|
);
|
|
assert.deepEqual(transformed, { action: "transform", text: "please audit" });
|
|
} finally {
|
|
await dispose(h);
|
|
}
|
|
});
|
|
});
|