Merge branch 'build/706-pi-adapter'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 9bac11d, 2b36e9b · Browse files · 3 files·+1456 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+1456 added−0 removed
- tests:+934 added−0 removed
- other:+522 added−0 removed
Provenance
- Commit
4de6bd1- Tree
2acbcb1- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
9bac11d- Parent 2
2b36e9b
3 files changed+1456 added−0 removed
added:apps/cli/src/pi.ts+520 added
1+/**2+ * The pi adapter: what `pi install npm:<package>` loads, at user level,3+ * through the published package's `"pi"` key (`dist/pi.js`), never from a4+ * project's `.pi/extensions/` (a stranger's repo runs no code in your5+ * harness). It is thin: three pi events, each answered by the one hook6+ * policy behind `<cli> hook` (`./hook/decide.ts`), through `PiDeps`.7+ */8+import type {9+ AgentBeforeSettleEvent,10+ AgentBeforeSettleEventResult,11+ BeforeAgentStartEvent,12+ BeforeAgentStartEventResult,13+ CustomMessageEntryDraft,14+ ExtensionContext,15+ ExtensionFactory,16+ ExtensionUIContext,17+ ToolCallEvent,18+ ToolCallEventResult,19+} from "@earendil-works/pi-coding-agent";20+import {21+ BunChildProcessSpawner,22+ BunFileSystem,23+ BunPath,24+} from "@effect/platform-bun";25+import { claudeEventOf } from "@repo/agent-kit/hook-events";26+import type { HookEvent } from "@repo/agent-kit/hook-events";27+import { Brand } from "@repo/brand";28+import type { Client } from "@repo/protocol/contracts";29+import type { Refusal } from "@repo/protocol/refusal";30+import { explain } from "@repo/protocol/render";31+import {32+ Array,33+ Cause,34+ Data,35+ Effect,36+ Layer,37+ Match,38+ Option,39+ Schema,40+} from "effect";41+import type { FileSystem, Path } from "effect";42+import type { ChildProcessSpawner } from "effect/process";43+44+import { CredentialsFile } from "./credentials.ts";45+import { decideHook, MAX_HOLDS } from "./hook/decide.ts";46+import type { HookFacts } from "./hook/decide.ts";47+import { gatherFacts } from "./hook/facts.ts";48+import type { HookInput } from "./hook/input.ts";49+import { PushCheck, pushCheckWith } from "./hook/push-check.ts";50+import { loadSession, saveSession } from "./hook/session.ts";51+import type { SessionState } from "./hook/session.ts";52+import { RemoteClient } from "./remote.ts";53+54+/** The policy could not answer; the adapter allows, and says why. */55+export class HookFailed extends Schema.TaggedError<HookFailed>()("HookFailed", {56+ reason: Schema.String,57+}) {58+ override get message() {59+ return `the hook policy gave no answer: ${this.reason}`;60+ }61+}62+63+/** One pi session: its id, and the folder its agent runs in. */64+export interface PiSession {65+ readonly cwd: string;66+ readonly id: string;67+}68+69+/** A tool call the policy judges before it runs, read from pi's own. */70+export type GuardedCall =71+ /** pi's `edit` or `write`: the file it is about to change, as the tool names it. */72+ | { readonly _tag: "Write"; readonly file: string }73+ /** pi's `bash`, running `git push`. */74+ | { readonly _tag: "Push" };75+76+export const GuardedCall = Data.taggedEnum<GuardedCall>();77+78+/** Where the session's answer stands when its agent is about to stop. */79+export type SettleVerdict =80+ | { readonly _tag: "Landed" }81+ | { readonly _tag: "Waiting" }82+ | {83+ readonly _tag: "Refused";84+ readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;85+ /** Whether the agent can act on them now (the policy's call). */86+ readonly actionable: boolean;87+ };88+89+export const SettleVerdict = Data.taggedEnum<SettleVerdict>();90+91+/** The boundary to the hook policy: what the adapter asks it, per session. */92+export interface PiDeps {93+ /** The claim's brief for the session's repo; none without a claim. */94+ readonly brief: (95+ session: PiSession96+ ) => Effect.Effect<Option.Option<string>, HookFailed>;97+ /** What the gate would refuse of the call; none when it would pass. */98+ readonly guardTool: (99+ session: PiSession,100+ call: GuardedCall101+ ) => Effect.Effect<102+ Option.Option<Array.NonEmptyReadonlyArray<Refusal>>,103+ HookFailed104+ >;105+ readonly settle: (106+ session: PiSession107+ ) => Effect.Effect<SettleVerdict, HookFailed>;108+}109+110+/** What the adapter reads of a handler's context. */111+export type PiContext = Pick<ExtensionContext, "cwd"> & {112+ readonly sessionManager: Pick<113+ ExtensionContext["sessionManager"],114+ "getSessionId"115+ >;116+ readonly ui?: Pick<ExtensionUIContext, "notify">;117+};118+119+/** The adapter's handlers, by pi event, as pi 1.0.3 types each event. */120+export interface PiHandlers {121+ readonly agent_before_settle: (122+ event: AgentBeforeSettleEvent,123+ ctx: PiContext124+ ) => Promise<AgentBeforeSettleEventResult | undefined>;125+ readonly before_agent_start: (126+ event: BeforeAgentStartEvent,127+ ctx: PiContext128+ ) => Promise<BeforeAgentStartEventResult | undefined>;129+ readonly tool_call: (130+ event: ToolCallEvent,131+ ctx: PiContext132+ ) => Promise<ToolCallEventResult | undefined>;133+}134+135+/** The part of pi's `ExtensionAPI` the adapter uses: `on`, for three events. */136+export interface PiEvents {137+ readonly on: {138+ (139+ event: "agent_before_settle",140+ handler: PiHandlers["agent_before_settle"]141+ ): () => void;142+ (143+ event: "before_agent_start",144+ handler: PiHandlers["before_agent_start"]145+ ): () => void;146+ (event: "tool_call", handler: PiHandlers["tool_call"]): () => void;147+ };148+}149+150+export interface PiOptions {151+ /**152+ * The most times one session is sent back to work: the hook policy's153+ * `MAX_HOLDS` (3) unless given. pi has no cap of its own.154+ */155+ readonly maxContinuations?: number;156+}157+158+/** The custom type of the brief pi shows before the agent starts. */159+const BRIEF = `${Brand.slug}-brief`;160+161+/** The custom type of the verdict a settle sends the agent back with. */162+const VERDICT = `${Brand.slug}-verdict`;163+164+/** What the agent reads when it is sent back: why, then the gateway's own text. */165+const verdictEntry = (166+ refusals: Array.NonEmptyReadonlyArray<Refusal>167+): CustomMessageEntryDraft => ({168+ content: [169+ `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:`,170+ ...explain(refusals),171+ ].join("\n"),172+ customType: VERDICT,173+ display: true,174+ type: "custom_message",175+});176+177+/** pi's `edit` and `write` name the file they change as `path`. */178+const decodeFile = Schema.decodeUnknownOption(179+ Schema.Struct({ path: Schema.String })180+);181+182+/** pi's `bash` runs `command`. */183+const decodeCommand = Schema.decodeUnknownOption(184+ Schema.Struct({ command: Schema.String })185+);186+187+/**188+ * git running `push`, wherever it starts in the command line and after any189+ * of git's own options: `git push`, `cd a && git push`, `git -C dir push`.190+ * A false match only runs the preflight, which blocks nothing a real push191+ * would not be refused.192+ */193+const GIT_PUSH =194+ /(?:^|[\s;&|(`])git(?:\s+-[Cc]\s+\S+|\s+-\S+)*\s+push(?![\w-])/u;195+196+/**197+ * The call the policy judges, read from pi's tool call at the boundary:198+ * `edit` and `write` change a file, and `bash` may push. Every other call199+ * runs unjudged. The adapter never changes a call, only blocks one.200+ */201+const guardedCall = (event: ToolCallEvent): Option.Option<GuardedCall> =>202+ Match.value(event.toolName).pipe(203+ Match.when(Match.is("edit", "write"), () =>204+ Option.map(decodeFile(event.input), ({ path }) =>205+ GuardedCall.Write({ file: path })206+ )207+ ),208+ Match.when("bash", () =>209+ Option.flatMap(decodeCommand(event.input), ({ command }) =>210+ GIT_PUSH.test(command) ? Option.some(GuardedCall.Push()) : Option.none()211+ )212+ ),213+ Match.orElse(() => Option.none())214+ );215+216+/**217+ * The refusals retrying cannot help: the ones the agent must fix. A218+ * retryable refusal is a wait (the repo was busy), as the stop hook reads it.219+ */220+const fixable = (refusals: readonly Refusal[]) =>221+ refusals.filter((refusal) => !refusal.retryable);222+223+/**224+ * pi's block for what the gate would refuse that retrying cannot help, with225+ * the gateway's own text; a retryable refusal is a wait, never a block.226+ */227+const blockFor = (228+ refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>229+): Option.Option<ToolCallEventResult> => {230+ const final = fixable(Option.getOrElse(refusals, () => []));231+232+ return Array.isReadonlyArrayNonEmpty(final)233+ ? Option.some({ block: true, reason: explain(final).join("\n") })234+ : Option.none();235+};236+237+/**238+ * What a verdict tells the agent to act on: the refusals it can fix, as the239+ * stop hook's hold names them, or every refusal when the policy holds on240+ * retryable ones alone.241+ */242+const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>243+ Array.match(fixable(refusals), {244+ onEmpty: () => refusals,245+ onNonEmpty: (final) => final,246+ });247+248+/** The session a handler runs in. */249+const sessionOf = (ctx: PiContext): PiSession => ({250+ cwd: ctx.cwd,251+ id: ctx.sessionManager.getSessionId(),252+});253+254+/** A failure's first line, for the note. */255+const firstLine = (cause: Cause.Cause<unknown>) =>256+ String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";257+258+/**259+ * Runs one handler's reply for pi, which awaits a promise. The gate stays260+ * the authority, so a policy that fails, or any defect, lets pi go on as it261+ * would without the adapter (a `tool_call` handler that rejects would block262+ * the tool), and says why through `ctx.ui.notify` when pi gives one.263+ */264+const reply = <A>(265+ ctx: PiContext,266+ event: keyof PiHandlers,267+ decided: Effect.Effect<Option.Option<A>, HookFailed>268+): Promise<A | undefined> =>269+ Effect.runPromise(270+ decided.pipe(271+ Effect.catchCause((cause) =>272+ Effect.as(273+ Effect.sync(() =>274+ ctx.ui?.notify(275+ `${Brand.cli} ${event}: ${firstLine(cause)}; allowing, and the gateway still judges every push`,276+ "warning"277+ )278+ ),279+ Option.none<A>()280+ )281+ ),282+ Effect.map(Option.getOrUndefined)283+ )284+ );285+286+/**287+ * The adapter over `deps`: registers its three handlers on `pi`, and no288+ * other event or tool. Each pi load counts its own continuations, by289+ * session, so no state outlives the extension.290+ */291+export const piAdapter =292+ (deps: PiDeps, options: PiOptions = {}) =>293+ (pi: PiEvents): void => {294+ const most = options.maxContinuations ?? MAX_HOLDS;295+ const continued = new Map<string, number>();296+ const briefed = new Set<string>();297+298+ // pi starts the agent on every prompt; the brief stays in the session,299+ // so each session gets it once, at its first prompt with a claim.300+ pi.on("before_agent_start", (_event, ctx) => {301+ const session = sessionOf(ctx);302+303+ return reply(304+ ctx,305+ "before_agent_start",306+ briefed.has(session.id)307+ ? Effect.succeedNone308+ : deps.brief(session).pipe(309+ Effect.tap((brief) =>310+ Effect.sync(() => {311+ if (Option.isSome(brief)) {312+ briefed.add(session.id);313+ }314+ })315+ ),316+ Effect.map(317+ Option.map((content): BeforeAgentStartEventResult => ({318+ message: { content, customType: BRIEF, display: true },319+ }))320+ )321+ )322+ );323+ });324+325+ pi.on("tool_call", (event, ctx) =>326+ reply(327+ ctx,328+ "tool_call",329+ Option.match(guardedCall(event), {330+ onNone: () => Effect.succeedNone,331+ onSome: (call) =>332+ Effect.map(deps.guardTool(sessionOf(ctx), call), blockFor),333+ })334+ )335+ );336+337+ // Only a verdict the agent can act on sends it back, at most `most`338+ // times a session, and only a run that completed: a run the person339+ // stopped, or one that failed, stays stopped. Otherwise the policy is340+ // not even asked. `event.context.canContinue` is no guide: pi computes341+ // it before this handler's entry, and a run that ends on the agent's own342+ // reply reads false until the verdict is appended.343+ pi.on("agent_before_settle", (event, ctx) => {344+ const session = sessionOf(ctx);345+ const used = continued.get(session.id) ?? 0;346+347+ return reply(348+ ctx,349+ "agent_before_settle",350+ event.outcome !== "completed" || used >= most351+ ? Effect.succeedNone352+ : Effect.flatMap(deps.settle(session), (verdict) =>353+ SettleVerdict.$is("Refused")(verdict) && verdict.actionable354+ ? Effect.sync(() => {355+ continued.set(session.id, used + 1);356+357+ return Option.some<AgentBeforeSettleEventResult>({358+ continue: true,359+ entries: [360+ ...event.entries,361+ verdictEntry(toActOn(verdict.refusals)),362+ ],363+ });364+ })365+ : Effect.succeedNone366+ )367+ );368+ });369+ };370+371+// ------------------------------------------------------------ live372+373+/**374+ * The session's facts, kept in the hook's own session file under pi's375+ * session id: gathered once, and again by the brief and the settle376+ * (`look`) while they hold no claim, so a claim taken mid-session is found377+ * at the next prompt or stop, and a tool call never waits on the platform.378+ * As `<cli> hook` keeps them (its `sessionFacts`).379+ */380+const factsOf = (session: PiSession, look: boolean) =>381+ Effect.gen(function* () {382+ const kept = yield* loadSession(session.id);383+384+ if (Option.isSome(kept) && (kept.value.claim !== undefined || !look)) {385+ return kept.value;386+ }387+388+ const gathered = yield* gatherFacts(session.cwd);389+390+ // A cache: facts that cannot be kept are gathered again next time.391+ yield* Effect.ignore(saveSession(session.id, gathered));392+393+ return gathered;394+ });395+396+/**397+ * What the policy decides over. Holds are 0: the adapter counts pi's398+ * continuations itself, so the policy only says whether a stop would hold.399+ */400+const hookFacts = (401+ state: SessionState,402+ refusals: readonly Refusal[]403+): HookFacts => ({404+ claim: Option.fromUndefinedOr(state.claim),405+ holds: 0,406+ judge: state.judge,407+ refusals,408+ root: state.root,409+});410+411+/** The policy's input for `event`, in the hook format it reads. */412+const hookInput = (event: HookEvent, session: PiSession): HookInput => ({413+ cwd: session.cwd,414+ hook_event_name: claudeEventOf[event],415+ session_id: session.id,416+});417+418+/**419+ * What `<cli> check --shape-only` refuses of the work as it stands, by the420+ * policy's own `PushCheck`; nothing is asked without a claim.421+ */422+const localCheck = (state: SessionState) =>423+ state.claim === undefined424+ ? Effect.succeed<readonly Refusal[]>([])425+ : Effect.flatMap(Effect.service(PushCheck), (check) =>426+ check.run(state.root)427+ );428+429+/** What the hook policy runs on. */430+export type PolicyServices =431+ | ChildProcessSpawner.ChildProcessSpawner432+ | Client433+ | FileSystem.FileSystem434+ | Path.Path435+ | PushCheck;436+437+/** The hook policy, in process, as `PiDeps`, over `services`. */438+export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({439+ brief: (session) =>440+ Effect.gen(function* () {441+ const state = yield* factsOf(session, true);442+443+ const { output } = decideHook(444+ "session-start",445+ hookInput("session-start", session),446+ hookFacts(state, [])447+ );448+449+ return "hookSpecificOutput" in output &&450+ "additionalContext" in output.hookSpecificOutput451+ ? Option.some(output.hookSpecificOutput.additionalContext)452+ : Option.none();453+ }).pipe(Effect.provide(services)),454+455+ guardTool: (session, call) =>456+ GuardedCall.$match(call, {457+ Push: () =>458+ Effect.gen(function* () {459+ const refusals = yield* localCheck(yield* factsOf(session, false));460+461+ return Array.isReadonlyArrayNonEmpty(refusals)462+ ? Option.some(refusals)463+ : Option.none();464+ }).pipe(465+ Effect.mapError(466+ (failed) => new HookFailed({ reason: failed.message })467+ ),468+ Effect.provide(services)469+ ),470+ // The policy decides an edit (`decideHook`'s pre-tool-use) but hands471+ // back only its text, not the refusals; until it hands them back, a472+ // pi edit is left to the gateway.473+ Write: () => Effect.succeedNone,474+ }),475+476+ settle: (session) =>477+ Effect.gen(function* () {478+ const state = yield* factsOf(session, true);479+ const refusals = yield* localCheck(state);480+481+ if (!Array.isReadonlyArrayNonEmpty(refusals)) {482+ return SettleVerdict.Waiting();483+ }484+485+ const { output } = decideHook(486+ "stop",487+ hookInput("stop", session),488+ hookFacts(state, refusals)489+ );490+491+ // The policy holds a stop on a refusal the agent can fix.492+ return SettleVerdict.Refused({493+ actionable: "decision" in output,494+ refusals,495+ });496+ }).pipe(497+ Effect.mapError((failed) => new HookFailed({ reason: failed.message })),498+ Effect.provide(services)499+ ),500+});501+502+/**503+ * The policy's services in pi's process: the stored credentials and the504+ * platform over HTTP, and the local check run as the CLI on `PATH` (the505+ * same package's bin, where git finds its credential helper too). Node's506+ * own file system, paths and processes, which Bun's layers are.507+ */508+const LiveServices = Layer.mergeAll(509+ RemoteClient.pipe(Layer.provide(CredentialsFile)),510+ pushCheckWith([Brand.cli])511+).pipe(512+ Layer.provideMerge(BunChildProcessSpawner.layer),513+ Layer.provideMerge(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))514+);515+516+/** The hook policy as pi's process runs it. */517+export const livePiDeps = policyDeps(LiveServices);518+519+/** What `pi install npm:<package>` loads: the adapter over the live policy. */520+export default piAdapter(livePiDeps) satisfies ExtensionFactory;added:apps/cli/test/pi.test.ts+934 added
1+/**2+ * The pi adapter on a fake pi: a registry that records each `pi.on` handler,3+ * and events shaped as pi 1.0.3 types them, fired at those handlers. The4+ * policy behind `PiDeps` is a fake for the adapter's own tests; the last5+ * group runs the live deps over the hook policy's modules, with a stand-in6+ * local check (`hook.test.ts` tests the policy itself).7+ */8+import type {9+ AgentBeforeSettleEvent,10+ BeforeAgentStartEvent,11+ SessionBoundaryDraft,12+ ToolCallEvent,13+} from "@earendil-works/pi-coding-agent";14+import { NodeServices } from "@effect/platform-node";15+import { describe, expect, it } from "@effect/vitest";16+import { Brand } from "@repo/brand";17+import { Client } from "@repo/protocol/contracts";18+import { Glob } from "@repo/protocol/domain/common";19+import { AskId, ProjectName, RepoPath } from "@repo/protocol/ids";20+import {21+ ChecksFailed,22+ OutOfScope,23+ RepoBusy,24+ TouchedJudge,25+} from "@repo/protocol/refusal";26+import type { Refusal } from "@repo/protocol/refusal";27+import { explain } from "@repo/protocol/render";28+import {29+ Array,30+ ConfigProvider,31+ Effect,32+ FileSystem,33+ Layer,34+ Option,35+} from "effect";36+37+import { PushCheck, PushCheckFailed } from "../src/hook/push-check.ts";38+import { saveSession } from "../src/hook/session.ts";39+import type { SessionState } from "../src/hook/session.ts";40+import extension, {41+ GuardedCall,42+ HookFailed,43+ piAdapter,44+ policyDeps,45+ SettleVerdict,46+} from "../src/pi.ts";47+import type { PiContext, PiDeps, PiEvents, PiHandlers } from "../src/pi.ts";48+49+const cwd = "/work/datekit";50+51+/** The brief the fake policy gives a session that holds a claim. */52+const briefText = "# Your claim: fix-week in datekit";53+54+/** The config folder's project file: in every judge closure. */55+const projectFile = RepoPath.make(`${Brand.configDir}/project.ts`);56+57+/** A change outside the claim's territory. */58+const outside = new OutOfScope({ paths: [RepoPath.make("README.md")] });59+60+/** What the fake policy answers. */61+interface Policy {62+ readonly brief?: Option.Option<string>;63+ readonly guard?: (64+ call: GuardedCall65+ ) => Option.Option<Array.NonEmptyReadonlyArray<Refusal>>;66+ readonly settle?: () => SettleVerdict;67+}68+69+/** The fake policy, and what the adapter asked it. */70+const fakeDeps = (policy: Policy) => {71+ const asked: string[] = [];72+73+ const deps: PiDeps = {74+ brief: (session) =>75+ Effect.sync(() => {76+ asked.push(`brief ${session.id} ${session.cwd}`);77+78+ return policy.brief ?? Option.none();79+ }),80+ guardTool: (session, call) =>81+ Effect.sync(() => {82+ asked.push(`guardTool ${session.id} ${call._tag}`);83+84+ return policy.guard?.(call) ?? Option.none();85+ }),86+ settle: (session) =>87+ Effect.sync(() => {88+ asked.push(`settle ${session.id}`);89+90+ return policy.settle?.() ?? SettleVerdict.Waiting();91+ }),92+ };93+94+ return { asked, deps };95+};96+97+/** A policy whose every call fails as `failure` does. */98+const broken = (failure: Effect.Effect<never, HookFailed>): PiDeps => ({99+ brief: () => failure,100+ guardTool: () => failure,101+ settle: () => failure,102+});103+104+/** The fake policy's judge: the config folder's project file is in its closure. */105+const judging = (call: GuardedCall) =>106+ GuardedCall.$is("Write")(call) && call.file === projectFile107+ ? Option.some(Array.of(new TouchedJudge({ paths: [projectFile] })))108+ : Option.none();109+110+/** A fake preflight: what `<cli> check` refuses of the work as it stands. */111+const preflight =112+ (...refusals: readonly Refusal[]) =>113+ (call: GuardedCall) =>114+ GuardedCall.$is("Push")(call) && Array.isReadonlyArrayNonEmpty(refusals)115+ ? Option.some(refusals)116+ : Option.none();117+118+/** A fake pi: it records each handler the adapter registers, by event. */119+const fakePi = () => {120+ const handlers: { -readonly [K in keyof PiHandlers]?: PiHandlers[K] } = {};121+ const events: string[] = [];122+123+ const pi: PiEvents = {124+ on: <K extends keyof PiHandlers>(event: K, handler: PiHandlers[K]) => {125+ events.push(event);126+ handlers[event] = handler;127+128+ return () => {};129+ },130+ };131+132+ return { events, handlers, pi };133+};134+135+/** A handler's context in session `id`, with the notes `ui.notify` got. */136+const contextOf = (id: string, withUi = true) => {137+ const notes: string[] = [];138+ const bare: PiContext = { cwd, sessionManager: { getSessionId: () => id } };139+140+ const ui = {141+ notify: (note: string) => {142+ notes.push(note);143+ },144+ };145+146+ return { ctx: withUi ? { ...bare, ui } : bare, notes };147+};148+149+/** pi set up with `policy` behind the adapter. */150+const loaded = (policy: Policy) => {151+ const { asked, deps } = fakeDeps(policy);152+ const { events, handlers, pi } = fakePi();153+154+ piAdapter(deps)(pi);155+156+ return { asked, events, handlers };157+};158+159+/** Fires one recorded handler at `event`, as pi does, and awaits it. */160+const fire = <E, R>(161+ handler: ((event: E, ctx: PiContext) => Promise<R>) | undefined,162+ event: E,163+ ctx: PiContext164+) =>165+ handler === undefined166+ ? Effect.sync(() =>167+ expect.unreachable("the adapter registered no handler for this event")168+ )169+ : Effect.promise(() => handler(event, ctx));170+171+const startEvent: BeforeAgentStartEvent = {172+ prompt: "Answer the ask you claimed.",173+ systemPrompt: "You are pi.",174+ systemPromptOptions: {175+ appendSystemPrompt: "",176+ contextFiles: [],177+ cwd,178+ promptGuidelines: [],179+ sections: {},180+ selectedTools: ["read", "bash", "edit", "write"],181+ skills: [],182+ toolGuidelines: {},183+ toolSnippets: {},184+ },185+ type: "before_agent_start",186+};187+188+const editOf = (path: string): ToolCallEvent => ({189+ input: { edits: [{ newText: "export default {};", oldText: "" }], path },190+ toolCallId: "call-1",191+ toolName: "edit",192+ type: "tool_call",193+});194+195+const bashOf = (command: string): ToolCallEvent => ({196+ input: { command },197+ toolCallId: "call-2",198+ toolName: "bash",199+ type: "tool_call",200+});201+202+/**203+ * A completed run's settle with `entries` already proposed by earlier204+ * handlers, as pi 1.0.3 hands it over: the run ended on the agent's own205+ * reply, so the preview says it cannot go on (`canContinue` is false while206+ * the last message is the assistant's, `_buildBoundaryContext` in207+ * `dist/core/agent-session.js`) until a handler appends a message.208+ */209+const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({210+ context: {211+ canContinue: false,212+ contextEntries: [],213+ contextMessages: [],214+ llmMessages: [],215+ pendingMessages: [],216+ },217+ continue: false,218+ entries,219+ outcome: "completed",220+ type: "agent_before_settle",221+});222+223+const failing = new ChecksFailed({224+ lane: "test",225+ logRef: "logs/test",226+ next: `${Brand.cli} check`,227+});228+229+const refused = (actionable: boolean) => () =>230+ SettleVerdict.Refused({ actionable, refusals: [failing] });231+232+const unreachable = Effect.fail(233+ new HookFailed({ reason: "the platform did not answer within 10s" })234+);235+236+describe("the pi adapter", () => {237+ describe("before_agent_start", () => {238+ it.effect("gives the agent the policy's brief when a claim exists", () =>239+ Effect.gen(function* () {240+ const { handlers } = loaded({ brief: Option.some(briefText) });241+ const { ctx } = contextOf("s1");242+243+ const result = yield* fire(244+ handlers.before_agent_start,245+ startEvent,246+ ctx247+ );248+249+ expect(result).toStrictEqual({250+ message: {251+ content: briefText,252+ customType: `${Brand.slug}-brief`,253+ display: true,254+ },255+ });256+ })257+ );258+259+ it.effect("gives nothing without a claim", () =>260+ Effect.gen(function* () {261+ const { asked, handlers } = loaded({ brief: Option.none() });262+ const { ctx } = contextOf("s1");263+264+ const result = yield* fire(265+ handlers.before_agent_start,266+ startEvent,267+ ctx268+ );269+270+ expect(result).toBeUndefined();271+ expect(asked).toStrictEqual([`brief s1 ${cwd}`]);272+ })273+ );274+275+ it.effect(276+ "briefs a session once, at its first prompt that has a claim",277+ () =>278+ Effect.gen(function* () {279+ const briefs = [Option.none(), Option.some(briefText)];280+ const { deps } = fakeDeps({});281+ const { handlers, pi } = fakePi();282+ const one = contextOf("s1").ctx;283+ const other = contextOf("s2").ctx;284+ const given: string[] = [];285+286+ // No claim at the first prompt; one is taken before the second.287+ piAdapter({288+ ...deps,289+ brief: () =>290+ Effect.succeed(briefs.shift() ?? Option.some(briefText)),291+ })(pi);292+293+ for (const ctx of [one, one, one, other]) {294+ const result = yield* fire(295+ handlers.before_agent_start,296+ startEvent,297+ ctx298+ );299+300+ given.push(result === undefined ? "nothing" : "the brief");301+ }302+303+ expect(given).toStrictEqual([304+ "nothing",305+ "the brief",306+ "nothing",307+ "the brief",308+ ]);309+ })310+ );311+ });312+313+ describe("tool_call", () => {314+ it.effect(315+ "blocks an edit to the judge closure with the refusal's rendered text",316+ () =>317+ Effect.gen(function* () {318+ const { handlers } = loaded({ guard: judging });319+ const { ctx } = contextOf("s1");320+321+ const result = yield* fire(322+ handlers.tool_call,323+ editOf(projectFile),324+ ctx325+ );326+327+ expect(result).toStrictEqual({328+ block: true,329+ reason: explain([new TouchedJudge({ paths: [projectFile] })]).join(330+ "\n"331+ ),332+ });333+334+ expect(result?.reason?.split("\n")[0]).toMatch(/^TouchedJudge: /u);335+ })336+ );337+338+ it.effect("lets a write the policy passes run", () =>339+ Effect.gen(function* () {340+ const { asked, handlers } = loaded({ guard: judging });341+ const { ctx } = contextOf("s1");342+343+ const result = yield* fire(344+ handlers.tool_call,345+ {346+ input: { content: "export const week = 1;", path: "src/week.ts" },347+ toolCallId: "call-3",348+ toolName: "write",349+ type: "tool_call",350+ },351+ ctx352+ );353+354+ expect(result).toBeUndefined();355+ expect(asked).toStrictEqual(["guardTool s1 Write"]);356+ })357+ );358+359+ it.effect("never asks the policy about a tool that changes nothing", () =>360+ Effect.gen(function* () {361+ const { asked, handlers } = loaded({ guard: judging });362+ const { ctx } = contextOf("s1");363+364+ const result = yield* fire(365+ handlers.tool_call,366+ {367+ input: { path: projectFile },368+ toolCallId: "call-4",369+ toolName: "read",370+ type: "tool_call",371+ },372+ ctx373+ );374+375+ expect(result).toBeUndefined();376+ expect(asked).toStrictEqual([]);377+ })378+ );379+380+ it.effect(381+ "blocks a git push whose preflight has a refusal retrying cannot help",382+ () =>383+ Effect.gen(function* () {384+ const { handlers } = loaded({385+ guard: preflight(new RepoBusy(), outside),386+ });387+388+ const { ctx } = contextOf("s1");389+390+ const result = yield* fire(391+ handlers.tool_call,392+ bashOf("git push origin HEAD"),393+ ctx394+ );395+396+ expect(result).toStrictEqual({397+ block: true,398+ reason: explain([outside]).join("\n"),399+ });400+ })401+ );402+403+ it.effect(404+ "lets a git push run when its preflight is clean or only retryable",405+ () =>406+ Effect.gen(function* () {407+ for (const refusals of [[], [new RepoBusy()]]) {408+ const { asked, handlers } = loaded({409+ guard: preflight(...refusals),410+ });411+412+ const { ctx } = contextOf("s1");413+414+ const result = yield* fire(415+ handlers.tool_call,416+ bashOf("git push"),417+ ctx418+ );419+420+ expect(result).toBeUndefined();421+ expect(asked).toStrictEqual(["guardTool s1 Push"]);422+ }423+ })424+ );425+426+ it.effect("reads a push however the command spells it", () =>427+ Effect.gen(function* () {428+ const pushes = [429+ "git push",430+ "git push -u origin HEAD",431+ "cd packages/a && git push",432+ `git -C ${cwd} push origin`,433+ "git --no-pager push;",434+ "bun test && git commit -am wip && git push",435+ ];436+437+ const others = [438+ "git status",439+ "git log --grep push",440+ "echo pushed",441+ "bun run push",442+ "git pushd",443+ ];444+445+ for (const command of [...pushes, ...others]) {446+ const { handlers } = loaded({ guard: preflight(outside) });447+ const { ctx } = contextOf("s1");448+ const result = yield* fire(handlers.tool_call, bashOf(command), ctx);449+450+ expect({ blocked: result?.block === true, command }).toStrictEqual({451+ blocked: pushes.includes(command),452+ command,453+ });454+ }455+ })456+ );457+ });458+459+ describe("agent_before_settle", () => {460+ /** What another handler already appended at this boundary. */461+ const earlier: SessionBoundaryDraft = {462+ customType: "other-extension",463+ type: "custom",464+ };465+466+ it.effect(467+ "sends the agent back with the refusal while the verdict is one it can act on",468+ () =>469+ Effect.gen(function* () {470+ const { handlers } = loaded({ settle: refused(true) });471+ const { ctx } = contextOf("s1");472+473+ const result = yield* fire(474+ handlers.agent_before_settle,475+ settleOf([earlier]),476+ ctx477+ );478+479+ expect(result).toStrictEqual({480+ continue: true,481+ entries: [482+ earlier,483+ {484+ content: [485+ `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:`,486+ ...explain([failing]),487+ ].join("\n"),488+ customType: `${Brand.slug}-verdict`,489+ display: true,490+ type: "custom_message",491+ },492+ ],493+ });494+ })495+ );496+497+ it.effect(498+ "continues at most three times in one session, and lets the fourth settle stand",499+ () =>500+ Effect.gen(function* () {501+ const { asked, handlers } = loaded({ settle: refused(true) });502+ const one = contextOf("s1").ctx;503+ const other = contextOf("s2").ctx;504+ const continued: (boolean | undefined)[] = [];505+506+ for (const ctx of [one, one, one, one, other]) {507+ const result = yield* fire(508+ handlers.agent_before_settle,509+ settleOf([]),510+ ctx511+ );512+513+ continued.push(result?.continue);514+ }515+516+ expect(continued).toStrictEqual([true, true, true, undefined, true]);517+518+ // Past the cap, the policy is not even asked.519+ expect(asked).toStrictEqual([520+ "settle s1",521+ "settle s1",522+ "settle s1",523+ "settle s2",524+ ]);525+ })526+ );527+528+ it.effect("takes its cap from the options", () =>529+ Effect.gen(function* () {530+ const { deps } = fakeDeps({ settle: refused(true) });531+ const { handlers, pi } = fakePi();532+ const { ctx } = contextOf("s1");533+534+ piAdapter(deps, { maxContinuations: 1 })(pi);535+536+ const first = yield* fire(537+ handlers.agent_before_settle,538+ settleOf([]),539+ ctx540+ );541+542+ const second = yield* fire(543+ handlers.agent_before_settle,544+ settleOf([]),545+ ctx546+ );547+548+ expect([first?.continue, second]).toStrictEqual([true, undefined]);549+ })550+ );551+552+ it.effect(553+ "sends back a completed run whose context ends on the agent's own reply",554+ () =>555+ Effect.gen(function* () {556+ const { asked, handlers } = loaded({ settle: refused(true) });557+ const { ctx } = contextOf("s1");558+ const event = settleOf([]);559+560+ const result = yield* fire(handlers.agent_before_settle, event, ctx);561+562+ // The verdict the adapter appends is what lets the run go on.563+ expect({564+ asked,565+ canContinue: event.context.canContinue,566+ continued: result?.continue,567+ entries: result?.entries?.length,568+ }).toStrictEqual({569+ asked: ["settle s1"],570+ canContinue: false,571+ continued: true,572+ entries: 1,573+ });574+ })575+ );576+577+ it.effect(578+ "lists only the refusals the agent can fix, as the stop hook does",579+ () =>580+ Effect.gen(function* () {581+ const { handlers } = loaded({582+ settle: () =>583+ SettleVerdict.Refused({584+ actionable: true,585+ refusals: [new RepoBusy(), outside],586+ }),587+ });588+589+ const { ctx } = contextOf("s1");590+591+ const result = yield* fire(592+ handlers.agent_before_settle,593+ settleOf([]),594+ ctx595+ );596+597+ expect(result?.entries).toStrictEqual([598+ {599+ content: [600+ `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:`,601+ ...explain([outside]),602+ ].join("\n"),603+ customType: `${Brand.slug}-verdict`,604+ display: true,605+ type: "custom_message",606+ },607+ ]);608+ })609+ );610+611+ it.effect("never sends back a run the person stopped or that failed", () =>612+ Effect.gen(function* () {613+ const ended: readonly AgentBeforeSettleEvent[] = [614+ { ...settleOf([]), outcome: "aborted" },615+ { ...settleOf([]), outcome: "error" },616+ ];617+618+ for (const event of ended) {619+ const { asked, handlers } = loaded({ settle: refused(true) });620+ const { ctx } = contextOf("s1");621+622+ const result = yield* fire(handlers.agent_before_settle, event, ctx);623+624+ expect({ asked, result }).toStrictEqual({625+ asked: [],626+ result: undefined,627+ });628+ }629+ })630+ );631+632+ it.effect(633+ "never continues on a landing, a wait, or a refusal the agent cannot act on",634+ () =>635+ Effect.gen(function* () {636+ const verdicts = [637+ SettleVerdict.Landed(),638+ SettleVerdict.Waiting(),639+ SettleVerdict.Refused({640+ actionable: false,641+ refusals: [new RepoBusy()],642+ }),643+ ];644+645+ for (const verdict of verdicts) {646+ const { handlers } = loaded({ settle: () => verdict });647+ const { ctx } = contextOf("s1");648+649+ const result = yield* fire(650+ handlers.agent_before_settle,651+ settleOf([]),652+ ctx653+ );654+655+ expect({ result, verdict: verdict._tag }).toStrictEqual({656+ result: undefined,657+ verdict: verdict._tag,658+ });659+ }660+ })661+ );662+ });663+664+ describe("when the policy fails", () => {665+ it.effect(666+ "allows the tool, and says why through ctx.ui.notify when pi gives one",667+ () =>668+ Effect.gen(function* () {669+ const failures = [unreachable, Effect.die("a bug in the policy")];670+671+ for (const failure of failures) {672+ const { handlers, pi } = fakePi();673+ const { ctx, notes } = contextOf("s1");674+675+ piAdapter(broken(failure))(pi);676+677+ const result = yield* fire(678+ handlers.tool_call,679+ editOf(projectFile),680+ ctx681+ );682+683+ expect(result).toBeUndefined();684+ expect(notes).toHaveLength(1);685+ }686+ })687+ );688+689+ it.effect("names the failure in its note", () =>690+ Effect.gen(function* () {691+ const { handlers, pi } = fakePi();692+ const { ctx, notes } = contextOf("s1");693+694+ piAdapter(broken(unreachable))(pi);695+696+ yield* fire(handlers.tool_call, bashOf("git push"), ctx);697+698+ expect(notes).toHaveLength(1);699+ expect(notes[0]).toContain("the platform did not answer within 10s");700+ })701+ );702+703+ it.effect("gives no brief and no continuation, with or without a ui", () =>704+ Effect.gen(function* () {705+ for (const withUi of [true, false]) {706+ const { handlers, pi } = fakePi();707+ const { ctx, notes } = contextOf("s1", withUi);708+709+ piAdapter(broken(unreachable))(pi);710+711+ const brief = yield* fire(712+ handlers.before_agent_start,713+ startEvent,714+ ctx715+ );716+717+ const settled = yield* fire(718+ handlers.agent_before_settle,719+ settleOf([]),720+ ctx721+ );722+723+ expect({ brief, notes: notes.length, settled }).toStrictEqual({724+ brief: undefined,725+ notes: withUi ? 2 : 0,726+ settled: undefined,727+ });728+ }729+ })730+ );731+ });732+733+ it.effect(734+ "registers only before_agent_start, tool_call and agent_before_settle",735+ () =>736+ Effect.sync(() => {737+ const { events } = loaded({});738+739+ expect(events.toSorted()).toStrictEqual([740+ "agent_before_settle",741+ "before_agent_start",742+ "tool_call",743+ ]);744+ })745+ );746+747+ it.effect(748+ "is what the package's pi entry exports, over the live policy",749+ () =>750+ Effect.sync(() => {751+ const { events, pi } = fakePi();752+753+ extension(pi);754+755+ expect(events.toSorted()).toStrictEqual([756+ "agent_before_settle",757+ "before_agent_start",758+ "tool_call",759+ ]);760+ })761+ );762+});763+764+// ------------------------------------------------------------ live deps765+766+const want = "An ISO week date parses to the Monday of that week.";767+768+/** Kept facts for a session on `fix-week` in a clone at `root`. */769+const claimedIn = (root: string): SessionState => ({770+ claim: {771+ ask: AskId.make("fix-week"),772+ checkCommand: "bun test packages/a",773+ project: ProjectName.make("datekit"),774+ territory: { module: "a", paths: [Glob.make("packages/a/**")] },775+ want,776+ },777+ holds: 0,778+ judge: { paths: [Glob.make(`/${Brand.configDir}/**`)], pointers: [] },779+ root,780+});781+782+/**783+ * The live deps with their state in a temp folder, a local check that784+ * answers `checked`, and a platform that must not be called. Gives the785+ * deps, a folder that is no repo, the roots the check ran in, and a way to786+ * keep a session's facts.787+ */788+const policyWith = (789+ checked: Effect.Effect<readonly Refusal[], PushCheckFailed>790+) =>791+ Effect.gen(function* () {792+ const fs = yield* FileSystem.FileSystem;793+ const state = yield* fs.makeTempDirectoryScoped();794+ const folder = yield* fs.makeTempDirectoryScoped();795+ const roots: string[] = [];796+797+ const env = ConfigProvider.layer(798+ ConfigProvider.fromEnv({ env: { XDG_STATE_HOME: state } })799+ );800+801+ const deps = policyDeps(802+ Layer.mergeAll(803+ NodeServices.layer,804+ Layer.mock(Client)({}),805+ Layer.succeed(PushCheck)({806+ run: (root) =>807+ Effect.andThen(808+ Effect.sync(() => roots.push(root)),809+ checked810+ ),811+ }),812+ env813+ )814+ );815+816+ const keep = (id: string, facts: SessionState) =>817+ saveSession(id, facts).pipe(818+ Effect.provide(Layer.mergeAll(NodeServices.layer, env)),819+ Effect.orDie820+ );821+822+ return { deps, folder, keep, roots };823+ }).pipe(Effect.provide(NodeServices.layer));824+825+const refusing = (...refusals: readonly Refusal[]) => Effect.succeed(refusals);826+827+describe("the live deps, over the hook policy's own modules", () => {828+ it.live("brief a session whose kept facts hold a claim", () =>829+ Effect.gen(function* () {830+ const { deps, folder, keep } = yield* policyWith(refusing());831+832+ yield* keep("s1", claimedIn(folder));833+834+ const brief = Option.getOrElse(835+ yield* deps.brief({ cwd: folder, id: "s1" }),836+ () => ""837+ );838+839+ expect(brief).toContain(want);840+ expect(brief).toContain("bun test packages/a");841+ })842+ );843+844+ it.live("give no brief, and run no check, in a folder that is no repo", () =>845+ Effect.gen(function* () {846+ const { deps, folder, roots } = yield* policyWith(refusing(outside));847+ const session = { cwd: folder, id: "s2" };848+ const brief = yield* deps.brief(session);849+ const push = yield* deps.guardTool(session, GuardedCall.Push());850+ const settled = yield* deps.settle(session);851+852+ expect({ brief, push, roots, settled }).toStrictEqual({853+ brief: Option.none(),854+ push: Option.none(),855+ roots: [],856+ settled: SettleVerdict.Waiting(),857+ });858+ })859+ );860+861+ it.live("preflight a push by the local check, in the claim's repo", () =>862+ Effect.gen(function* () {863+ const busy = new RepoBusy();864+865+ const { deps, folder, keep, roots } = yield* policyWith(866+ refusing(busy, outside)867+ );868+869+ yield* keep("s3", claimedIn(folder));870+871+ const push = yield* deps.guardTool(872+ { cwd: `${folder}/packages/a`, id: "s3" },873+ GuardedCall.Push()874+ );875+876+ expect({ push, roots }).toStrictEqual({877+ push: Option.some([busy, outside]),878+ roots: [folder],879+ });880+ })881+ );882+883+ it.live(884+ "settle as the policy's stop would hold: on a refusal the agent can fix",885+ () =>886+ Effect.gen(function* () {887+ const busy = new RepoBusy();888+889+ const cases = [890+ {891+ refusals: [outside],892+ verdict: SettleVerdict.Refused({893+ actionable: true,894+ refusals: [outside],895+ }),896+ },897+ {898+ refusals: [busy],899+ verdict: SettleVerdict.Refused({900+ actionable: false,901+ refusals: [busy],902+ }),903+ },904+ { refusals: [], verdict: SettleVerdict.Waiting() },905+ ];906+907+ for (const { refusals, verdict } of cases) {908+ const { deps, folder, keep } = yield* policyWith(909+ refusing(...refusals)910+ );911+912+ yield* keep("s4", claimedIn(folder));913+914+ expect(yield* deps.settle({ cwd: folder, id: "s4" })).toStrictEqual(915+ verdict916+ );917+ }918+ })919+ );920+921+ it.live("fail as HookFailed when the local check gives no answer", () =>922+ Effect.gen(function* () {923+ const { deps, folder, keep } = yield* policyWith(924+ Effect.fail(new PushCheckFailed({ reason: "it ran past 1m" }))925+ );926+927+ yield* keep("s5", claimedIn(folder));928+929+ const failed = yield* Effect.flip(deps.settle({ cwd: folder, id: "s5" }));930+931+ expect(failed.message).toContain("it ran past 1m");932+ })933+ );934+});modified:apps/cli/tsdown.config.ts+2 added
49 unmodified lines5051525354555649 unmodified lines
export default defineConfig([ { ...shared, dts: false, entry: { bin: "src/bin.ts" } }, { ...shared, dts: false, entry: library }, // The pi extension (W7 706), which the publish manifest's `"pi"` key names. { ...shared, dts: false, entry: { pi: "src/pi.ts" } },]);