8000 feat: run the first turn of a review in a throwaway worktree by dominikwozniak · Pull Request #29 · dominikwozniak/dw-mc · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/v1-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ repos:

Each line says whether it was run or read.

- Run: `claude -p "/code-review low" --output-format stream-json` works headless. The findings come back as text in `result`, one `file:line — description` per line. No `ReportFindings` tool call appears in the stream and `structured_output` is empty.
- Run: `claude -p "/code-review low" --output-format stream-json --verbose` works headless; in print mode that output format refuses without `--verbose`. The findings come back as text in `result`, one `file:line — description` per line, beside the `session_id`. No `ReportFindings` tool call appears in the stream and `structured_output` is empty.
- Run: a detached worktree cut from the tool's own bare clone is enough for the built-in review: the clone carries `refs/heads/main`, so `git merge-base HEAD main` resolves there and the review diffs the pull request against the base branch as it would in my own checkout. Neither `git clone --bare` nor `gh repo clone -- --bare` writes a `remote.origin.fetch`, so that base branch only moves on where the fetch asks for it by refspec.
- Run: the report is every assistant turn's text, not the `result` alone. A repository whose own `/code-review` fans out to subagents ends on a remark about the notification that came back, and that remark is what `result` carries; the report is the turn before it.
- Run: passing `--json-schema` on that same call breaks it: `result` becomes `Command completed`.
- Run: `claude -p --resume <session_id> "Report the findings as structured output…" --output-format json --json-schema <schema>` returns the findings as validated JSON under `structured_output`, with line numbers more accurate than the text. The `session_id` comes from the first call's JSON result.
- Run: `claude -p "/security-review"` headless returns nothing: zero turns, empty result. Not a runner.
Expand Down
136 changes: 136 additions & 0 deletions src/adapters/git.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { assert, describe, it } from "@effect/vitest"
import { ConfigProvider, Effect, Layer, Path } from "effect"

import { withWorktree } from "#adapters/git.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"

const state = "/home/dw/.local/state/dw-mc"
const clone = `${state}/repos/dominikwozniak/dw-mc.git`
const worktree = `${state}/worktrees/dominikwozniak/dw-mc/28`
const head = "284d599022a55d4dcae74b31b9a49a0f50061014"
const fetched = `-C ${clone} fetch --no-tags --force origin +refs/pull/28/head:refs/dw-mc/pr/28 +refs/heads/*:refs/heads/*`

/** What the real `git` says, captured from `git` itself. */
const said = {
noRepository: `fatal: cannot change to '${clone}': No such file or directory\n`,
conflict: "fatal: 'refs/pull/28/head' does not appear to be a git repository\n"
}

/** A `git` that answers from fixtures and records every vector handed to it. */
const git = (options: {
readonly spawned: Array<string>
/** Whether the bare clone is already there. */
readonly cloned?: boolean | undefined
/** The vector that refuses, and what `git` says on stderr instead. */
readonly refuses?: { readonly argv: string; readonly detail: string } | undefined
}) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("git.test: the fake was handed a piped command")
}
const argv = command.args.join(" ")
options.spawned.push(`${command.command} ${argv}`)

if (options.refuses?.argv === argv) {
return Effect.succeed(fakeHandle({ exitCode: 128, stderr: options.refuses.detail }))
}
if (argv === `-C ${clone} rev-parse --is-bare-repository`) {
return options.cloned === true
? Effect.succeed(fakeHandle({ stdout: "true\n" }))
: Effect.succeed(fakeHandle({ exitCode: 128, stderr: said.noRepository }))
}
if (argv === `-C ${clone} rev-parse refs/dw-mc/pr/28`) {
return Effect.succeed(fakeHandle({ stdout: `${head}\n` }))
}
return Effect.succeed(fakeHandle({}))
})

const machine = (spawner: Layer.Layer<never> | ReturnType<typeof git>) =>
Layer.mergeAll(ConfigProvider.layer(ConfigProvider.fromEnvRecord({ HOME: "/home/dw" })), Path.layer, spawner)

describe("the tool's own clone and its throwaway worktree", () => {
it.effect("cuts the worktree at the pull request's head and takes it down after", () => {
const spawned: Array<string> = []

return Effect.gen(function* () {
const cut = yield* withWorktree("dominikwozniak/dw-mc", 28, (worktree_) => Effect.succeed(worktree_))

assert.deepStrictEqual(cut, { directory: worktree, head })
assert.deepStrictEqual(spawned, [
`git -C ${clone} rev-parse --is-bare-repository`,
`git clone --bare --filter=blob:none https://github.com/dominikwozniak/dw-mc.git ${clone}`,
`git ${fetched}`,
`git -C ${clone} rev-parse refs/dw-mc/pr/28`,
`git -C ${clone} worktree remove --force ${worktree}`,
`git -C ${clone} worktree add --detach ${worktree} ${head}`,
`git -C ${clone} worktree remove --force ${worktree}`
])
}).pipe(Effect.provide(machine(git({ spawned }))))
})

it.effect("brings the base branch up to date with the pull request's head", () => {
const spawned: Array<string> = []

return Effect.gen(function* () {
yield* withWorktree("dominikwozniak/dw-mc", 28, () => Effect.void)

// A bare clone is made with no refspec, so nothing else moves `main` on:
// a review diffing against it would report every commit since the clone.
assert.include(spawned, `git ${fetched}`)
assert.include(fetched, "+refs/heads/*:refs/heads/*")
}).pipe(Effect.provide(machine(git({ spawned, cloned: true }))))
})

it.effect("clones once and fetches every run after that", () => {
const spawned: Array<string> = []

return Effect.gen(function* () {
yield* withWorktree("dominikwozniak/dw-mc", 28, () => Effect.void)

assert.isFalse(spawned.some((vector) => vector.startsWith("git clone")))
assert.include(spawned, `git ${fetched}`)
}).pipe(Effect.provide(machine(git({ spawned, cloned: true }))))
})

it.effect("takes the worktree down when the run failed", () => {
const spawned: Array<string> = []

return Effect.gen(function* () {
const error = yield* Effect.flip(
8000 withWorktree("dominikwozniak/dw-mc", 28, () => Effect.fail("the runner gave up" as const))
)

assert.strictEqual(error, "the runner gave up")
assert.strictEqual(spawned.at(-1), `git -C ${clone} worktree remove --force ${worktree}`)
}).pipe(Effect.provide(machine(git({ spawned, cloned: true }))))
})

it.effect("never reaches outside the state directory", () => {
const spawned: Array<string> = []

return Effect.gen(function* () {
yield* withWorktree("dominikwozniak/dw-mc", 28, () => Effect.void)

assert.isTrue(
spawned.every((vector) => vector.startsWith(`git -C ${clone} `) || vector.startsWith("git clone --bare")),
spawned.join("\n")
)
}).pipe(Effect.provide(machine(git({ spawned }))))
})

it.effect("hands on what git said when git refuses", () => {
const spawned: Array<string> = []
const refuses = { argv: fetched, detail: said.conflict }

return Effect.gen(function* () {
const error = yield* Effect.flip(withWorktree("dominikwozniak/dw-mc", 28, () => Effect.void))

if (error._tag !== "GitFailed") {
return assert.fail(`expected a GitFailed, got ${error._tag}`)
}
assert.include(error.message, "does not appear to be a git repository")
assert.include(error.message, "fetch")
assert.isFalse(spawned.some((vector) => vector.includes("worktree add")))
}).pipe(Effect.provide(machine(git({ spawned, cloned: true, refuses }))))
})
})
89 changes: 89 additions & 0 deletions src/adapters/git.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Effect, Path, Schema } from "effect"

import { capture } from "#adapters/spawner.ts"
import { stateDirectory } from "#adapters/store.ts"

/** A `git` command that ran and refused, or would not run at all. */
export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {
args: Schema.Array(Schema.String),
detail: Schema.String
}) {
override get message(): string {
return `git ${this.args.join(" ")} failed: ${this.detail}`
}
}

/** One `git` command, with both ways it can go wrong in our words. */
const git = (args: ReadonlyArray<string>) =>
capture("git", args).pipe(
Effect.catchTags({
PlatformError: (error) => Effect.fail(new GitFailed({ args, detail: error.message })),
CommandFailed: (error) => Effect.fail(new GitFailed({ args, detail: error.stderr }))
})
)

/** A checkout cut for one run, and the commit it stands on. */
export interface Worktree {
readonly directory: string
readonly head: string
}

/**
* Runs `use` in a throwaway worktree at the head of `number`, and takes the
* worktree down afterwards however the run ended.
*
* Everything happens in the tool's own bare clone under the state directory, so
* my checkout is neither read nor written while a run is going: a review that
* reached into the directory I am working in would review whatever I had half
* finished there, and a run that left a worktree behind would grow the state
* directory by a copy of the repository per run.
*
* The clone is made once and fetched on every run after that. The fetch brings
* the branch heads with the pull request's own, because a bare clone is made
* with no refspec at all: without them the base branch stays at whatever it was
* the day the clone was made, and a review that diffs against it would report
* every commit since as the pull request's.
*
* The head comes from the pull request's ref rather than from what a sweep last
* saw, so what the run is recorded against is the commit it actually read. The
* worktree is removed before it is cut as well as after, because the run before
* this one may have been killed rather than ended.
*/
export const withWorktree = Effect.fn("git.withWorktree")(function* <A, E, R>(
repo: string,
number: number,
use: (worktree: Worktree) => Effect.Effect<A, E, R>
) {
const path = yield* Path.Path
const state = yield* stateDirectory
const clone = path.join(state, "repos", `${repo}.git`)
const directory = path.join(state, "worktrees", repo, String(number))

const bare = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", "--is-bare-repository"]), () => "")
if (bare !== "true") {
yield* git(["clone", "--bare", "--filter=blob:none", `https://github.com/${repo}.git`, clone])
}

const pullRef = `refs/dw-mc/pr/${number}`
yield* git([
"-C",
clone,
"fetch",
"--no-tags",
"--force",
"origin",
`+refs/pull/${number}/head:${pullRef}`,
"+refs/heads/*:refs/heads/*"
])
const head = yield* git(["-C", clone, "rev-parse", pullRef])

// A worktree that is not there cannot be removed, and that is the ordinary
// case rather than a problem: both ends of the run ask for the same thing.
const remove = Effect.ignore(git(["-C", clone, "worktree", "remove", "--force", directory]))

return yield* Effect.acquireUseRelease(
Effect.flatMap(remove, () => git(["-C", clone, "worktree", "add", "--detach", directory, head])),
() => use({ directory, head }),
() => remove
)
})
65 changes: 65 additions & 0 deletions src/adapters/notify.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { assert, describe, it } from "@effect/vitest"
import { Effect, Layer, PlatformError } from "effect"

import { announce } from "#adapters/notify.ts"
import { layerScripted } from "#adapters/picker.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"

const desktop = (spawned: Array<ReadonlyArray<string>>) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("notify.test: the fake was handed a piped command")
}
spawned.push([command.command, ...command.args])
return Effect.succeed(fakeHandle({}))
})

const noDesktop = layerFake(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "spawn osascript ENOENT"
})
)
)

describe("the end of a run", () => {
it.effect("rings the terminal and puts the news on the desktop", () => {
const spawned: Array<ReadonlyArray<string>> = []
const drawn: Array<string> = []

return Effect.gen(function* () {
yield* announce("dw-mc review", "dominikwozniak/dw-mc#28: 3 findings")

assert.deepStrictEqual(drawn, ["\u0007"])
assert.deepStrictEqual(spawned, [
["osascript", "-e", `display notification "dominikwozniak/dw-mc#28: 3 findings" with title "dw-mc review"`]
])
}).pipe(Effect.provide(Layer.mergeAll(layerScripted([], drawn), desktop(spawned))))
})

it.effect("says it in a quotation mark the notification cannot end early", () => {
const spawned: Array<ReadonlyArray<string>> = []

return Effect.gen(function* () {
yield* announce("dw-mc review", `a "quoted" \\ backslash`)

assert.strictEqual(
spawned[0]?.[2],
`display notification "a \\"quoted\\" \\\\ backslash" with title "dw-mc review"`
)
}).pipe(Effect.provide(Layer.mergeAll(layerScripted([]), desktop(spawned))))
})

it.effect("ends the run anyway on a machine that cannot show a notification", () => {
const drawn: Array<string> = []

return Effect.gen(function* () {
yield* announce("dw-mc review", "dominikwozniak/dw-mc#28: 3 findings")

assert.deepStrictEqual(drawn, ["\u0007"])
}).pipe(Effect.provide(Layer.mergeAll(layerScripted([], drawn), noDesktop)))
})
})
23 changes: 23 additions & 0 deletions src/adapters/notify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Effect, Terminal } from "effect"

import { capture } from "#adapters/spawner.ts"

/** A string as AppleScript spells one, so a quotation mark cannot end it early. */
const quoted = (text: string): string => `"${text.replaceAll("\\", "\\\\").replaceAll(`"`, `\\"`)}"`

/**
* Says a foreground run has ended, twice: the bell for the terminal I left, and
* a desktop notification for the window I went to instead.
*
* A review run takes minutes, and the whole point of it running in the
* foreground is that I go and do something else while it does. Neither half is
* worth failing a finished run over: `osascript` is macOS's, and a machine
* without it still finished the review.
*/
export const announce = Effect.fn("notify.announce")(function* (title: string, message: string) {
const terminal = yield* Terminal.Terminal
yield* Effect.ignore(terminal.display("\u0007"))
yield* Effect.ignore(
capture("osascript", ["-e", `display notification ${quoted(message)} with title ${quoted(title)}`])
)
})
13 changes: 10 additions & 3 deletions src/adapters/picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,22 @@ export const key = (name: string): Terminal.UserInput => ({
})

/**
* A terminal that answers with `keys` and draws nowhere, for tests.
* A terminal that answers with `keys` and draws into `drawn`, for tests.
*
* Effect ships no test terminal, so this builds one from `Terminal.make`. A
* prompt only ever asks for `columns`, `display` and `readInput`; it never
* calls `readLine`. The keys are queued once, so a second prompt over the same
* terminal finds the script spent rather than replaying it. Running out of keys
* ends the queue, which a prompt reads as the user quitting.
*
* What is drawn is kept only where a caller asks for it: a prompt redraws
* itself on every keypress, and a test that is about the answer does not want
* the frames.
*/
export const layerScripted = (keys: ReadonlyArray<Terminal.UserInput>): Layer.Layer<Terminal.Terminal> =>
export const layerScripted = (
keys: ReadonlyArray<Terminal.UserInput>,
drawn?: Array<string>
): Layer.Layer<Terminal.Terminal> =>
Layer.effect(
Terminal.Terminal,
Effect.gen(function* () {
Expand All @@ -47,7 +54,7 @@ export const layerScripted = (keys: ReadonlyArray<Terminal.UserInput>): Layer.La
rows: Effect.succeed(24),
readInput: Effect.succeed(queue),
readLine: Effect.die("picker: a prompt never reads a line"),
display: () => Effect.void
display: (text) => Effect.sync(() => drawn?.push(text))
})
})
)
Loading
0