decide.ts
This file
Path
apps/cli/src/hook/decide.ts
262 lines · 7.5 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 25a727e point at it.
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 1why, one step back1// A hook is early feedback and the gateway stays the authority, so anything it cannot judge it allows.Run the swarm's pell on opencode-go/qwen3.8-flash, since pi here has no OpenCode Zen keyoscabrielbefore adoption25a727e
lines 2–181why, one step back2import { claudeEventOf } from "@repo/agent-kit/hook-events";3import type { HookEvent } from "@repo/agent-kit/hook-events";4import { Brand } from "@repo/brand";5import { matchAny } from "@repo/gate/glob";6import type { Policy } from "@repo/protocol/domain/policy";7import { Territory } from "@repo/protocol/domain/territory";8import { AskId, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";9import { OutOfScope, TouchedJudge } from "@repo/protocol/refusal";10import type { Refusal } from "@repo/protocol/refusal";11import { explain } from "@repo/protocol/render";12import { Array, Option, Predicate, Schema } from "effect";1314import type { HookInput } from "./input.ts";1516export const HookClaim = Schema.Struct({17 ask: AskId,18 base: CommitSha,19 checkCommand: Schema.NonEmptyString,20 project: ProjectName,21 territory: Territory,22 want: Schema.NonEmptyString,23});2425export type HookClaim = typeof HookClaim.Type;2627export interface HookFacts {28 readonly root: string;29 readonly claim: Option.Option<HookClaim>;30 readonly judge: Policy["judge"];31 readonly refusals: readonly Refusal[];32 readonly holds: number;33}3435type GoOn = Readonly<Record<string, never>>;3637interface Deny {38 readonly hookSpecificOutput: {39 readonly hookEventName: (typeof claudeEventOf)["pre-tool-use"];40 readonly permissionDecision: "deny";41 readonly permissionDecisionReason: string;42 };43}4445interface Brief {46 readonly hookSpecificOutput: {47 readonly additionalContext: string;48 readonly hookEventName: (typeof claudeEventOf)["session-start"];49 };50}5152interface Hold {53 readonly decision: "block";54 readonly reason: string;55}5657export type HookOutput = GoOn | Deny | Brief | Hold;5859export interface HookDecision {60 readonly output: HookOutput;61 readonly holds: number;62 readonly note: Option.Option<string>;63}6465const NO_CLAIM =66 "no claim in this session's repo, so the hook allows everything; the gateway still judges every push";6768const allow = (holds: number, note?: string): HookDecision => ({69 holds,70 note: Option.fromUndefinedOr(note),71 output: {},72});7374const normalize = (path: string) => {75 const parts: string[] = [];7677 for (const part of path.split("/")) {78 if (part === "..") {79 parts.pop();80 } else if (part !== "." && part !== "") {81 parts.push(part);82 }83 }8485 return `/${parts.join("/")}`;86};8788const repoPathOf = (89 root: string,90 cwd: string,91 file: string92): Option.Option<RepoPath> => {93 const top = normalize(root);94 const absolute = normalize(file.startsWith("/") ? file : `${cwd}/${file}`);95 const prefix = top === "/" ? "/" : `${top}/`;9697 return absolute.startsWith(prefix) && absolute.length > prefix.length98 ? Option.some(RepoPath.make(absolute.slice(prefix.length)))99 : Option.none();100};101102const WRITERS = new Map([103 ["Edit", "file_path"],104 ["MultiEdit", "file_path"],105 ["NotebookEdit", "notebook_path"],106 ["Write", "file_path"],107]);108109const fileOf = (input: HookInput): Option.Option<string> =>110 Option.flatMap(Option.fromUndefinedOr(input.tool_name), (name) =>111 Option.flatMap(Option.fromUndefinedOr(WRITERS.get(name)), (key) =>112 Option.filter(113 Option.fromNullishOr(input.tool_input?.[key]),114 Predicate.isString115 )116 )117 );118119const pathRefusals = (120 claim: HookClaim,121 judge: Policy["judge"],122 path: RepoPath123): readonly Refusal[] => {124 if (matchAny(judge.paths, path)) {125 return [new TouchedJudge({ paths: [path] })];126 }127128 return matchAny(claim.territory.paths, path)129 ? []130 : [new OutOfScope({ paths: [path] })];131};132133export const toolRefusals = (134 input: HookInput,135 facts: Pick<HookFacts, "claim" | "judge" | "root">136): readonly Refusal[] =>137 Option.match(facts.claim, {138 onNone: () => [],139 onSome: (claim) =>140 Option.match(141 Option.flatMap(fileOf(input), (file) =>142 repoPathOf(facts.root, input.cwd, file)143 ),144 {145 onNone: () => [],146 onSome: (path) => pathRefusals(claim, facts.judge, path),147 }148 ),149 });150151const preToolUse = (input: HookInput, facts: HookFacts): HookDecision =>152 Option.match(facts.claim, {153 onNone: () => allow(facts.holds, NO_CLAIM),154 onSome: () => {155 const refusals = toolRefusals(input, facts);156157 return Array.isReadonlyArrayNonEmpty(refusals)158 ? {159 holds: facts.holds,160 note: Option.none(),161 output: {162 hookSpecificOutput: {163 hookEventName: claudeEventOf["pre-tool-use"],164 permissionDecision: "deny",165 permissionDecisionReason: explain(refusals).join("\n"),166 },167 },168 }169 : allow(facts.holds);170 },171 });172173const bullets = (items: readonly string[]) =>174 items.map((item) => `- \`${item}\``);175176const brief = ({ ask, checkCommand, project, territory, want }: HookClaim) =>177 [178 `# Your claim: ${ask} in ${project}`,179 "",180 `**Want:** ${want}`,181 "",Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 182why, one step back182 // A paths territory (module `.`) reads as its paths alone.Close the wave: a listed posture is the project's own, and the new pages are written downoscabrielbefore adoption57bb629
lines 183–185why, one step back183 territory.module === "."184 ? "**Territory:** these paths. Change only these:"185 : `**Territory:** the module \`${territory.module}\`. Change only these paths:`,Run the swarm's pell on opencode-go/qwen3.8-flash, since pi here has no OpenCode Zen keyoscabrielbefore adoption25a727e
lines 186–219why, one step back186 ...bullets(territory.paths),187 ...(territory.publicFiles === undefined ||188 territory.publicFiles.length === 0189 ? []190 : [191 "",192 `**Public files:** what \`${territory.module}\` exports; other modules import only these:`,193 ...bullets(territory.publicFiles),194 ]),195 "",196 `**Check:** \`${checkCommand}\``,197 "",198 "Files that decide what the checks do (the config folder, test and lint config, CI and hook files, the ask's own check) are not yours to change. An edit outside the territory or to one of those files is refused at push; this session's hooks deny it before it is made, with the same text.",199 "",200 `Run \`${Brand.cli} check\` before you push.`,201 ].join("\n");202203const sessionStart = (facts: HookFacts): HookDecision =>204 Option.match(facts.claim, {205 onNone: () => allow(facts.holds, NO_CLAIM),206 onSome: (claim) => ({207 holds: facts.holds,208 note: Option.none(),209 output: {210 hookSpecificOutput: {211 additionalContext: brief(claim),212 hookEventName: claudeEventOf["session-start"],213 },214 },215 }),216 });217218export const MAX_HOLDS = 3;219Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 220why, one step back220/** A retryable refusal never holds. `stop_hook_active` counts as at least one hold even if the session's count was lost. */Run the swarm's pell on opencode-go/qwen3.8-flash, since pi here has no OpenCode Zen keyoscabrielbefore adoption25a727e
lines 221–262why, one step back221const stopHook = (input: HookInput, facts: HookFacts): HookDecision => {222 const before =223 input.stop_hook_active === true ? Math.max(facts.holds, 1) : facts.holds;224225 const fixable = facts.refusals.filter((refusal) => !refusal.retryable);226227 if (Option.isNone(facts.claim)) {228 return allow(0, NO_CLAIM);229 }230231 if (!Array.isReadonlyArrayNonEmpty(fixable)) {232 return allow(0);233 }234235 if (before >= MAX_HOLDS) {236 return allow(237 0,238 `held ${MAX_HOLDS} times in a row; letting the agent stop, though ${Brand.cli} check still refuses its work (${fixable.map((refusal) => refusal._tag).join(", ")})`239 );240 }241242 return {243 holds: before + 1,244 note: Option.none(),245 output: { decision: "block", reason: explain(fixable).join("\n") },246 };247};248249const policies = {250 "pre-tool-use": preToolUse,251 "session-start": (_input, facts) => sessionStart(facts),252 stop: stopHook,253} as const satisfies Record<254 HookEvent,255 (input: HookInput, facts: HookFacts) => HookDecision256>;257258export const decideHook = (259 event: HookEvent,260 input: HookInput,261 facts: HookFacts262): HookDecision => policies[event](input, facts);