662 lines
24 KiB
TypeScript
662 lines
24 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, { after } from "node:test";
|
||
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
||
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
||
import fc from "fast-check";
|
||
import { Value } from "typebox/value";
|
||
import registerExtension from "../src/index.ts";
|
||
import { extractWorkflowJournals, persistedWorkflowJournal, WORKFLOW_RUN_ENTRY } from "../src/persistence.ts";
|
||
import { UltraParams } from "../src/schemas.ts";
|
||
import type { WorkflowStartResult } from "../src/workflow-run.ts";
|
||
import {
|
||
INLINE_WORKFLOW_FILE_PATH,
|
||
WorkflowValidationError,
|
||
parseInlineWorkflow,
|
||
parseWorkflow,
|
||
} from "../src/workflow-plan.ts";
|
||
import { FakeRunner } from "./helpers.ts";
|
||
|
||
const tempRoots: string[] = [];
|
||
|
||
after(() => {
|
||
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
|
||
});
|
||
|
||
type Execute = (
|
||
id: string,
|
||
params: any,
|
||
signal?: AbortSignal,
|
||
onUpdate?: unknown,
|
||
ctx?: ExtensionToolContext,
|
||
) => Promise<AgentToolResult<any>>;
|
||
|
||
interface Confirmation {
|
||
title: string;
|
||
message: string;
|
||
}
|
||
|
||
interface HarnessOptions {
|
||
trusted?: boolean;
|
||
confirmResult?: boolean | boolean[];
|
||
}
|
||
|
||
async function harness(options: HarnessOptions = {}) {
|
||
const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-ultra-"));
|
||
tempRoots.push(cwd);
|
||
const agentsDir = path.join(cwd, ".pi", "agents");
|
||
await fs.promises.mkdir(agentsDir, { recursive: true });
|
||
await fs.promises.writeFile(
|
||
path.join(agentsDir, "scout.md"),
|
||
"---\nname: scout\ndescription: Test project agent\n---\nTest prompt\n",
|
||
);
|
||
|
||
const runner = new FakeRunner();
|
||
const tools = new Map<string, { name: string; description?: string; execute: Execute }>();
|
||
const commands = new Map<string, (args: string, ctx: ExtensionToolContext) => Promise<void>>();
|
||
const events = new Map<string, (event: any, ctx: ExtensionToolContext) => unknown>();
|
||
const entries: unknown[] = [];
|
||
const notifications: string[] = [];
|
||
const confirmations: Confirmation[] = [];
|
||
const confirmAnswers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined;
|
||
const confirmFallback = typeof options.confirmResult === "boolean" ? options.confirmResult : true;
|
||
|
||
const pi = {
|
||
registerTool(definition: { name: string; description?: string; execute: Execute }) {
|
||
tools.set(definition.name, definition);
|
||
},
|
||
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(type: string, data: unknown) {
|
||
entries.push({ type: "custom", customType: type, data });
|
||
},
|
||
};
|
||
registerExtension(pi as unknown as ExtensionAPI, runner);
|
||
|
||
const ctx = {
|
||
cwd,
|
||
mode: "tui",
|
||
hasUI: true,
|
||
model: undefined,
|
||
thinkingLevel: undefined,
|
||
isProjectTrusted: () => options.trusted ?? true,
|
||
ui: {
|
||
confirm: async (title: string, message: string) => {
|
||
confirmations.push({ title, message });
|
||
return confirmAnswers && confirmAnswers.length > 0 ? confirmAnswers.shift()! : confirmFallback;
|
||
},
|
||
notify: (text: string) => {
|
||
notifications.push(text);
|
||
},
|
||
setStatus: () => {},
|
||
},
|
||
sessionManager: {
|
||
getBranch: () => [],
|
||
getSessionId: () => "test-session",
|
||
},
|
||
} as unknown as ExtensionToolContext;
|
||
|
||
return { cwd, runner, tools, commands, events, entries, notifications, confirmations, ctx };
|
||
}
|
||
|
||
function textOf(result: AgentToolResult<any>): string {
|
||
return result.content[0]?.type === "text" ? result.content[0].text : "";
|
||
}
|
||
|
||
interface PlanOptions {
|
||
name?: string;
|
||
description?: string;
|
||
args?: string[];
|
||
}
|
||
|
||
function inlinePlan(steps: Array<Record<string, unknown>>, options: PlanOptions = {}): string {
|
||
const frontmatter = {
|
||
name: options.name ?? "test-plan",
|
||
description: options.description ?? "Test inline plan",
|
||
args: options.args ?? [],
|
||
steps,
|
||
};
|
||
return `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\nInline notes.\n`;
|
||
}
|
||
|
||
const SKETCH = `---
|
||
name: audit-routes
|
||
description: Audit every route handler for missing auth checks
|
||
args: [glob]
|
||
steps:
|
||
- id: scan
|
||
agent: scout
|
||
task: List files matching {args.glob} under src/routes/, one per line.
|
||
- id: audit
|
||
agent: reviewer
|
||
each: {steps.scan.output}
|
||
task: Audit {item} for missing authentication checks.
|
||
needs: [scan]
|
||
model: sonnet
|
||
cwd: src/routes
|
||
- id: merge
|
||
agent: merger
|
||
task: Merge these findings into one ranked list: {steps.audit.output}
|
||
needs: [audit]
|
||
---
|
||
Optional prose notes.
|
||
`;
|
||
|
||
test("inline and file sources produce the same plan modulo provenance", () => {
|
||
const filePlan = parseWorkflow(SKETCH, { source: "project", filePath: "/repo/.pi/workflows/audit-routes.md" });
|
||
const inline = parseInlineWorkflow(SKETCH);
|
||
assert.deepEqual(inline, {
|
||
...filePlan,
|
||
source: "inline",
|
||
filePath: INLINE_WORKFLOW_FILE_PATH,
|
||
});
|
||
assert.equal(inline.source, "inline");
|
||
assert.equal(inline.filePath, "ultra:inline");
|
||
});
|
||
|
||
test("property: identical content parses identically inline and from a file, modulo source/filePath", () => {
|
||
fc.assert(
|
||
fc.property(fc.oneof(fc.constant(SKETCH), fc.string({ maxLength: 400 })), (content) => {
|
||
let filePlan;
|
||
try {
|
||
filePlan = parseWorkflow(content, { source: "project", filePath: "/repo/.pi/workflows/test.md" });
|
||
} catch (error) {
|
||
assert.ok(error instanceof WorkflowValidationError, `unexpected error: ${String(error)}`);
|
||
const fileMessage = error.message;
|
||
assert.throws(
|
||
() => parseInlineWorkflow(content),
|
||
(inlineError: unknown) => {
|
||
assert.ok(inlineError instanceof WorkflowValidationError);
|
||
assert.equal(
|
||
inlineError.message,
|
||
fileMessage.replace("/repo/.pi/workflows/test.md", INLINE_WORKFLOW_FILE_PATH),
|
||
);
|
||
return true;
|
||
},
|
||
);
|
||
return;
|
||
}
|
||
|
||
assert.deepEqual(parseInlineWorkflow(content), {
|
||
...filePlan,
|
||
source: "inline",
|
||
filePath: INLINE_WORKFLOW_FILE_PATH,
|
||
});
|
||
}),
|
||
{ numRuns: 150 },
|
||
);
|
||
});
|
||
|
||
test("the review card names every step, fan-out source, agent source, and the caps", async () => {
|
||
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||
const h = await harness();
|
||
try {
|
||
const userDir = path.join(h.cwd, "user-agent-dir");
|
||
fs.mkdirSync(path.join(userDir, "agents"), { recursive: true });
|
||
fs.writeFileSync(
|
||
path.join(userDir, "agents", "global.md"),
|
||
"---\nname: global\ndescription: Global agent\n---\nYou are global.\n",
|
||
"utf-8",
|
||
);
|
||
process.env.PI_CODING_AGENT_DIR = userDir;
|
||
|
||
const plan = inlinePlan(
|
||
[
|
||
{ id: "scan", agent: "global", task: "scan {args.glob}" },
|
||
{ id: "audit", agent: "scout", task: "audit {item}", each: "{steps.scan.output}", needs: ["scan"] },
|
||
{ id: "merge", agent: "global", task: "merge {steps.audit.output}", needs: ["audit"] },
|
||
],
|
||
{ name: "audit-routes", description: "Audit every route handler", args: ["glob"] },
|
||
);
|
||
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan, args: { glob: "src/**" } },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.confirmations.length, 1);
|
||
|
||
const card = h.confirmations[0];
|
||
assert.match(card.title, /Run inline plan "audit-routes"\?/);
|
||
assert.match(card.message, /Inline plan "audit-routes" — Audit every route handler/);
|
||
assert.match(card.message, /- scan \(global\) — needs: none/);
|
||
assert.match(card.message, /- audit \(scout\) — needs: scan; each: \{steps\.scan\.output\}/);
|
||
assert.match(card.message, /- merge \(global\) — needs: audit/);
|
||
assert.match(card.message, /Children: 3–34 estimated \(2 fixed steps \+ 1 fan-out step × up to 32 items\)/);
|
||
assert.match(card.message, /Caps: 32 items per each-step, 256 children per run/);
|
||
assert.match(card.message, /Steps \(3 of 64 max\)/);
|
||
assert.match(card.message, /- global \(user\)/);
|
||
assert.match(card.message, /- scout \(project\)/);
|
||
|
||
const started = result.details as WorkflowStartResult;
|
||
assert.equal(h.runner.calls.length, 1);
|
||
assert.equal(h.runner.calls[0].task.task, "scan src/**");
|
||
const text = textOf(result);
|
||
assert.match(text, /Started ultra run job_\d+/);
|
||
assert.match(text, /Inline plan: audit-routes/);
|
||
assert.match(text, /The run's journal \(plan source "inline"\) is the only persisted copy of this plan\./);
|
||
assert.equal(h.entries.length, 0);
|
||
assert.ok(started.id);
|
||
} finally {
|
||
if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
||
else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
}
|
||
});
|
||
|
||
test("the review card warns when a plan's fan-outs can exceed the run cap", async () => {
|
||
const h = await harness();
|
||
try {
|
||
const fanOuts = Array.from({ length: 9 }, (_, index) => ({
|
||
id: `fan_${index}`,
|
||
agent: "scout",
|
||
task: "audit {item}",
|
||
each: "{steps.scan.output}",
|
||
needs: ["scan"],
|
||
}));
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan files" }, ...fanOuts], { name: "too-wide" }) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.confirmations.length, 1);
|
||
assert.match(h.confirmations[0].message, /Children: 10–289 estimated/);
|
||
assert.match(h.confirmations[0].message, /This plan can exceed the 256-child run cap/);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("declining the review card returns an error and spawns nothing", async () => {
|
||
const h = await harness({ confirmResult: false });
|
||
try {
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.equal(result.isError, true);
|
||
assert.match(textOf(result), /Canceled: inline plan "test-plan" not approved/);
|
||
assert.equal(h.confirmations.length, 1);
|
||
assert.equal(h.runner.calls.length, 0);
|
||
assert.equal(h.entries.length, 0);
|
||
} finally {
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("no-UI sessions never prompt and start directly", async () => {
|
||
const h = await harness();
|
||
try {
|
||
for (const mode of ["print", "json"]) {
|
||
const ctx = { ...h.ctx, hasUI: false, mode } as ExtensionToolContext;
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: `scan in ${mode} mode` }]) },
|
||
undefined,
|
||
undefined,
|
||
ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.runner.calls.at(-1)?.task.task, `scan in ${mode} mode`);
|
||
}
|
||
assert.equal(h.confirmations.length, 0);
|
||
assert.equal(h.runner.calls.length, 2);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
}
|
||
});
|
||
|
||
test("mode on with no UI also starts directly, with no prompt or card", async () => {
|
||
const h = await harness();
|
||
try {
|
||
await h.commands.get("ultra")!("on", h.ctx);
|
||
for (const mode of ["print", "json"]) {
|
||
const ctx = { ...h.ctx, hasUI: false, mode } as ExtensionToolContext;
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: `mode on in ${mode}` }]) },
|
||
undefined,
|
||
undefined,
|
||
ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.runner.calls.at(-1)?.task.task, `mode on in ${mode}`);
|
||
assert.match(textOf(result), /Size guideline: medium \(aim for fewer than 10 children\)/);
|
||
}
|
||
assert.equal(h.confirmations.length, 0);
|
||
assert.equal(h.runner.calls.length, 2);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
}
|
||
});
|
||
|
||
test("the ultra start cwd resolves agents and step cwd against it", async () => {
|
||
const h = await harness();
|
||
try {
|
||
const project = path.join(h.cwd, "project");
|
||
const nested = path.join(project, "nested");
|
||
await fs.promises.mkdir(path.join(project, ".pi", "agents"), { recursive: true });
|
||
await fs.promises.mkdir(nested, { recursive: true });
|
||
await fs.promises.writeFile(
|
||
path.join(project, ".pi", "agents", "nested.md"),
|
||
"---\nname: nested\ndescription: Nested agent\n---\nNested prompt\n",
|
||
);
|
||
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{
|
||
plan: inlinePlan([{ id: "scan", agent: "nested", task: "scan from the start cwd", cwd: "nested" }]),
|
||
cwd: "project",
|
||
},
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.runner.calls.length, 1);
|
||
assert.equal(h.runner.calls[0].task.cwd, nested);
|
||
assert.equal(h.runner.calls[0].task.agent.filePath, path.join(project, ".pi", "agents", "nested.md"));
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("project agents referenced by an inline plan still hit the existing trust confirmation", async () => {
|
||
const h = await harness({ trusted: false, confirmResult: [true, true] });
|
||
try {
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
assert.equal(h.confirmations.length, 2);
|
||
assert.match(h.confirmations[0].message, /repo-controlled/);
|
||
assert.ok(h.confirmations[0].message.includes(path.join(h.cwd, ".pi", "agents")));
|
||
assert.match(h.confirmations[1].title, /Run inline plan "test-plan"\?/);
|
||
assert.equal(h.runner.calls.length, 1);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
}
|
||
});
|
||
|
||
test("declining project-agent trust aborts before the review card and any spawn", async () => {
|
||
const h = await harness({ trusted: false, confirmResult: [false] });
|
||
try {
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.equal(result.isError, true);
|
||
assert.match(textOf(result), /not approved/);
|
||
assert.equal(h.confirmations.length, 1);
|
||
assert.equal(h.runner.calls.length, 0);
|
||
assert.equal(h.entries.length, 0);
|
||
} finally {
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("malformed plans, unknown agents, argument violations, and cap violations fail before the card or any spawn", async () => {
|
||
const h = await harness();
|
||
try {
|
||
const tooManySteps = inlinePlan(
|
||
Array.from({ length: 65 }, (_, index) => ({ id: `step_${index}`, agent: "scout", task: `task ${index}` })),
|
||
);
|
||
const cases: Array<[string, Record<string, unknown>, RegExp]> = [
|
||
["malformed", { plan: "no frontmatter here" }, /missing YAML frontmatter/],
|
||
["unknown-agent", { plan: inlinePlan([{ id: "scan", agent: "ghost", task: "scan" }]) }, /Unknown agent: "ghost"/],
|
||
["undeclared-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.missing}" }]) }, /undeclared argument "missing"/],
|
||
["missing-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], { args: ["glob"] }) }, /missing required argument "glob"/],
|
||
["unknown-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], { args: ["glob"] }), args: { glob: "src/**", other: "x" } }, /unknown argument "other"/],
|
||
["too-many-steps", { plan: tooManySteps }, /too many steps \(65\).*Max is 64/],
|
||
];
|
||
|
||
for (const [label, request, expected] of cases) {
|
||
const result = await h.tools.get("ultra")!.execute("ultra", request, undefined, undefined, h.ctx);
|
||
assert.equal(result.isError, true, label);
|
||
assert.match(textOf(result), expected, label);
|
||
}
|
||
assert.equal(h.confirmations.length, 0);
|
||
assert.equal(h.runner.calls.length, 0);
|
||
assert.equal(h.entries.length, 0);
|
||
} finally {
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("an inline-sourced run journals source inline and round-trips through the journal entry", async () => {
|
||
const h = await harness();
|
||
try {
|
||
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
|
||
const result = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "journal this run" }], { name: "journal-flow" }) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(result.isError, true);
|
||
const started = result.details as WorkflowStartResult;
|
||
h.runner.complete("journal this run", "done");
|
||
await new Promise((resolve) => setImmediate(resolve));
|
||
const waited = await h.tools.get("subagent_jobs")!.execute(
|
||
"wait",
|
||
{ action: "wait", jobId: started.id, timeoutSeconds: 1 },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.equal((waited.details as any).run.status, "succeeded");
|
||
|
||
const journals = extractWorkflowJournals(h.entries);
|
||
assert.equal(journals.length, 1);
|
||
const journal = journals[0];
|
||
assert.equal(journal.plan.source, "inline");
|
||
assert.equal(journal.plan.filePath, INLINE_WORKFLOW_FILE_PATH);
|
||
assert.equal(journal.plan.name, "journal-flow");
|
||
|
||
const serialized = (entry: unknown) => JSON.parse(JSON.stringify(entry));
|
||
const entry = serialized({
|
||
type: "custom",
|
||
customType: WORKFLOW_RUN_ENTRY,
|
||
data: persistedWorkflowJournal("test-session", journal),
|
||
});
|
||
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
}
|
||
});
|
||
|
||
test("PI_SUBAGENT_ULTRA=off prevents ultra registration while the workflow surface stays", async () => {
|
||
const previous = process.env.PI_SUBAGENT_ULTRA;
|
||
process.env.PI_SUBAGENT_ULTRA = "off";
|
||
const h = await harness();
|
||
try {
|
||
assert.equal(h.tools.has("ultra"), false);
|
||
assert.equal(h.tools.has("workflow"), true);
|
||
} finally {
|
||
if (previous === undefined) delete process.env.PI_SUBAGENT_ULTRA;
|
||
else process.env.PI_SUBAGENT_ULTRA = previous;
|
||
}
|
||
});
|
||
|
||
test("an invalid PI_SUBAGENT_ULTRA value warns and keeps the default on", async () => {
|
||
const previous = process.env.PI_SUBAGENT_ULTRA;
|
||
process.env.PI_SUBAGENT_ULTRA = "sometimes";
|
||
const h = await harness();
|
||
try {
|
||
assert.equal(h.tools.has("ultra"), true);
|
||
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="sometimes"/);
|
||
assert.match(h.notifications[0], /using on/);
|
||
} finally {
|
||
if (previous === undefined) delete process.env.PI_SUBAGENT_ULTRA;
|
||
else process.env.PI_SUBAGENT_ULTRA = previous;
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("the ultra tool exposes plan/args/cwd and a token-budgeted description", async () => {
|
||
const h = await harness();
|
||
try {
|
||
const tool = h.tools.get("ultra");
|
||
assert.ok(tool);
|
||
assert.ok((tool.description?.length ?? Number.POSITIVE_INFINITY) < 6000);
|
||
assert.ok((tool.description?.length ?? 0) > 1000);
|
||
assert.equal(Value.Check(UltraParams, { plan: "---\nname: x\ndescription: d\nsteps: []\n---" }), true);
|
||
assert.equal(Value.Check(UltraParams, { plan: "p", args: { glob: "src/**" }, cwd: "." }), true);
|
||
assert.equal(Value.Check(UltraParams, {}), false);
|
||
assert.equal(Value.Check(UltraParams, { plan: 1 }), false);
|
||
assert.equal(Value.Check(UltraParams, { plan: "p", args: { glob: 1 } }), false);
|
||
} finally {
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
function promptEvent(sections: Record<string, string> = {}) {
|
||
return {
|
||
messageType: "user",
|
||
prompt: "a prompt",
|
||
images: [],
|
||
systemPrompt: "",
|
||
systemPromptOptions: { sections },
|
||
};
|
||
}
|
||
|
||
test("/ultra toggles the mode, reports bare status, defaults off, and rejects other words", async () => {
|
||
const h = await harness();
|
||
try {
|
||
await h.commands.get("ultra")!("", h.ctx);
|
||
assert.equal(h.notifications.at(-1), "Ultra mode is off.");
|
||
await h.commands.get("ultra")!("on", h.ctx);
|
||
assert.equal(h.notifications.at(-1), "Ultra mode is on.");
|
||
await h.commands.get("ultra")!("", h.ctx);
|
||
assert.equal(h.notifications.at(-1), "Ultra mode is on.");
|
||
await h.commands.get("ultra")!("off", h.ctx);
|
||
assert.equal(h.notifications.at(-1), "Ultra mode is off.");
|
||
await h.commands.get("ultra")!("sometimes", h.ctx);
|
||
assert.equal(h.notifications.at(-1), "Usage: /ultra [on|off]");
|
||
assert.equal(h.confirmations.length, 0);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("the PI_SUBAGENT_ULTRACODE default is respected for on and off", async () => {
|
||
const previous = process.env.PI_SUBAGENT_ULTRACODE;
|
||
try {
|
||
for (const setting of ["on", "off"] as const) {
|
||
process.env.PI_SUBAGENT_ULTRACODE = setting;
|
||
const h = await harness();
|
||
try {
|
||
await h.commands.get("ultra")!("", h.ctx);
|
||
assert.equal(h.notifications.at(-1), `Ultra mode is ${setting}.`);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
}
|
||
} finally {
|
||
if (previous === undefined) delete process.env.PI_SUBAGENT_ULTRACODE;
|
||
else process.env.PI_SUBAGENT_ULTRACODE = previous;
|
||
}
|
||
});
|
||
|
||
test("the guidance section is present exactly while the mode is on and stable across consecutive runs", async () => {
|
||
const h = await harness();
|
||
try {
|
||
const off = promptEvent();
|
||
await h.events.get("before_agent_start")!(off, h.ctx);
|
||
assert.equal("ultracode" in off.systemPromptOptions.sections, false);
|
||
|
||
await h.commands.get("ultra")!("on", h.ctx);
|
||
const first = promptEvent();
|
||
await h.events.get("before_agent_start")!(first, h.ctx);
|
||
const guidance = first.systemPromptOptions.sections.ultracode;
|
||
assert.equal(typeof guidance, "string");
|
||
assert.match(guidance, /Ultra mode is on/);
|
||
assert.match(guidance, /`ultra` tool/);
|
||
assert.match(guidance, /Size guideline: medium \(aim for fewer than 10 children\)/);
|
||
assert.match(guidance, /Hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run/);
|
||
assert.match(guidance, /last succeeded step's bounded output — the consolidated answer/);
|
||
|
||
const second = promptEvent();
|
||
await h.events.get("before_agent_start")!(second, h.ctx);
|
||
assert.equal(second.systemPromptOptions.sections.ultracode, guidance);
|
||
|
||
await h.commands.get("ultra")!("off", h.ctx);
|
||
const reused = promptEvent({ ultracode: guidance });
|
||
await h.events.get("before_agent_start")!(reused, h.ctx);
|
||
assert.equal("ultracode" in reused.systemPromptOptions.sections, false);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test("mode on is the consent: the review card is skipped while off still shows it, and the start result names the guideline", async () => {
|
||
const h = await harness();
|
||
try {
|
||
await h.commands.get("ultra")!("on", h.ctx);
|
||
const onResult = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan while on" }], { name: "consent-plan" }) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(onResult.isError, true);
|
||
assert.equal(h.confirmations.length, 0);
|
||
assert.equal(h.runner.calls.length, 1);
|
||
const onText = textOf(onResult);
|
||
assert.match(onText, /Inline plan: consent-plan/);
|
||
assert.match(
|
||
onText,
|
||
/Size guideline: medium \(aim for fewer than 10 children\); hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run\./,
|
||
);
|
||
|
||
await h.commands.get("ultra")!("off", h.ctx);
|
||
const offResult = await h.tools.get("ultra")!.execute(
|
||
"ultra",
|
||
{ plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan while off" }], { name: "card-plan" }) },
|
||
undefined,
|
||
undefined,
|
||
h.ctx,
|
||
);
|
||
assert.notEqual(offResult.isError, true);
|
||
assert.equal(h.confirmations.length, 1);
|
||
assert.match(h.confirmations[0].title, /Run inline plan "card-plan"\?/);
|
||
assert.equal(h.runner.calls.length, 2);
|
||
} finally {
|
||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||
}
|
||
});
|