hook.ts
This file
Path
apps/cli/src/hook.ts
222 lines · 7.0 KiB · TypeScript
Last changed by
Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042
History of this fileTake it
The walk stopped after 200 commits: lines older than 878da37 point at it.
Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 1–38why, one step back1/**2 * `<cli> hook <event> --json`: the one command behind every harness hook in3 * Claude Code's format (Claude Code itself, and Cursor and Copilot CLI, which4 * read it). It reads the harness's JSON on stdin, gathers the session's facts5 * once (cached per session), asks `decideHook`, and prints the decision as6 * the one JSON document on stdout.7 *8 * Hooks are early feedback; the gateway is the authority. So the hook fails9 * open: without a claim, without the platform, with input it cannot read, or10 * on any failure of its own, it prints `{}` (go on), says why on stderr, and11 * exits 0. Only a wrong event name, a mistake in the hook's own config, is a12 * usage error (exit 2).13 */14import { HookEvent } from "@repo/agent-kit/hook-events";15import { Brand } from "@repo/brand";16import {17 Cause,18 Console,19 Effect,20 Option,21 Runtime,22 Schema,23 Stdio,24 Stream,25} from "effect";26import { Argument, Command, Flag } from "effect/cli";2728import { decideHook } from "./hook/decide.ts";29import type { HookOutput } from "./hook/decide.ts";30import { gatherFacts } from "./hook/facts.ts";31import { decodeHookInput } from "./hook/input.ts";32import type { HookInput } from "./hook/input.ts";33import { PushCheck, PushCheckChild } from "./hook/push-check.ts";34import type { PushCheckFailed } from "./hook/push-check.ts";35import { loadSession, saveSession } from "./hook/session.ts";36import type { SessionState } from "./hook/session.ts";37import { Output } from "./output.ts";38Fit W4 group A together on main: every CLI test runs signed out, the binary runs on the real client, usage errors exit 2 as typed failures, and the heaviest tests get a hang limitoscabrielbefore adoptionb08d5f6
lines 39–40why, one step back39const EVENTS = HookEvent.literals.join(", ");40Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 41–42why, one step back41/**42 * The hook was called with an event it does not answer: its config isFit W4 group A together on main: every CLI test runs signed out, the binary runs on the real client, usage errors exit 2 as typed failures, and the heaviest tests get a hang limitoscabrielbefore adoptionb08d5f6
line 43why, one step back43 * wrong. A usage error: `program` prints its one line and exits 2.Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 44–49why, one step back44 */45export class HookUsage extends Schema.TaggedError<HookUsage>()("HookUsage", {46 event: Schema.String,47}) {48 override readonly [Runtime.errorExitCode] = 2;49 override readonly [Runtime.errorReported] = false;Fit W4 group A together on main: every CLI test runs signed out, the binary runs on the real client, usage errors exit 2 as typed failures, and the heaviest tests get a hang limitoscabrielbefore adoptionb08d5f6
lines 50–53why, one step back5051 override get message() {52 return `hook: no event ${this.event}; the events are ${EVENTS}`;53 }Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 54–101why, one step back54}5556const decodeEvent = Schema.decodeUnknownOption(HookEvent);5758/** The whole of stdin, as text. */59const stdinText = Effect.flatMap(Stdio.Stdio, ({ stdin }) =>60 stdin.pipe(Stream.decodeText(), Stream.mkString)61);6263/** The PushCheck the caller provided, or this CLI run again as a child. */64const pushCheck = Effect.flatMap(65 Effect.serviceOption(PushCheck),66 Option.match({67 onNone: () => Effect.provide(Effect.service(PushCheck), PushCheckChild),68 onSome: Effect.succeed,69 })70);7172/**73 * The session's facts: kept from an earlier event, else gathered and kept.74 * A claim, once found, holds for the session, so `pre-tool-use` never asks75 * the platform again. Without one, `session-start` and `stop` look again76 * (once a turn), so a claim the agent takes mid-session is found at the end77 * of that turn; `pre-tool-use` never does, so an edit never waits on the78 * network.79 */80const sessionFacts = (event: HookEvent, input: HookInput) =>81 Effect.gen(function* () {82 const kept = yield* loadSession(input.session_id);8384 if (85 Option.isSome(kept) &&86 (kept.value.claim !== undefined || event === "pre-tool-use")87 ) {88 return kept.value;89 }9091 const gathered = yield* gatherFacts(input.cwd);9293 yield* saveSession(input.session_id, gathered).pipe(94 Effect.catchTag("SessionUnsaved", (unsaved) =>95 Output.use((output) => output.note(unsaved.message))96 )97 );9899 return gathered;100 });101Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042
lines 102–107why, one step back102/** Stop asks the local check, from the claim's base; nothing else does, and only with a claim. */103const refusalsFor = (event: HookEvent, state: SessionState) => {104 const { claim } = state;105106 return event === "stop" && claim !== undefined107 ? Effect.flatMap(pushCheck, (check) => check.run(state.root, claim.base))Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
line 108why, one step back108 : Effect.succeed([]);Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042
line 109why, one step back109};Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 110–175why, one step back110111/** Answers one event: the decision's JSON, with its note on stderr. */112const answer = (event: HookEvent, input: HookInput) =>113 Effect.gen(function* () {114 const output = yield* Output;115 const state = yield* sessionFacts(event, input);116117 const decision = decideHook(event, input, {118 claim: Option.fromUndefinedOr(state.claim),119 holds: state.holds,120 judge: state.judge,121 refusals: yield* refusalsFor(event, state),122 root: state.root,123 });124125 const counted =126 decision.holds === state.holds127 ? true128 : yield* saveSession(input.session_id, {129 ...state,130 holds: decision.holds,131 }).pipe(132 Effect.as(true),133 Effect.catchTag("SessionUnsaved", (unsaved) =>134 Effect.as(output.note(unsaved.message), false)135 )136 );137138 // A hold the session cannot count could never reach the cap: allow.139 if (!counted && decision.holds > state.holds) {140 yield* output.note(141 `${event}: this hold could not be counted, so the agent may stop; ${Brand.cli} check still refuses its work`142 );143144 return {};145 }146147 // Why the session has no claim says more than the policy's "no claim".148 const why = Option.orElse(149 Option.fromUndefinedOr(state.why),150 () => decision.note151 );152153 if (Option.isSome(why)) {154 yield* output.note(`${event}: ${why.value}`);155 }156157 return decision.output;158 });159160/** The answer on stdout: one line of JSON, or indented for a person. */161const print = (json: boolean, output: HookOutput) =>162 Console.log(json ? JSON.stringify(output) : JSON.stringify(output, null, 2));163164/** Says why the hook allows, on stderr, and lets the harness go on. */165const failOpen = (json: boolean, why: string) =>166 Effect.andThen(167 Output.use((output) => output.note(`hook: ${why}; allowing`)),168 print(json, {})169 );170171const run = (name: string, json: boolean) =>172 Effect.gen(function* () {173 const event = decodeEvent(name);174175 if (Option.isNone(event)) {Fit W4 group A together on main: every CLI test runs signed out, the binary runs on the real client, usage errors exit 2 as typed failures, and the heaviest tests get a hang limitoscabrielbefore adoptionb08d5f6
line 176why, one step back176 return yield* new HookUsage({ event: name });Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 177–222why, one step back177 }178179 const input = yield* Effect.flatMap(stdinText, decodeHookInput).pipe(180 Effect.option181 );182183 if (Option.isNone(input)) {184 return yield* failOpen(185 json,186 "could not read the harness's JSON on stdin"187 );188 }189190 return yield* answer(event.value, input.value).pipe(191 Effect.flatMap((output) => print(json, output)),192 Effect.catchTag("PushCheckFailed", (failed: PushCheckFailed) =>193 failOpen(json, failed.message)194 ),195 // Any defect of the hook's own: the gateway still judges the push.196 Effect.catchCauseIf(197 (cause) => !Cause.hasInterruptsOnly(cause),198 (cause) =>199 failOpen(json, String(Cause.squash(cause)).split("\n")[0] ?? "")200 )201 );202 });203204export const hook = Command.make(205 "hook",206 {207 event: Argument.String("event").pipe(208 Argument.withDescription(`The harness event: ${EVENTS}.`)209 ),210 json: Flag.Boolean("json").pipe(211 Flag.withDefault(false),212 Flag.withDescription(213 "Print the answer as one line of JSON, as a harness reads it; without it, indented."214 )215 ),216 },217 ({ event, json }) => run(event, json)218).pipe(219 Command.withDescription(220 "Answer a harness hook (session-start, pre-tool-use, stop) with the gate's policy."221 )222);