8000 feat(state): take back the disk, and say goodbye by dominikwozniak · Pull Request #72 · 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
11 changes: 11 additions & 0 deletions .changeset/brave-moons-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"dw-mc": patch
---

`dw-mc cleanup` takes back the disk the tool spends on itself — the bare clones and the worktrees a
review run left behind — and keeps your configuration, your records and the clone of any repository a
`fix` or `resolve` session still stands on. `dw-mc uninstall` removes everything the tool wrote on the
machine, takes the configuration file too with `--config`, and prints the one step it cannot take:
removing the package. Both print what they would take with its weight and ask first, and neither
touches a session worktree holding uncommitted changes or a commit the pull request's head does not
have until `--force` says so.
14 changes: 14 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,17 @@ _Avoid_: icon, badge, glyph
**Block**:
How a command that reports rather than tabulates writes: a heading, an indented body, and a blank line before the next one. What each command says is its own; the shape is not.
_Avoid_: section, panel, group

### Housekeeping

**Clone**:
The bare copy of a repository mission control keeps for itself, and cuts every worktree from. It is never my checkout, and nothing in it is mine: a run that needs it again makes it again.
_Avoid_: cache, mirror, checkout

**Cleanup**:
Taking back the disk mission control spends on itself: the clones, and the worktrees a review run left behind. It keeps what I decided and what it recorded, and it leaves a clone a session stands on where it is, because that session's history lives inside it.
_Avoid_: prune, gc, purge

**Uninstall**:
Removing everything mission control wrote on this machine, which no package manager does. The state goes in full and the configuration file only when I ask; the binary is the one step it cannot take and prints instead.
_Avoid_: remove, reset, wipe
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ Every command that takes a pull request takes it as `62` inside the repository,
| `dw-mc resolve <pr>` | `--print` | Opens a session on the conflict that stopped a rebase. |
| `dw-mc rerun <pr>` | — | Runs a flaky red CI again, once per head. |
| `dw-mc merge <pr>` | — | Squash-merges a Ready, stamped pull request of yours and deletes its branch. |
| `dw-mc cleanup` | `--yes` | Takes back the disk spent on clones and review worktrees, and keeps everything you decided. |
| `dw-mc uninstall` | `--config`, `--force`, `--yes` | Removes everything the tool wrote on this machine, and says how to remove the binary. |

`dw-mc <command> --help` prints the flags and what each one is worth.

Expand Down Expand Up @@ -132,6 +134,18 @@ repos:
# the same keys, overriding defaults
```

## Taking it back

Removing the package removes the binary and nothing else — a package manager runs no uninstall script, so the two directories above would stay where they are. The tool takes them back itself.

```sh
dw-mc cleanup # the bare clones and the worktrees a review run left: disk the tool spends on itself
dw-mc uninstall # every record, report, clone and worktree
pnpm remove -g dw-mc
```

Both print what they would take, with its weight, and ask before taking it; `--yes` answers for a machine with no terminal. `cleanup` keeps your configuration and every record, and keeps the clone of a repository a `fix` or `resolve` session still stands on, because that session's history lives inside it. `uninstall` keeps the configuration file too unless `--config` asks for it. A worktree a `fix` or `resolve` session left standing is yours: `cleanup` never touches one, and `uninstall` names what it still holds — uncommitted changes, or a commit your pull request's head does not have — and removes nothing until `--force`.

## The skill

An agent session can reach mission control's state through the `/dw-mc` skill, which lives in this repository and calls the CLI and nothing else:
Expand Down
23 changes: 13 additions & 10 deletions skills/dw-mc/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,24 @@ Print findings again in the turn that needs them. The printed run is the state;

These change something, so run one only when I ask for it by name.

| I want | run |
| ------------------------------------------------------ | --------------------------------- |
| a review run against the current head | `dw-mc review <pr>` |
| that run where the re-run rule would skip it | `dw-mc review <pr> --force` |
| that run at a chosen effort, over the configured one | `dw-mc review <pr> --effort high` |
| the stamp off, until the head changes | `dw-mc stamp <pr> --withdraw` |
| the branch rebased onto its base and pushed | `dw-mc rebase <pr>` |
| a flaky red CI run again, once | `dw-mc rerun <pr>` |
| a Ready, stamped pull request landed | `dw-mc merge <pr>` |
| this machine set up and the repository I am in tracked | `dw-mc init` |
| I want | run |
| ----------------------------------------------------------- | --------------------------------- |
| a review run against the current head | `dw-mc review <pr>` |
| that run where the re-run rule would skip it | `dw-mc review <pr> --force` |
| that run at a chosen effort, over the configured one | `dw-mc review <pr> --effort high` |
| the stamp off, until the head changes | `dw-mc stamp <pr> --withdraw` |
| the branch rebased onto its base and pushed | `dw-mc rebase <pr>` |
| a flaky red CI run again, once | `dw-mc rerun <pr>` |
| a Ready, stamped pull request landed | `dw-mc merge <pr>` |
| this machine set up and the repository I am in tracked | `dw-mc init` |
| the disk the tool spent on clones and review worktrees back | `dw-mc cleanup` |

`dw-mc review` runs a model and takes minutes.

`dw-mc init` is what "No repositories registered" asks for. It writes my config on this machine and reaches nothing else.

`dw-mc cleanup` removes only what the tool rebuilds by itself, and never a worktree a session stands in. `dw-mc uninstall` removes everything the tool wrote and is mine to run, never yours: ask me for it rather than running it.

`dw-mc rebase`, `dw-mc rerun` and `dw-mc merge` are the three commands that write to GitHub, and the CLI owns all three: run them as they are, and leave every write of my own - comment, review, label, approval, status - unmade (ADR 0002).

`dw-mc rebase` and `dw-mc rerun` stay inside that boundary: a `--force-with-lease` push to a branch I author, and the failed jobs of a workflow run on a pull request I author. `dw-mc rerun` refuses a failure the classifier calls legitimate, and refuses a head it has already re-run, so running it on a red CI is never a way to hide one.
Expand Down
91 changes: 76 additions & 15 deletions src/adapters/git.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Effect, Path, Result, Schema } from "effect"

import { capture } from "#adapters/spawner.ts"
import { stateDirectory } from "#adapters/store.ts"
import type { Cut, Session } from "#adapters/store.ts"
import { clonesIn, stateDirectory, under } 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", {
Expand Down Expand Up @@ -41,7 +42,7 @@ export class WorktreeHeld extends Schema.TaggedError<WorktreeHeld>()("WorktreeHe
/**
* Where a worktree is cut from, what it is cut at, and where it goes: the tool's
* own bare clone of `repo`, the pull request's head, and a directory under
* `under` in the state directory.
* `cut` in the state directory.
*
* Everything happens in this clone and never in my checkout: a run that reached
* into the directory I am working in would read whatever I had half finished
Expand All @@ -56,14 +57,10 @@ export class WorktreeHeld extends Schema.TaggedError<WorktreeHeld>()("WorktreeHe
* The head comes from the pull request's ref rather than from what a sweep last
* saw, so what is cut is the commit the run really reads.
*/
const whereToCut = Effect.fn("git.whereToCut")(function* (
repo: string,
number: number,
under: "worktrees" | "fixes" | "rebases"
) {
const whereToCut = Effect.fn("git.whereToCut")(function* (repo: string, number: number, cut: Cut) {
const path = yield* Path.Path
const state = yield* stateDirectory
const clone = path.join(state, "repos", `${repo}.git`)
const clone = path.join(state, clonesIn, `${repo}.git`)

const bare = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", "--is-bare-repository"]), () => "")
if (bare !== "true") {
Expand All @@ -82,7 +79,7 @@ const whereToCut = Effect.fn("git.whereToCut")(function* (
"+refs/heads/*:refs/heads/*"
])
const head = yield* git(["-C", clone, "rev-parse", pullRef])
return { clone, head, directory: path.join(state, under, repo, String(number)) }
return { clone, head, directory: path.join(state, cut, repo, String(number)) }
})

/**
Expand Down Expand Up @@ -152,12 +149,6 @@ const perWorktreeConfig = Effect.fn("git.perWorktreeConfig")(function* (clone: s
yield* Effect.ignore(git(["-C", clone, "config", "--unset", "core.bare"]))
})

/** What a standing worktree is for, which names its branch and the directory it is cut in. */
export type Session = "fix" | "rebase"

/** Where each kind of session's worktrees live under the state directory. */
const under = { fix: "fixes", rebase: "rebases" } as const

/**
* Turns the clone's reuse of a resolution on, which is what the session on a
* conflict is worth beyond the one conflict.
Expand Down Expand Up @@ -402,3 +393,73 @@ export const rebaseOnto = Effect.fn("git.rebaseOnto")(function* (
})
)
})

/** What a standing session worktree still holds, or nothing at all. */
export type Holding = { readonly _tag: "clear" } | { readonly _tag: "held"; readonly detail: string }

const clear: Holding = { _tag: "clear" }

/**
* What the worktree of a fix or resolve session still holds, asked without
* reaching GitHub.
*
* Nothing that takes a directory away may fetch first: a command asked to
* remove things would be cloning to answer whether it may, and a machine that
* is offline would be told its work is gone. So the pull request's head is read
* from the ref the last run left in the clone, and where there is no ref to
10BC8 * read the answer is that this cannot be told - which holds the worktree rather
* than letting it through, because the one mistake worth avoiding here is
* taking away a commit I have not pushed.
*
* Uncommitted changes are asked of the worktree and commits are asked of the
* branch, for the reason `standingWorktree` asks the same two: a worktree
* pruned or moved by hand still leaves the branch holding the commits.
*/
export const holding = Effect.fn("git.holding")(function* (repo: string, number: number, session: Session) {
const path = yield* Path.Path
const state = yield* stateDirectory
const clone = path.join(state, clonesIn, `${repo}.git`)
const directory = path.join(state, under[session], repo, String(number))
const branch = `dw-mc/${session}/${number}`

const changes = yield* Effect.orElseSucceed(git(["-C", directory, "status", "--porcelain"]), () => "")
if (changes.trim() !== "") {
return { _tag: "held", detail: "changes that are not committed" } satisfies Holding
}

const ref = `refs/heads/${branch}`
const found = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", "--verify", "--quiet", ref]), () => "")
if (found.trim() === "") {
return clear
}

const head = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", `refs/dw-mc/pr/${number}`]), () => "")
if (head.trim() === "") {
return {
_tag: "held",
detail: `the clone no longer knows what ${repo}#${number} points at, so what ${branch} holds cannot be told`
} satisfies Holding
}

const ahead = yield* aheadOf(clone, branch, head.trim())
return ahead === 0
? clear
: ({
_tag: "held",
detail: `${ahead} commit${ahead === 1 ? "" : "s"} that the pull request's head does not have`
} satisfies Holding)
})

/**
* Forgets the worktrees a clone has been left with, once their directories are
* gone.
*
* A directory taken from under the clone leaves the clone's record of it
* behind, and the next session on that pull request is cut at the same path,
* which is then refused as already registered. Pruning is the whole repair, and
* only a clone that stays needs it: one being removed takes its records with
* it.
*/
export const prune = Effect.fn("git.prune")(function* (clone: string) {
yield* Effect.ignore(git(["-C", clone, "worktree", "prune"]))
})
107 changes: 105 additions & 2 deletions src/adapters/store.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { NodeServices } from "@effect/platform-node"
import { assert, describe, it } from "@effect/vitest"
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path, Schema } from "effect"
import { ByteSize, ConfigProvider, Effect, FileSystem, Layer, Option, Path, Schema } from "effect"
import { KeyValueStore } from "effect/unstable/persistence"

import { layer, layerTest, stateDirectory, storeFor, textStoreFor } from "#adapters/store.ts"
import {
discard,
inventory,
layer,
layerTest,
sessionOf,
stateDirectory,
storeFor,
textStoreFor
} from "#adapters/store.ts"

class ReviewRun extends Schema.Class<ReviewRun>("dw-mc/test/ReviewRun")({
pr: Schema.Int,
Expand Down Expand Up @@ -113,6 +122,100 @@ describe("store", () => {
}).pipe(Effect.provide(NodeServices.layer))
)

/** A state directory with a clone, a review worktree, a fix worktree and a record. */
const laidOut = Effect.fnUntraced(function* (state: string) {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const put = (where: ReadonlyArray<string>, contents: string) =>
Effect.gen(function* () {
const file = path.join(state, ...where)
yield* fs.makeDirectory(path.dirname(file), { recursive: true })
yield* fs.writeFileString(file, contents)
})

yield* put(["repos", "dw", "one.git", "HEAD"], "ref: refs/heads/main\n")
yield* put(["worktrees", "dw", "one", "28", "README.md"], "cut for a review run\n")
yield* put(["fixes", "dw", "one", "28", "README.md"], "cut for a fix session\n")
yield* put(["repos", "dw", "two.git", "HEAD"], "ref: refs/heads/main\n")
yield* put(["prs%2Fdw%2Fone%2328"], `{"number":28}`)
yield* put(["runs%2Fdw%2Fone%2328.md"], "# One finding\n")
})

const inventoryOf = (state: string) =>
inventory.pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
ConfigProvider.layer(
ConfigProvider.fromEnvRecord({
XDG_STATE_HOME: state
})
)
)
)
)

it.effect("the inventory names the clones, the checkouts and the records it finds", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const home = yield* fs.makeTempDirectoryScoped()
const state = path.join(home, "dw-mc")
yield* laidOut(state)

const found = yield* inventoryOf(home)

assert.strictEqual(found.directory, state)
assert.deepStrictEqual(
found.clones.map((one) => one.repo),
["dw/one", "dw/two"]
)
assert.deepStrictEqual(
found.cuttings.map((one) => `${one.cut}/${one.repo}#${one.number}`),
["worktrees/dw/one#28", "fixes/dw/one#28"]
)
assert.strictEqual(found.records.keys, 2)
assert.isTrue(ByteSize.toBigInt(found.records.size) > BigInt(0))
assert.isTrue(ByteSize.toBigInt(found.clones[0]?.size ?? ByteSize.bytes(0)) > BigInt(0))
}).pipe(Effect.provide(NodeServices.layer))
)

it.effect("the inventory of a machine that has run nothing is empty rather than an error", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem
const home = yield* fs.makeTempDirectoryScoped()

const found = yield* inventoryOf(home)

assert.deepStrictEqual(found.clones, [])
assert.deepStrictEqual(found.cuttings, [])
assert.strictEqual(found.records.keys, 0)
}).pipe(Effect.provide(NodeServices.layer))
)

it.effect("what is discarded is gone, and discarding it twice is not an error", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const home = yield* fs.makeTempDirectoryScoped()
const state = path.join(home, "dw-mc")
yield* laidOut(state)
const clone = path.join(state, "repos", "dw", "one.git")

yield* discard(clone)
yield* discard(clone)

assert.isFalse(yield* fs.exists(clone))
assert.isTrue(yield* fs.exists(path.join(state, "repos", "dw", "two.git")))
}).pipe(Effect.provide(NodeServices.layer))
)

it("a review worktree stands for no session, where the two session directories do", () => {
assert.strictEqual(sessionOf("worktrees"), undefined)
assert.strictEqual(sessionOf("fixes"), "fix")
assert.strictEqual(sessionOf("rebases"), "rebase")
})

it.effect("the in-memory layer forgets between builds, where the one on disk remembers", () =>
Effect.gen(function* () {
const run = new ReviewRun({ pr: 7, head: "cafe1234", verdict: "clean" })
Expand Down
Loading
0