pi.test.ts
This file
Path
apps/cli/test/pi.test.ts
936 lines · 25.6 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
1import type {2 AgentBeforeSettleEvent,3 BeforeAgentStartEvent,4 SessionBoundaryDraft,5 ToolCallEvent,6} from "@earendil-works/pi-coding-agent";7import { NodeServices } from "@effect/platform-node";8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client } from "@repo/protocol/contracts";11import { Glob } from "@repo/protocol/domain/common";12import { AskId, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";13import {14 ChecksFailed,15 OutOfScope,16 RepoBusy,17 TouchedJudge,18} from "@repo/protocol/refusal";19import type { Refusal } from "@repo/protocol/refusal";20import { explain } from "@repo/protocol/render";21import {22 Array,23 ConfigProvider,24 Effect,25 FileSystem,26 Layer,27 Option,28} from "effect";2930import { PushCheck, PushCheckFailed } from "../src/hook/push-check.ts";31import { saveSession } from "../src/hook/session.ts";32import type { SessionState } from "../src/hook/session.ts";33import extension, {34 GuardedCall,35 HookFailed,36 piAdapter,37 policyDeps,38 SettleVerdict,39} from "../src/pi.ts";40import type { PiContext, PiDeps, PiEvents, PiHandlers } from "../src/pi.ts";4142const cwd = "/work/datekit";4344const briefText = "# Your claim: fix-week in datekit";4546const projectFile = RepoPath.make(`${Brand.configDir}/project.ts`);4748const outside = new OutOfScope({ paths: [RepoPath.make("README.md")] });4950interface Policy {51 readonly brief?: Option.Option<string>;52 readonly guard?: (53 call: GuardedCall54 ) => Option.Option<Array.NonEmptyReadonlyArray<Refusal>>;55 readonly settle?: () => SettleVerdict;56}5758const fakeDeps = (policy: Policy) => {59 const asked: string[] = [];6061 const deps: PiDeps = {62 brief: (session) =>63 Effect.sync(() => {64 asked.push(`brief ${session.id} ${session.cwd}`);6566 return policy.brief ?? Option.none();67 }),68 guardTool: (session, call) =>69 Effect.sync(() => {70 asked.push(`guardTool ${session.id} ${call._tag}`);7172 return policy.guard?.(call) ?? Option.none();73 }),74 settle: (session) =>75 Effect.sync(() => {76 asked.push(`settle ${session.id}`);7778 return policy.settle?.() ?? SettleVerdict.Waiting();79 }),80 };8182 return { asked, deps };83};8485const broken = (failure: Effect.Effect<never, HookFailed>): PiDeps => ({86 brief: () => failure,87 guardTool: () => failure,88 settle: () => failure,89});9091const judging = (call: GuardedCall) =>92 GuardedCall.$is("Write")(call) && call.file === projectFile93 ? Option.some(Array.of(new TouchedJudge({ paths: [projectFile] })))94 : Option.none();9596const preflight =97 (...refusals: readonly Refusal[]) =>98 (call: GuardedCall) =>99 GuardedCall.$is("Push")(call) && Array.isReadonlyArrayNonEmpty(refusals)100 ? Option.some(refusals)101 : Option.none();102103const fakePi = () => {104 const handlers: { -readonly [K in keyof PiHandlers]?: PiHandlers[K] } = {};105 const events: string[] = [];106107 const pi: PiEvents = {108 on: <K extends keyof PiHandlers>(event: K, handler: PiHandlers[K]) => {109 events.push(event);110 handlers[event] = handler;111112 return () => {};113 },114 };115116 return { events, handlers, pi };117};118119const contextOf = (id: string, withUi = true) => {120 const notes: string[] = [];121 const bare: PiContext = { cwd, sessionManager: { getSessionId: () => id } };122123 const ui = {124 notify: (note: string) => {125 notes.push(note);126 },127 };128129 return { ctx: withUi ? { ...bare, ui } : bare, notes };130};131132const loaded = (policy: Policy) => {133 const { asked, deps } = fakeDeps(policy);134 const { events, handlers, pi } = fakePi();135136 piAdapter(deps)(pi);137138 return { asked, events, handlers };139};140141const fire = <E, R>(142 handler: ((event: E, ctx: PiContext) => Promise<R>) | undefined,143 event: E,144 ctx: PiContext145) =>146 handler === undefined147 ? Effect.sync(() =>148 expect.unreachable("the adapter registered no handler for this event")149 )150 : Effect.promise(() => handler(event, ctx));151152const startEvent: BeforeAgentStartEvent = {153 prompt: "Answer the ask you claimed.",154 systemPrompt: "You are pi.",155 systemPromptOptions: {156 appendSystemPrompt: "",157 contextFiles: [],158 cwd,159 promptGuidelines: [],160 sections: {},161 selectedTools: ["read", "bash", "edit", "write"],162 skills: [],163 toolGuidelines: {},164 toolSnippets: {},165 },166 type: "before_agent_start",167};168169const editOf = (path: string): ToolCallEvent => ({170 input: { edits: [{ newText: "export default {};", oldText: "" }], path },171 toolCallId: "call-1",172 toolName: "edit",173 type: "tool_call",174});175176const bashOf = (command: string): ToolCallEvent => ({177 input: { command },178 toolCallId: "call-2",179 toolName: "bash",180 type: "tool_call",181});182183// pi 1.0.3 previews a run that ended on the agent's reply as unable to go on184// until a handler appends a message.185const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({186 context: {187 canContinue: false,188 contextEntries: [],189 contextMessages: [],190 llmMessages: [],191 pendingMessages: [],192 },193 continue: false,194 entries,195 outcome: "completed",196 type: "agent_before_settle",197});198199const failing = new ChecksFailed({200 lane: "test",201 logRef: "logs/test",202 next: `${Brand.cli} check`,203});204205const refused = (actionable: boolean) => () =>206 SettleVerdict.Refused({ actionable, refusals: [failing] });207208const unreachable = Effect.fail(209 new HookFailed({ reason: "the platform did not answer within 10s" })210);211212describe("the pi adapter", () => {213 describe("before_agent_start", () => {214 it.effect("gives the agent the policy's brief when a claim exists", () =>215 Effect.gen(function* () {216 const { handlers } = loaded({ brief: Option.some(briefText) });217 const { ctx } = contextOf("s1");218219 const result = yield* fire(220 handlers.before_agent_start,221 startEvent,222 ctx223 );224225 expect(result).toStrictEqual({226 message: {227 content: briefText,228 customType: `${Brand.slug}-brief`,229 display: true,230 },231 });232 })233 );234235 it.effect("gives nothing without a claim", () =>236 Effect.gen(function* () {237 const { asked, handlers } = loaded({ brief: Option.none() });238 const { ctx } = contextOf("s1");239240 const result = yield* fire(241 handlers.before_agent_start,242 startEvent,243 ctx244 );245246 expect(result).toBeUndefined();247 expect(asked).toStrictEqual([`brief s1 ${cwd}`]);248 })249 );250251 it.effect(252 "briefs a session once, at its first prompt that has a claim",253 () =>254 Effect.gen(function* () {255 const briefs = [Option.none(), Option.some(briefText)];256 const { deps } = fakeDeps({});257 const { handlers, pi } = fakePi();258 const one = contextOf("s1").ctx;259 const other = contextOf("s2").ctx;260 const given: string[] = [];261262 // No claim at the first prompt; one is taken before the second.263 piAdapter({264 ...deps,265 brief: () =>266 Effect.succeed(briefs.shift() ?? Option.some(briefText)),267 })(pi);268269 for (const ctx of [one, one, one, other]) {270 const result = yield* fire(271 handlers.before_agent_start,272 startEvent,273 ctx274 );275276 given.push(result === undefined ? "nothing" : "the brief");277 }278279 expect(given).toStrictEqual([280 "nothing",281 "the brief",282 "nothing",283 "the brief",284 ]);285 })286 );287 });288289 describe("tool_call", () => {290 it.effect(291 "blocks an edit to the judge closure with the refusal's rendered text",292 () =>293 Effect.gen(function* () {294 const { handlers } = loaded({ guard: judging });295 const { ctx } = contextOf("s1");296297 const result = yield* fire(298 handlers.tool_call,299 editOf(projectFile),300 ctx301 );302303 expect(result).toStrictEqual({304 block: true,305 reason: explain([new TouchedJudge({ paths: [projectFile] })]).join(306 "\n"307 ),308 });309310 expect(result?.reason?.split("\n")[0]).toMatch(/^TouchedJudge: /u);311 })312 );313314 it.effect("lets a write the policy passes run", () =>315 Effect.gen(function* () {316 const { asked, handlers } = loaded({ guard: judging });317 const { ctx } = contextOf("s1");318319 const result = yield* fire(320 handlers.tool_call,321 {322 input: { content: "export const week = 1;", path: "src/week.ts" },323 toolCallId: "call-3",324 toolName: "write",325 type: "tool_call",326 },327 ctx328 );329330 expect(result).toBeUndefined();331 expect(asked).toStrictEqual(["guardTool s1 Write"]);332 })333 );334335 it.effect("never asks the policy about a tool that changes nothing", () =>336 Effect.gen(function* () {337 const { asked, handlers } = loaded({ guard: judging });338 const { ctx } = contextOf("s1");339340 const result = yield* fire(341 handlers.tool_call,342 {343 input: { path: projectFile },344 toolCallId: "call-4",345 toolName: "read",346 type: "tool_call",347 },348 ctx349 );350351 expect(result).toBeUndefined();352 expect(asked).toStrictEqual([]);353 })354 );355356 it.effect(357 "blocks a git push whose preflight has a refusal retrying cannot help",358 () =>359 Effect.gen(function* () {360 const { handlers } = loaded({361 guard: preflight(new RepoBusy(), outside),362 });363364 const { ctx } = contextOf("s1");365366 const result = yield* fire(367 handlers.tool_call,368 bashOf("git push origin HEAD"),369 ctx370 );371372 expect(result).toStrictEqual({373 block: true,374 reason: explain([outside]).join("\n"),375 });376 })377 );378379 it.effect(380 "lets a git push run when its preflight is clean or only retryable",381 () =>382 Effect.gen(function* () {383 for (const refusals of [[], [new RepoBusy()]]) {384 const { asked, handlers } = loaded({385 guard: preflight(...refusals),386 });387388 const { ctx } = contextOf("s1");389390 const result = yield* fire(391 handlers.tool_call,392 bashOf("git push"),393 ctx394 );395396 expect(result).toBeUndefined();397 expect(asked).toStrictEqual(["guardTool s1 Push"]);398 }399 })400 );401402 it.effect("reads a push however the command spells it", () =>403 Effect.gen(function* () {404 const pushes = [405 "git push",406 "git push -u origin HEAD",407 "cd packages/a && git push",408 `git -C ${cwd} push origin`,409 "git --no-pager push;",410 "bun test && git commit -am wip && git push",411 ];412413 const others = [414 "git status",415 "git log --grep push",416 "echo pushed",417 "bun run push",418 "git pushd",419 ];420421 for (const command of [...pushes, ...others]) {422 const { handlers } = loaded({ guard: preflight(outside) });423 const { ctx } = contextOf("s1");424 const result = yield* fire(handlers.tool_call, bashOf(command), ctx);425426 expect({ blocked: result?.block === true, command }).toStrictEqual({427 blocked: pushes.includes(command),428 command,429 });430 }431 })432 );433 });434435 describe("agent_before_settle", () => {436 const earlier: SessionBoundaryDraft = {437 customType: "other-extension",438 type: "custom",439 };440441 it.effect(442 "sends the agent back with the refusal while the verdict is one it can act on",443 () =>444 Effect.gen(function* () {445 const { handlers } = loaded({ settle: refused(true) });446 const { ctx } = contextOf("s1");447448 const result = yield* fire(449 handlers.agent_before_settle,450 settleOf([earlier]),451 ctx452 );453454 expect(result).toStrictEqual({455 continue: true,456 entries: [457 earlier,458 {459 content: [460 `The gate refuses this answer as it stands, so you are not done. Fix what follows, then run \`${Brand.cli} check\` before you push again:`,461 ...explain([failing]),462 ].join("\n"),463 customType: `${Brand.slug}-verdict`,464 display: true,465 type: "custom_message",466 },467 ],468 });469 })470 );471472 it.effect(473 "continues at most three times in one session, and lets the fourth settle stand",474 () =>475 Effect.gen(function* () {476 const { asked, handlers } = loaded({ settle: refused(true) });477 const one = contextOf("s1").ctx;478 const other = contextOf("s2").ctx;479 const continued: (boolean | undefined)[] = [];480481 for (const ctx of [one, one, one, one, other]) {482 const result = yield* fire(483 handlers.agent_before_settle,484 settleOf([]),485 ctx486 );487488 continued.push(result?.continue);489 }490491 expect(continued).toStrictEqual([true, true, true, undefined, true]);492493 // Past the cap, the policy is not even asked.494 expect(asked).toStrictEqual([495 "settle s1",496 "settle s1",497 "settle s1",498 "settle s2",499 ]);500 })501 );502503 it.effect("takes its cap from the options", () =>504 Effect.gen(function* () {505 const { deps } = fakeDeps({ settle: refused(true) });506 const { handlers, pi } = fakePi();507 const { ctx } = contextOf("s1");508509 piAdapter(deps, { maxContinuations: 1 })(pi);510511 const first = yield* fire(512 handlers.agent_before_settle,513 settleOf([]),514 ctx515 );516517 const second = yield* fire(518 handlers.agent_before_settle,519 settleOf([]),520 ctx521 );522523 expect([first?.continue, second]).toStrictEqual([true, undefined]);524 })525 );526527 it.effect(528 "sends back a completed run whose context ends on the agent's own reply",529 () =>530 Effect.gen(function* () {531 const { asked, handlers } = loaded({ settle: refused(true) });532 const { ctx } = contextOf("s1");533 const event = settleOf([]);534535 const result = yield* fire(handlers.agent_before_settle, event, ctx);536537 // The verdict the adapter appends is what lets the run go on.538 expect({539 asked,540 canContinue: event.context.canContinue,541 continued: result?.continue,542 entries: result?.entries?.length,543 }).toStrictEqual({544 asked: ["settle s1"],545 canContinue: false,546 continued: true,547 entries: 1,548 });549 })550 );551552 it.effect(553 "lists only the refusals the agent can fix, as the stop hook does",554 () =>555 Effect.gen(function* () {556 const { handlers } = loaded({557 settle: () =>558 SettleVerdict.Refused({559 actionable: true,560 refusals: [new RepoBusy(), outside],561 }),562 });563564 const { ctx } = contextOf("s1");565566 const result = yield* fire(567 handlers.agent_before_settle,568 settleOf([]),569 ctx570 );571572 expect(result?.entries).toStrictEqual([573 {574 content: [575 `The gate refuses this answer as it stands, so you are not done. Fix what follows, then run \`${Brand.cli} check\` before you push again:`,576 ...explain([outside]),577 ].join("\n"),578 customType: `${Brand.slug}-verdict`,579 display: true,580 type: "custom_message",581 },582 ]);583 })584 );585586 it.effect("never sends back a run the person stopped or that failed", () =>587 Effect.gen(function* () {588 const ended: readonly AgentBeforeSettleEvent[] = [589 { ...settleOf([]), outcome: "aborted" },590 { ...settleOf([]), outcome: "error" },591 ];592593 for (const event of ended) {594 const { asked, handlers } = loaded({ settle: refused(true) });595 const { ctx } = contextOf("s1");596597 const result = yield* fire(handlers.agent_before_settle, event, ctx);598599 expect({ asked, result }).toStrictEqual({600 asked: [],601 result: undefined,602 });603 }604 })605 );606607 it.effect(608 "never continues on a landing, a wait, or a refusal the agent cannot act on",609 () =>610 Effect.gen(function* () {611 const verdicts = [612 SettleVerdict.Landed(),613 SettleVerdict.Waiting(),614 SettleVerdict.Refused({615 actionable: false,616 refusals: [new RepoBusy()],617 }),618 ];619620 for (const verdict of verdicts) {621 const { handlers } = loaded({ settle: () => verdict });622 const { ctx } = contextOf("s1");623624 const result = yield* fire(625 handlers.agent_before_settle,626 settleOf([]),627 ctx628 );629630 expect({ result, verdict: verdict._tag }).toStrictEqual({631 result: undefined,632 verdict: verdict._tag,633 });634 }635 })636 );637 });638639 describe("when the policy fails", () => {640 it.effect(641 "allows the tool, and says why through ctx.ui.notify when pi gives one",642 () =>643 Effect.gen(function* () {644 const failures = [unreachable, Effect.die("a bug in the policy")];645646 for (const failure of failures) {647 const { handlers, pi } = fakePi();648 const { ctx, notes } = contextOf("s1");649650 piAdapter(broken(failure))(pi);651652 const result = yield* fire(653 handlers.tool_call,654 editOf(projectFile),655 ctx656 );657658 expect(result).toBeUndefined();659 expect(notes).toHaveLength(1);660 }661 })662 );663664 it.effect("names the failure in its note", () =>665 Effect.gen(function* () {666 const { handlers, pi } = fakePi();667 const { ctx, notes } = contextOf("s1");668669 piAdapter(broken(unreachable))(pi);670671 yield* fire(handlers.tool_call, bashOf("git push"), ctx);672673 expect(notes).toHaveLength(1);674 expect(notes[0]).toContain("the platform did not answer within 10s");675 })676 );677678 it.effect("gives no brief and no continuation, with or without a ui", () =>679 Effect.gen(function* () {680 for (const withUi of [true, false]) {681 const { handlers, pi } = fakePi();682 const { ctx, notes } = contextOf("s1", withUi);683684 piAdapter(broken(unreachable))(pi);685686 const brief = yield* fire(687 handlers.before_agent_start,688 startEvent,689 ctx690 );691692 const settled = yield* fire(693 handlers.agent_before_settle,694 settleOf([]),695 ctx696 );697698 expect({ brief, notes: notes.length, settled }).toStrictEqual({699 brief: undefined,700 notes: withUi ? 2 : 0,701 settled: undefined,702 });703 }704 })705 );706 });707708 it.effect(709 "registers only before_agent_start, tool_call and agent_before_settle",710 () =>711 Effect.sync(() => {712 const { events } = loaded({});713714 expect(events.toSorted()).toStrictEqual([715 "agent_before_settle",716 "before_agent_start",717 "tool_call",718 ]);719 })720 );721722 it.effect(723 "is what the package's pi entry exports, over the live policy",724 () =>725 Effect.sync(() => {726 const { events, pi } = fakePi();727728 extension(pi);729730 expect(events.toSorted()).toStrictEqual([731 "agent_before_settle",732 "before_agent_start",733 "tool_call",734 ]);735 })736 );737});738739const want = "An ISO week date parses to the Monday of that week.";740741const claimedIn = (root: string): SessionState => ({742 claim: {743 ask: AskId.make("fix-week"),744 base: CommitSha.make("1".repeat(40)),745 checkCommand: "bun test packages/a",746 project: ProjectName.make("oscabriel/datekit"),747 territory: { module: "a", paths: [Glob.make("packages/a/**")] },748 want,749 },750 holds: 0,751 judge: { paths: [Glob.make(`/${Brand.configDir}/**`)], pointers: [] },752 root,753});754755const policyWith = (756 checked: Effect.Effect<readonly Refusal[], PushCheckFailed>757) =>758 Effect.gen(function* () {759 const fs = yield* FileSystem.FileSystem;760 const state = yield* fs.makeTempDirectoryScoped();761 const folder = yield* fs.makeTempDirectoryScoped();762 const roots: string[] = [];763764 const env = ConfigProvider.layer(765 ConfigProvider.fromEnv({ env: { XDG_STATE_HOME: state } })766 );767768 const deps = policyDeps(769 Layer.mergeAll(770 NodeServices.layer,771 Layer.mock(Client)({}),772 Layer.succeed(PushCheck)({773 run: (root) =>774 Effect.andThen(775 Effect.sync(() => roots.push(root)),776 checked777 ),778 }),779 env780 )781 );782783 const keep = (id: string, facts: SessionState) =>784 saveSession(id, facts).pipe(785 Effect.provide(Layer.mergeAll(NodeServices.layer, env)),786 Effect.orDie787 );788789 return { deps, folder, keep, roots };790 }).pipe(Effect.provide(NodeServices.layer));791792const refusing = (...refusals: readonly Refusal[]) => Effect.succeed(refusals);793794describe("the live deps, over the hook policy's own modules", () => {795 it.live("brief a session whose kept facts hold a claim", () =>796 Effect.gen(function* () {797 const { deps, folder, keep } = yield* policyWith(refusing());798799 yield* keep("s1", claimedIn(folder));800801 const brief = Option.getOrElse(802 yield* deps.brief({ cwd: folder, id: "s1" }),803 () => ""804 );805806 expect(brief).toContain(want);807 expect(brief).toContain("bun test packages/a");808 })809 );810811 it.live("give no brief, and run no check, in a folder that is no repo", () =>812 Effect.gen(function* () {813 const { deps, folder, roots } = yield* policyWith(refusing(outside));814 const session = { cwd: folder, id: "s2" };815 const brief = yield* deps.brief(session);816 const push = yield* deps.guardTool(session, GuardedCall.Push());817 const settled = yield* deps.settle(session);818819 expect({ brief, push, roots, settled }).toStrictEqual({820 brief: Option.none(),821 push: Option.none(),822 roots: [],823 settled: SettleVerdict.Waiting(),824 });825 })826 );827828 it.live("preflight a push by the local check, in the claim's repo", () =>829 Effect.gen(function* () {830 const busy = new RepoBusy();831832 const { deps, folder, keep, roots } = yield* policyWith(833 refusing(busy, outside)834 );835836 yield* keep("s3", claimedIn(folder));837838 const push = yield* deps.guardTool(839 { cwd: `${folder}/packages/a`, id: "s3" },840 GuardedCall.Push()841 );842843 expect({ push, roots }).toStrictEqual({844 push: Option.some([busy, outside]),845 roots: [folder],846 });847 })848 );849850 it.live(851 "settle as the policy's stop would hold: on a refusal the agent can fix",852 () =>853 Effect.gen(function* () {854 const busy = new RepoBusy();855856 const cases = [857 {858 refusals: [outside],859 verdict: SettleVerdict.Refused({860 actionable: true,861 refusals: [outside],862 }),863 },864 {865 refusals: [busy],866 verdict: SettleVerdict.Refused({867 actionable: false,868 refusals: [busy],869 }),870 },871 { refusals: [], verdict: SettleVerdict.Waiting() },872 ];873874 for (const { refusals, verdict } of cases) {875 const { deps, folder, keep } = yield* policyWith(876 refusing(...refusals)877 );878879 yield* keep("s4", claimedIn(folder));880881 expect(yield* deps.settle({ cwd: folder, id: "s4" })).toStrictEqual(882 verdict883 );884 }885 })886 );887888 it.live(889 "judge an edit as the hook's pre-tool-use does, from the kept facts and without the check",890 () =>891 Effect.gen(function* () {892 const { deps, folder, keep, roots } = yield* policyWith(893 refusing(outside)894 );895896 yield* keep("s6", claimedIn(folder));897898 // pi names a file absolutely, or from the agent's folder.899 const session = { cwd: `${folder}/packages/a`, id: "s6" };900901 const judged = yield* Effect.forEach(902 [`${folder}/${projectFile}`, "../../README.md", "src/week.ts"],903 (file) => deps.guardTool(session, GuardedCall.Write({ file }))904 );905906 const unclaimed = yield* deps.guardTool(907 { cwd: folder, id: "s7" },908 GuardedCall.Write({ file: projectFile })909 );910911 expect({ judged, roots, unclaimed }).toStrictEqual({912 judged: [913 Option.some([new TouchedJudge({ paths: [projectFile] })]),914 Option.some([outside]),915 Option.none(),916 ],917 roots: [],918 unclaimed: Option.none(),919 });920 })921 );922923 it.live("fail as HookFailed when the local check gives no answer", () =>924 Effect.gen(function* () {925 const { deps, folder, keep } = yield* policyWith(926 Effect.fail(new PushCheckFailed({ reason: "it ran past 1m" }))927 );928929 yield* keep("s5", claimedIn(folder));930931 const failed = yield* Effect.flip(deps.settle({ cwd: folder, id: "s5" }));932933 expect(failed.message).toContain("it ran past 1m");934 })935 );936});