Skip to content
Myr

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

3 files+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 */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 * 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 */220const fixable = (refusals: readonly Refusal[]) =>221 refusals.filter((refusal) => !refusal.retryable);222223/**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 */227const blockFor = (228 refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>229): Option.Option<ToolCallEventResult> => {230 const final = fixable(Option.getOrElse(refusals, () => []));231232 return Array.isReadonlyArrayNonEmpty(final)233 ? Option.some({ block: true, reason: explain(final).join("\n") })234 : Option.none();235};236237/**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 */242const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>243 Array.match(fixable(refusals), {244 onEmpty: () => refusals,245 onNonEmpty: (final) => final,246 });247248/** The session a handler runs in. */249const sessionOf = (ctx: PiContext): PiSession => ({250 cwd: ctx.cwd,251 id: ctx.sessionManager.getSessionId(),252});253254/** A failure's first line, for the note. */255const firstLine = (cause: Cause.Cause<unknown>) =>256 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";257258/**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 */264const 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 );285286/**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 */291export 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>();297298 // 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);302303 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 });324325 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 );336337 // 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;346347 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);356357 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 };370371// ------------------------------------------------------------ live372373/**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 */380const factsOf = (session: PiSession, look: boolean) =>381 Effect.gen(function* () {382 const kept = yield* loadSession(session.id);383384 if (Option.isSome(kept) && (kept.value.claim !== undefined || !look)) {385 return kept.value;386 }387388 const gathered = yield* gatherFacts(session.cwd);389390 // A cache: facts that cannot be kept are gathered again next time.391 yield* Effect.ignore(saveSession(session.id, gathered));392393 return gathered;394 });395396/**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 */400const 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});410411/** The policy's input for `event`, in the hook format it reads. */412const hookInput = (event: HookEvent, session: PiSession): HookInput => ({413 cwd: session.cwd,414 hook_event_name: claudeEventOf[event],415 session_id: session.id,416});417418/**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 */422const localCheck = (state: SessionState) =>423 state.claim === undefined424 ? Effect.succeed<readonly Refusal[]>([])425 : Effect.flatMap(Effect.service(PushCheck), (check) =>426 check.run(state.root)427 );428429/** What the hook policy runs on. */430export type PolicyServices =431 | ChildProcessSpawner.ChildProcessSpawner432 | Client433 | FileSystem.FileSystem434 | Path.Path435 | PushCheck;436437/** The hook policy, in process, as `PiDeps`, over `services`. */438export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({439 brief: (session) =>440 Effect.gen(function* () {441 const state = yield* factsOf(session, true);442443 const { output } = decideHook(444 "session-start",445 hookInput("session-start", session),446 hookFacts(state, [])447 );448449 return "hookSpecificOutput" in output &&450 "additionalContext" in output.hookSpecificOutput451 ? Option.some(output.hookSpecificOutput.additionalContext)452 : Option.none();453 }).pipe(Effect.provide(services)),454455 guardTool: (session, call) =>456 GuardedCall.$match(call, {457 Push: () =>458 Effect.gen(function* () {459 const refusals = yield* localCheck(yield* factsOf(session, false));460461 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 }),475476 settle: (session) =>477 Effect.gen(function* () {478 const state = yield* factsOf(session, true);479 const refusals = yield* localCheck(state);480481 if (!Array.isReadonlyArrayNonEmpty(refusals)) {482 return SettleVerdict.Waiting();483 }484485 const { output } = decideHook(486 "stop",487 hookInput("stop", session),488 hookFacts(state, refusals)489 );490491 // 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});501502/**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 */508const 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);515516/** The hook policy as pi's process runs it. */517export const livePiDeps = policyDeps(LiveServices);518519/** What `pi install npm:<package>` loads: the adapter over the live policy. */520export 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 */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/**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 */209const 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});222223const failing = new ChecksFailed({224 lane: "test",225 logRef: "logs/test",226 next: `${Brand.cli} check`,227});228229const refused = (actionable: boolean) => () =>230 SettleVerdict.Refused({ actionable, refusals: [failing] });231232const unreachable = Effect.fail(233 new HookFailed({ reason: "the platform did not answer within 10s" })234);235236describe("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");242243 const result = yield* fire(244 handlers.before_agent_start,245 startEvent,246 ctx247 );248249 expect(result).toStrictEqual({250 message: {251 content: briefText,252 customType: `${Brand.slug}-brief`,253 display: true,254 },255 });256 })257 );258259 it.effect("gives nothing without a claim", () =>260 Effect.gen(function* () {261 const { asked, handlers } = loaded({ brief: Option.none() });262 const { ctx } = contextOf("s1");263264 const result = yield* fire(265 handlers.before_agent_start,266 startEvent,267 ctx268 );269270 expect(result).toBeUndefined();271 expect(asked).toStrictEqual([`brief s1 ${cwd}`]);272 })273 );274275 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[] = [];285286 // 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);292293 for (const ctx of [one, one, one, other]) {294 const result = yield* fire(295 handlers.before_agent_start,296 startEvent,297 ctx298 );299300 given.push(result === undefined ? "nothing" : "the brief");301 }302303 expect(given).toStrictEqual([304 "nothing",305 "the brief",306 "nothing",307 "the brief",308 ]);309 })310 );311 });312313 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");320321 const result = yield* fire(322 handlers.tool_call,323 editOf(projectFile),324 ctx325 );326327 expect(result).toStrictEqual({328 block: true,329 reason: explain([new TouchedJudge({ paths: [projectFile] })]).join(330 "\n"331 ),332 });333334 expect(result?.reason?.split("\n")[0]).toMatch(/^TouchedJudge: /u);335 })336 );337338 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");342343 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 );353354 expect(result).toBeUndefined();355 expect(asked).toStrictEqual(["guardTool s1 Write"]);356 })357 );358359 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");363364 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 );374375 expect(result).toBeUndefined();376 expect(asked).toStrictEqual([]);377 })378 );379380 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 });387388 const { ctx } = contextOf("s1");389390 const result = yield* fire(391 handlers.tool_call,392 bashOf("git push origin HEAD"),393 ctx394 );395396 expect(result).toStrictEqual({397 block: true,398 reason: explain([outside]).join("\n"),399 });400 })401 );402403 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 });411412 const { ctx } = contextOf("s1");413414 const result = yield* fire(415 handlers.tool_call,416 bashOf("git push"),417 ctx418 );419420 expect(result).toBeUndefined();421 expect(asked).toStrictEqual(["guardTool s1 Push"]);422 }423 })424 );425426 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 ];436437 const others = [438 "git status",439 "git log --grep push",440 "echo pushed",441 "bun run push",442 "git pushd",443 ];444445 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);449450 expect({ blocked: result?.block === true, command }).toStrictEqual({451 blocked: pushes.includes(command),452 command,453 });454 }455 })456 );457 });458459 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 };465466 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");472473 const result = yield* fire(474 handlers.agent_before_settle,475 settleOf([earlier]),476 ctx477 );478479 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 );496497 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)[] = [];505506 for (const ctx of [one, one, one, one, other]) {507 const result = yield* fire(508 handlers.agent_before_settle,509 settleOf([]),510 ctx511 );512513 continued.push(result?.continue);514 }515516 expect(continued).toStrictEqual([true, true, true, undefined, true]);517518 // 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 );527528 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");533534 piAdapter(deps, { maxContinuations: 1 })(pi);535536 const first = yield* fire(537 handlers.agent_before_settle,538 settleOf([]),539 ctx540 );541542 const second = yield* fire(543 handlers.agent_before_settle,544 settleOf([]),545 ctx546 );547548 expect([first?.continue, second]).toStrictEqual([true, undefined]);549 })550 );551552 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([]);559560 const result = yield* fire(handlers.agent_before_settle, event, ctx);561562 // 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 );576577 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 });588589 const { ctx } = contextOf("s1");590591 const result = yield* fire(592 handlers.agent_before_settle,593 settleOf([]),594 ctx595 );596597 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 );610611 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 ];617618 for (const event of ended) {619 const { asked, handlers } = loaded({ settle: refused(true) });620 const { ctx } = contextOf("s1");621622 const result = yield* fire(handlers.agent_before_settle, event, ctx);623624 expect({ asked, result }).toStrictEqual({625 asked: [],626 result: undefined,627 });628 }629 })630 );631632 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 ];644645 for (const verdict of verdicts) {646 const { handlers } = loaded({ settle: () => verdict });647 const { ctx } = contextOf("s1");648649 const result = yield* fire(650 handlers.agent_before_settle,651 settleOf([]),652 ctx653 );654655 expect({ result, verdict: verdict._tag }).toStrictEqual({656 result: undefined,657 verdict: verdict._tag,658 });659 }660 })661 );662 });663664 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")];670671 for (const failure of failures) {672 const { handlers, pi } = fakePi();673 const { ctx, notes } = contextOf("s1");674675 piAdapter(broken(failure))(pi);676677 const result = yield* fire(678 handlers.tool_call,679 editOf(projectFile),680 ctx681 );682683 expect(result).toBeUndefined();684 expect(notes).toHaveLength(1);685 }686 })687 );688689 it.effect("names the failure in its note", () =>690 Effect.gen(function* () {691 const { handlers, pi } = fakePi();692 const { ctx, notes } = contextOf("s1");693694 piAdapter(broken(unreachable))(pi);695696 yield* fire(handlers.tool_call, bashOf("git push"), ctx);697698 expect(notes).toHaveLength(1);699 expect(notes[0]).toContain("the platform did not answer within 10s");700 })701 );702703 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);708709 piAdapter(broken(unreachable))(pi);710711 const brief = yield* fire(712 handlers.before_agent_start,713 startEvent,714 ctx715 );716717 const settled = yield* fire(718 handlers.agent_before_settle,719 settleOf([]),720 ctx721 );722723 expect({ brief, notes: notes.length, settled }).toStrictEqual({724 brief: undefined,725 notes: withUi ? 2 : 0,726 settled: undefined,727 });728 }729 })730 );731 });732733 it.effect(734 "registers only before_agent_start, tool_call and agent_before_settle",735 () =>736 Effect.sync(() => {737 const { events } = loaded({});738739 expect(events.toSorted()).toStrictEqual([740 "agent_before_settle",741 "before_agent_start",742 "tool_call",743 ]);744 })745 );746747 it.effect(748 "is what the package's pi entry exports, over the live policy",749 () =>750 Effect.sync(() => {751 const { events, pi } = fakePi();752753 extension(pi);754755 expect(events.toSorted()).toStrictEqual([756 "agent_before_settle",757 "before_agent_start",758 "tool_call",759 ]);760 })761 );762});763764// ------------------------------------------------------------ live deps765766const want = "An ISO week date parses to the Monday of that week.";767768/** Kept facts for a session on `fix-week` in a clone at `root`. */769const 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});781782/**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 */788const 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[] = [];796797 const env = ConfigProvider.layer(798 ConfigProvider.fromEnv({ env: { XDG_STATE_HOME: state } })799 );800801 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 );815816 const keep = (id: string, facts: SessionState) =>817 saveSession(id, facts).pipe(818 Effect.provide(Layer.mergeAll(NodeServices.layer, env)),819 Effect.orDie820 );821822 return { deps, folder, keep, roots };823 }).pipe(Effect.provide(NodeServices.layer));824825const refusing = (...refusals: readonly Refusal[]) => Effect.succeed(refusals);826827describe("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());831832 yield* keep("s1", claimedIn(folder));833834 const brief = Option.getOrElse(835 yield* deps.brief({ cwd: folder, id: "s1" }),836 () => ""837 );838839 expect(brief).toContain(want);840 expect(brief).toContain("bun test packages/a");841 })842 );843844 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);851852 expect({ brief, push, roots, settled }).toStrictEqual({853 brief: Option.none(),854 push: Option.none(),855 roots: [],856 settled: SettleVerdict.Waiting(),857 });858 })859 );860861 it.live("preflight a push by the local check, in the claim's repo", () =>862 Effect.gen(function* () {863 const busy = new RepoBusy();864865 const { deps, folder, keep, roots } = yield* policyWith(866 refusing(busy, outside)867 );868869 yield* keep("s3", claimedIn(folder));870871 const push = yield* deps.guardTool(872 { cwd: `${folder}/packages/a`, id: "s3" },873 GuardedCall.Push()874 );875876 expect({ push, roots }).toStrictEqual({877 push: Option.some([busy, outside]),878 roots: [folder],879 });880 })881 );882883 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();888889 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 ];906907 for (const { refusals, verdict } of cases) {908 const { deps, folder, keep } = yield* policyWith(909 refusing(...refusals)910 );911912 yield* keep("s4", claimedIn(folder));913914 expect(yield* deps.settle({ cwd: folder, id: "s4" })).toStrictEqual(915 verdict916 );917 }918 })919 );920921 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 );926927 yield* keep("s5", claimedIn(folder));928929 const failed = yield* Effect.flip(deps.settle({ cwd: folder, id: "s5" }));930931 expect(failed.message).toContain("it ran past 1m");932 })933 );934});
modified:apps/cli/tsdown.config.ts+2 added