Skip to content
Myr

Give a pi user's agent the claim's brief, a guard before a push the gate would refuse, and a capped send-back at stop

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The pi adapter (706), `apps/cli/src/pi.ts`, built by a new tsdown entry into `dist/pi.js` for the publish manifest's `"pi"` key (715). It is thin: three pi events, each answered by the one hook policy behind `<cli> hook` through `PiDeps`. - Typed against @earendil-works/pi-coding-agent 1.0.3 by a type-only import (ExtensionAPI, ExtensionContext, ExtensionFactory, ToolCallEvent, BeforeAgentStartEvent, AgentBeforeSettleEvent and their results, CustomMessageEntryDraft). The adapter takes `PiEvents`, an `on` with only the three events, so no other event and no registerTool can be registered; `export default piAdapter(livePiDeps) satisfies ExtensionFactory` proves pi's ExtensionAPI is a PiEvents. No casts, no escape directives. - before_agent_start: the policy's brief as a `<slug>-brief` custom message, once per session (pi starts the agent on every prompt), at the first prompt that has a claim. - tool_call: pi's edit/write become `Write{file}` and a bash command that runs `git push` (after any git options, anywhere in the line) becomes `Push`, decoded at the boundary; every other call is never judged. The adapter blocks only on refusals retrying cannot help (PI §4.4), with `explain`'s text as the reason, and never changes a call (PI R3). - agent_before_settle: an actionable Refused verdict appends one `<slug>-verdict` custom message to the boundary's entries and continues, at most 3 times per session (default: the policy's MAX_HOLDS), counted in a Map made per pi load. Past the cap the policy is not asked. A run that was aborted, errored or cannot continue is never sent back. - Every handler fails open: a HookFailed or a defect lets pi go on (a rejecting tool_call handler would block the tool) and is noted through ctx.ui.notify when present. - Live deps (`policyDeps(services)`, `livePiDeps` over Bun's node-compatible fs/path/spawner, the stored credentials and the remote client): facts kept in the hook's own session file under pi's session id (gatherFacts/loadSession/saveSession, as hook.ts's sessionFacts); the brief and the stop hold come from decideHook; the push preflight and the settle's refusals from PushCheck (`<cli> check --shape-only --offline --json`). Smoked under Node against the built dist/pi.js with a stand-in CLI: brief, push block and three continuations then none. - Departures from the issue's interface: PiDeps calls take a PiSession {cwd, id} (the id keys the session file and the cap) and guardTool a typed GuardedCall, not `{tool, input: unknown}` (anti-slop's no-unknown-parameters; parse at the boundary). SettleVerdict and GuardedCall are Data.taggedEnum plain unions. - Gap, for 799: the live edit guard allows every edit, because decideHook returns only the denial's text, not the refusals; the issue's Comments give the two-line export it needs in hook/decide.ts. - ASSUMPTION: the CLI is on PATH in pi's process (git needs its credential helper there too); the preflight runs `<cli> check` by name. - Tests: apps/cli/test/pi.test.ts, 24 cases: the adapter over a fake pi registry and fake deps (brief, edit block, push block or allow, push spellings, settle cap and its options, never on Landed, Waiting, a non-actionable refusal or an ended run, fail-open with and without ui, only three events, the default export), and policyDeps over a temp state folder with a stand-in PushCheck.

authored by oscabriel · committed by oscabriel · parent d7064cb · Browse files · 3 files+1385 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+1385 added−0 removed

  • tests:+879 added−0 removed
  • other:+506 added−0 removed

3 files+1385 added−0 removed

added:apps/cli/src/pi.ts+504 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 */8import 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";20import {21 BunChildProcessSpawner,22 BunFileSystem,23 BunPath,24} from "@effect/platform-bun";25import { claudeEventOf } from "@repo/agent-kit/hook-events";26import type { HookEvent } from "@repo/agent-kit/hook-events";27import { Brand } from "@repo/brand";28import type { Client } from "@repo/protocol/contracts";29import type { Refusal } from "@repo/protocol/refusal";30import { explain } from "@repo/protocol/render";31import {32 Array,33 Cause,34 Data,35 Effect,36 Layer,37 Match,38 Option,39 Schema,40} from "effect";41import type { FileSystem, Path } from "effect";42import type { ChildProcessSpawner } from "effect/process";4344import { CredentialsFile } from "./credentials.ts";45import { decideHook, MAX_HOLDS } from "./hook/decide.ts";46import type { HookFacts } from "./hook/decide.ts";47import { gatherFacts } from "./hook/facts.ts";48import type { HookInput } from "./hook/input.ts";49import { PushCheck, pushCheckWith } from "./hook/push-check.ts";50import { loadSession, saveSession } from "./hook/session.ts";51import type { SessionState } from "./hook/session.ts";52import { RemoteClient } from "./remote.ts";5354/** The policy could not answer; the adapter allows, and says why. */55export 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}6263/** One pi session: its id, and the folder its agent runs in. */64export interface PiSession {65 readonly cwd: string;66 readonly id: string;67}6869/** A tool call the policy judges before it runs, read from pi's own. */70export 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" };7576export const GuardedCall = Data.taggedEnum<GuardedCall>();7778/** Where the session's answer stands when its agent is about to stop. */79export 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 };8889export const SettleVerdict = Data.taggedEnum<SettleVerdict>();9091/** The boundary to the hook policy: what the adapter asks it, per session. */92export 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}109110/** What the adapter reads of a handler's context. */111export type PiContext = Pick<ExtensionContext, "cwd"> & {112 readonly sessionManager: Pick<113 ExtensionContext["sessionManager"],114 "getSessionId"115 >;116 readonly ui?: Pick<ExtensionUIContext, "notify">;117};118119/** The adapter's handlers, by pi event, as pi 1.0.3 types each event. */120export 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}134135/** The part of pi's `ExtensionAPI` the adapter uses: `on`, for three events. */136export 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}149150export 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}157158/** The custom type of the brief pi shows before the agent starts. */159const BRIEF = `${Brand.slug}-brief`;160161/** The custom type of the verdict a settle sends the agent back with. */162const VERDICT = `${Brand.slug}-verdict`;163164/** What the agent reads when it is sent back: why, then the gateway's own text. */165const 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});176177/** pi's `edit` and `write` name the file they change as `path`. */178const decodeFile = Schema.decodeUnknownOption(179 Schema.Struct({ path: Schema.String })180);181182/** pi's `bash` runs `command`. */183const decodeCommand = Schema.decodeUnknownOption(184 Schema.Struct({ command: Schema.String })185);186187/**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 */193const GIT_PUSH =194 /(?:^|[\s;&|(`])git(?:\s+-[Cc]\s+\S+|\s+-\S+)*\s+push(?![\w-])/u;195196/**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 */201const 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 );215216/**217 * pi's block for what the gate would refuse that retrying cannot help, with218 * the gateway's own text; a retryable refusal is a wait, never a block.219 */220const blockFor = (221 refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>222): Option.Option<ToolCallEventResult> => {223 const final = Option.getOrElse(refusals, () => []).filter(224 (refusal) => !refusal.retryable225 );226227 return Array.isReadonlyArrayNonEmpty(final)228 ? Option.some({ block: true, reason: explain(final).join("\n") })229 : Option.none();230};231232/** The session a handler runs in. */233const sessionOf = (ctx: PiContext): PiSession => ({234 cwd: ctx.cwd,235 id: ctx.sessionManager.getSessionId(),236});237238/** A failure's first line, for the note. */239const firstLine = (cause: Cause.Cause<unknown>) =>240 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";241242/**243 * Runs one handler's answer for pi, which awaits a promise. The gate stays244 * the authority, so a policy that fails, or any defect, lets pi go on as it245 * would without the adapter (a `tool_call` handler that rejects would block246 * the tool), and says why through `ctx.ui.notify` when pi gives one.247 */248const answer = <A>(249 ctx: PiContext,250 event: keyof PiHandlers,251 decided: Effect.Effect<Option.Option<A>, HookFailed>252): Promise<A | undefined> =>253 Effect.runPromise(254 decided.pipe(255 Effect.catchCause((cause) =>256 Effect.as(257 Effect.sync(() =>258 ctx.ui?.notify(259 `${Brand.cli} ${event}: ${firstLine(cause)}; allowing, and the gateway still judges every push`,260 "warning"261 )262 ),263 Option.none<A>()264 )265 ),266 Effect.map(Option.getOrUndefined)267 )268 );269270/**271 * The adapter over `deps`: registers its three handlers on `pi`, and no272 * other event or tool. Each pi load counts its own continuations, by273 * session, so no state outlives the extension.274 */275export const piAdapter =276 (deps: PiDeps, options: PiOptions = {}) =>277 (pi: PiEvents): void => {278 const most = options.maxContinuations ?? MAX_HOLDS;279 const continued = new Map<string, number>();280 const briefed = new Set<string>();281282 // pi starts the agent on every prompt; the brief stays in the session,283 // so each session gets it once, at its first prompt with a claim.284 pi.on("before_agent_start", (_event, ctx) => {285 const session = sessionOf(ctx);286287 return answer(288 ctx,289 "before_agent_start",290 briefed.has(session.id)291 ? Effect.succeedNone292 : deps.brief(session).pipe(293 Effect.tap((brief) =>294 Effect.sync(() => {295 if (Option.isSome(brief)) {296 briefed.add(session.id);297 }298 })299 ),300 Effect.map(301 Option.map((content): BeforeAgentStartEventResult => ({302 message: { content, customType: BRIEF, display: true },303 }))304 )305 )306 );307 });308309 pi.on("tool_call", (event, ctx) =>310 answer(311 ctx,312 "tool_call",313 Option.match(guardedCall(event), {314 onNone: () => Effect.succeedNone,315 onSome: (call) =>316 Effect.map(deps.guardTool(sessionOf(ctx), call), blockFor),317 })318 )319 );320321 // Only a verdict the agent can act on sends it back, at most `most`322 // times a session, and only a run that completed and can go on: a run323 // the person stopped, or one that failed, stays stopped. Otherwise the324 // policy is not even asked.325 pi.on("agent_before_settle", (event, ctx) => {326 const session = sessionOf(ctx);327 const used = continued.get(session.id) ?? 0;328329 const ended = event.outcome !== "completed" || !event.context.canContinue;330331 return answer(332 ctx,333 "agent_before_settle",334 ended || used >= most335 ? Effect.succeedNone336 : Effect.flatMap(deps.settle(session), (verdict) =>337 SettleVerdict.$is("Refused")(verdict) && verdict.actionable338 ? Effect.sync(() => {339 continued.set(session.id, used + 1);340341 return Option.some<AgentBeforeSettleEventResult>({342 continue: true,343 entries: [344 ...event.entries,345 verdictEntry(verdict.refusals),346 ],347 });348 })349 : Effect.succeedNone350 )351 );352 });353 };354355// ------------------------------------------------------------ live356357/**358 * The session's facts, kept in the hook's own session file under pi's359 * session id: gathered once, and again by the brief and the settle360 * (`look`) while they hold no claim, so a claim taken mid-session is found361 * at the next prompt or stop, and a tool call never waits on the platform.362 * As `<cli> hook` keeps them (its `sessionFacts`).363 */364const factsOf = (session: PiSession, look: boolean) =>365 Effect.gen(function* () {366 const kept = yield* loadSession(session.id);367368 if (Option.isSome(kept) && (kept.value.claim !== undefined || !look)) {369 return kept.value;370 }371372 const gathered = yield* gatherFacts(session.cwd);373374 // A cache: facts that cannot be kept are gathered again next time.375 yield* Effect.ignore(saveSession(session.id, gathered));376377 return gathered;378 });379380/**381 * What the policy decides over. Holds are 0: the adapter counts pi's382 * continuations itself, so the policy only says whether a stop would hold.383 */384const hookFacts = (385 state: SessionState,386 refusals: readonly Refusal[]387): HookFacts => ({388 claim: Option.fromUndefinedOr(state.claim),389 holds: 0,390 judge: state.judge,391 refusals,392 root: state.root,393});394395/** The policy's input for `event`, in the hook format it reads. */396const hookInput = (event: HookEvent, session: PiSession): HookInput => ({397 cwd: session.cwd,398 hook_event_name: claudeEventOf[event],399 session_id: session.id,400});401402/**403 * What `<cli> check --shape-only` refuses of the work as it stands, by the404 * policy's own `PushCheck`; nothing is asked without a claim.405 */406const localCheck = (state: SessionState) =>407 state.claim === undefined408 ? Effect.succeed<readonly Refusal[]>([])409 : Effect.flatMap(Effect.service(PushCheck), (check) =>410 check.run(state.root)411 );412413/** What the hook policy runs on. */414export type PolicyServices =415 | ChildProcessSpawner.ChildProcessSpawner416 | Client417 | FileSystem.FileSystem418 | Path.Path419 | PushCheck;420421/** The hook policy, in process, as `PiDeps`, over `services`. */422export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({423 brief: (session) =>424 Effect.gen(function* () {425 const state = yield* factsOf(session, true);426427 const { output } = decideHook(428 "session-start",429 hookInput("session-start", session),430 hookFacts(state, [])431 );432433 return "hookSpecificOutput" in output &&434 "additionalContext" in output.hookSpecificOutput435 ? Option.some(output.hookSpecificOutput.additionalContext)436 : Option.none();437 }).pipe(Effect.provide(services)),438439 guardTool: (session, call) =>440 GuardedCall.$match(call, {441 Push: () =>442 Effect.gen(function* () {443 const refusals = yield* localCheck(yield* factsOf(session, false));444445 return Array.isReadonlyArrayNonEmpty(refusals)446 ? Option.some(refusals)447 : Option.none();448 }).pipe(449 Effect.mapError(450 (failed) => new HookFailed({ reason: failed.message })451 ),452 Effect.provide(services)453 ),454 // The policy decides an edit (`decideHook`'s pre-tool-use) but hands455 // back only its text, not the refusals; until it hands them back, a456 // pi edit is left to the gateway.457 Write: () => Effect.succeedNone,458 }),459460 settle: (session) =>461 Effect.gen(function* () {462 const state = yield* factsOf(session, true);463 const refusals = yield* localCheck(state);464465 if (!Array.isReadonlyArrayNonEmpty(refusals)) {466 return SettleVerdict.Waiting();467 }468469 const { output } = decideHook(470 "stop",471 hookInput("stop", session),472 hookFacts(state, refusals)473 );474475 // The policy holds a stop on a refusal the agent can fix.476 return SettleVerdict.Refused({477 actionable: "decision" in output,478 refusals,479 });480 }).pipe(481 Effect.mapError((failed) => new HookFailed({ reason: failed.message })),482 Effect.provide(services)483 ),484});485486/**487 * The policy's services in pi's process: the stored credentials and the488 * platform over HTTP, and the local check run as the CLI on `PATH` (the489 * same package's bin, where git finds its credential helper too). Node's490 * own file system, paths and processes, which Bun's layers are.491 */492const LiveServices = Layer.mergeAll(493 RemoteClient.pipe(Layer.provide(CredentialsFile)),494 pushCheckWith([Brand.cli])495).pipe(496 Layer.provideMerge(BunChildProcessSpawner.layer),497 Layer.provideMerge(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))498);499500/** The hook policy as pi's process runs it. */501export const livePiDeps = policyDeps(LiveServices);502503/** What `pi install npm:<package>` loads: the adapter over the live policy. */504export default piAdapter(livePiDeps) satisfies ExtensionFactory;
added:apps/cli/test/pi.test.ts+879 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 */8import type {9 AgentBeforeSettleEvent,10 BeforeAgentStartEvent,11 SessionBoundaryDraft,12 ToolCallEvent,13} from "@earendil-works/pi-coding-agent";14import { NodeServices } from "@effect/platform-node";15import { describe, expect, it } from "@effect/vitest";16import { Brand } from "@repo/brand";17import { Client } from "@repo/protocol/contracts";18import { Glob } from "@repo/protocol/domain/common";19import { AskId, ProjectName, RepoPath } from "@repo/protocol/ids";20import {21 ChecksFailed,22 OutOfScope,23 RepoBusy,24 TouchedJudge,25} from "@repo/protocol/refusal";26import type { Refusal } from "@repo/protocol/refusal";27import { explain } from "@repo/protocol/render";28import {29 Array,30 ConfigProvider,31 Effect,32 FileSystem,33 Layer,34 Option,35} from "effect";3637import { PushCheck, PushCheckFailed } from "../src/hook/push-check.ts";38import { saveSession } from "../src/hook/session.ts";39import type { SessionState } from "../src/hook/session.ts";40import extension, {41 GuardedCall,42 HookFailed,43 piAdapter,44 policyDeps,45 SettleVerdict,46} from "../src/pi.ts";47import type { PiContext, PiDeps, PiEvents, PiHandlers } from "../src/pi.ts";4849const cwd = "/work/datekit";5051/** The brief the fake policy gives a session that holds a claim. */52const briefText = "# Your claim: fix-week in datekit";5354/** The config folder's project file: in every judge closure. */55const projectFile = RepoPath.make(`${Brand.configDir}/project.ts`);5657/** A change outside the claim's territory. */58const outside = new OutOfScope({ paths: [RepoPath.make("README.md")] });5960/** What the fake policy answers. */61interface Policy {62 readonly brief?: Option.Option<string>;63 readonly guard?: (64 call: GuardedCall65 ) => Option.Option<Array.NonEmptyReadonlyArray<Refusal>>;66 readonly settle?: () => SettleVerdict;67}6869/** The fake policy, and what the adapter asked it. */70const fakeDeps = (policy: Policy) => {71 const asked: string[] = [];7273 const deps: PiDeps = {74 brief: (session) =>75 Effect.sync(() => {76 asked.push(`brief ${session.id} ${session.cwd}`);7778 return policy.brief ?? Option.none();79 }),80 guardTool: (session, call) =>81 Effect.sync(() => {82 asked.push(`guardTool ${session.id} ${call._tag}`);8384 return policy.guard?.(call) ?? Option.none();85 }),86 settle: (session) =>87 Effect.sync(() => {88 asked.push(`settle ${session.id}`);8990 return policy.settle?.() ?? SettleVerdict.Waiting();91 }),92 };9394 return { asked, deps };95};9697/** A policy whose every call fails as `failure` does. */98const broken = (failure: Effect.Effect<never, HookFailed>): PiDeps => ({99 brief: () => failure,100 guardTool: () => failure,101 settle: () => failure,102});103104/** The fake policy's judge: the config folder's project file is in its closure. */105const judging = (call: GuardedCall) =>106 GuardedCall.$is("Write")(call) && call.file === projectFile107 ? Option.some(Array.of(new TouchedJudge({ paths: [projectFile] })))108 : Option.none();109110/** A fake preflight: what `<cli> check` refuses of the work as it stands. */111const preflight =112 (...refusals: readonly Refusal[]) =>113 (call: GuardedCall) =>114 GuardedCall.$is("Push")(call) && Array.isReadonlyArrayNonEmpty(refusals)115 ? Option.some(refusals)116 : Option.none();117118/** A fake pi: it records each handler the adapter registers, by event. */119const fakePi = () => {120 const handlers: { -readonly [K in keyof PiHandlers]?: PiHandlers[K] } = {};121 const events: string[] = [];122123 const pi: PiEvents = {124 on: <K extends keyof PiHandlers>(event: K, handler: PiHandlers[K]) => {125 events.push(event);126 handlers[event] = handler;127128 return () => {};129 },130 };131132 return { events, handlers, pi };133};134135/** A handler's context in session `id`, with the notes `ui.notify` got. */136const contextOf = (id: string, withUi = true) => {137 const notes: string[] = [];138 const bare: PiContext = { cwd, sessionManager: { getSessionId: () => id } };139140 const ui = {141 notify: (note: string) => {142 notes.push(note);143 },144 };145146 return { ctx: withUi ? { ...bare, ui } : bare, notes };147};148149/** pi set up with `policy` behind the adapter. */150const loaded = (policy: Policy) => {151 const { asked, deps } = fakeDeps(policy);152 const { events, handlers, pi } = fakePi();153154 piAdapter(deps)(pi);155156 return { asked, events, handlers };157};158159/** Fires one recorded handler at `event`, as pi does, and awaits it. */160const 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));170171const 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};187188const editOf = (path: string): ToolCallEvent => ({189 input: { edits: [{ newText: "export default {};", oldText: "" }], path },190 toolCallId: "call-1",191 toolName: "edit",192 type: "tool_call",193});194195const bashOf = (command: string): ToolCallEvent => ({196 input: { command },197 toolCallId: "call-2",198 toolName: "bash",199 type: "tool_call",200});201202/** A settle with `entries` already proposed by earlier handlers. */203const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({204 context: {205 canContinue: true,206 contextEntries: [],207 contextMessages: [],208 llmMessages: [],209 pendingMessages: [],210 },211 continue: false,212 entries,213 outcome: "completed",214 type: "agent_before_settle",215});216217const failing = new ChecksFailed({218 lane: "test",219 logRef: "logs/test",220 next: `${Brand.cli} check`,221});222223const refused = (actionable: boolean) => () =>224 SettleVerdict.Refused({ actionable, refusals: [failing] });225226const unreachable = Effect.fail(227 new HookFailed({ reason: "the platform did not answer within 10s" })228);229230describe("the pi adapter", () => {231 describe("before_agent_start", () => {232 it.effect("gives the agent the policy's brief when a claim exists", () =>233 Effect.gen(function* () {234 const { handlers } = loaded({ brief: Option.some(briefText) });235 const { ctx } = contextOf("s1");236237 const result = yield* fire(238 handlers.before_agent_start,239 startEvent,240 ctx241 );242243 expect(result).toStrictEqual({244 message: {245 content: briefText,246 customType: `${Brand.slug}-brief`,247 display: true,248 },249 });250 })251 );252253 it.effect("gives nothing without a claim", () =>254 Effect.gen(function* () {255 const { asked, handlers } = loaded({ brief: Option.none() });256 const { ctx } = contextOf("s1");257258 const result = yield* fire(259 handlers.before_agent_start,260 startEvent,261 ctx262 );263264 expect(result).toBeUndefined();265 expect(asked).toStrictEqual([`brief s1 ${cwd}`]);266 })267 );268269 it.effect(270 "briefs a session once, at its first prompt that has a claim",271 () =>272 Effect.gen(function* () {273 const briefs = [Option.none(), Option.some(briefText)];274 const { deps } = fakeDeps({});275 const { handlers, pi } = fakePi();276 const one = contextOf("s1").ctx;277 const other = contextOf("s2").ctx;278 const given: string[] = [];279280 // No claim at the first prompt; one is taken before the second.281 piAdapter({282 ...deps,283 brief: () =>284 Effect.succeed(briefs.shift() ?? Option.some(briefText)),285 })(pi);286287 for (const ctx of [one, one, one, other]) {288 const result = yield* fire(289 handlers.before_agent_start,290 startEvent,291 ctx292 );293294 given.push(result === undefined ? "nothing" : "the brief");295 }296297 expect(given).toStrictEqual([298 "nothing",299 "the brief",300 "nothing",301 "the brief",302 ]);303 })304 );305 });306307 describe("tool_call", () => {308 it.effect(309 "blocks an edit to the judge closure with the refusal's rendered text",310 () =>311 Effect.gen(function* () {312 const { handlers } = loaded({ guard: judging });313 const { ctx } = contextOf("s1");314315 const result = yield* fire(316 handlers.tool_call,317 editOf(projectFile),318 ctx319 );320321 expect(result).toStrictEqual({322 block: true,323 reason: explain([new TouchedJudge({ paths: [projectFile] })]).join(324 "\n"325 ),326 });327328 expect(result?.reason?.split("\n")[0]).toMatch(/^TouchedJudge: /u);329 })330 );331332 it.effect("lets a write the policy passes run", () =>333 Effect.gen(function* () {334 const { asked, handlers } = loaded({ guard: judging });335 const { ctx } = contextOf("s1");336337 const result = yield* fire(338 handlers.tool_call,339 {340 input: { content: "export const week = 1;", path: "src/week.ts" },341 toolCallId: "call-3",342 toolName: "write",343 type: "tool_call",344 },345 ctx346 );347348 expect(result).toBeUndefined();349 expect(asked).toStrictEqual(["guardTool s1 Write"]);350 })351 );352353 it.effect("never asks the policy about a tool that changes nothing", () =>354 Effect.gen(function* () {355 const { asked, handlers } = loaded({ guard: judging });356 const { ctx } = contextOf("s1");357358 const result = yield* fire(359 handlers.tool_call,360 {361 input: { path: projectFile },362 toolCallId: "call-4",363 toolName: "read",364 type: "tool_call",365 },366 ctx367 );368369 expect(result).toBeUndefined();370 expect(asked).toStrictEqual([]);371 })372 );373374 it.effect(375 "blocks a git push whose preflight has a refusal retrying cannot help",376 () =>377 Effect.gen(function* () {378 const { handlers } = loaded({379 guard: preflight(new RepoBusy(), outside),380 });381382 const { ctx } = contextOf("s1");383384 const result = yield* fire(385 handlers.tool_call,386 bashOf("git push origin HEAD"),387 ctx388 );389390 expect(result).toStrictEqual({391 block: true,392 reason: explain([outside]).join("\n"),393 });394 })395 );396397 it.effect(398 "lets a git push run when its preflight is clean or only retryable",399 () =>400 Effect.gen(function* () {401 for (const refusals of [[], [new RepoBusy()]]) {402 const { asked, handlers } = loaded({403 guard: preflight(...refusals),404 });405406 const { ctx } = contextOf("s1");407408 const result = yield* fire(409 handlers.tool_call,410 bashOf("git push"),411 ctx412 );413414 expect(result).toBeUndefined();415 expect(asked).toStrictEqual(["guardTool s1 Push"]);416 }417 })418 );419420 it.effect("reads a push however the command spells it", () =>421 Effect.gen(function* () {422 const pushes = [423 "git push",424 "git push -u origin HEAD",425 "cd packages/a && git push",426 `git -C ${cwd} push origin`,427 "git --no-pager push;",428 "bun test && git commit -am wip && git push",429 ];430431 const others = [432 "git status",433 "git log --grep push",434 "echo pushed",435 "bun run push",436 "git pushd",437 ];438439 for (const command of [...pushes, ...others]) {440 const { handlers } = loaded({ guard: preflight(outside) });441 const { ctx } = contextOf("s1");442 const result = yield* fire(handlers.tool_call, bashOf(command), ctx);443444 expect({ blocked: result?.block === true, command }).toStrictEqual({445 blocked: pushes.includes(command),446 command,447 });448 }449 })450 );451 });452453 describe("agent_before_settle", () => {454 /** What another handler already appended at this boundary. */455 const earlier: SessionBoundaryDraft = {456 customType: "other-extension",457 type: "custom",458 };459460 it.effect(461 "sends the agent back with the refusal while the verdict is one it can act on",462 () =>463 Effect.gen(function* () {464 const { handlers } = loaded({ settle: refused(true) });465 const { ctx } = contextOf("s1");466467 const result = yield* fire(468 handlers.agent_before_settle,469 settleOf([earlier]),470 ctx471 );472473 expect(result).toStrictEqual({474 continue: true,475 entries: [476 earlier,477 {478 content: [479 `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:`,480 ...explain([failing]),481 ].join("\n"),482 customType: `${Brand.slug}-verdict`,483 display: true,484 type: "custom_message",485 },486 ],487 });488 })489 );490491 it.effect(492 "continues at most three times in one session, and lets the fourth settle stand",493 () =>494 Effect.gen(function* () {495 const { asked, handlers } = loaded({ settle: refused(true) });496 const one = contextOf("s1").ctx;497 const other = contextOf("s2").ctx;498 const continued: (boolean | undefined)[] = [];499500 for (const ctx of [one, one, one, one, other]) {501 const result = yield* fire(502 handlers.agent_before_settle,503 settleOf([]),504 ctx505 );506507 continued.push(result?.continue);508 }509510 expect(continued).toStrictEqual([true, true, true, undefined, true]);511512 // Past the cap, the policy is not even asked.513 expect(asked).toStrictEqual([514 "settle s1",515 "settle s1",516 "settle s1",517 "settle s2",518 ]);519 })520 );521522 it.effect("takes its cap from the options", () =>523 Effect.gen(function* () {524 const { deps } = fakeDeps({ settle: refused(true) });525 const { handlers, pi } = fakePi();526 const { ctx } = contextOf("s1");527528 piAdapter(deps, { maxContinuations: 1 })(pi);529530 const first = yield* fire(531 handlers.agent_before_settle,532 settleOf([]),533 ctx534 );535536 const second = yield* fire(537 handlers.agent_before_settle,538 settleOf([]),539 ctx540 );541542 expect([first?.continue, second]).toStrictEqual([true, undefined]);543 })544 );545546 it.effect(547 "never sends back a run that was stopped, failed, or cannot go on",548 () =>549 Effect.gen(function* () {550 const ended: readonly AgentBeforeSettleEvent[] = [551 { ...settleOf([]), outcome: "aborted" },552 { ...settleOf([]), outcome: "error" },553 {554 ...settleOf([]),555 context: { ...settleOf([]).context, canContinue: false },556 },557 ];558559 for (const event of ended) {560 const { asked, handlers } = loaded({ settle: refused(true) });561 const { ctx } = contextOf("s1");562563 const result = yield* fire(564 handlers.agent_before_settle,565 event,566 ctx567 );568569 expect({ asked, result }).toStrictEqual({570 asked: [],571 result: undefined,572 });573 }574 })575 );576577 it.effect(578 "never continues on a landing, a wait, or a refusal the agent cannot act on",579 () =>580 Effect.gen(function* () {581 const verdicts = [582 SettleVerdict.Landed(),583 SettleVerdict.Waiting(),584 SettleVerdict.Refused({585 actionable: false,586 refusals: [new RepoBusy()],587 }),588 ];589590 for (const verdict of verdicts) {591 const { handlers } = loaded({ settle: () => verdict });592 const { ctx } = contextOf("s1");593594 const result = yield* fire(595 handlers.agent_before_settle,596 settleOf([]),597 ctx598 );599600 expect({ result, verdict: verdict._tag }).toStrictEqual({601 result: undefined,602 verdict: verdict._tag,603 });604 }605 })606 );607 });608609 describe("when the policy fails", () => {610 it.effect(611 "allows the tool, and says why through ctx.ui.notify when pi gives one",612 () =>613 Effect.gen(function* () {614 const failures = [unreachable, Effect.die("a bug in the policy")];615616 for (const failure of failures) {617 const { handlers, pi } = fakePi();618 const { ctx, notes } = contextOf("s1");619620 piAdapter(broken(failure))(pi);621622 const result = yield* fire(623 handlers.tool_call,624 editOf(projectFile),625 ctx626 );627628 expect(result).toBeUndefined();629 expect(notes).toHaveLength(1);630 }631 })632 );633634 it.effect("names the failure in its note", () =>635 Effect.gen(function* () {636 const { handlers, pi } = fakePi();637 const { ctx, notes } = contextOf("s1");638639 piAdapter(broken(unreachable))(pi);640641 yield* fire(handlers.tool_call, bashOf("git push"), ctx);642643 expect(notes).toHaveLength(1);644 expect(notes[0]).toContain("the platform did not answer within 10s");645 })646 );647648 it.effect("gives no brief and no continuation, with or without a ui", () =>649 Effect.gen(function* () {650 for (const withUi of [true, false]) {651 const { handlers, pi } = fakePi();652 const { ctx, notes } = contextOf("s1", withUi);653654 piAdapter(broken(unreachable))(pi);655656 const brief = yield* fire(657 handlers.before_agent_start,658 startEvent,659 ctx660 );661662 const settled = yield* fire(663 handlers.agent_before_settle,664 settleOf([]),665 ctx666 );667668 expect({ brief, notes: notes.length, settled }).toStrictEqual({669 brief: undefined,670 notes: withUi ? 2 : 0,671 settled: undefined,672 });673 }674 })675 );676 });677678 it.effect(679 "registers only before_agent_start, tool_call and agent_before_settle",680 () =>681 Effect.sync(() => {682 const { events } = loaded({});683684 expect(events.toSorted()).toStrictEqual([685 "agent_before_settle",686 "before_agent_start",687 "tool_call",688 ]);689 })690 );691692 it.effect(693 "is what the package's pi entry exports, over the live policy",694 () =>695 Effect.sync(() => {696 const { events, pi } = fakePi();697698 extension(pi);699700 expect(events.toSorted()).toStrictEqual([701 "agent_before_settle",702 "before_agent_start",703 "tool_call",704 ]);705 })706 );707});708709// ------------------------------------------------------------ live deps710711const want = "An ISO week date parses to the Monday of that week.";712713/** Kept facts for a session on `fix-week` in a clone at `root`. */714const claimedIn = (root: string): SessionState => ({715 claim: {716 ask: AskId.make("fix-week"),717 checkCommand: "bun test packages/a",718 project: ProjectName.make("datekit"),719 territory: { module: "a", paths: [Glob.make("packages/a/**")] },720 want,721 },722 holds: 0,723 judge: { paths: [Glob.make(`/${Brand.configDir}/**`)], pointers: [] },724 root,725});726727/**728 * The live deps with their state in a temp folder, a local check that729 * answers `checked`, and a platform that must not be called. Gives the730 * deps, a folder that is no repo, the roots the check ran in, and a way to731 * keep a session's facts.732 */733const policyWith = (734 checked: Effect.Effect<readonly Refusal[], PushCheckFailed>735) =>736 Effect.gen(function* () {737 const fs = yield* FileSystem.FileSystem;738 const state = yield* fs.makeTempDirectoryScoped();739 const folder = yield* fs.makeTempDirectoryScoped();740 const roots: string[] = [];741742 const env = ConfigProvider.layer(743 ConfigProvider.fromEnv({ env: { XDG_STATE_HOME: state } })744 );745746 const deps = policyDeps(747 Layer.mergeAll(748 NodeServices.layer,749 Layer.mock(Client)({}),750 Layer.succeed(PushCheck)({751 run: (root) =>752 Effect.andThen(753 Effect.sync(() => roots.push(root)),754 checked755 ),756 }),757 env758 )759 );760761 const keep = (id: string, facts: SessionState) =>762 saveSession(id, facts).pipe(763 Effect.provide(Layer.mergeAll(NodeServices.layer, env)),764 Effect.orDie765 );766767 return { deps, folder, keep, roots };768 }).pipe(Effect.provide(NodeServices.layer));769770const refusing = (...refusals: readonly Refusal[]) => Effect.succeed(refusals);771772describe("the live deps, over the hook policy's own modules", () => {773 it.live("brief a session whose kept facts hold a claim", () =>774 Effect.gen(function* () {775 const { deps, folder, keep } = yield* policyWith(refusing());776777 yield* keep("s1", claimedIn(folder));778779 const brief = Option.getOrElse(780 yield* deps.brief({ cwd: folder, id: "s1" }),781 () => ""782 );783784 expect(brief).toContain(want);785 expect(brief).toContain("bun test packages/a");786 })787 );788789 it.live("give no brief, and run no check, in a folder that is no repo", () =>790 Effect.gen(function* () {791 const { deps, folder, roots } = yield* policyWith(refusing(outside));792 const session = { cwd: folder, id: "s2" };793 const brief = yield* deps.brief(session);794 const push = yield* deps.guardTool(session, GuardedCall.Push());795 const settled = yield* deps.settle(session);796797 expect({ brief, push, roots, settled }).toStrictEqual({798 brief: Option.none(),799 push: Option.none(),800 roots: [],801 settled: SettleVerdict.Waiting(),802 });803 })804 );805806 it.live("preflight a push by the local check, in the claim's repo", () =>807 Effect.gen(function* () {808 const busy = new RepoBusy();809810 const { deps, folder, keep, roots } = yield* policyWith(811 refusing(busy, outside)812 );813814 yield* keep("s3", claimedIn(folder));815816 const push = yield* deps.guardTool(817 { cwd: `${folder}/packages/a`, id: "s3" },818 GuardedCall.Push()819 );820821 expect({ push, roots }).toStrictEqual({822 push: Option.some([busy, outside]),823 roots: [folder],824 });825 })826 );827828 it.live(829 "settle as the policy's stop would hold: on a refusal the agent can fix",830 () =>831 Effect.gen(function* () {832 const busy = new RepoBusy();833834 const cases = [835 {836 refusals: [outside],837 verdict: SettleVerdict.Refused({838 actionable: true,839 refusals: [outside],840 }),841 },842 {843 refusals: [busy],844 verdict: SettleVerdict.Refused({845 actionable: false,846 refusals: [busy],847 }),848 },849 { refusals: [], verdict: SettleVerdict.Waiting() },850 ];851852 for (const { refusals, verdict } of cases) {853 const { deps, folder, keep } = yield* policyWith(854 refusing(...refusals)855 );856857 yield* keep("s4", claimedIn(folder));858859 expect(yield* deps.settle({ cwd: folder, id: "s4" })).toStrictEqual(860 verdict861 );862 }863 })864 );865866 it.live("fail as HookFailed when the local check gives no answer", () =>867 Effect.gen(function* () {868 const { deps, folder, keep } = yield* policyWith(869 Effect.fail(new PushCheckFailed({ reason: "it ran past 1m" }))870 );871872 yield* keep("s5", claimedIn(folder));873874 const failed = yield* Effect.flip(deps.settle({ cwd: folder, id: "s5" }));875876 expect(failed.message).toContain("it ran past 1m");877 })878 );879});
modified:apps/cli/tsdown.config.ts+2 added