Skip to content
Myr

hook.test.ts

This file

Path

apps/cli/test/hook.test.ts

1,192 lines · 35.1 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { defaultJudgeGlobs, judgeClosure } from "@repo/checks/judge";5import { PushTarget } from "@repo/gate/facts";6import type { PushFacts } from "@repo/gate/facts";7import { scan } from "@repo/gate/stages/shape";8import { Client, Contracts } from "@repo/protocol/contracts";9import { Ask } from "@repo/protocol/domain/ask";10import { CheckSpec } from "@repo/protocol/domain/check";11import { ClaimView } from "@repo/protocol/domain/claim";12import { Glob, RefNameText } from "@repo/protocol/domain/common";13import { Policy } from "@repo/protocol/domain/policy";14import { RunBlock } from "@repo/protocol/domain/run";15import { Envelope } from "@repo/protocol/envelope";16import { CommitSha, Handle, LandedSha, RepoPath } from "@repo/protocol/ids";17import { Person } from "@repo/protocol/principal";18import {19  OutOfScope,20  RepoBusy,21  TouchedJudge,22  Weakened,23} from "@repo/protocol/refusal";24import type { Refusal } from "@repo/protocol/refusal";25import { explain } from "@repo/protocol/render";26import { asPerson, unanswered } from "@repo/protocol/testing";27import { gitOk } from "@repo/testkit/git";28import {29  Array,30  Cause,31  ConfigProvider,32  Deferred,33  Effect,34  Exit,35  Fiber,36  FileSystem,37  Layer,38  Option,39  Path,40  Predicate,41  Ref,42  Result,43  Runtime,44  Schema,45  Stdio,46  Stream,47} from "effect";48import { CliOutput } from "effect/cli";49import { RpcTest } from "effect/rpc";50import { TestClock, TestConsole } from "effect/testing";5152import { decideHook } from "../src/hook/decide.ts";53import type { HookClaim, HookFacts } from "../src/hook/decide.ts";54import type { HookInput } from "../src/hook/input.ts";55import { askJudge } from "../src/hook/judge.ts";56import {57  PushCheck,58  PushCheckFailed,59  selfCommand,60  pushCheckWith,61} from "../src/hook/push-check.ts";62import { program } from "../src/main.ts";63import { OutputPlain } from "../src/output.ts";64import { SignedOut } from "./signed-out.ts";6566const root = "/work/datekit";6768const checkPath = "packages/a/test/week.test.ts";6970const landedSha = "4444444444444444444444444444444444444444";7172const askWire = {73  askedBy: "bob",74  blockedBy: [],75  brief: { want: "An ISO week date parses to the Monday of that week." },76  check: Schema.encodeSync(CheckSpec)(77    CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(checkPath) })78  ),79  file: `${Brand.configDir}/asks/fix-week.ask.ts`,80  id: "fix-week",81  kind: "fix",82  openedAt: "2026-10-07T12:00:00.000Z",83  openedIn: landedSha,84  project: "oscabriel/datekit",85  state: "claimed",86  territory: {87    module: "a",88    paths: ["packages/a/**"],89    publicFiles: ["packages/a/src/index.ts"],90  },91} as const;9293const ask = Schema.decodeSync(Ask)(askWire);9495const claim: HookClaim = {96  ask: ask.id,97  base: CommitSha.make("1".repeat(40)),98  checkCommand: `bun test ${checkPath}`,99  project: ask.project,100  territory: ask.territory,101  want: ask.brief.want,102};103104const weakened = new Weakened({105  at: { line: 3, path: RepoPath.make(checkPath) },106  weakening: { marker: ".skip(" },107});108109const sha = (digit: string) => CommitSha.make(digit.repeat(40));110111const facts: HookFacts = {112  claim: Option.some(claim),113  holds: 0,114  judge: {115    paths: [...defaultJudgeGlobs, Glob.make(`/${checkPath}`)],116    pointers: ["package.json#/scripts"],117  },118  refusals: [],119  root,120};121122const input = (fields: Partial<HookInput>): HookInput => ({123  cwd: root,124  hook_event_name: "PreToolUse",125  session_id: "session-1",126  ...fields,127});128129const tool = (name: string, toolInput: NonNullable<HookInput["tool_input"]>) =>130  input({ tool_input: toolInput, tool_name: name });131132const deny = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({133  hookSpecificOutput: {134    hookEventName: "PreToolUse",135    permissionDecision: "deny",136    permissionDecisionReason: explain(refusals).join("\n"),137  },138});139140describe("pre-tool-use", () => {141  it.each([142    {143      expected: deny([144        new OutOfScope({ paths: [RepoPath.make("packages/b/src/x.ts")] }),145      ]),146      name: "a Write outside the territory is denied as OutOfScope",147      payload: tool("Write", {148        content: "export {}",149        file_path: `${root}/packages/b/src/x.ts`,150      }),151    },152    {153      expected: deny([154        new TouchedJudge({155          paths: [RepoPath.make(`${Brand.configDir}/project.ts`)],156        }),157      ]),158      name: "an Edit of the config folder is denied as TouchedJudge",159      payload: tool("Edit", {160        file_path: `${root}/${Brand.configDir}/project.ts`,161        new_string: "b",162        old_string: "a",163      }),164    },165    {166      expected: {},167      name: "a MultiEdit inside the territory is allowed",168      payload: tool("MultiEdit", {169        edits: [],170        file_path: `${root}/packages/a/src/week.ts`,171      }),172    },173    {174      expected: deny([175        new OutOfScope({ paths: [RepoPath.make("packages/b/notes.ipynb")] }),176      ]),177      name: "a NotebookEdit is judged by its notebook_path",178      payload: tool("NotebookEdit", {179        new_source: "",180        notebook_path: `${root}/packages/b/notes.ipynb`,181      }),182    },183    {184      expected: {},185      name: "Bash is the gateway's to judge, so it is allowed",186      payload: tool("Bash", { command: "rm -rf packages/b" }),187    },188    {189      expected: {},190      name: "Read changes nothing, so it is allowed",191      payload: tool("Read", { file_path: `${root}/${Brand.configDir}/x.ts` }),192    },193    {194      expected: {},195      name: "a file outside the repo is not ours to judge",196      payload: tool("Write", { content: "", file_path: "/tmp/scratch.ts" }),197    },198    {199      expected: deny([new TouchedJudge({ paths: [RepoPath.make(checkPath)] })]),200      name: "the ask's own check, inside the territory, is TouchedJudge",201      payload: tool("Edit", { file_path: `${root}/${checkPath}` }),202    },203    {204      expected: deny([205        new TouchedJudge({206          paths: [RepoPath.make("packages/a/vitest.config.ts")],207        }),208      ]),209      name: "a judged file inside the territory is TouchedJudge, not OutOfScope",210      payload: tool("Write", {211        file_path: `${root}/packages/a/vitest.config.ts`,212      }),213    },214    {215      expected: deny([216        new OutOfScope({ paths: [RepoPath.make("packages/b/src/y.ts")] }),217      ]),218      name: "a relative path is read from the harness's cwd, with .. resolved",219      payload: input({220        cwd: `${root}/packages/a`,221        tool_input: { file_path: "../b/src/./y.ts" },222        tool_name: "Write",223      }),224    },225  ])("$name", ({ expected, payload }) => {226    expect(decideHook("pre-tool-use", payload, facts).output).toStrictEqual(227      expected228    );229  });230231  it("allows every edit when the session has no claim, and says why", () => {232    const decision = decideHook(233      "pre-tool-use",234      tool("Write", { file_path: `${root}/packages/b/src/x.ts` }),235      { ...facts, claim: Option.none() }236    );237238    expect(decision.output).toStrictEqual({});239    expect(Option.isSome(decision.note)).toBeTruthy();240  });241});242243describe("session-start", () => {244  const start = input({ hook_event_name: "SessionStart" });245246  it("briefs the agent on its claim: the want, the territory and the check", () => {247    const { output } = decideHook("session-start", start, facts);248249    const context = Schema.decodeUnknownSync(250      Schema.Struct({251        hookSpecificOutput: Schema.Struct({252          additionalContext: Schema.String,253          hookEventName: Schema.Literal("SessionStart"),254        }),255      })256    )(output).hookSpecificOutput.additionalContext;257258    expect(context).toContain(claim.want);259    expect(context).toContain("`packages/a/**`");260    expect(context).toContain("`packages/a/src/index.ts`");261    expect(context).toContain(`\`${claim.checkCommand}\``);262    expect(context.split("\n")).toContain(263      `Run \`${Brand.cli} check\` before you push.`264    );265  });266267  it("briefs a paths territory as its paths, not as the module `.`", () => {268    const { territory } = Schema.decodeSync(Ask)({269      ...askWire,270      territory: { module: ".", paths: ["src/trim.ts", "test/trim.test.ts"] },271    });272273    const { output } = decideHook("session-start", start, {274      ...facts,275      claim: Option.some({ ...claim, territory }),276    });277278    const context = Schema.decodeUnknownSync(279      Schema.Struct({280        hookSpecificOutput: Schema.Struct({ additionalContext: Schema.String }),281      })282    )(output).hookSpecificOutput.additionalContext;283284    expect(context.split("\n")).toContain(285      "**Territory:** these paths. Change only these:"286    );287    expect(context).not.toContain("module");288  });289290  it("says nothing to the agent without a claim", () => {291    expect(292      decideHook("session-start", start, { ...facts, claim: Option.none() })293        .output294    ).toStrictEqual({});295  });296});297298const stop = (fields: Partial<HookInput> = {}) =>299  input({ hook_event_name: "Stop", stop_hook_active: false, ...fields });300301const hold = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({302  decision: "block",303  reason: explain(refusals).join("\n"),304});305306describe("stop", () => {307  it("holds the agent with the check's refusal as the reason", () => {308    const decision = decideHook("stop", stop(), {309      ...facts,310      refusals: [weakened],311    });312313    expect(decision.output).toStrictEqual(hold([weakened]));314    expect(decision.holds).toBe(1);315  });316317  it("holds a third time in a row, and that hold is the last", () => {318    const third = decideHook("stop", stop({ stop_hook_active: true }), {319      ...facts,320      holds: 2,321      refusals: [weakened],322    });323324    expect(third.output).toStrictEqual(hold([weakened]));325    expect(third.holds).toBe(3);326327    const fourth = decideHook("stop", stop({ stop_hook_active: true }), {328      ...facts,329      holds: 3,330      refusals: [weakened],331    });332333    expect(fourth.output).toStrictEqual({});334    expect(fourth.holds).toBe(0);335    expect(Option.getOrElse(fourth.note, () => "")).toContain("Weakened");336  });337338  it("counts Claude Code's stop_hook_active as a hold in a row", () => {339    // The session's count was lost, but Claude Code says this stop follows a340    // hold: it is the second in a row.341    const decision = decideHook("stop", stop({ stop_hook_active: true }), {342      ...facts,343      holds: 0,344      refusals: [weakened],345    });346347    expect(decision.output).toStrictEqual(hold([weakened]));348    expect(decision.holds).toBe(2);349  });350351  it("lets the agent stop when the check is clean", () => {352    const decision = decideHook("stop", stop(), { ...facts, holds: 2 });353354    expect(decision.output).toStrictEqual({});355    expect(decision.holds).toBe(0);356  });357358  it("never holds on a retryable wait alone, and explains only what the agent can fix", () => {359    const busy = new RepoBusy({});360361    expect(362      decideHook("stop", stop(), { ...facts, refusals: [busy] }).output363    ).toStrictEqual({});364    expect(365      decideHook("stop", stop(), { ...facts, refusals: [busy, weakened] })366        .output367    ).toStrictEqual(hold([weakened]));368  });369370  it("lets the agent stop without a claim", () => {371    expect(372      decideHook("stop", stop(), {373        ...facts,374        claim: Option.none(),375        refusals: [weakened],376      }).output377    ).toStrictEqual({});378  });379});380381describe("the gateway's own reading of a path", () => {382  const policy = Schema.decodeSync(Policy)({383    agents: "trailer",384    asks: [askWire],385    at: landedSha,386    budget: { decisionsPerDay: 5, expireDays: 14 },387    caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },388    claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },389    deciders: [{ handles: ["bob"], paths: "**" }],390    functions: { admit: false, opensAlone: false },391    judge: judgeClosure(392      Schema.decodeSync(RunBlock)({393        checks: { lint: "bun run lint" },394        test: "bun test {path}",395      }),396      [397        {398          content: '{"extends": "./tsconfig.base.json"}',399          path: "tsconfig.json",400        },401        { content: "{}", path: "tsconfig.base.json" },402        { content: '{"scripts": {}}', path: "package.json" },403      ]404    ),405    kinds: [],406    modules: [askWire.territory, { module: "b", paths: ["packages/b/**"] }],407    ratchets: [],408    record: { countsAfterDays: 30, windowDays: 365 },409    run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },410    source: "config",411    vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },412    vouches: [],413    weakening: { markers: [] },414  });415416  const push = (path: string): PushFacts => ({417    addedLines: new Map(),418    ask: Option.some(ask),419    base: sha("1"),420    changes: [{ path: RepoPath.make(path), status: "modified" }],421    claim: Option.none(),422    claimsHeld: 1,423    head: sha("2"),424    landed: LandedSha.make(sha("4")),425    layerPaths: new Set(),426    opensAsk: false,427    policy,428    pusher: Person.make({ handle: Handle.make("alice") }),429    ref: RefNameText.make("refs/heads/main"),430    scriptsChanged: false,431    target: PushTarget.ClaimFork({432      ask: ask.id,433      claimant: Handle.make("alice"),434      project: ask.project,435    }),436  });437438  const session: HookFacts = {439    ...facts,440    judge: askJudge(policy.judge, ask),441  };442443  it.effect.each([444    "packages/a/src/week.ts",445    "packages/b/src/x.ts",446    `${Brand.configDir}/project.ts`,447    `${Brand.configDir}/asks/fix-week.ask.ts`,448    checkPath,449    "packages/a/test/other.test.ts",450    "packages/a/vitest.config.ts",451    "packages/a/tsconfig.json",452    "tsconfig.base.json",453    ".github/workflows/ci.yml",454    "package.json",455    "packages/a/.env.production",456    "packages/a/.env.production.local",457    "README.md",458  ])("%s: the hook denies what the shape stage refuses, in its words", (path) =>459    Effect.gen(function* () {460      const refusals = (yield* scan.run(push(path))).filter(461        (refusal) =>462          Schema.is(OutOfScope)(refusal) || Schema.is(TouchedJudge)(refusal)463      );464465      const decision = decideHook(466        "pre-tool-use",467        tool("Edit", { file_path: `${root}/${path}` }),468        session469      );470471      expect(decision.output).toStrictEqual(472        Array.isReadonlyArrayNonEmpty(refusals) ? deny(refusals) : {}473      );474    })475  );476});477478const liveClaim = (base: string) =>479  Schema.decodeSync(ClaimView)({480    ask: "fix-week",481    base,482    checkCommand: claim.checkCommand,483    claimant: "alice",484    fork: "datekit--fix-week--alice",485    lapsesAt: "2026-10-08T12:00:00.000Z",486    openedAt: "2026-10-07T12:00:00.000Z",487    project: "oscabriel/datekit",488    remote: "https://platform.example/datekit--fix-week--alice.git",489    state: "live",490    warnsAt: "2026-10-07T14:00:00.000Z",491  });492493const aClone = (remote: string) =>494  Effect.gen(function* () {495    const fs = yield* FileSystem.FileSystem;496    const path = yield* Path.Path;497    const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());498499    const files = new Map([500      [`${Brand.configDir}/project.ts`, "export default {};\n"],501      [checkPath, "test('week', () => {});\n"],502      [503        "package.json",504        '{"name": "oscabriel/datekit", "scripts": {"test": "bun test"}}\n',505      ],506      ["packages/a/src/index.ts", "export {};\n"],507      ["packages/b/src/x.ts", "export {};\n"],508      // The judge closure follows a tsconfig's `extends` among the root's files.509      ["base.json", "{}\n"],510      ["tsconfig.json", '{"extends": "./base"}\n'],511      // And the scripts a harness's hook config runs, with what they import,512      // wherever they sit, as the platform's closure does.513      [514        ".claude/settings.json",515        JSON.stringify({516          hooks: {517            PreToolUse: [518              { hooks: [{ command: "bun scripts/hooks/guard.ts" }] },519            ],520          },521        }),522      ],523      ["scripts/hooks/guard.ts", 'import "./lib/policy.ts";\n'],524      ["scripts/hooks/lib/policy.ts", "export {};\n"],525    ]);526527    for (const [file, content] of files) {528      yield* fs.makeDirectory(path.dirname(path.join(dir, file)), {529        recursive: true,530      });531      yield* fs.writeFileString(path.join(dir, file), content);532    }533534    yield* gitOk(dir, "init", "--quiet", "--initial-branch", "main");535    yield* gitOk(dir, "add", "--all");536    yield* gitOk(dir, "commit", "--quiet", "--message", "base");537    yield* gitOk(dir, "remote", "add", "origin", remote);538539    return { base: yield* gitOk(dir, "rev-parse", "HEAD"), dir };540  });541542const platformOf = (543  claims: Ref.Ref<readonly ClaimView[]>,544  asked: Ref.Ref<{ readonly showAsk: number; readonly status: number }>545) =>546  Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(547    Layer.provide([548      Layer.mergeAll(549        unanswered,550        Contracts.toLayerHandler("showAsk", () =>551          Effect.as(552            Ref.update(asked, (count) => ({553              ...count,554              showAsk: count.showAsk + 1,555            })),556            { ask, brief: `# ${ask.id}` }557          )558        ),559        Contracts.toLayerHandler("status", () =>560          Effect.zipWith(561            Ref.get(claims),562            Ref.update(asked, (count) => ({563              ...count,564              status: count.status + 1,565            })),566            (held) => ({567              answers: [],568              claims: held,569              handle: Handle.make("alice"),570            })571          )572        )573      ),574      asPerson(Handle.make("alice")),575    ])576  );577578const platformFor = (base: string) =>579  Effect.gen(function* () {580    const asked = yield* Ref.make({ showAsk: 0, status: 0 });581582    return {583      asked,584      platform: platformOf(585        yield* Ref.make<readonly ClaimView[]>([liveClaim(base)]),586        asked587      ),588    };589  });590591interface Ran {592  readonly code: number;593  readonly out: readonly string[];594  readonly err: readonly string[];595}596597interface StateEnv {598  readonly HOME?: string;599  readonly XDG_STATE_HOME?: string;600}601602const runHook = (603  argv: readonly string[],604  stdin: string,605  env: string | StateEnv,606  services: Layer.Layer<Client> | Layer.Layer<Client | PushCheck>607) =>608  Effect.gen(function* () {609    const exit = yield* Effect.exit(program(argv));610611    return {612      code: Exit.match(exit, {613        onFailure: (cause) => Runtime.getErrorExitCode(Cause.squash(cause)),614        onSuccess: () => 0,615      }),616      err: (yield* TestConsole.errorLines).map(String),617      out: (yield* TestConsole.logLines).map(String),618    } satisfies Ran;619  }).pipe(620    Effect.provide(621      Layer.mergeAll(622        NodeServices.layer,623        TestConsole.layer,624        CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),625        OutputPlain,626        services,627        SignedOut,628        ConfigProvider.layer(629          ConfigProvider.fromEnv({630            env: Predicate.isString(env) ? { XDG_STATE_HOME: env } : { ...env },631          })632        ),633        // Last, so it stands in for the process's own stdio.634        Stdio.layerTest({635          stdin: Stream.make(new TextEncoder().encode(stdin)),636        })637      )638    )639  );640641const touchedJudgeOf = (path: string) =>642  new TouchedJudge({ paths: [RepoPath.make(path)] });643644const tempDir = Effect.flatMap(FileSystem.FileSystem, (fs) =>645  fs.makeTempDirectoryScoped()646);647648const fork = "https://platform.example/datekit--fix-week--alice.git";649650describe(`${Brand.cli} hook, as a harness runs it`, () => {651  it.live(652    "briefs the session once, then denies an edit with the gateway's text, asking the platform nothing more",653    () =>654      Effect.gen(function* () {655        const { base, dir } = yield* aClone(fork);656        const state = yield* tempDir;657        const { asked, platform } = yield* platformFor(base);658659        const started = yield* runHook(660          ["hook", "session-start", "--json"],661          JSON.stringify({662            cwd: dir,663            hook_event_name: "SessionStart",664            session_id: "s-1",665            source: "startup",666          }),667          state,668          platform669        );670671        expect(started.code).toBe(0);672        expect(started.out.join("\n")).toContain(claim.checkCommand);673674        const edit = (file: string) =>675          runHook(676            ["hook", "pre-tool-use", "--json"],677            JSON.stringify({678              cwd: dir,679              hook_event_name: "PreToolUse",680              session_id: "s-1",681              tool_input: { content: "", file_path: `${dir}/${file}` },682              tool_name: "Write",683            }),684            state,685            // The session's facts are kept: the platform is not asked again.686            Layer.mock(Client)({})687          );688689        const edits = [690          yield* edit("packages/b/src/x.ts"),691          yield* edit(checkPath),692          yield* edit("packages/a/src/week.ts"),693          yield* edit("base.json"),694          yield* edit("scripts/hooks/lib/policy.ts"),695        ];696697        const outOfScope = new OutOfScope({698          paths: [RepoPath.make("packages/b/src/x.ts")],699        });700701        expect(edits).toStrictEqual([702          { code: 0, err: [], out: [JSON.stringify(deny([outOfScope]))] },703          {704            code: 0,705            err: [],706            out: [JSON.stringify(deny([touchedJudgeOf(checkPath)]))],707          },708          { code: 0, err: [], out: ["{}"] },709          {710            code: 0,711            err: [],712            out: [JSON.stringify(deny([touchedJudgeOf("base.json")]))],713          },714          {715            code: 0,716            err: [],717            out: [718              JSON.stringify(719                deny([touchedJudgeOf("scripts/hooks/lib/policy.ts")])720              ),721            ],722          },723        ]);724        expect((yield* Ref.get(asked)).showAsk).toBe(1);725      }).pipe(Effect.provide(NodeServices.layer))726  );727728  it.live(729    "holds a stop three times in a row while the check refuses, then lets it go with a note",730    () =>731      Effect.gen(function* () {732        const { base, dir } = yield* aClone(fork);733        const state = yield* tempDir;734        const { platform } = yield* platformFor(base);735        const asked: string[] = [];736737        const refusing = Layer.mergeAll(738          platform,739          Layer.succeed(PushCheck)({740            run: (_root, from) =>741              Effect.as(742                Effect.sync(() => asked.push(from)),743                [weakened]744              ),745          })746        );747748        const stopRun = runHook(749          ["hook", "stop", "--json"],750          JSON.stringify({751            cwd: dir,752            hook_event_name: "Stop",753            session_id: "s-2",754            stop_hook_active: false,755          }),756          state,757          refusing758        );759760        const held = JSON.stringify(hold([weakened]));761762        for (const _ of [1, 2, 3]) {763          expect((yield* stopRun).out).toStrictEqual([held]);764        }765766        const fourth = yield* stopRun;767768        expect(fourth.out).toStrictEqual(["{}"]);769        expect(fourth.code).toBe(0);770        expect(fourth.err.join("\n")).toContain("Weakened");771        expect((yield* stopRun).out).toStrictEqual([held]);772        // Each check starts from the claim's base, not from main.773        expect(new Set(asked)).toStrictEqual(new Set([base]));774      }).pipe(Effect.provide(NodeServices.layer))775  );776777  it.live(778    "lets a stop go when the hold could not be counted, so the cap of three still binds",779    () =>780      Effect.gen(function* () {781        const fs = yield* FileSystem.FileSystem;782        const path = yield* Path.Path;783        const { base, dir } = yield* aClone(fork);784        const { platform } = yield* platformFor(base);785786        // The state home is a file: no session's state can be kept under it.787        const blocked = path.join(yield* tempDir, "state");788789        yield* fs.writeFileString(blocked, "");790791        const refusing = Layer.mergeAll(792          platform,793          Layer.succeed(PushCheck)({ run: () => Effect.succeed([weakened]) })794        );795796        const stops = yield* Effect.forEach(797          [false, true, true, true],798          (again) =>799            runHook(800              ["hook", "stop", "--json"],801              JSON.stringify({802                cwd: dir,803                hook_event_name: "Stop",804                session_id: "s-6",805                stop_hook_active: again,806              }),807              blocked,808              refusing809            )810        );811812        expect(stops.map(({ code, out }) => ({ code, out }))).toStrictEqual(813          globalThis.Array.from({ length: 4 }, () => ({ code: 0, out: ["{}"] }))814        );815        expect(stops[0]?.err.join("\n")).toContain(blocked);816      }).pipe(Effect.provide(NodeServices.layer))817  );818819  it.effect(820    "allows a session whose platform never answers once its time is up, and says why",821    () =>822      Effect.gen(function* () {823        const { dir } = yield* aClone(fork);824        const asked = yield* Deferred.make<string | undefined>();825826        const hung = Layer.mock(Client)({827          status: ({ project }) =>828            Effect.andThen(Deferred.succeed(asked, project), Effect.never),829        });830831        const running = yield* runHook(832          ["hook", "session-start", "--json"],833          JSON.stringify({834            cwd: dir,835            hook_event_name: "SessionStart",836            session_id: "s-7",837          }),838          yield* tempDir,839          hung840        ).pipe(Effect.forkChild);841842        expect(yield* Deferred.await(asked)).toBe("oscabriel/datekit");843844        yield* TestClock.adjust("10 seconds");845846        // A hook still waiting a real second later never answers.847        const ran = yield* Fiber.join(running).pipe(848          Effect.timeoutOption("1 second"),849          TestClock.withLive850        );851852        expect(853          Option.map(ran, ({ code, out }) => ({ code, out }))854        ).toStrictEqual(Option.some({ code: 0, out: ["{}"] }));855        expect(856          Option.getOrElse(857            Option.map(ran, ({ err }) => err.join("\n")),858            () => ""859          )860        ).toContain("did not answer");861      }).pipe(Effect.provide(NodeServices.layer))862  );863864  it.live(865    "keeps a session's facts under XDG_STATE_HOME, else under HOME's .local/state, readable by its owner alone",866    () =>867      Effect.gen(function* () {868        const fs = yield* FileSystem.FileSystem;869        const path = yield* Path.Path;870        const { base, dir } = yield* aClone(fork);871        const { platform } = yield* platformFor(base);872        const state = yield* tempDir;873        const home = yield* tempDir;874875        const start = (session: string, env: StateEnv) =>876          runHook(877            ["hook", "session-start", "--json"],878            JSON.stringify({879              cwd: dir,880              hook_event_name: "SessionStart",881              session_id: session,882            }),883            env,884            platform885          );886887        yield* start("s-8", { HOME: home, XDG_STATE_HOME: state });888        yield* start("s-9", { HOME: home });889890        const kept = [891          path.join(state, Brand.slug, "hooks", "s-8.json"),892          path.join(home, ".local", "state", Brand.slug, "hooks", "s-9.json"),893        ];894895        expect(896          yield* Effect.forEach(kept, (file) =>897            Effect.map(898              Effect.option(fs.stat(file)),899              Option.map(({ mode }) => mode % 0o1000)900            )901          )902        ).toStrictEqual([Option.some(0o600), Option.some(0o600)]);903      }).pipe(Effect.provide(NodeServices.layer))904  );905906  it.live.each([907    {908      check: Effect.fail(new PushCheckFailed({ reason: "it printed nothing" })),909      name: "fails",910      why: "it printed nothing",911    },912    {913      check: Effect.die("the check's process vanished"),914      name: "dies",915      why: "the check's process vanished",916    },917  ])(918    "lets a stop go when the local check $name, and says why",919    ({ check, why }) =>920      Effect.gen(function* () {921        const { base, dir } = yield* aClone(fork);922        const { platform } = yield* platformFor(base);923924        const ran = yield* runHook(925          ["hook", "stop", "--json"],926          JSON.stringify({927            cwd: dir,928            hook_event_name: "Stop",929            session_id: "s-10",930          }),931          yield* tempDir,932          Layer.mergeAll(933            platform,934            Layer.succeed(PushCheck)({ run: () => check })935          )936        );937938        expect({ code: ran.code, out: ran.out }).toStrictEqual({939          code: 0,940          out: ["{}"],941        });942        expect(ran.err.join("\n")).toContain(why);943      }).pipe(Effect.provide(NodeServices.layer))944  );945946  it.live("reads stdin it cannot parse as a reason to allow, and says so", () =>947    Effect.gen(function* () {948      const ran = yield* runHook(949        ["hook", "pre-tool-use", "--json"],950        "not json",951        yield* tempDir,952        Layer.mock(Client)({})953      );954955      expect(ran.code).toBe(0);956      expect(ran.out).toStrictEqual(["{}"]);957      expect(ran.err).toHaveLength(1);958    }).pipe(Effect.provide(NodeServices.layer))959  );960961  it.live("answers without --json too, for a person trying it by hand", () =>962    Effect.gen(function* () {963      const ran = yield* runHook(964        ["hook", "stop"],965        JSON.stringify({966          cwd: "/",967          hook_event_name: "Stop",968          session_id: "s-4",969        }),970        yield* tempDir,971        Layer.mock(Client)({})972      );973974      expect({ code: ran.code, out: ran.out }).toStrictEqual({975        code: 0,976        out: ["{}"],977      });978    }).pipe(Effect.provide(NodeServices.layer))979  );980981  it.live(982    "allows a session in a repo that is none of the platform's, and says why",983    () =>984      Effect.gen(function* () {985        const { dir } = yield* aClone("git@github.com:owner/datekit.git");986987        const ran = yield* runHook(988          ["hook", "session-start", "--json"],989          JSON.stringify({990            cwd: dir,991            hook_event_name: "SessionStart",992            session_id: "s-3",993          }),994          yield* tempDir,995          Layer.mock(Client)({})996        );997998        expect(ran.out).toStrictEqual(["{}"]);999        expect(ran.err.join("\n")).toContain("none of the platform's");1000      }).pipe(Effect.provide(NodeServices.layer))1001  );10021003  it.live(1004    "finds a claim taken mid-session at the next stop, in a clone of main, and guards from then on",1005    () =>1006      Effect.gen(function* () {1007        const { base, dir } = yield* aClone(1008          "https://platform.example/datekit.git"1009        );10101011        const state = yield* tempDir;1012        const claims = yield* Ref.make<readonly ClaimView[]>([]);1013        const asked = yield* Ref.make({ showAsk: 0, status: 0 });10141015        const platform = Layer.mergeAll(1016          platformOf(claims, asked),1017          Layer.succeed(PushCheck)({ run: () => Effect.succeed([weakened]) })1018        );10191020        const event = (name: string, fields: Partial<HookInput> = {}) =>1021          runHook(1022            ["hook", name, "--json"],1023            JSON.stringify({1024              cwd: dir,1025              hook_event_name: name,1026              session_id: "s-5",1027              ...fields,1028            }),1029            state,1030            platform1031          );10321033        const edit = event("pre-tool-use", {1034          tool_input: { file_path: `${dir}/packages/b/src/x.ts` },1035          tool_name: "Edit",1036        });10371038        const before = [yield* event("session-start"), yield* edit];10391040        yield* Ref.set(claims, [liveClaim(base)]);10411042        const after = [yield* edit, yield* event("stop"), yield* edit];10431044        expect([...before, ...after].map(({ out }) => out)).toStrictEqual([1045          ["{}"],1046          ["{}"],1047          // An edit before the stop still reads the facts kept at the start.1048          ["{}"],1049          [JSON.stringify(hold([weakened]))],1050          [1051            JSON.stringify(1052              deny([1053                new OutOfScope({1054                  paths: [RepoPath.make("packages/b/src/x.ts")],1055                }),1056              ])1057            ),1058          ],1059        ]);1060        expect(yield* Ref.get(asked)).toStrictEqual({ showAsk: 1, status: 2 });1061      }).pipe(Effect.provide(NodeServices.layer))1062  );10631064  it.live("refuses an event it does not answer as a usage error, exit 2", () =>1065    Effect.gen(function* () {1066      const ran = yield* runHook(1067        ["hook", "post-tool-use", "--json"],1068        "{}",1069        yield* tempDir,1070        Layer.mock(Client)({})1071      );10721073      expect(ran.code).toBe(2);1074      expect(ran.out).toStrictEqual([]);1075      expect(ran.err.join("\n")).toContain("session-start");1076    }).pipe(Effect.provide(NodeServices.layer))1077  );1078});10791080const encodeEnvelope = Schema.encodeSync(1081  Schema.fromJsonString(Envelope(Schema.Unknown))1082);10831084const checkPrinting = (stdout: string, code: number) =>1085  Effect.gen(function* () {1086    const fs = yield* FileSystem.FileSystem;1087    const path = yield* Path.Path;1088    const dir = yield* tempDir;1089    const printed = path.join(dir, "envelope.json");10901091    yield* fs.writeFileString(printed, stdout);10921093    const check = yield* Effect.provide(1094      Effect.service(PushCheck),1095      pushCheckWith(["sh", "-c", `cat '${printed}'; exit ${code}`])1096    );10971098    return yield* Effect.result(check.run(dir, "main"));1099  }).pipe(Effect.provide(NodeServices.layer));11001101describe("the default push check: this CLI, run again", () => {1102  it.live("reads the refusals from a refused envelope, though it exits 1", () =>1103    Effect.gen(function* () {1104      const result = yield* checkPrinting(1105        `${encodeEnvelope({ command: "check", ok: false, refusals: [weakened], v: 1 })}\n`,1106        11107      );11081109      expect(result).toStrictEqual(Result.succeed([weakened]));1110    })1111  );11121113  it.live("reads a passing envelope as no refusals", () =>1114    Effect.gen(function* () {1115      const result = yield* checkPrinting(1116        encodeEnvelope({ command: "check", data: {}, ok: true, v: 1 }),1117        01118      );11191120      expect(result).toStrictEqual(Result.succeed([]));1121    })1122  );11231124  it.live(1125    "asks the check from the claim's base, as the gateway diffs, so work committed on main is seen",1126    () =>1127      Effect.gen(function* () {1128        const fs = yield* FileSystem.FileSystem;1129        const path = yield* Path.Path;1130        const dir = yield* tempDir;1131        const args = path.join(dir, "args");1132        const printed = path.join(dir, "envelope.json");11331134        yield* fs.writeFileString(1135          printed,1136          encodeEnvelope({ command: "check", data: {}, ok: true, v: 1 })1137        );11381139        const check = yield* Effect.provide(1140          Effect.service(PushCheck),1141          pushCheckWith([1142            "sh",1143            "-c",1144            `printf '%s\\n' "$@" > '${args}'; cat '${printed}'`,1145            "check",1146          ])1147        );11481149        yield* check.run(dir, sha("1"));11501151        expect((yield* fs.readFileString(args)).split("\n")).toStrictEqual([1152          "check",1153          "--shape-only",1154          "--offline",1155          "--json",1156          "--base",1157          sha("1"),1158          "",1159        ]);1160      }).pipe(Effect.provide(NodeServices.layer))1161  );11621163  it.live("fails, for the hook to allow, when no envelope comes back", () =>1164    Effect.gen(function* () {1165      const result = yield* checkPrinting("error: not built", 1);11661167      expect(Result.isFailure(result)).toBeTruthy();1168    })1169  );11701171  it.each([1172    {1173      expected: ["/usr/bin/bun", "/home/a/cli/src/bin.ts"],1174      started: {1175        argv: ["/usr/bin/bun", "/home/a/cli/src/bin.ts", "hook"],1176        execPath: "/usr/bin/bun",1177      },1178    },1179    {1180      expected: [`/usr/local/bin/${Brand.cli}`],1181      started: {1182        argv: ["bun", `/$bunfs/root/${Brand.cli}`, "hook"],1183        execPath: `/usr/local/bin/${Brand.cli}`,1184      },1185    },1186  ])(1187    "runs $expected for a CLI started as $started.argv",1188    ({ expected, started }) => {1189      expect(selfCommand(started)).toStrictEqual(expected);1190    }1191  );1192});