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
25 changes: 14 additions & 11 deletions .agents/skills/tidy-context/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,27 @@ metadata:
pattern: tool-wrapper
source_files:
- path: cli/src/engine-native/tidy.ts
lines: "1-1276"
lines: "1-1427"
- path: cli/src/engine-native/tidyReport.ts
lines: "1-509"
lines: "1-589"
- path: cli/src/engine-native/kitLock.ts
lines: "1-121"
- path: cli/src/engine-native/processes.ts
lines: "1-16"
- path: cli/src/engine-native/scratch.ts
lines: "1-206"
- path: cli/src/commands/tidy.ts
lines: "1-148"
lines: "1-193"
- path: cli/src/commands/scratch.ts
lines: "1-75"
- path: SoT/.omp/plugin/extensions/hygiene.ts
lines: "1-2291"
- path: cli/test/unit/tidy.test.ts
lines: "1-665"
lines: "1-1466"
- path: cli/test/unit/kitLock.test.ts
lines: "1-398"
- path: cli/test/unit/tidyReport.test.ts
lines: "1-168"
lines: "1-178"
- path: cli/test/unit/scratch.test.ts
lines: "1-187"
- path: cli/test/unit/ompKitPluginExtension.test.ts
Expand Down Expand Up @@ -56,7 +56,7 @@ Pointers here name concepts, not coordinates — if a path or symbol moved, trus
|---|---|
| A new leftover class, keep reason, or threshold | `cli/src/engine-native/tidy.ts` — `planTidy`, `checkWorktree` |
| Apply order, signals, Docker or git removal calls | `cli/src/engine-native/tidy.ts` — `applyTidy` |
| The apply lock: when it is taken, what a held lock prints | `cli/src/commands/tidy.ts` — `runTidy`; `cli/src/engine-native/kitLock.ts` — `acquireKitLock` |
| The apply lock: when it is taken, what a held lock prints | `cli/src/commands/tidy.ts` — `runTidy`; `cli/src/engine-native/kitLock.ts` — `tryAcquireKitLock` |
| `--report` sections, hints, process filters | `cli/src/engine-native/tidyReport.ts` — `buildTidyReport` |
| Scratch creation, removal roots, path trust | `cli/src/engine-native/scratch.ts` — `createScratchDir`, `removeTemporaryPath` |
| CLI flags, output lines, exit status | `cli/src/commands/tidy.ts` — `runTidy`, `tidyCommand`; `cli/src/commands/scratch.ts` — `scratchCommand` |
Expand All @@ -70,7 +70,7 @@ Pointers here name concepts, not coordinates — if a path or symbol moved, trus
- `cli/src/engine-native/tidy.ts` — `applyTidy` — performs a `TidyPlan` and appends to `tidy.log`; its caller holds `tidy-lock.db` (verify: `bunx vitest run cli/test/unit/tidy.test.ts -t "containers first, then the worktree"`)
- `cli/src/engine-native/tidy.ts` — `TidyHost`, `defaultTidyHost` — the injection seam for `git`, `docker`, `dockerEndpoint`, `run`, `processes`, `now` (verify: `grep -n "export interface TidyHost" cli/src/engine-native/tidy.ts`)
- `cli/src/commands/tidy.ts` — `runTidy` — `tidyCommand` resolves the inputs and calls it. With `--apply`, it takes `tidy-lock.db` before `planTidy` and releases it before `--report` runs (verify: `bunx vitest run cli/test/unit/tidy.test.ts -t "plans only under the lock"` and `bunx vitest run cli/test/unit/tidy.test.ts -t "releases the lock before the report runs"`)
- `cli/src/engine-native/kitLock.ts` — `acquireKitLock`, `releaseKitLock` — the SQLite lock of `tidy --apply`; sync and the root tier toggles take their locks as scoped Effects over `tryAcquireKitLock` and `releaseKitLock` (`syncDispatch.ts engineSync`, `homeAndFolderLocks`). It imports only `node:` modules, so a test child can load it alone (verify: `grep -n 'from "' cli/src/engine-native/kitLock.ts`)
- `cli/src/engine-native/kitLock.ts` — `tryAcquireKitLock`, `releaseKitLock` — the SQLite lock primitives; `tidy --apply`, sync, and the root tier toggles take their locks as scoped Effects over them (`commands/tidy.ts runTidy`, `syncDispatch.ts engineSync`, `homeAndFolderLocks`). The Promise poll `acquireKitLock` keeps only test callers. It imports only `node:` modules, so a test child can load it alone (verify: `grep -n 'from "' cli/src/engine-native/kitLock.ts`)
- `cli/src/engine-native/processes.ts` — `processExited` — true only when `process.kill(pid, 0)` throws ESRCH. `tidy.ts darwinProcesses` (the macOS cwd probe) uses it to tell an exited PID from an unreadable cwd. Unprobed: no unit test runs the macOS probe (verify: `grep -n "processExited(pid)" cli/src/engine-native/tidy.ts`)
- `cli/src/engine-native/tidyReport.ts` — `buildTidyReport` — read-only sections; reuses `tidy.ts` helpers (verify: `grep -n 'from "./tidy"' cli/src/engine-native/tidyReport.ts`)
- `cli/src/engine-native/scratch.ts` — `kitCacheDir`, `scratchRoot`, `tidyApplyLockPath`, `syncLockPath` — owner of `~/.cache/docks-kit`, its `scratch/` child, and the lock files `tidy-lock.db` and `sync-lock.db` (verify: `grep -n -e "export function kitCacheDir" -e "LockPath(home" cli/src/engine-native/scratch.ts`)
Expand Down Expand Up @@ -135,15 +135,17 @@ Probe: `bunx vitest run cli/test/unit/tidy.test.ts -t "removes the merged idle w

### Apply order

1. `runTidy` takes `tidy-lock.db` with `waitMs: 0`, then runs `planTidy`. When another run holds the lock, it prints only `another docks-kit tidy run holds <path>`, with no plan and no report, and leaves the exit code unset.
1. `runTidy` takes `tidy-lock.db` with one `tryAcquireKitLock` try in `Effect.acquireRelease`, then runs `planTidy`. When another run holds the lock, it prints only `another docks-kit tidy run holds <path>`, with no plan and no report, and leaves the exit code unset.
2. `applyTidy` sends SIGTERM to each `stop-process` PID.
3. Each `remove-worktree`: `docker rm --force --volumes` its containers, remove its compose networks, then `git worktree remove -- <path>`; then `git worktree prune` once per touched repository.
4. `docker stop` for `stop-containers`; `docker rm --force --volumes` plus networks for `remove-containers`.
5. Scratch removals; append all lines to `tidy.log` (rotated to `tidy.log.1` past the byte limit).
6. `runTidy` releases the lock (`Effect.acquireUseRelease`), then runs `--report` when it is set.
6. `runTidy` releases the lock when the scope of the apply closes, then runs `--report` when it is set.

Probes: `bunx vitest run cli/test/unit/tidy.test.ts -t "containers first, then the worktree"` asserts the order, the `--host` prefix, and no git `--force`. `bunx vitest run cli/test/unit/tidy.test.ts -t "prints the held line and plans nothing while another run holds the lock"` asserts step 1. `bunx vitest run cli/test/unit/tidy.test.ts -t "releases the lock before the report runs"` asserts step 6.

Signals: `tidyCommand` runs inside `exitOnSignal` (`cli/src/engine.ts`), so SIGINT or SIGTERM exits 130 at once, as the base `BunRuntime.runMain` interrupt did. `applyTidy` takes `deferSignalExit` in a scope that closes after its result is printed and before `--report`, so a signal in the apply exits 130 only after the printed lines; each `git` and `docker` call of the apply runs in `signalExitPoint`, where a signal still exits at once. Probes: `bunx vitest run cli/test/unit/tidy.test.ts -t "defers a SIGTERM at the"`; `bunx vitest run cli/test/unit/tidy.test.ts -t "while docker rm of --apply waits"`.

### Temporary-path removal

`removeTemporaryPath` removes a path only when all checks pass. It runs the checks in this order and refuses at the first failed check:
Expand Down Expand Up @@ -176,7 +178,7 @@ Probes: `bunx vitest run cli/test/unit/scratch.test.ts -t "refuses a symbolic li

### Report

- Linux and macOS only. Each section runs alone; a throw becomes `unavailable: <message>`; an empty section is dropped.
- Linux and macOS only. Each section runs alone; a failure or a defect of a section, but not an interruption, becomes `unavailable: <message>`; an empty section is dropped.
- The process section lists old orphans whose argument file names match `DEV_PROCESS`, plus old processes in agent or temporary roots, never a protected process.
- Docker data comes from `docker system df` through `localDocker` with the plan's access.
- List the sections: `grep -n 'section("' cli/src/engine-native/tidyReport.ts`.
Expand Down Expand Up @@ -226,7 +228,8 @@ Re-derive before you rely on a value.
| `isProtectedProcess` matches `/.omp/` or `/tern/` anywhere in `args` | An orphan started with a config path under `~/.omp/` is never stopped | `bunx vitest run cli/test/unit/tidyReport.test.ts -t "lists old orphaned tools"` |
| `removeProjectNetworks` ignores a failed `network rm` | A network that another container uses stays with no `failed` line | By design; do not count it as a failure |
| `hygiene.ts` copies `kitCacheDir`, `LABEL_PATTERN`, and `processes.ts processExited` (as `hasExited`) | A change on one side splits `tidy.stamp` from `tidy-lock.db`, lets the tool accept a label that the CLI rejects, or makes the probe cleanup and the CLI disagree on when a PID has exited | `grep -n -e "kitCacheDir" -e "LABEL_PATTERN =" -e "function hasExited" -e "function processExited" SoT/.omp/plugin/extensions/hygiene.ts cli/src/engine-native/scratch.ts cli/src/engine-native/processes.ts` |
| Untested paths | Network removal, log rotation, `--repo` listing, the apply-time scratch recheck, the `tidyCommand` input resolution, and the `session_start` spawn have no unit test | Add a should-fail case with any change there |
| Untested paths | The `tidyCommand` resolution of the home and the worktree root, and the `session_start` spawn, have no unit test | Add a should-fail case with any change there |
| `runBounded` is not `Effect.forEach` | `Effect.forEach` with `concurrency` interrupts the started siblings when one task fails, so a half-done probe loses its result; `runBounded` drains the started tasks and reports the lowest-index failure | `bunx vitest run cli/test/unit/syncConcurrency.test.ts -t "reports the lowest-index failure"` |

## References

Expand Down
213 changes: 129 additions & 84 deletions cli/src/commands/tidy.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { resolve } from "node:path";

import { Command, Flag } from "effect/cli";
import { Console, Effect, Option } from "effect";
import { Console, Effect, type FileSystem, Option, Schema } from "effect";

import { bail } from "../engine";
import { bail, exitOnSignal } from "../engine";
import { bridgeSync, type LegacyStepFailed } from "../engine-native/bridge";
import { errorMessage } from "../engine-native/errorText";
import { engineHome } from "../engine-native/home";
import { acquireKitLock, releaseKitLock } from "../engine-native/kitLock";
import { releaseKitLock, tryAcquireKitLock } from "../engine-native/kitLock";
import { scratchRoot, tidyApplyLockPath } from "../engine-native/scratch";
import {
actionSubject,
Expand Down Expand Up @@ -34,113 +36,156 @@ const report = Flag.Boolean("report").pipe(
Flag.withDefault(false),
);

/** The try of the tidy lock failed; `cause` is the error of the lock primitive. */
export class TidyLockFailed extends Schema.TaggedError<
TidyLockFailed,
{ readonly brand: unique symbol }
>()("TidyLockFailed", {
message: Schema.String,
cause: Schema.Defect(),
}) {}

export interface TidyOptions {
readonly apply: boolean;
readonly report: boolean;
}

/** Print the plan, then perform it when `perform` is true or print the dry-run line. Return the plan. */
function planAndApply(
/**
* Print the plan, then perform it when `perform` is true or print the dry-run
* line. Return the plan. The apply and the printing of its result run as one
* region that an interrupt does not stop, in a scope that defers a signal exit
* (`applyTidy`) and closes right after the printing.
*/
const planAndApply = Effect.fnUntraced(function* (
perform: boolean,
inputs: TidyInputs,
host: TidyHost,
): Effect.Effect<TidyPlan> {
return Effect.gen(function* () {
const plan = yield* Effect.promise(() => planTidy(inputs, host));
for (const action of plan.actions) {
yield* Console.log(`${actionVerb(action)} ${actionSubject(action)}: ${action.reason}`);
}
for (const kept of plan.kept) yield* Console.log(`keep ${kept.subject}: ${kept.reason}`);
for (const note of plan.notes) yield* Console.log(`note: ${note}`);
): Effect.fn.Return<TidyPlan, LegacyStepFailed, FileSystem.FileSystem> {
const plan = yield* planTidy(inputs, host);
for (const action of plan.actions) {
yield* Console.log(`${actionVerb(action)} ${actionSubject(action)}: ${action.reason}`);
}
for (const kept of plan.kept) yield* Console.log(`keep ${kept.subject}: ${kept.reason}`);
for (const note of plan.notes) yield* Console.log(`note: ${note}`);

if (plan.actions.length === 0) {
yield* Console.log("Nothing to tidy.");
} else if (perform) {
const outcome = yield* Effect.promise(() => applyTidy(plan, inputs, host));
for (const line of outcome.lines) yield* Console.log(line);
if (outcome.failures > 0) {
yield* Effect.sync(() => {
process.exitCode = 1;
});
}
} else {
// In --repo mode a bare `tidy --apply` would perform a different plan.
const applyCommand =
inputs.repo === undefined
? "docks-kit tidy --apply"
: `docks-kit tidy --repo ${inputs.repo} --apply`;
yield* Console.log(
`Dry run: ${plan.actions.length} actions. Run '${applyCommand}' to perform them.`,
);
}
return plan;
});
}
if (plan.actions.length === 0) {
yield* Console.log("Nothing to tidy.");
} else if (perform) {
yield* Effect.uninterruptible(
Effect.scoped(
Effect.gen(function* () {
const outcome = yield* applyTidy(plan, inputs, host);
for (const line of outcome.lines) yield* Console.log(line);
if (outcome.failures > 0) {
yield* Effect.sync(() => {
process.exitCode = 1;
});
}
}),
),
);
} else {
// In --repo mode a bare `tidy --apply` would perform a different plan.
const applyCommand =
inputs.repo === undefined
? "docks-kit tidy --apply"
: `docks-kit tidy --repo ${inputs.repo} --apply`;
yield* Console.log(
`Dry run: ${plan.actions.length} actions. Run '${applyCommand}' to perform them.`,
);
}
return plan;
});

/**
* Plan and apply under the tidy lock, so that a second run cannot act on a
* plan that the first run makes stale. When another run holds the lock, print
* only the held line, with no plan, and return `undefined`. The exit code
* stays unset.
* plan that the first run makes stale. The lock is one try with no wait
* (`tryAcquireKitLock`), released when the scope closes. When another run
* holds the lock, print only the held line, with no plan, and return
* `undefined`. The exit code stays unset.
*/
function planAndApplyUnderLock(
const planAndApplyUnderLock = Effect.fnUntraced(function* (
inputs: TidyInputs,
host: TidyHost,
): Effect.Effect<TidyPlan | undefined> {
): Effect.fn.Return<
TidyPlan | undefined,
LegacyStepFailed | TidyLockFailed,
FileSystem.FileSystem
> {
const path = tidyApplyLockPath(inputs.home);
return Effect.acquireUseRelease(
Effect.promise(() => acquireKitLock(path, { waitMs: 0 })),
(result) =>
result.kind === "acquired"
? planAndApply(true, inputs, host)
: Console.log(`another docks-kit tidy run holds ${path}`).pipe(Effect.as(undefined)),
(result) =>
Effect.sync(() => {
if (result.kind === "acquired") releaseKitLock(result.lock);
}),
return yield* Effect.scoped(
Effect.gen(function* () {
const lock = yield* Effect.acquireRelease(
Effect.try({
try: () => tryAcquireKitLock(path, { privateDirectory: true }),
catch: (cause) => new TidyLockFailed({ message: errorMessage(cause), cause }),
}),
(held) =>
Effect.sync(() => {
if (held !== undefined) releaseKitLock(held);
}),
);
if (lock === undefined) {
yield* Console.log(`another docks-kit tidy run holds ${path}`);
return undefined;
}
return yield* planAndApply(true, inputs, host);
}),
);
}
});

/**
* Run `docks-kit tidy` with resolved inputs. `apply` takes the tidy lock
* before `planTidy`; a dry run and `--report` take no lock.
* before `planTidy` and releases it before `--report` runs; a dry run and
* `--report` take no lock.
*/
export function runTidy(
export const runTidy = Effect.fn("runTidy")(function* (
options: TidyOptions,
inputs: TidyInputs,
host: TidyHost,
): Effect.Effect<void> {
return Effect.gen(function* () {
const plan = options.apply
? yield* planAndApplyUnderLock(inputs, host)
: yield* planAndApply(false, inputs, host);
if (plan === undefined || !options.report) return;
const sections = yield* Effect.promise(() => buildTidyReport(inputs, host, plan.docker));
for (const section of sections) {
yield* Console.log(`== ${section.title}`);
for (const line of section.lines) yield* Console.log(line);
}
});
}
): Effect.fn.Return<void, LegacyStepFailed | TidyLockFailed, FileSystem.FileSystem> {
const plan = options.apply
? yield* planAndApplyUnderLock(inputs, host)
: yield* planAndApply(false, inputs, host);
if (plan === undefined || !options.report) return;
const sections = yield* buildTidyReport(inputs, host, plan.docker);
for (const section of sections) {
yield* Console.log(`== ${section.title}`);
for (const line of section.lines) yield* Console.log(line);
}
});

/**
* Resolve the inputs and run tidy inside `exitOnSignal`: a SIGINT or SIGTERM
* exits with 130 at once, except inside the apply, which defers it. A typed
* failure ends the command as a defect of its original cause, so the runtime
* prints it and exits 1.
*/
export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config) =>
Effect.gen(function* () {
const host = defaultTidyHost();
const home = engineHome();
let repository: string | undefined;
if (Option.isSome(config.repo)) {
const typed = config.repo.value;
repository = yield* Effect.promise(() => mainRepository(resolve(process.cwd(), typed), host));
if (repository === undefined) return yield* bail(`--repo ${typed} is not a git repository`);
}
const inputs: TidyInputs = {
home,
worktreeRoot: agentWorktreeRoot(home, process.env),
scratchRoot: scratchRoot(home),
...(repository === undefined ? {} : { repo: repository }),
};
yield* runTidy({ apply: config.apply, report: config.report }, inputs, host);
}),
Effect.scoped(
Effect.gen(function* () {
yield* exitOnSignal;
const host = defaultTidyHost();
const home = yield* bridgeSync("engineHome", () => engineHome());
let repository: string | undefined;
if (Option.isSome(config.repo)) {
const typed = config.repo.value;
repository = yield* mainRepository(resolve(process.cwd(), typed), host);
if (repository === undefined) return yield* bail(`--repo ${typed} is not a git repository`);
}
const inputs: TidyInputs = {
home,
worktreeRoot: agentWorktreeRoot(home, process.env),
scratchRoot: scratchRoot(home),
...(repository === undefined ? {} : { repo: repository }),
};
yield* runTidy({ apply: config.apply, report: config.report }, inputs, host);
}),
).pipe(
Effect.catch((error) =>
Effect.die(error.cause !== undefined ? error.cause : new Error(error.message)),
),
),
).pipe(
Command.withDescription(
"List or remove safe agent leftovers (merged idle worktrees, their containers, orphaned processes in agent directories, idle scratch directories); --report lists other disk and memory use.",
Expand Down
Loading
Loading