From 837eca31b049618b83247caca01361a5abf51238 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:46:29 -0300 Subject: [PATCH 1/3] Move tidy, its report, and the bounded runner to Effect Step tidy of #295 (child of #290): - runBounded runs Effect tasks with workers that cannot fail; a failure drains the started tasks and the lowest-index cause wins, so no started task is interrupted. - tidy.ts and tidyReport.ts: the host returns Effects, file work goes through FileSystem with the base outcome per call, base throws are tagged failures, legacy calls are bridged. - commands/tidy.ts: the apply lock is a scoped tryAcquireKitLock; the command runs inside exitOnSignal; the apply defers the signal exit except at its git and docker calls (deferSignalExit, signalExitPoint in engine.ts), until its result is printed. - Runner cases move to syncConcurrency.test.ts with the two error-order cases; tidy and report tests run on Effect stubs; new cases cover the untested paths and the spawned CLI. Verified: bun x --no-install vitest run cli/test/unit/syncConcurrency.test.ts cli/test/unit/engine-di.test.ts cli/test/unit/tidy.test.ts cli/test/unit/tidyReport.test.ts cli/test/unit/kitLock.test.ts cli/test/unit/scratch.test.ts cli/test/unit/skillMetadata.test.ts; bun run check:types; bun run lint; bun run check --- cli/src/commands/tidy.ts | 213 +++-- cli/src/engine-native/syncConcurrency.ts | 66 +- cli/src/engine-native/tidy.ts | 771 +++++++++------- cli/src/engine-native/tidyReport.ts | 372 +++++--- cli/src/engine.ts | 61 +- cli/test/unit/engine-di.test.ts | 123 --- cli/test/unit/syncConcurrency.test.ts | 222 +++++ cli/test/unit/tidy.test.ts | 1027 +++++++++++++++++++--- cli/test/unit/tidyReport.test.ts | 36 +- 9 files changed, 2046 insertions(+), 845 deletions(-) create mode 100644 cli/test/unit/syncConcurrency.test.ts diff --git a/cli/src/commands/tidy.ts b/cli/src/commands/tidy.ts index 22b84bc1..17467633 100644 --- a/cli/src/commands/tidy.ts +++ b/cli/src/commands/tidy.ts @@ -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, @@ -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 { - 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 { + 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 { +): 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 { - 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 { + 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.", diff --git a/cli/src/engine-native/syncConcurrency.ts b/cli/src/engine-native/syncConcurrency.ts index f5e240e3..9fa7db9a 100644 --- a/cli/src/engine-native/syncConcurrency.ts +++ b/cli/src/engine-native/syncConcurrency.ts @@ -3,44 +3,56 @@ * for their parallel probes. index.ts re-exports it so existing import paths * keep working. */ +import { Cause, Effect, Exit } from "effect"; export type SyncConcurrency = 1 | 2 | 3; -export type SyncTask = () => Promise; +export type SyncTask = Effect.Effect; -type PoolState = +type PoolState = | { readonly kind: "accepting"; nextIndex: number } - | { readonly kind: "draining"; readonly index: number; readonly reason: unknown }; + | { readonly kind: "draining"; readonly index: number; readonly cause: Cause.Cause }; -function drainAfterFailure(state: PoolState, index: number, reason: unknown): PoolState { +function drainAfterFailure( + state: PoolState, + index: number, + cause: Cause.Cause, +): PoolState { return state.kind === "draining" && state.index < index ? state - : { kind: "draining", index, reason }; + : { kind: "draining", index, cause }; } /** - * Run input-ordered tasks with bounded overlap. Once one task rejects, queued - * tasks stay queued while already-started tasks drain; the earliest rejection - * in input order is then propagated. + * Run input-ordered tasks with bounded overlap. Each worker fiber takes the + * next queued task while the pool accepts and cannot fail itself: a failed + * task (a typed failure or a defect) stops the pool from accepting, and the + * tasks that already started run to their end, uninterrupted. The failure + * with the lowest input index is then propagated; otherwise the results come + * back in input order. An interrupt of the caller interrupts every worker. + * `Effect.forEach` with `concurrency` would interrupt the started tasks at + * the first failure instead. */ -export async function runBounded( - tasks: ReadonlyArray>, +export const runBounded = ( + tasks: ReadonlyArray>, concurrency: SyncConcurrency, -): Promise> { - const results = new Array(tasks.length); - const pool: { state: PoolState } = { state: { kind: "accepting", nextIndex: 0 } }; - - const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, async () => { - while (pool.state.kind === "accepting" && pool.state.nextIndex < tasks.length) { - const index = pool.state.nextIndex++; - try { - results[index] = await tasks[index]!(); - } catch (reason) { - pool.state = drainAfterFailure(pool.state, index, reason); +): Effect.Effect, E, R> => + Effect.suspend(() => { + const results = new Array(tasks.length); + const pool: { state: PoolState } = { state: { kind: "accepting", nextIndex: 0 } }; + const worker = Effect.gen(function* () { + while (pool.state.kind === "accepting" && pool.state.nextIndex < tasks.length) { + const index = pool.state.nextIndex++; + const exit = yield* Effect.exit(tasks[index]!); + if (Exit.isSuccess(exit)) results[index] = exit.value; + else pool.state = drainAfterFailure(pool.state, index, exit.cause); } - } + }); + const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker); + return Effect.all(workers, { concurrency: "unbounded", discard: true }).pipe( + Effect.andThen(() => + pool.state.kind === "draining" + ? Effect.failCause(pool.state.cause) + : Effect.succeed(results), + ), + ); }); - await Promise.all(workers); - - if (pool.state.kind === "draining") throw pool.state.reason; - return results; -} diff --git a/cli/src/engine-native/tidy.ts b/cli/src/engine-native/tidy.ts index 00dd122b..c12058f8 100644 --- a/cli/src/engine-native/tidy.ts +++ b/cli/src/engine-native/tidy.ts @@ -6,19 +6,13 @@ * check fails closed: a candidate that a check cannot prove safe stays, with * its reason. */ -import { - appendFileSync, - lstatSync, - readdirSync, - readFileSync, - readlinkSync, - realpathSync, - renameSync, - statSync, - type Stats, -} from "node:fs"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; +import { Cause, Effect, FileSystem, Option, Result, Schema, type Scope } from "effect"; +import type { PlatformError } from "effect/PlatformError"; + +import { deferSignalExit, signalExitPoint } from "../engine"; +import { bridgePromise, bridgeSync, type LegacyStepFailed } from "./bridge"; import { errorMessage } from "./errorText"; import { spawnProcess, type AsyncProcessResult } from "./exec"; import { ensureDirectory } from "./ompFileDeploy"; @@ -43,6 +37,68 @@ const DOCKER_PS_FORMAT = /** Process names that tidy never stops: the agent harness, its launcher, and the kit. */ const PROTECTED_NAMES = ["omp", "tern", "docks-kit"] as const; +// ---------------------------------------------------------------- errors ---- + +/** + * A path or activity check, the log rotation, or the log append failed. + * `message` is the text of the check (`cannot check : `) or the + * message of the Node error; `cause` is that Node error when one exists. + */ +export class TidyCheckFailed extends Schema.TaggedError< + TidyCheckFailed, + { readonly brand: unique symbol } +>()("TidyCheckFailed", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +/** A failure of a tidy step: a check, or a bridged tool call. */ +export type TidyFailure = TidyCheckFailed | LegacyStepFailed; + +function errorCode(cause: unknown): string | undefined { + return cause instanceof Error && "code" in cause && typeof cause.code === "string" + ? cause.code + : undefined; +} + +/** + * The Node error of a failed file operation: the cause that the + * `PlatformError` keeps, else the `PlatformError`. Its errno code and its + * message are the ones that the synchronous `node:fs` call threw. + */ +export function nodeError(error: PlatformError): unknown { + return error.cause ?? error; +} + +/** A typed failure of tidy or of its report: a check, a report section, or a bridged call. */ +interface TaggedFailure { + readonly _tag: string; + readonly message: string; + readonly cause?: unknown; +} + +/** + * The text of the first failure or defect of `cause`, as `errorMessage` gave + * it for the value that the Promise code threw: the message of a check or a + * section, or of the value that a bridged call threw or rejected with. + */ +export function causeMessage(cause: Cause.Cause): string { + const reason = cause.reasons.find((entry) => !Cause.isInterruptReason(entry)); + if (reason === undefined) return errorMessage(undefined); + if (!Cause.isFailReason(reason)) return errorMessage(reason.defect); + const error = reason.error; + return error._tag === "LegacyStepFailed" ? errorMessage(error.cause) : error.message; +} + +/** `cannot check : `, with the message when the error has no code. */ +function checkFailed(path: string, error: PlatformError): TidyCheckFailed { + const cause = nodeError(error); + return new TidyCheckFailed({ + message: `cannot check ${path}: ${errorCode(cause) ?? errorMessage(cause)}`, + cause, + }); +} + // ----------------------------------------------------------------- paths ---- /** The plan-lifecycle worktree root: `$XDG_DATA_HOME/agent-worktrees`. */ @@ -61,14 +117,11 @@ export function tidyLogPath(home: string): string { * Resolve a path, then take its real path when it exists. Tidy compares only * these forms, so macOS `/private` and Windows drive spellings agree. */ -export function normalizePath(path: string): string { +export const normalizePath = Effect.fnUntraced(function* (path: string) { + const fs = yield* FileSystem.FileSystem; const resolved = resolve(path); - try { - return realpathSync(resolved); - } catch { - return resolved; - } -} + return yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)); +}); // ------------------------------------------------------------------ host ---- @@ -89,46 +142,49 @@ export interface ProcessRow { readonly cwd: string | undefined; } +/** One tool call of the host; a bridged call fails when the spawn throws or rejects. */ +export type ToolCall = Effect.Effect; + export interface TidyHost { - readonly git: (args: ReadonlyArray) => Promise; + readonly git: (args: ReadonlyArray) => ToolCall; /** * Runs `docker `. Tidy calls it only through `localDocker`, which puts * `--host ` first. */ - readonly docker: (args: ReadonlyArray) => Promise; + readonly docker: (args: ReadonlyArray) => ToolCall; /** * Prints the endpoint that a plain docker command uses, after `DOCKER_HOST`, * `DOCKER_CONTEXT`, and the current context apply. It does not connect. */ - readonly dockerEndpoint: () => Promise; - readonly run: (command: string, args: ReadonlyArray) => Promise; + readonly dockerEndpoint: () => ToolCall; + readonly run: (command: string, args: ReadonlyArray) => ToolCall; /** `undefined` when the host cannot list processes with their working directories. */ - readonly processes: () => Promise | undefined>; + readonly processes: () => Effect.Effect< + ReadonlyArray | undefined, + LegacyStepFailed, + FileSystem.FileSystem + >; readonly now: () => number; } -function errorCode(cause: unknown): string | undefined { - return cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : undefined; -} - function isMissingCommand(result: AsyncProcessResult): boolean { const error = result.error; if (error === undefined) return false; return errorCode(error) === "ENOENT" || error.message.startsWith("command not found on PATH"); } -async function runTool(command: string, args: ReadonlyArray): Promise { - const result = await spawnProcess(command, args, { stdio: ["ignore", "pipe", "pipe"] }); - const stderr = - result.stderr === "" && result.error !== undefined ? result.error.message : result.stderr; - return { - code: result.exitCode, - stdout: result.stdout, - stderr, - missing: isMissingCommand(result), - }; +function runTool(command: string, args: ReadonlyArray): ToolCall { + return bridgePromise(`run ${command}`, () => + spawnProcess(command, args, { stdio: ["ignore", "pipe", "pipe"] }), + ).pipe( + Effect.map((result) => ({ + code: result.exitCode, + stdout: result.stdout, + stderr: + result.stderr === "" && result.error !== undefined ? result.error.message : result.stderr, + missing: isMissingCommand(result), + })), + ); } /** First non-empty output line of a failed command, for a one-line reason. */ @@ -242,13 +298,13 @@ const UNREADABLE_CWD_NAMES: ReadonlyArray = [ * `systemd` subreaper, and it protects no directory. Any other unreadable cwd * returns `undefined`, because that process could use an agent directory. */ -export function resolveProcessCwds( +export const resolveProcessCwds = Effect.fnUntraced(function* ( rows: ReadonlyArray, - readCwd: (pid: number) => CwdProbe, -): ReadonlyArray | undefined { + readCwd: (pid: number) => Effect.Effect, +): Effect.fn.Return | undefined, E, R> { const resolved: Array = []; for (const row of rows) { - const probe = readCwd(row.pid); + const probe = yield* readCwd(row.pid); if (probe.kind === "exited") continue; if (probe.kind === "cwd") { resolved.push({ ...row, cwd: probe.path }); @@ -262,7 +318,7 @@ export function resolveProcessCwds( resolved.push({ ...row, cwd: undefined }); } return resolved; -} +}); /** * Join the two `ps` reads by PID. Two reads keep `comm` unambiguous: as the @@ -283,51 +339,67 @@ function joinRows( } /** `readlink /proc//cwd`; ENOENT or ESRCH means that the process exited. */ -function readLinuxCwd(pid: number): CwdProbe { - try { - return { kind: "cwd", path: readlinkSync(`/proc/${pid}/cwd`) }; - } catch (cause) { - const code = errorCode(cause); - return code === "ENOENT" || code === "ESRCH" ? { kind: "exited" } : { kind: "unreadable" }; - } -} +const readLinuxCwd = Effect.fnUntraced(function* (pid: number) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readLink(`/proc/${pid}/cwd`).pipe( + Effect.map((path): CwdProbe => ({ kind: "cwd", path })), + Effect.catchTag("PlatformError", (error) => { + const code = errorCode(nodeError(error)); + return Effect.succeed( + code === "ENOENT" || code === "ESRCH" ? { kind: "exited" } : { kind: "unreadable" }, + ); + }), + ); +}); -async function linuxProcesses(uid: number): Promise | undefined> { +const linuxProcesses = Effect.fnUntraced(function* (uid: number) { const user = ["-u", String(uid)]; - const [fields, names] = await Promise.all([ - runTool("ps", [...user, "-o", "pid=,ppid=,etimes=,rss=,args="]), - runTool("ps", [...user, "-o", "pid=,comm="]), - ]); + const [fields, names] = yield* Effect.all( + [ + runTool("ps", [...user, "-o", "pid=,ppid=,etimes=,rss=,args="]), + runTool("ps", [...user, "-o", "pid=,comm="]), + ], + { concurrency: "unbounded" }, + ); if (fields.code !== 0 || names.code !== 0) return undefined; const rows = joinRows(parsePsFields(fields.stdout, parseSeconds), parsePsNames(names.stdout)); - return rows === undefined ? undefined : resolveProcessCwds(rows, readLinuxCwd); -} + return rows === undefined ? undefined : yield* resolveProcessCwds(rows, readLinuxCwd); +}); -async function darwinProcesses(uid: number): Promise | undefined> { +const darwinProcesses = Effect.fnUntraced(function* (uid: number) { const user = ["-x", "-U", String(uid)]; - const [fields, names, lsof] = await Promise.all([ - runTool("ps", [...user, "-o", "pid=,ppid=,etime=,rss=,args="]), - runTool("ps", [...user, "-o", "pid=,comm="]), - runTool("lsof", ["-nP", "-a", "-u", String(uid), "-d", "cwd", "-Fpn"]), - ]); + const [fields, names, lsof] = yield* Effect.all( + [ + runTool("ps", [...user, "-o", "pid=,ppid=,etime=,rss=,args="]), + runTool("ps", [...user, "-o", "pid=,comm="]), + runTool("lsof", ["-nP", "-a", "-u", String(uid), "-d", "cwd", "-Fpn"]), + ], + { concurrency: "unbounded" }, + ); if (fields.code !== 0 || names.code !== 0 || lsof.code !== 0) return undefined; const cwds = parseLsofCwd(lsof.stdout); const rows = joinRows(parsePsFields(fields.stdout, parseElapsed), parsePsNames(names.stdout)); if (cwds === undefined || rows === undefined) return undefined; // A PID without an `lsof` cwd exited (ESRCH) or is alive but unreadable (EPERM). - return resolveProcessCwds(rows, (pid) => { + return yield* resolveProcessCwds(rows, (pid) => { const cwd = cwds.get(pid); - if (cwd !== undefined) return { kind: "cwd", path: cwd }; - return processExited(pid) ? { kind: "exited" } : { kind: "unreadable" }; + if (cwd !== undefined) return Effect.succeed({ kind: "cwd", path: cwd }); + return bridgeSync("processExited", () => processExited(pid)).pipe( + Effect.map((exited): CwdProbe => (exited ? { kind: "exited" } : { kind: "unreadable" })), + ); }); -} +}); -async function listProcesses(): Promise | undefined> { +function listProcesses(): Effect.Effect< + ReadonlyArray | undefined, + LegacyStepFailed, + FileSystem.FileSystem +> { const uid = process.getuid?.(); - if (uid === undefined) return undefined; + if (uid === undefined) return Effect.undefined; if (process.platform === "linux") return linuxProcesses(uid); if (process.platform === "darwin") return darwinProcesses(uid); - return undefined; + return Effect.undefined; } export function defaultTidyHost(): TidyHost { @@ -372,20 +444,22 @@ export type DockerAccess = | { readonly kind: "not-local"; readonly endpoint: string }; /** Resolve the effective endpoint once per run; the plan carries it to the apply. */ -export async function resolveDockerAccess(host: TidyHost): Promise { - const result = await host.dockerEndpoint(); +export const resolveDockerAccess = Effect.fnUntraced(function* ( + host: TidyHost, +): Effect.fn.Return { + const result = yield* host.dockerEndpoint(); if (result.missing) return { kind: "missing", reason: firstLine(result) }; const endpoint = result.code === 0 ? result.stdout.trim() : ""; return isLocalDockerEndpoint(endpoint) ? { kind: "local", endpoint } : { kind: "not-local", endpoint }; -} +}); export function notLocalMessage(endpoint: string): string { return `docker endpoint ${endpoint === "" ? "" : endpoint} is not local`; } -export type DockerRunner = (args: ReadonlyArray) => Promise; +export type DockerRunner = (args: ReadonlyArray) => ToolCall; /** * The only path from tidy to a Docker call. It checks the endpoint again and @@ -490,22 +564,24 @@ interface AgentRoots { } /** Normalize both roots and drop a root that equals or contains the home directory. */ -export function agentRoots(inputs: TidyInputs): AgentRoots { - const home = normalizePath(inputs.home); +export const agentRoots = Effect.fnUntraced(function* ( + inputs: TidyInputs, +): Effect.fn.Return { + const home = yield* normalizePath(inputs.home); const notes: Array = []; - const guard = (root: string): string | undefined => { - const path = normalizePath(root); + const guard = Effect.fnUntraced(function* (root: string) { + const path = yield* normalizePath(root); if (!isSameOrInside(path, home)) return path; notes.push(`refusing root ${path}: it contains the home directory`); return undefined; - }; + }); return { - worktreeRoot: guard(inputs.worktreeRoot), - scratchRoot: guard(inputs.scratchRoot), + worktreeRoot: yield* guard(inputs.worktreeRoot), + scratchRoot: yield* guard(inputs.scratchRoot), home, notes, }; -} +}); // -------------------------------------------------------------- worktrees ---- @@ -521,61 +597,58 @@ export interface WorktreeListing { readonly notes: ReadonlyArray; } -export function lstatOrUndefined(path: string): Stats | undefined { - try { - return lstatSync(path); - } catch { - return undefined; - } -} +/** The `lstat` information of `path`; `undefined` when `lstat` fails for any reason. */ +export const lstatOrUndefined = Effect.fnUntraced(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.lstat(path).pipe(Effect.orElseSucceed(() => undefined)); +}); -export function sortedEntries(directory: string): Array { - try { - return readdirSync(directory).sort(); - } catch { - return []; - } -} +/** The sorted names in `directory`; none when it cannot be read. */ +export const sortedEntries = Effect.fnUntraced(function* (directory: string) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readDirectory(directory).pipe( + Effect.map((names) => names.sort()), + Effect.orElseSucceed((): Array => []), + ); +}); /** The admin directory from a `gitdir: ` file at `/.git`. */ -function adminDirectory(worktree: string): string | undefined { - try { - const text = readFileSync(join(worktree, ".git"), "utf8"); - if (!text.startsWith("gitdir: ")) return undefined; - return normalizePath(resolve(worktree, text.slice("gitdir: ".length).trim())); - } catch { - return undefined; - } -} +const adminDirectory = Effect.fnUntraced(function* (worktree: string) { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString(join(worktree, ".git")).pipe(Effect.option); + if (Option.isNone(text) || !text.value.startsWith("gitdir: ")) return undefined; + return yield* normalizePath(resolve(worktree, text.value.slice("gitdir: ".length).trim())); +}); /** * Scan `/` and `//` with `lstat`. Never follow a symbolic * link, and never descend into a directory that has a `.git` entry. */ -function scanWorktreeRoot(root: string): { - readonly candidates: Array; - readonly kept: Array; -} { +const scanWorktreeRoot = Effect.fnUntraced(function* (root: string) { const candidates: Array = []; const kept: Array = []; - const visit = (directory: string, depth: number): void => { - for (const entry of sortedEntries(directory)) { - const path = join(directory, entry); - if (lstatOrUndefined(path)?.isDirectory() !== true) continue; - const marker = lstatOrUndefined(join(path, ".git")); - if (marker === undefined) { - if (depth === 0) visit(path, 1); - continue; + const visit = ( + directory: string, + depth: number, + ): Effect.Effect => + Effect.gen(function* () { + for (const entry of yield* sortedEntries(directory)) { + const path = join(directory, entry); + if ((yield* lstatOrUndefined(path))?.type !== "Directory") continue; + const marker = yield* lstatOrUndefined(join(path, ".git")); + if (marker === undefined) { + if (depth === 0) yield* visit(path, 1); + continue; + } + const admin = marker.type === "File" ? yield* adminDirectory(path) : undefined; + if (admin === undefined) + kept.push({ subject: `directory ${path}`, reason: "not a linked worktree" }); + else candidates.push({ path, admin }); } - const admin = marker.isFile() ? adminDirectory(path) : undefined; - if (admin === undefined) - kept.push({ subject: `directory ${path}`, reason: "not a linked worktree" }); - else candidates.push({ path, admin }); - } - }; - visit(root, 0); + }); + yield* visit(root, 0); return { candidates, kept }; -} +}); /** One entry of `git worktree list --porcelain`. */ export interface WorktreeEntry { @@ -585,60 +658,64 @@ export interface WorktreeEntry { readonly branch: string | undefined; } -function parseWorktreeList(stdout: string): Array { - return stdout +function parseWorktreeList( + stdout: string, +): Effect.Effect, never, FileSystem.FileSystem> { + const blocks = stdout .split(/\r?\n\r?\n/) .map((block) => block.split(/\r?\n/).filter((line) => line !== "")) - .filter((lines) => lines.length > 0 && lines[0]!.startsWith("worktree ")) - .map((lines) => ({ - path: normalizePath(lines[0]!.slice("worktree ".length)), - prunable: lines.some((line) => line === "prunable" || line.startsWith("prunable ")), - branch: lines.find((line) => line.startsWith("branch "))?.slice("branch ".length), - })); + .filter((lines) => lines.length > 0 && lines[0]!.startsWith("worktree ")); + return Effect.forEach(blocks, (lines) => + normalizePath(lines[0]!.slice("worktree ".length)).pipe( + Effect.map((path) => ({ + path, + prunable: lines.some((line) => line === "prunable" || line.startsWith("prunable ")), + branch: lines.find((line) => line.startsWith("branch "))?.slice("branch ".length), + })), + ), + ); } /** Every worktree entry of a repository, the main worktree first. */ -export async function repositoryWorktrees( - repo: string, - host: TidyHost, -): Promise | undefined> { - const result = await host.git(["-C", repo, "worktree", "list", "--porcelain"]); - return result.code === 0 ? parseWorktreeList(result.stdout) : undefined; -} +export const repositoryWorktrees = Effect.fnUntraced(function* (repo: string, host: TidyHost) { + const result = yield* host.git(["-C", repo, "worktree", "list", "--porcelain"]); + return result.code === 0 ? yield* parseWorktreeList(result.stdout) : undefined; +}); /** * Worktree candidates (rule 4): a scan of the worktree root by default, or the * linked worktrees of `inputs.repo`, at any location. */ -export async function listWorktreeCandidates( +export const listWorktreeCandidates = Effect.fnUntraced(function* ( inputs: TidyInputs, host: TidyHost, -): Promise { +): Effect.fn.Return { if (inputs.repo !== undefined) { - const entries = await repositoryWorktrees(inputs.repo, host); + const entries = yield* repositoryWorktrees(inputs.repo, host); if (entries === undefined) { return { candidates: [], kept: [], notes: [`git worktree list failed in ${inputs.repo}`] }; } - const candidates = entries - .slice(1) - .filter((entry) => !entry.prunable) - .map((entry) => ({ path: entry.path, admin: adminDirectory(entry.path) })); + const candidates = yield* Effect.forEach( + entries.slice(1).filter((entry) => !entry.prunable), + (entry) => + adminDirectory(entry.path).pipe(Effect.map((admin) => ({ path: entry.path, admin }))), + ); return { candidates, kept: [], notes: [] }; } - const root = agentRoots(inputs).worktreeRoot; + const root = (yield* agentRoots(inputs)).worktreeRoot; if (root === undefined) return { candidates: [], kept: [], notes: [] }; - if (lstatOrUndefined(root)?.isDirectory() !== true) { + if ((yield* lstatOrUndefined(root))?.type !== "Directory") { return { candidates: [], kept: [], notes: [`worktree root ${root} does not exist`] }; } - return { ...scanWorktreeRoot(root), notes: [] }; -} + return { ...(yield* scanWorktreeRoot(root)), notes: [] }; +}); /** The default branch ref: `origin/HEAD`, else `origin/main`, else `origin/master`. */ -export async function defaultBranchRef( +export const defaultBranchRef = Effect.fnUntraced(function* ( directory: string, host: TidyHost, -): Promise { - const symbolic = await host.git([ +): Effect.fn.Return { + const symbolic = yield* host.git([ "-C", directory, "symbolic-ref", @@ -648,7 +725,7 @@ export async function defaultBranchRef( const refs = ["refs/remotes/origin/main", "refs/remotes/origin/master"]; if (symbolic.code === 0 && symbolic.stdout.trim() !== "") refs.unshift(symbolic.stdout.trim()); for (const ref of refs) { - const verify = await host.git([ + const verify = yield* host.git([ "-C", directory, "rev-parse", @@ -659,7 +736,7 @@ export async function defaultBranchRef( if (verify.code === 0) return ref; } return undefined; -} +}); export function shortRef(ref: string): string { return ref.replace(/^refs\/(remotes|heads)\//, ""); @@ -672,8 +749,11 @@ interface GitLocation { readonly repo: string; } -async function gitLocation(directory: string, host: TidyHost): Promise { - const result = await host.git([ +const gitLocation = Effect.fnUntraced(function* ( + directory: string, + host: TidyHost, +): Effect.fn.Return { + const result = yield* host.git([ "-C", directory, "rev-parse", @@ -681,75 +761,89 @@ async function gitLocation(directory: string, host: TidyHost): Promise { - return (await gitLocation(directory, host))?.repo; -} +) { + return (yield* gitLocation(directory, host))?.repo; +}); /** * The main repository of a linked worktree. `undefined` unless the admin * directory lies in `/worktrees`, so a submodule never matches. */ -export async function worktreeRepository( +export const worktreeRepository = Effect.fnUntraced(function* ( worktree: string, admin: string, host: TidyHost, -): Promise { - const location = await gitLocation(worktree, host); +) { + const location = yield* gitLocation(worktree, host); if (location === undefined) return undefined; - const expected = normalizePath(join(location.common, "worktrees")); - return normalizePath(dirname(admin)) === expected ? location.repo : undefined; -} + const expected = yield* normalizePath(join(location.common, "worktrees")); + return (yield* normalizePath(dirname(admin))) === expected ? location.repo : undefined; +}); /** - * `lstat` with three outcomes: the stats; `undefined` when the path is absent - * (ENOENT or ENOTDIR); or a thrown `cannot check : ` for any other - * error. An unknown state never counts as absent, so it never permits an action. + * `lstat` with three outcomes: the information; `undefined` when the path is + * absent (ENOENT or ENOTDIR); or a `cannot check : ` failure for + * any other error. An unknown state never counts as absent, so it never + * permits an action. */ -function lstatIfPresent(path: string): Stats | undefined { - try { - return lstatSync(path); - } catch (cause) { - const code = errorCode(cause); - if (code === "ENOENT" || code === "ENOTDIR") return undefined; - throw new Error(`cannot check ${path}: ${code ?? errorMessage(cause)}`, { cause }); - } +const lstatIfPresent = Effect.fnUntraced(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.lstat(path).pipe( + Effect.catchTag("PlatformError", (error) => { + const code = errorCode(nodeError(error)); + return code === "ENOENT" || code === "ENOTDIR" + ? Effect.undefined + : Effect.fail(checkFailed(path, error)); + }), + ); +}); + +/** + * The `lstat` mtime of `path` in ms. Information without a modification time + * is an unknown state, which keeps the candidate. + */ +function mtimeOf( + path: string, + info: { readonly mtime: Option.Option }, +): Effect.Effect { + return Option.match(info.mtime, { + onNone: () => + Effect.fail(new TidyCheckFailed({ message: `cannot check ${path}: no modification time` })), + onSome: (mtime) => Effect.succeed(mtime.getTime()), + }); } /** Latest `lstat` mtime of the paths that exist; `undefined` when none exists. */ -function latestMtime(paths: ReadonlyArray): number | undefined { +const latestMtime = Effect.fnUntraced(function* (paths: ReadonlyArray) { let latest: number | undefined; for (const path of paths) { - const stats = lstatIfPresent(path); - if (stats !== undefined && (latest === undefined || stats.mtimeMs > latest)) { - latest = stats.mtimeMs; - } + const stats = yield* lstatIfPresent(path); + if (stats === undefined) continue; + const mtime = yield* mtimeOf(path, stats); + if (latest === undefined || mtime > latest) latest = mtime; } return latest; -} +}); -/** Latest mtime of a scratch entry and its immediate children; it throws when unknown. */ -function entryActivity(path: string): number | undefined { - const stats = lstatIfPresent(path); +/** Latest mtime of a scratch entry and its immediate children; it fails when unknown. */ +const entryActivity = Effect.fnUntraced(function* (path: string) { + const stats = yield* lstatIfPresent(path); if (stats === undefined) return undefined; - if (!stats.isDirectory()) return stats.mtimeMs; - let children: Array; - try { - children = readdirSync(path); - } catch (cause) { - throw new Error(`cannot check ${path}: ${errorCode(cause) ?? errorMessage(cause)}`, { - cause, - }); - } - return latestMtime([path, ...children.map((entry) => join(path, entry))]); -} + if (stats.type !== "Directory") return yield* mtimeOf(path, stats); + const fs = yield* FileSystem.FileSystem; + const children = yield* fs + .readDirectory(path) + .pipe(Effect.mapError((error) => checkFailed(path, error))); + return yield* latestMtime([path, ...children.map((entry) => join(path, entry))]); +}); /** * Paths that `git status --porcelain -z` lists, resolved against the worktree. @@ -797,28 +891,33 @@ function inUseReason(path: string, inUse: ReadonlyArray | undefined): st return inUse.some((cwd) => isSameOrInside(path, cwd)) ? IN_USE : undefined; } -/** Candidate checks (rule 5); a path that tidy cannot check keeps the worktree. */ -async function inspectWorktree( +/** + * Candidate checks (rule 5); a path that tidy cannot check, and any other + * failure or defect of the checks, keeps the worktree with its message. + */ +function inspectWorktree( candidate: WorktreeCandidate, context: PlanContext, -): Promise { - try { - return await checkWorktree(candidate, context); - } catch (cause) { - return { - path: candidate.path, - repo: undefined, - stackActivity: undefined, - verdict: { remove: false, reason: errorMessage(cause) }, - }; - } +): Effect.Effect { + return checkWorktree(candidate, context).pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.succeed({ + path: candidate.path, + repo: undefined, + stackActivity: undefined, + verdict: { remove: false, reason: causeMessage(cause) }, + }), + ), + ); } /** The checks in order; the first failed check keeps the worktree. */ -async function checkWorktree( +const checkWorktree = Effect.fnUntraced(function* ( candidate: WorktreeCandidate, context: PlanContext, -): Promise { +): Effect.fn.Return { const { path, admin } = candidate; const { host, now } = context; const keep = (reason: string, stackActivity?: number): InspectedWorktree => ({ @@ -828,26 +927,37 @@ async function checkWorktree( verdict: { remove: false, reason }, }); if (isSameOrInside(path, context.home)) return keep("contains the home directory"); - if (admin === undefined || lstatIfPresent(admin) === undefined) { + if (admin === undefined || (yield* lstatIfPresent(admin)) === undefined) { return keep("main repository is missing"); } const adminFiles = [join(admin, "HEAD"), join(admin, "index"), join(admin, "logs", "HEAD")]; - const activity = latestMtime(adminFiles) ?? lstatIfPresent(path)?.mtimeMs; - const status = await host.git(["-C", path, "--no-optional-locks", "status", "--porcelain", "-z"]); + let activity = yield* latestMtime(adminFiles); + if (activity === undefined) { + const stats = yield* lstatIfPresent(path); + if (stats !== undefined) activity = yield* mtimeOf(path, stats); + } + const status = yield* host.git([ + "-C", + path, + "--no-optional-locks", + "status", + "--porcelain", + "-z", + ]); const changed = status.code === 0 ? changedPaths(path, status.stdout) : []; - const latest = latestMtime([...adminFiles, ...changed]) ?? activity; - if (lstatIfPresent(join(admin, "locked")) !== undefined) return keep("locked", latest); + const latest = (yield* latestMtime([...adminFiles, ...changed])) ?? activity; + if ((yield* lstatIfPresent(join(admin, "locked"))) !== undefined) return keep("locked", latest); if (status.code !== 0) return keep(`git status failed: ${firstLine(status)}`, latest); if (changed.length > 0) return keep("has changes", latest); - const ref = await defaultBranchRef(path, host); + const ref = yield* defaultBranchRef(path, host); if (ref === undefined) return keep("no remote default branch", latest); - const merged = await host.git(["-C", path, "merge-base", "--is-ancestor", "HEAD", ref]); + const merged = yield* host.git(["-C", path, "merge-base", "--is-ancestor", "HEAD", ref]); if (merged.code !== 0) return keep(`not merged into ${shortRef(ref)}`, latest); const idle = activity === undefined ? 0 : now - activity; if (idle < WORKTREE_IDLE_MS) return keep(`active ${hours(idle)} h ago`, latest); const blocked = inUseReason(path, context.inUse); if (blocked !== undefined) return keep(blocked, latest); - const repo = await worktreeRepository(path, admin, host); + const repo = yield* worktreeRepository(path, admin, host); if (repo === undefined) return keep("not a linked worktree", latest); return { path, @@ -855,7 +965,7 @@ async function checkWorktree( stackActivity: latest, verdict: { remove: true, reason: `merged into ${shortRef(ref)}, idle ${hours(idle)} h` }, }; -} +}); // ------------------------------------------------------------- containers ---- @@ -866,15 +976,15 @@ interface ContainerRow { readonly workingDir: string; } -function parseContainerRows(stdout: string): Array { +const parseContainerRows = Effect.fnUntraced(function* (stdout: string) { const rows: Array = []; for (const line of stdout.split("\n")) { const [id = "", state = "", project = "", workingDir = ""] = line.trim().split("\t"); if (id === "" || workingDir.trim() === "") continue; - rows.push({ id, state, project, workingDir: normalizePath(workingDir.trim()) }); + rows.push({ id, state, project, workingDir: yield* normalizePath(workingDir.trim()) }); } return rows; -} +}); /** The first-level scratch entry that holds `path`, or `undefined`. */ function scratchEntryOf(scratchRoot: string | undefined, path: string): string | undefined { @@ -883,27 +993,39 @@ function scratchEntryOf(scratchRoot: string | undefined, path: string): string | return first === undefined || first === "" ? undefined : join(scratchRoot, first); } +/** The activity of a first-level scratch entry; `symbolic link` for a link, which stays. */ +const scratchEntryActivity = Effect.fnUntraced(function* (path: string) { + if ((yield* lstatIfPresent(path))?.type === "SymbolicLink") return "symbolic link" as const; + return yield* entryActivity(path); +}); + // ------------------------------------------------------------------ plan ---- /** Build the sweep plan. Read-only: it runs only listing commands. */ -export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise { - const roots = agentRoots(inputs); +export const planTidy = Effect.fn("planTidy")(function* ( + inputs: TidyInputs, + host: TidyHost, +): Effect.fn.Return { + const roots = yield* agentRoots(inputs); const notes: Array = [...roots.notes]; const kept: Array = []; const now = host.now(); - const rows = await host.processes(); + const rows = yield* host.processes(); if (rows === undefined) notes.push(PROCESS_LIST_UNAVAILABLE_NOTE); const inUse = rows === undefined ? undefined - : rows.flatMap((row) => (row.cwd === undefined ? [] : [normalizePath(row.cwd)])); + : yield* Effect.forEach( + rows.flatMap((row) => (row.cwd === undefined ? [] : [row.cwd])), + (cwd) => normalizePath(cwd), + ); const context: PlanContext = { home: roots.home, now, inUse, host }; - const listing = await listWorktreeCandidates(inputs, host); + const listing = yield* listWorktreeCandidates(inputs, host); kept.push(...listing.kept); notes.push(...listing.notes); - const inspected = await runBounded( - listing.candidates.map((candidate) => () => inspectWorktree(candidate, context)), + const inspected = yield* runBounded( + listing.candidates.map((candidate) => inspectWorktree(candidate, context)), 3, ); const removals = new Map< @@ -925,7 +1047,7 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise = []; const removeContainers: Array = []; - const docker = await resolveDockerAccess(host); + const docker = yield* resolveDockerAccess(host); const runDocker = localDocker(host, docker); // A worktree with an unknown container list stays: removing it could leave // a running stack without its directory. A host without docker has no stack. @@ -936,7 +1058,7 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise candidate.path)), ].filter((path): path is string => path !== undefined); const groups = new Map>(); - for (const row of listed.code === 0 ? parseContainerRows(listed.stdout) : []) { + for (const row of listed.code === 0 ? yield* parseContainerRows(listed.stdout) : []) { const key = `${row.project}\0${row.workingDir}`; groups.set(key, [...(groups.get(key) ?? []), row]); } @@ -963,14 +1085,12 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise isSameOrInside(root, workingDir))) continue; // Only a path that `lstat` reports absent is gone; an unknown state keeps the rows. - let present: boolean; - try { - present = lstatIfPresent(workingDir) !== undefined; - } catch (cause) { - notes.push(errorMessage(cause)); + const presence = yield* Effect.result(lstatIfPresent(workingDir)); + if (Result.isFailure(presence)) { + notes.push(presence.failure.message); continue; } - if (!present) { + if (presence.success === undefined) { removeContainers.push({ kind: "remove-containers", project, @@ -988,13 +1108,14 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise isSameOrInside(root, cwd))) continue; stopProcesses.push({ kind: "stop-process", @@ -1048,19 +1169,18 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise = []; const scratch = roots.scratchRoot; - if (scratch !== undefined && lstatOrUndefined(scratch)?.isDirectory() === true) { - for (const entry of sortedEntries(scratch)) { + if (scratch !== undefined && (yield* lstatOrUndefined(scratch))?.type === "Directory") { + for (const entry of yield* sortedEntries(scratch)) { const path = join(scratch, entry); const subject = `scratch ${path}`; - let activity: number | undefined; - try { - if (lstatIfPresent(path)?.isSymbolicLink() === true) { - kept.push({ subject, reason: "is a symbolic link" }); - continue; - } - activity = entryActivity(path); - } catch (cause) { - kept.push({ subject, reason: errorMessage(cause) }); + const checked = yield* Effect.result(scratchEntryActivity(path)); + if (Result.isFailure(checked)) { + kept.push({ subject, reason: checked.failure.message }); + continue; + } + const activity = checked.success; + if (activity === "symbolic link") { + kept.push({ subject, reason: "is a symbolic link" }); continue; } if (activity === undefined) continue; @@ -1095,7 +1215,7 @@ export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise, now: number): void { - if (lines.length === 0) return; - try { - if (statSync(log).size > LOG_ROTATE_BYTES) renameSync(log, `${log}.1`); - } catch (cause) { - if (errorCode(cause) !== "ENOENT") throw cause; - } - const stamp = new Date(now).toISOString(); - appendFileSync(log, lines.map((line) => `${stamp} ${line}\n`).join(""), { mode: 0o600 }); +/** A failed log rotation or append, with the message of its Node error. */ +function logFailed(error: PlatformError): TidyCheckFailed { + const cause = nodeError(error); + return new TidyCheckFailed({ message: errorMessage(cause), cause }); } -async function removeProjectNetworks( +const appendLog = Effect.fnUntraced(function* ( + log: string, + lines: ReadonlyArray, + now: number, +) { + if (lines.length === 0) return; + const fs = yield* FileSystem.FileSystem; + yield* fs.stat(log).pipe( + Effect.flatMap((info) => + info.size > BigInt(LOG_ROTATE_BYTES) ? fs.rename(log, `${log}.1`) : Effect.void, + ), + Effect.catchTag("PlatformError", (error) => + errorCode(nodeError(error)) === "ENOENT" ? Effect.void : Effect.fail(logFailed(error)), + ), + ); + const stamp = new Date(now).toISOString(); + yield* fs + .writeFileString(log, lines.map((line) => `${stamp} ${line}\n`).join(""), { + flag: "a", + mode: 0o600, + }) + .pipe(Effect.mapError(logFailed)); +}); + +const removeProjectNetworks = Effect.fnUntraced(function* ( projects: ReadonlyArray, runDocker: DockerRunner, -): Promise { +) { for (const project of projects) { - const list = await runDocker([ + const list = yield* runDocker([ "network", "ls", "-q", @@ -1146,9 +1285,9 @@ async function removeProjectNetworks( .filter((id) => id !== "") : []; // A network that another container still uses stays; that failure is not a tidy failure. - if (ids.length > 0) await runDocker(["network", "rm", ...ids]); + if (ids.length > 0) yield* runDocker(["network", "rm", ...ids]); } -} +}); /** * Perform a plan. The caller holds the tidy lock from before `planTidy`. Order: @@ -1156,16 +1295,23 @@ async function removeProjectNetworks( * touched repository, stop containers, remove containers, remove scratch * entries. Never `git worktree remove --force`. Every Docker call uses the * endpoint that the plan verified. + * + * It defers a signal exit for the rest of the scope of its caller + * (`deferSignalExit`), so its plain steps, the log rotation and the log + * append included, run to their end; only a `git` or `docker` call that waits + * is a signal exit point (`signalExitPoint`), as the awaited tool calls were. */ -export async function applyTidy( +export const applyTidy = Effect.fn("applyTidy")(function* ( plan: TidyPlan, inputs: TidyInputs, host: TidyHost, -): Promise<{ - readonly failures: number; - readonly lines: ReadonlyArray; -}> { - ensureDirectory(kitCacheDir(inputs.home)); +): Effect.fn.Return< + { readonly failures: number; readonly lines: ReadonlyArray }, + LegacyStepFailed, + FileSystem.FileSystem | Scope.Scope +> { + yield* deferSignalExit; + yield* bridgeSync("ensureDirectory", () => ensureDirectory(kitCacheDir(inputs.home))); const lines: Array = []; let failures = 0; const done = (outcome: "removed" | "stopped", subject: string): void => { @@ -1179,19 +1325,26 @@ export async function applyTidy( plan.actions.filter( (action): action is Extract => action.kind === kind, ); + const git = (args: ReadonlyArray) => signalExitPoint(host.git(args)); for (const action of byKind("stop-process")) { const subject = actionSubject(action); - try { - process.kill(action.pid, "SIGTERM"); + const sent = yield* Effect.result( + Effect.try({ + try: () => process.kill(action.pid, "SIGTERM"), + catch: (cause) => new TidyCheckFailed({ message: errorMessage(cause), cause }), + }), + ); + if (Result.isSuccess(sent) || errorCode(sent.failure.cause) === "ESRCH") { done("stopped", subject); - } catch (cause) { - if (errorCode(cause) === "ESRCH") done("stopped", subject); - else failed(subject, errorMessage(cause)); + } else { + failed(subject, sent.failure.message); } } // A container action without a verified local endpoint fails and changes nothing. - const runDocker = localDocker(host, plan.docker); + const verified = localDocker(host, plan.docker); + const runDocker: DockerRunner | undefined = + verified === undefined ? undefined : (args) => signalExitPoint(verified(args)); const noDocker = plan.docker.kind === "missing" ? "docker unavailable" : notLocalMessage(plan.docker.endpoint); @@ -1203,20 +1356,20 @@ export async function applyTidy( failed(subject, noDocker); continue; } - const removed = await runDocker(["rm", "--force", "--volumes", ...action.containerIds]); + const removed = yield* runDocker(["rm", "--force", "--volumes", ...action.containerIds]); if (removed.code !== 0) { failed(subject, `docker rm: ${firstLine(removed)}`); continue; } - await removeProjectNetworks(action.projects, runDocker); + yield* removeProjectNetworks(action.projects, runDocker); } touched.add(action.repo); - const result = await host.git(["-C", action.repo, "worktree", "remove", "--", action.path]); + const result = yield* git(["-C", action.repo, "worktree", "remove", "--", action.path]); if (result.code === 0) done("removed", subject); else failed(subject, firstLine(result)); } for (const repo of touched) { - const result = await host.git(["-C", repo, "worktree", "prune"]); + const result = yield* git(["-C", repo, "worktree", "prune"]); if (result.code !== 0) failed(`worktree prune in ${repo}`, firstLine(result)); } @@ -1225,7 +1378,7 @@ export async function applyTidy( failed(actionSubject(action), noDocker); continue; } - const result = await runDocker(["stop", ...action.ids]); + const result = yield* runDocker(["stop", ...action.ids]); if (result.code === 0) done("stopped", actionSubject(action)); else failed(actionSubject(action), firstLine(result)); } @@ -1235,42 +1388,40 @@ export async function applyTidy( failed(actionSubject(action), noDocker); continue; } - const result = await runDocker(["rm", "--force", "--volumes", ...action.ids]); + const result = yield* runDocker(["rm", "--force", "--volumes", ...action.ids]); if (result.code !== 0) { failed(actionSubject(action), firstLine(result)); continue; } - await removeProjectNetworks(action.project === "" ? [] : [action.project], runDocker); + yield* removeProjectNetworks(action.project === "" ? [] : [action.project], runDocker); done("removed", actionSubject(action)); } - const scratch = agentRoots(inputs).scratchRoot; + const scratch = (yield* agentRoots(inputs)).scratchRoot; for (const action of byKind("remove-scratch")) { const subject = actionSubject(action); if (scratch === undefined) { failed(subject, "the scratch root is refused"); continue; } - let activity: number | undefined; - try { - activity = entryActivity(action.path); - } catch (cause) { - lines.push(`kept ${subject}: ${errorMessage(cause)}`); + const checked = yield* Effect.result(entryActivity(action.path)); + if (Result.isFailure(checked)) { + lines.push(`kept ${subject}: ${checked.failure.message}`); continue; } + const activity = checked.success; if (activity !== undefined && host.now() - activity < SCRATCH_IDLE_MS) { lines.push(`kept ${subject}: active ${hours(host.now() - activity)} h ago`); continue; } - const outcome = removeTemporaryPath(action.path, [scratch], inputs.home); + const outcome = yield* bridgeSync("removeTemporaryPath", () => + removeTemporaryPath(action.path, [scratch], inputs.home), + ); if (outcome.kind === "removed") done("removed", subject); else failed(subject, outcome.reason); } - try { - appendLog(tidyLogPath(inputs.home), lines, host.now()); - } catch (cause) { - failed(`log ${tidyLogPath(inputs.home)}`, errorMessage(cause)); - } + const logged = yield* Effect.result(appendLog(tidyLogPath(inputs.home), lines, host.now())); + if (Result.isFailure(logged)) failed(`log ${tidyLogPath(inputs.home)}`, logged.failure.message); return { failures, lines }; -} +}); diff --git a/cli/src/engine-native/tidyReport.ts b/cli/src/engine-native/tidyReport.ts index 7563ee58..dfc5e8d4 100644 --- a/cli/src/engine-native/tidyReport.ts +++ b/cli/src/engine-native/tidyReport.ts @@ -1,16 +1,20 @@ /** * Read-only report of disk and memory use that `docks-kit tidy --apply` does * not remove. The report runs only listing and measuring commands. Each - * section runs on its own; a failure becomes one `unavailable: ` line. + * section runs on its own; a failure or a defect becomes one + * `unavailable: ` line. */ -import { readFileSync } from "node:fs"; import { join } from "node:path"; -import { isSameOrInside } from "./scratch"; +import { Cause, Effect, FileSystem, Option, Schema } from "effect"; + import { errorMessage } from "./errorText"; +import { parseJson } from "./jq"; +import { isSameOrInside } from "./scratch"; import { runBounded } from "./syncConcurrency"; import { agentRoots, + causeMessage, commandName, DAY_MS, defaultBranchRef, @@ -21,6 +25,7 @@ import { lstatOrUndefined, localDocker, mainRepository, + nodeError, normalizePath, notLocalMessage, orphanParents, @@ -32,6 +37,7 @@ import { worktreeRepository, type DockerAccess, type ProcessRow, + type TidyFailure, type TidyHost, type TidyInputs, } from "./tidy"; @@ -41,6 +47,25 @@ export interface TidyReportSection { readonly lines: ReadonlyArray; } +/** + * A report section cannot be built. `message` is its `unavailable:` text; + * `cause` is the Node error of a failed read when one exists. + */ +export class ReportSectionFailed extends Schema.TaggedError< + ReportSectionFailed, + { readonly brand: unique symbol } +>()("ReportSectionFailed", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +/** The lines of one section, or its failure. */ +type SectionLines = Effect.Effect< + ReadonlyArray, + TidyFailure | ReportSectionFailed, + FileSystem.FileSystem +>; + const REPORT_PROCESS_AGE_MS = 12 * HOUR_MS; const RECENT_MS = 30 * DAY_MS; const TEMP_ENTRY_COUNT = 5; @@ -92,28 +117,34 @@ function formatAge(ms: number): string { return ms < 2 * DAY_MS ? `${Math.floor(ms / HOUR_MS)} h` : `${Math.floor(ms / DAY_MS)} d`; } +/** The `lstat` mtime in ms, or `undefined` when the information has none. */ +function mtimeMs(info: { readonly mtime: Option.Option }): number | undefined { + return Option.getOrUndefined(Option.map(info.mtime, (mtime) => mtime.getTime())); +} + /** Disk use of one path in KiB, from `du -sk`. A partial read (exit 1) still counts. */ -async function sizeKb(path: string, host: TidyHost): Promise { - const result = await host.run("du", ["-sk", path]); +const sizeKb = Effect.fnUntraced(function* (path: string, host: TidyHost) { + const result = yield* host.run("du", ["-sk", path]); const kb = Number.parseInt(result.stdout.trim().split(/\s+/)[0] ?? "", 10); if (Number.isFinite(kb)) return kb; - throw new Error(result.missing ? "du is not on PATH" : `du ${path}: ${firstLine(result)}`); -} + return yield* new ReportSectionFailed({ + message: result.missing ? "du is not on PATH" : `du ${path}: ${firstLine(result)}`, + }); +}); /** ` ` lines for the paths that exist, plus their hints in order. */ -async function sizeLines( +const sizeLines = Effect.fnUntraced(function* ( entries: ReadonlyArray<{ readonly path: string; readonly hint?: string }>, home: string, host: TidyHost, -): Promise> { - const present = entries - .map((entry) => ({ - ...entry, - path: entry.path.startsWith("/") ? entry.path : join(home, entry.path), - })) - .filter((entry) => lstatOrUndefined(entry.path)?.isDirectory() === true); - const sizes = await runBounded( - present.map((entry) => () => sizeKb(entry.path, host)), +) { + const present: Array<{ readonly path: string; readonly hint?: string }> = []; + for (const entry of entries) { + const path = entry.path.startsWith("/") ? entry.path : join(home, entry.path); + if ((yield* lstatOrUndefined(path))?.type === "Directory") present.push({ ...entry, path }); + } + const sizes = yield* runBounded( + present.map((entry) => sizeKb(entry.path, host)), 3, ); const hints = [ @@ -123,17 +154,26 @@ async function sizeLines( ...present.map((entry, index) => `${formatKb(sizes[index]!)} ${entry.path}`), ...hints.map((hint) => `hint: ${hint}`), ]; -} +}); // --------------------------------------------------------------- sections ---- -async function memorySection( +const memorySection = Effect.fnUntraced(function* ( rows: ReadonlyArray | undefined, host: TidyHost, -): Promise> { +) { const lines: Array = []; if (process.platform === "linux") { - const meminfo = readFileSync("/proc/meminfo", "utf8"); + const fs = yield* FileSystem.FileSystem; + const meminfo = yield* fs.readFileString("/proc/meminfo").pipe( + Effect.mapError((error) => { + const cause = nodeError(error); + return new ReportSectionFailed({ + message: errorMessage(cause), + cause, + }); + }), + ); const field = (name: string): number | undefined => { const match = new RegExp(`^${name}:\\s+(\\d+) kB`, "m").exec(meminfo); return match === null ? undefined : Number(match[1]); @@ -143,8 +183,11 @@ async function memorySection( if (total !== undefined && free !== undefined) { lines.push(`swap: ${formatKb(total - free)} used of ${formatKb(total)}`); } - const mounts = ["/tmp", "/dev/shm"].filter((path) => lstatOrUndefined(path) !== undefined); - const df = await host.run("df", ["-kP", ...mounts]); + const mounts: Array = []; + for (const path of ["/tmp", "/dev/shm"]) { + if ((yield* lstatOrUndefined(path)) !== undefined) mounts.push(path); + } + const df = yield* host.run("df", ["-kP", ...mounts]); if (df.code !== 0) lines.push(`unavailable: df: ${firstLine(df)}`); else { const dfRows = df.stdout @@ -173,11 +216,11 @@ async function memorySection( lines.push("hint: close idle omp sessions"); } return lines; -} +}); -async function temporarySection(host: TidyHost, now: number): Promise> { +const temporarySection = Effect.fnUntraced(function* (host: TidyHost, now: number) { const uid = process.getuid?.(); - const roots = [...new Set(TEMP_ROOTS.map((root) => normalizePath(root)))]; + const roots = [...new Set(yield* Effect.forEach(TEMP_ROOTS, (root) => normalizePath(root)))]; const entries: Array<{ readonly path: string; readonly ageMs: number; @@ -185,21 +228,26 @@ async function temporarySection(host: TidyHost, now: number): Promise = []; for (const root of roots) { - for (const name of sortedEntries(root)) { + for (const name of yield* sortedEntries(root)) { const path = join(root, name); - const stats = lstatOrUndefined(path); - if (stats === undefined || (uid !== undefined && stats.uid !== uid)) continue; + const stats = yield* lstatOrUndefined(path); + if (stats === undefined) continue; + const owner = Option.getOrUndefined(stats.uid); + if (uid !== undefined && owner !== uid) continue; + const mtime = mtimeMs(stats); + if (mtime === undefined) continue; + const blocks = Option.getOrElse(stats.blocks, () => 0n); entries.push({ path, - ageMs: now - stats.mtimeMs, - directory: stats.isDirectory(), - kb: Math.ceil((stats.blocks * 512) / 1024), + ageMs: now - mtime, + directory: stats.type === "Directory", + kb: Math.ceil((Number(blocks) * 512) / 1024), }); } } const directories = entries.filter((entry) => entry.directory); - const sizes = await runBounded( - directories.map((entry) => () => sizeKb(entry.path, host)), + const sizes = yield* runBounded( + directories.map((entry) => sizeKb(entry.path, host)), 3, ); const measured = [ @@ -214,12 +262,12 @@ async function temporarySection(host: TidyHost, now: number): Promise removes an entry that an agent created", ]; -} +}); /** Listening TCP ports per PID, from `ss -ltnpH`. */ -async function listeningPorts(host: TidyHost): Promise>> { +const listeningPorts = Effect.fnUntraced(function* (host: TidyHost) { const ports = new Map>(); - const result = await host.run("ss", ["-ltnpH"]); + const result = yield* host.run("ss", ["-ltnpH"]); if (result.code !== 0) return ports; for (const line of result.stdout.split("\n")) { const local = line.trim().split(/\s+/)[3]; @@ -231,31 +279,35 @@ async function listeningPorts(host: TidyHost): Promise>> } } return ports; -} +}); -async function processSection( +const processSection = Effect.fnUntraced(function* ( rows: ReadonlyArray | undefined, territory: ReadonlyArray, host: TidyHost, -): Promise> { +) { if (rows === undefined) return [`unavailable: ${PROCESS_LIST_UNAVAILABLE}`]; const parents = orphanParents(rows); - const selected = rows.filter((row) => { + const selected: Array = []; + for (const row of rows) { // The report never suggests `kill` for the agent harness, its launcher, or the kit. - if (row.ageMs < REPORT_PROCESS_AGE_MS || isProtectedProcess(row)) return false; + if (row.ageMs < REPORT_PROCESS_AGE_MS || isProtectedProcess(row)) continue; const names = row.args .split(/\s+/) .map((word) => word.slice(word.lastIndexOf("/") + 1)) .join(" "); const devOrphan = parents.has(row.ppid) && DEV_PROCESS.test(names); - if (devOrphan) return true; - if (row.cwd === undefined) return false; - const cwd = normalizePath(row.cwd); - return territory.some((root) => isSameOrInside(root, cwd)); - }); + if (devOrphan) { + selected.push(row); + continue; + } + if (row.cwd === undefined) continue; + const cwd = yield* normalizePath(row.cwd); + if (territory.some((root) => isSameOrInside(root, cwd))) selected.push(row); + } if (selected.length === 0) return []; const ports = - process.platform === "linux" ? await listeningPorts(host) : new Map>(); + process.platform === "linux" ? yield* listeningPorts(host) : new Map>(); return [ ...selected.map((row) => { const listening = [...(ports.get(row.pid) ?? [])]; @@ -264,19 +316,25 @@ async function processSection( }), "hint: kill after you confirm that nothing uses it", ]; -} +}); -async function dockerSection(host: TidyHost, docker: DockerAccess): Promise> { - if (docker.kind === "missing") throw new Error("docker is not on PATH"); +const dockerSection = Effect.fnUntraced(function* (host: TidyHost, docker: DockerAccess) { + if (docker.kind === "missing") { + return yield* new ReportSectionFailed({ message: "docker is not on PATH" }); + } const runDocker = localDocker(host, docker); - if (runDocker === undefined) throw new Error(notLocalMessage(docker.endpoint)); - const result = await runDocker([ + if (runDocker === undefined) { + return yield* new ReportSectionFailed({ message: notLocalMessage(docker.endpoint) }); + } + const result = yield* runDocker([ "system", "df", "--format", "{{.Type}}\\t{{.Size}}\\t{{.Reclaimable}}", ]); - if (result.code !== 0) throw new Error(`docker system df: ${firstLine(result)}`); + if (result.code !== 0) { + return yield* new ReportSectionFailed({ message: `docker system df: ${firstLine(result)}` }); + } return result.stdout .split("\n") .filter((line) => line.trim() !== "") @@ -288,26 +346,26 @@ async function dockerSection(host: TidyHost, docker: DockerAccess): Promise> { - if (process.platform === "darwin") return sizeLines([{ path: ".Trash" }], home, host); +const trashSection = Effect.fnUntraced(function* (home: string, host: TidyHost) { + if (process.platform === "darwin") return yield* sizeLines([{ path: ".Trash" }], home, host); const files = join(home, ".local", "share", "Trash", "files"); - const lines = await sizeLines([{ path: files }], home, host); + const lines = yield* sizeLines([{ path: files }], home, host); if (lines.length === 0) return []; const info = join(home, ".local", "share", "Trash", "info"); + const fs = yield* FileSystem.FileSystem; let oldest: string | undefined; - for (const name of sortedEntries(info)) { + for (const name of yield* sortedEntries(info)) { if (!name.endsWith(".trashinfo")) continue; - try { - const date = /^DeletionDate=(.+)$/m.exec(readFileSync(join(info, name), "utf8"))?.[1]?.trim(); - if (date !== undefined && (oldest === undefined || date < oldest)) oldest = date; - } catch { - // An unreadable entry does not change the oldest date. - } + // An unreadable entry does not change the oldest date. + const text = yield* fs.readFileString(join(info, name)).pipe(Effect.option); + if (Option.isNone(text)) continue; + const date = /^DeletionDate=(.+)$/m.exec(text.value)?.[1]?.trim(); + if (date !== undefined && (oldest === undefined || date < oldest)) oldest = date; } if (oldest !== undefined) lines.push(`oldest item deleted ${oldest}`); - const setting = await host.run("gsettings", [ + const setting = yield* host.run("gsettings", [ "get", "org.gnome.desktop.privacy", "remove-old-trash-files", @@ -316,35 +374,35 @@ async function trashSection(home: string, host: TidyHost): Promise lines.push("hint: gsettings set org.gnome.desktop.privacy remove-old-trash-files true"); } return lines; -} +}); -async function gitSection( +const gitSection = Effect.fnUntraced(function* ( inputs: TidyInputs, worktreeRoot: string | undefined, host: TidyHost, -): Promise> { +) { const repos = new Set(); if (inputs.repo !== undefined) { - const repo = await mainRepository(inputs.repo, host); + const repo = yield* mainRepository(inputs.repo, host); if (repo !== undefined) repos.add(repo); } else { - const listing = await listWorktreeCandidates(inputs, host); + const listing = yield* listWorktreeCandidates(inputs, host); for (const candidate of listing.candidates) { if (candidate.admin === undefined) continue; - const repo = await worktreeRepository(candidate.path, candidate.admin, host); + const repo = yield* worktreeRepository(candidate.path, candidate.admin, host); if (repo !== undefined) repos.add(repo); } } const lines: Array = []; for (const repo of [...repos].sort()) { - const worktrees = (await repositoryWorktrees(repo, host)) ?? []; - const ref = await defaultBranchRef(repo, host); + const worktrees = (yield* repositoryWorktrees(repo, host)) ?? []; + const ref = yield* defaultBranchRef(repo, host); if (ref !== undefined) { const defaultBranch = ref.replace(/^refs\/remotes\/[^/]+\//, ""); const checkedOut = new Set( worktrees.flatMap((entry) => (entry.branch === undefined ? [] : [shortRef(entry.branch)])), ); - const merged = await host.git([ + const merged = yield* host.git([ "-C", repo, "branch", @@ -363,7 +421,7 @@ async function gitSection( lines.push("hint: git branch -d "); } } - const stash = await host.git(["-C", repo, "stash", "list"]); + const stash = yield* host.git(["-C", repo, "stash", "list"]); const stashes = stash.stdout.split("\n").filter((line) => line.trim() !== "").length; if (stash.code === 0 && stashes > 0) lines.push(`${repo}: stash entries: ${stashes}`); const outside = worktrees @@ -379,24 +437,27 @@ async function gitSection( } } return lines; -} +}); /** Names in `directory` whose entry changed in the last 30 days. */ -function recentNames( +const recentNames = Effect.fnUntraced(function* ( directory: string, now: number, keep: (name: string) => boolean, -): Array { - return sortedEntries(directory).filter((name) => { - if (!keep(name)) return false; - const stats = lstatOrUndefined(join(directory, name)); - return stats !== undefined && now - stats.mtimeMs <= RECENT_MS; - }); -} +) { + const names: Array = []; + for (const name of yield* sortedEntries(directory)) { + if (!keep(name)) continue; + const stats = yield* lstatOrUndefined(join(directory, name)); + const mtime = stats === undefined ? undefined : mtimeMs(stats); + if (mtime !== undefined && now - mtime <= RECENT_MS) names.push(name); + } + return names; +}); -async function scheduledSection(home: string, host: TidyHost, now: number): Promise> { +const scheduledSection = Effect.fnUntraced(function* (home: string, host: TidyHost, now: number) { const lines: Array = []; - const crontab = await host.run("crontab", ["-l"]); + const crontab = yield* host.run("crontab", ["-l"]); if (crontab.code === 0) { const entries = crontab.stdout .split("\n") @@ -406,8 +467,10 @@ async function scheduledSection(home: string, host: TidyHost, now: number): Prom } const units = process.platform === "darwin" - ? recentNames(join(home, "Library", "LaunchAgents"), now, (name) => name.endsWith(".plist")) - : recentNames(join(home, ".config", "systemd", "user"), now, (name) => + ? yield* recentNames(join(home, "Library", "LaunchAgents"), now, (name) => + name.endsWith(".plist"), + ) + : yield* recentNames(join(home, ".config", "systemd", "user"), now, (name) => /\.(service|timer|path)$/.test(name), ); if (units.length > 0) { @@ -415,95 +478,112 @@ async function scheduledSection(home: string, host: TidyHost, now: number): Prom lines.push(`${label} changed in the last 30 days: ${units.join(", ")}`); } return lines; -} +}); /** * Bun keeps the packages that `bun add -g` installed in the dependencies of * its global `package.json`; its `node_modules` also holds their dependencies. */ -function bunGlobalPackages(home: string): Array { - try { - const manifest: unknown = JSON.parse( - readFileSync(join(home, ".bun", "install", "global", "package.json"), "utf8"), - ); - const dependencies = - typeof manifest === "object" && manifest !== null && "dependencies" in manifest - ? manifest.dependencies - : undefined; - return typeof dependencies === "object" && dependencies !== null - ? Object.keys(dependencies).sort() - : []; - } catch { - return []; - } -} +const bunGlobalPackages = Effect.fnUntraced(function* (home: string) { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs + .readFileString(join(home, ".bun", "install", "global", "package.json")) + .pipe(Effect.option); + const manifest = Option.isNone(text) ? undefined : parseJson(text.value); + const dependencies = + typeof manifest === "object" && manifest !== null && "dependencies" in manifest + ? manifest["dependencies"] + : undefined; + return typeof dependencies === "object" && dependencies !== null + ? Object.keys(dependencies).sort() + : []; +}); -async function globalSection(home: string, host: TidyHost, now: number): Promise> { +const globalSection = Effect.fnUntraced(function* (home: string, host: TidyHost, now: number) { const keep = (name: string): boolean => name !== ".bin" && name !== ".cache"; const lines: Array = []; const bunModules = join(home, ".bun", "install", "global", "node_modules"); - const bun = bunGlobalPackages(home).filter((name) => { - const stats = lstatOrUndefined(join(bunModules, name)); - return stats !== undefined && now - stats.mtimeMs <= RECENT_MS; - }); + const bun: Array = []; + for (const name of yield* bunGlobalPackages(home)) { + const stats = yield* lstatOrUndefined(join(bunModules, name)); + const mtime = stats === undefined ? undefined : mtimeMs(stats); + if (mtime !== undefined && now - mtime <= RECENT_MS) bun.push(name); + } if (bun.length > 0) lines.push(`bun global installs changed in the last 30 days: ${bun.join(", ")}`); - const npmRoot = await host.run("npm", ["root", "-g"]); + const npmRoot = yield* host.run("npm", ["root", "-g"]); const root = npmRoot.code === 0 ? npmRoot.stdout.trim() : ""; if (root !== "") { - const npm = recentNames(root, now, keep); + const npm = yield* recentNames(root, now, keep); if (npm.length > 0) lines.push(`npm global installs changed in the last 30 days: ${npm.join(", ")}`); } return lines; -} +}); -async function section( +/** + * One section: its lines, or none when it has no line. A failure or a defect + * becomes `unavailable: `; an interruption stays an interruption. + */ +function section( title: string, - build: () => Promise>, -): Promise { - try { - const lines = await build(); - return lines.length === 0 ? undefined : { title, lines }; - } catch (cause) { - return { title, lines: [`unavailable: ${errorMessage(cause)}`] }; - } + build: SectionLines, +): Effect.Effect { + return build.pipe( + Effect.map((lines) => (lines.length === 0 ? undefined : { title, lines })), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.succeed({ title, lines: [`unavailable: ${causeMessage(cause)}`] }), + ), + ); } /** * Build the report sections in their fixed order; a section with no lines is * left out. `docker` is the access that the plan of the same run resolved. + * The sections run concurrently. */ -export async function buildTidyReport( +export const buildTidyReport = Effect.fn("buildTidyReport")(function* ( inputs: TidyInputs, host: TidyHost, docker: DockerAccess, -): Promise> { +): Effect.fn.Return, never, FileSystem.FileSystem> { if (process.platform === "win32") { return [{ title: "Report", lines: ["docks-kit tidy --report supports Linux and macOS"] }]; } const now = host.now(); - const home = normalizePath(inputs.home); - const roots = agentRoots(inputs); - const rows = await host.processes().catch(() => undefined); + const home = yield* normalizePath(inputs.home); + const roots = yield* agentRoots(inputs); + // A failed process list, a defect included, is an unavailable list. + const rows = yield* host + .processes() + .pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.undefined, + ), + ); // A process cwd keeps the spelling that it has when the path is gone, so // each temporary root counts in both its typed and its real spelling. - const territory = [ - roots.worktreeRoot, - roots.scratchRoot, - ...TEMP_ROOTS.flatMap((root) => [root, normalizePath(root)]), - ].filter((path): path is string => path !== undefined); - const sections = await Promise.all([ - section("Memory", () => memorySection(rows, host)), - section("Temporary directories", () => temporarySection(host, now)), - section("Processes", () => processSection(rows, territory, host)), - section("Docker", () => dockerSection(host, docker)), - section("Package and tool caches", () => sizeLines(CACHES, home, host)), - section("Trash", () => trashSection(home, host)), - section("Git", () => gitSection(inputs, roots.worktreeRoot, host)), - section("Agent histories", () => sizeLines(HISTORIES, home, host)), - section("Scheduled jobs and services", () => scheduledSection(home, host, now)), - section("Global installs", () => globalSection(home, host, now)), - ]); + const territory: Array = []; + for (const root of [roots.worktreeRoot, roots.scratchRoot]) { + if (root !== undefined) territory.push(root); + } + for (const root of TEMP_ROOTS) territory.push(root, yield* normalizePath(root)); + const sections = yield* Effect.all( + [ + section("Memory", memorySection(rows, host)), + section("Temporary directories", temporarySection(host, now)), + section("Processes", processSection(rows, territory, host)), + section("Docker", dockerSection(host, docker)), + section("Package and tool caches", sizeLines(CACHES, home, host)), + section("Trash", trashSection(home, host)), + section("Git", gitSection(inputs, roots.worktreeRoot, host)), + section("Agent histories", sizeLines(HISTORIES, home, host)), + section("Scheduled jobs and services", scheduledSection(home, host, now)), + section("Global installs", globalSection(home, host, now)), + ], + { concurrency: "unbounded" }, + ); return sections.filter((entry): entry is TidyReportSection => entry !== undefined); -} +}); diff --git a/cli/src/engine.ts b/cli/src/engine.ts index a46ab374..2d230c9f 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -51,17 +51,35 @@ export const engineFailureDetail = (cause: Cause.Cause): string = return Cause.isFailReason(last) ? failureDetail(last.error) : failureText(last.defect); }; +/** + * The signal state of `exitOnSignal`: `deferred` counts the open + * `deferSignalExit` scopes, `exitPoints` the calls that `signalExitPoint` + * runs, and `recorded` is true once a signal came while an exit was deferred. + */ +const signals = { deferred: 0, exitPoints: 0, recorded: false }; + +/** The exit of a signal while `exitOnSignal` is active: 130 for SIGINT and SIGTERM. */ +const exitNow = (): never => process.exit(130); + /** * While the engine runs, a SIGINT or SIGTERM ends the process at once with * 130, as the Promise seam did: an `omp` or installer child of a bridged pass * cannot be stopped from Effect code until #297, so an interrupt would wait * for it. The listeners go first, before the interrupt listeners of * `BunRuntime.runMain`, and leave when the run ends, so other commands keep - * that interrupt. The OS releases the SQLite locks with the process. + * that interrupt. The OS releases the SQLite locks with the process. Inside a + * `deferSignalExit` scope, a signal is recorded instead, unless a + * `signalExitPoint` call waits. `docks-kit tidy` runs inside it too. */ -const exitOnSignal = Effect.acquireRelease( +export const exitOnSignal = Effect.acquireRelease( Effect.sync(() => { - const exit = (): never => process.exit(130); + const exit = (): void => { + if (signals.deferred > 0 && signals.exitPoints === 0) { + signals.recorded = true; + return; + } + exitNow(); + }; process.prependListener("SIGINT", exit); process.prependListener("SIGTERM", exit); return exit; @@ -73,6 +91,43 @@ const exitOnSignal = Effect.acquireRelease( }), ); +/** + * For the rest of the scope, `exitOnSignal` records a SIGINT or SIGTERM + * instead of exiting, so the steps of the scope run to their end; when the + * last open scope closes after a recorded signal, the process exits with 130. + * The plain steps of `tidy --apply` and the printing of their result run in + * it, as they ran without a signal turn before; #297 replaces it with fiber + * interruption. + */ +export const deferSignalExit = Effect.acquireRelease( + Effect.sync(() => { + signals.deferred += 1; + }), + () => + Effect.sync(() => { + signals.deferred -= 1; + if (signals.deferred === 0 && signals.recorded) exitNow(); + }), +); + +/** + * Run `effect`, a call that can wait on a child process, as an exit point: a + * signal recorded before it, or one that comes while it waits, exits with 130 + * at once, also inside a `deferSignalExit` scope. + */ +export const signalExitPoint = (effect: Effect.Effect): Effect.Effect => + Effect.acquireUseRelease( + Effect.sync(() => { + if (signals.recorded) exitNow(); + signals.exitPoints += 1; + }), + () => effect, + () => + Effect.sync(() => { + signals.exitPoints -= 1; + }), + ); + export const engine = (args: ReadonlyArray) => Effect.gen(function* () { yield* requireSupportedHost(); diff --git a/cli/test/unit/engine-di.test.ts b/cli/test/unit/engine-di.test.ts index ce4209f5..37e6ca92 100644 --- a/cli/test/unit/engine-di.test.ts +++ b/cli/test/unit/engine-di.test.ts @@ -2,134 +2,11 @@ import { describe, expect, it } from "vitest"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { setImmediate as nextTurn } from "node:timers/promises"; -import { runBounded } from "../../src/engine-native"; import { syncLockPath } from "../../src/engine-native/scratch"; import { makeEngineServices } from "../../src/engine-native/services"; import { runEngine } from "../lib/engineRun"; -describe("sync pipeline coordinator", () => { - function gatedFailure(reason: unknown) { - const { promise, resolve } = Promise.withResolvers(); - return { - release: resolve, - task: async () => { - await promise; - throw reason; - }, - }; - } - - it("caps overlap and returns results in selection order", async () => { - const names = ["first", "second", "third"] as const; - const controls = names.map(() => Promise.withResolvers()); - const thirdStarted = Promise.withResolvers(); - const started: Array = []; - let active = 0; - let maxActive = 0; - const run = runBounded( - names.map((name, index) => async () => { - started.push(name); - active += 1; - maxActive = Math.max(maxActive, active); - if (index === 2) thirdStarted.resolve(); - const result = await controls[index]!.promise; - active -= 1; - return result; - }), - 2, - ); - expect(started).toEqual(["first", "second"]); - controls[1]!.resolve("second-result"); - await thirdStarted.promise; - expect(active).toBe(2); - controls[0]!.resolve("first-result"); - controls[2]!.resolve("third-result"); - await expect(run).resolves.toEqual(["first-result", "second-result", "third-result"]); - expect(maxActive).toBe(2); - }); - - it("runs the next pipeline only after the prior one settles at cap one", async () => { - const first = Promise.withResolvers(); - const secondStarted = Promise.withResolvers(); - const started: Array = []; - const run = runBounded( - [ - async () => { - started.push("first"); - return await first.promise; - }, - async () => { - started.push("second"); - secondStarted.resolve(); - return 2; - }, - ], - 1, - ); - expect(started).toEqual(["first"]); - first.resolve(1); - await secondStarted.promise; - await expect(run).resolves.toEqual([1, 2]); - }); - - it("drains started pipelines, stops queued work, and reports the first input failure", async () => { - const second = gatedFailure(new Error("second failed")); - const firstFailure = new Error("first failed"); - const first = gatedFailure(firstFailure); - let queued = false; - const run = runBounded( - [ - first.task, - second.task, - async () => { - queued = true; - return "should not run"; - }, - ], - 2, - ); - const result = expect(run).rejects.toBe(firstFailure); - second.release(); - first.release(); - await result; - expect(queued).toBe(false); - }); - - it("keeps an undefined rejection when a later input fails during drain", async () => { - const failing = gatedFailure(undefined); - const active = gatedFailure(new Error("later input failed")); - const events: Array = []; - const run = runBounded( - [ - failing.task, - active.task, - async () => { - events.push("queued task started"); - }, - ], - 2, - ); - const settled = run.then( - () => events.push("fulfilled"), - (reason: unknown) => { - events.push("rejected"); - return reason; - }, - ); - failing.release(); - try { - await nextTurn(); - expect(events).toEqual([]); - } finally { - active.release(); - } - expect(await settled).toBeUndefined(); - expect(events).toEqual(["rejected"]); - }); -}); - describe("native CLI argument and output behavior", () => { async function withIsolatedHome(run: (home: string) => Promise): Promise { const home = mkdtempSync(join(tmpdir(), "engine-di-")); diff --git a/cli/test/unit/syncConcurrency.test.ts b/cli/test/unit/syncConcurrency.test.ts new file mode 100644 index 00000000..9c1a8f91 --- /dev/null +++ b/cli/test/unit/syncConcurrency.test.ts @@ -0,0 +1,222 @@ +import { Deferred, Effect, Exit, Fiber } from "effect"; +import { describe, expect, it } from "vitest"; + +import { runBounded, type SyncTask } from "../../src/engine-native"; + +/** + * A task that records its start, waits for its gate, and then fails with + * `reason`. A worker fiber starts on a later turn of the scheduler, so a test + * awaits `started` before it releases a gate that would end the pool. + */ +function gatedFailure(reason: E) { + return Effect.gen(function* () { + const gate = yield* Deferred.make(); + const start = yield* Deferred.make(); + const task: SyncTask = Deferred.succeed(start, undefined).pipe( + Effect.andThen(Deferred.await(gate)), + Effect.andThen(Effect.fail(reason)), + ); + return { release: Deferred.succeed(gate, undefined), started: Deferred.await(start), task }; + }); +} + +/** + * Let every fiber that is ready take its turns, so that a run that could + * settle now has settled. The gates of the tasks are the synchronization; this + * only gives the runner the turns to record a failure. + */ +const settle = Effect.forEach(Array.from({ length: 20 }), () => Effect.yieldNow, { + discard: true, +}); + +describe("runBounded", () => { + it("caps overlap and returns results in selection order", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const names = ["first", "second", "third"] as const; + const controls = yield* Effect.forEach(names, () => Deferred.make()); + const starts = yield* Effect.forEach(names, () => Deferred.make()); + const started: Array = []; + let active = 0; + let maxActive = 0; + const run = yield* Effect.forkChild( + runBounded( + names.map((name, index) => + Effect.gen(function* () { + started.push(name); + active += 1; + maxActive = Math.max(maxActive, active); + yield* Deferred.succeed(starts[index]!, undefined); + const result = yield* Deferred.await(controls[index]!); + active -= 1; + return result; + }), + ), + 2, + ), + ); + yield* Deferred.await(starts[0]!); + yield* Deferred.await(starts[1]!); + expect(started).toEqual(["first", "second"]); + yield* Deferred.succeed(controls[1]!, "second-result"); + yield* Deferred.await(starts[2]!); + expect(active).toBe(2); + yield* Deferred.succeed(controls[0]!, "first-result"); + yield* Deferred.succeed(controls[2]!, "third-result"); + expect(yield* Fiber.join(run)).toEqual(["first-result", "second-result", "third-result"]); + expect(maxActive).toBe(2); + }), + ); + }); + + it("runs the next pipeline only after the prior one settles at cap one", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const first = yield* Deferred.make(); + const firstStarted = yield* Deferred.make(); + const started: Array = []; + const run = yield* Effect.forkChild( + runBounded( + [ + Effect.gen(function* () { + started.push("first"); + yield* Deferred.succeed(firstStarted, undefined); + return yield* Deferred.await(first); + }), + Effect.sync(() => { + started.push("second"); + return 2; + }), + ], + 1, + ), + ); + yield* Deferred.await(firstStarted); + yield* settle; + expect(started).toEqual(["first"]); + yield* Deferred.succeed(first, 1); + expect(yield* Fiber.join(run)).toEqual([1, 2]); + expect(started).toEqual(["first", "second"]); + }), + ); + }); + + it("drains started pipelines, stops queued work, and reports the first input failure", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const firstFailure = new Error("first failed"); + const first = yield* gatedFailure(firstFailure); + const second = yield* gatedFailure(new Error("second failed")); + let queued = false; + const run = yield* Effect.forkChild( + runBounded( + [ + first.task, + second.task, + Effect.sync(() => { + queued = true; + return "should not run"; + }), + ], + 2, + ), + ); + yield* first.started; + yield* second.started; + yield* second.release; + yield* first.release; + expect(yield* Effect.flip(Fiber.join(run))).toBe(firstFailure); + expect(queued).toBe(false); + }), + ); + }); + + it("keeps an undefined rejection when a later input fails during drain", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const failing = yield* gatedFailure(undefined); + const active = yield* gatedFailure(new Error("later input failed")); + const events: Array = []; + const run = yield* Effect.forkChild( + runBounded( + [ + failing.task, + active.task, + Effect.sync(() => { + events.push("queued task started"); + }), + ], + 2, + ), + ); + const observer = yield* Effect.forkChild( + Fiber.await(run).pipe( + Effect.tap((exit) => + Effect.sync(() => events.push(Exit.isSuccess(exit) ? "fulfilled" : "failed")), + ), + ), + ); + yield* failing.started; + yield* active.started; + yield* failing.release; + yield* settle; + expect(events).toEqual([]); + yield* active.release; + yield* Fiber.join(observer); + expect(yield* Effect.flip(Fiber.join(run))).toBeUndefined(); + expect(events).toEqual(["failed"]); + }), + ); + }); + + /** + * The error order of the first comment of #290: with concurrency 2, tasks 0 + * and 1 start and task 2 stays queued. Task 1 fails first; task 2 never + * starts, task 0 is not interrupted, and the run stays pending until task 0 + * ends. `Effect.forEach` with `concurrency` fails both cases: it interrupts + * task 0 at the failure of task 1. + */ + for (const zero of ["fails", "succeeds"] as const) { + it(`reports the lowest-index failure when task 1 fails first and task 0 then ${zero}`, async () => { + await Effect.runPromise( + Effect.gen(function* () { + const zeroFailure = new Error("task 0 failed"); + const oneFailure = new Error("task 1 failed"); + const gates = { zero: yield* Deferred.make(), one: yield* Deferred.make() }; + const starts = { zero: yield* Deferred.make(), one: yield* Deferred.make() }; + const oneEnded = yield* Deferred.make(); + const events: Array = []; + const task0: SyncTask = Effect.gen(function* () { + yield* Deferred.succeed(starts.zero, undefined); + yield* Deferred.await(gates.zero); + events.push("task 0 ended"); + return zero === "fails" ? yield* Effect.fail(zeroFailure) : "task 0 result"; + }).pipe(Effect.onInterrupt(() => Effect.sync(() => events.push("task 0 interrupted")))); + const task1: SyncTask = Effect.gen(function* () { + yield* Deferred.succeed(starts.one, undefined); + yield* Deferred.await(gates.one); + return yield* Effect.fail(oneFailure); + }).pipe(Effect.ensuring(Deferred.succeed(oneEnded, undefined))); + const task2: SyncTask = Effect.sync(() => { + events.push("task 2 started"); + return "task 2 result"; + }); + const run = yield* Effect.forkChild(runBounded([task0, task1, task2], 2)); + + yield* Deferred.await(starts.zero); + yield* Deferred.await(starts.one); + yield* Deferred.succeed(gates.one, undefined); + yield* Deferred.await(oneEnded); + yield* settle; + expect(events).toEqual([]); + expect(run.pollUnsafe()).toBeUndefined(); + + yield* Deferred.succeed(gates.zero, undefined); + const failure = yield* Effect.flip(Fiber.join(run)); + expect(failure).toBe(zero === "fails" ? zeroFailure : oneFailure); + expect(events).toEqual(["task 0 ended"]); + }), + ); + }); + } +}); diff --git a/cli/test/unit/tidy.test.ts b/cli/test/unit/tidy.test.ts index 8a383043..c2b59ce0 100644 --- a/cli/test/unit/tidy.test.ts +++ b/cli/test/unit/tidy.test.ts @@ -8,18 +8,22 @@ import { readdirSync, readFileSync, realpathSync, + rmdirSync, rmSync, + symlinkSync, utimesSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; -import { Effect } from "effect"; -import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { delimiter, join, resolve } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { BunServices } from "@effect/platform-bun"; +import { Effect, type FileSystem, type Scope } from "effect"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { runTidy } from "../../src/commands/tidy"; -import { acquireKitLock, releaseKitLock } from "../../src/engine-native/kitLock"; -import { kitCacheDir, tidyApplyLockPath } from "../../src/engine-native/scratch"; +import { acquireKitLock, releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock"; +import { kitCacheDir, scratchRoot, tidyApplyLockPath } from "../../src/engine-native/scratch"; import { applyTidy, defaultTidyHost, @@ -39,7 +43,7 @@ import { } from "../../src/engine-native/tidy"; import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; import { ageAdminFiles, createGitSandbox, type GitSandbox } from "../lib/gitSandbox"; -import { childEnv } from "../lib/goldenResources"; +import { REPO_DIR, childEnv } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; const HOUR_MS = 3_600_000; @@ -47,6 +51,8 @@ const DAY_MS = 24 * HOUR_MS; const POSIX = process.platform !== "win32"; /** Mode 000 blocks `lstat` below a directory only for a POSIX user that is not root. */ const CAN_DENY = POSIX && process.getuid?.() !== 0; +/** `tidy.ts LOG_ROTATE_BYTES`: a log past this size moves to `tidy.log.1` before the append. */ +const LOG_ROTATE_BYTES = 262_144; let sandbox: GitSandbox; let inputs: TidyInputs; @@ -75,11 +81,13 @@ function ok(stdout = ""): TidyProcess { } interface StubOptions { - readonly processes?: () => Promise | undefined>; + readonly processes?: () => Effect.Effect | undefined>; /** The `docker context inspect` result; a local socket by default. */ readonly endpoint?: TidyProcess; /** The `docker ps` result; the four stub containers by default. */ readonly ps?: TidyProcess; + /** The `docker network ls` result; no network by default. */ + readonly networks?: TidyProcess; } function stubHost(options: StubOptions = {}): TidyHost { @@ -93,31 +101,50 @@ function stubHost(options: StubOptions = {}): TidyHost { .map((fields) => fields.join("\t")) .join("\n"); return { - git: async (args) => { - calls.push(`git ${args.join(" ")}`); - return real.git(args); - }, - docker: async (args) => { - calls.push(`docker ${args.join(" ")}`); - return args[2] === "ps" ? (options.ps ?? ok(`${containerRows}\n`)) : ok(); - }, - dockerEndpoint: async () => options.endpoint ?? ok(`${LOCAL_ENDPOINT}\n`), - run: async () => ({ code: null, stdout: "", stderr: "", missing: true }), - processes: options.processes ?? (async () => rows), + git: (args) => + Effect.suspend(() => { + calls.push(`git ${args.join(" ")}`); + return real.git(args); + }), + docker: (args) => + Effect.sync(() => { + calls.push(`docker ${args.join(" ")}`); + if (args[2] === "ps") return options.ps ?? ok(`${containerRows}\n`); + if (args[2] === "network" && args[3] === "ls") return options.networks ?? ok(); + return ok(); + }), + dockerEndpoint: () => Effect.succeed(options.endpoint ?? ok(`${LOCAL_ENDPOINT}\n`)), + run: () => Effect.succeed({ code: null, stdout: "", stderr: "", missing: true }), + processes: options.processes ?? (() => Effect.succeed(rows)), now: () => Date.now(), }; } +/** Run a tidy Effect with the Bun services, as the CLI does. */ +function runWithServices( + effect: Effect.Effect, +): Promise { + return Effect.runPromise(effect.pipe(Effect.scoped, Effect.provide(BunServices.layer))); +} + +function plan(tidyInputs: TidyInputs, host: TidyHost): Promise { + return runWithServices(planTidy(tidyInputs, host)); +} + +function apply(tidyPlan: TidyPlan, tidyInputs: TidyInputs, host: TidyHost) { + return runWithServices(applyTidy(tidyPlan, tidyInputs, host)); +} + function dockerCalls(): Array { return calls.filter((call) => call.startsWith("docker ")); } -function kinds(plan: TidyPlan, kind: TidyAction["kind"]): Array { - return plan.actions.filter((action) => action.kind === kind); +function kinds(tidyPlan: TidyPlan, kind: TidyAction["kind"]): Array { + return tidyPlan.actions.filter((action) => action.kind === kind); } -function keptReason(plan: TidyPlan, subject: string): string | undefined { - return plan.kept.find((entry) => entry.subject === subject)?.reason; +function keptReason(tidyPlan: TidyPlan, subject: string): string | undefined { + return tidyPlan.kept.find((entry) => entry.subject === subject)?.reason; } function setAge(path: string, ageMs: number): void { @@ -125,6 +152,45 @@ function setAge(path: string, ageMs: number): void { utimesSync(path, time, time); } +/** An idle scratch entry with one file, both `ageMs` old. */ +function seedScratchEntry(path: string, ageMs = 8 * DAY_MS): void { + // Private, like the folders of a real home: `removeTemporaryPath` refuses an + // entry below a folder that another user can change, and the umask of the + // test run decides the mode of a new folder. + mkdirSync(path, { recursive: true, mode: 0o700 }); + writeFileSync(join(path, "result.txt"), "x\n"); + setAge(join(path, "result.txt"), ageMs); + setAge(path, ageMs); +} + +/** + * A separate home with empty roots and no containers below the sandbox, so a + * plan or an apply there changes nothing in the shared sandbox. Its folders + * have mode 0700, as `createScratchDir` gives the scratch root. + */ +function quietInputs(name: string): TidyInputs { + const quiet = join(sandbox.base, name); + const quietHome: TidyInputs = { + home: join(quiet, "home"), + worktreeRoot: join(quiet, "worktrees"), + scratchRoot: join(quiet, "scratch"), + }; + for (const directory of Object.values(quietHome)) { + mkdirSync(directory, { recursive: true, mode: 0o700 }); + } + return quietHome; +} + +/** A plan with only `actions` and the verified local endpoint. */ +function planOf(actions: ReadonlyArray): TidyPlan { + return { + actions, + kept: [], + notes: [], + docker: { kind: "local", endpoint: LOCAL_ENDPOINT }, + }; +} + beforeAll(() => { sandbox = createGitSandbox(); inputs = { @@ -132,11 +198,7 @@ beforeAll(() => { worktreeRoot: sandbox.worktreeRoot, scratchRoot: sandbox.scratchRoot, }; - const old = join(sandbox.scratchRoot, "old-ab12"); - mkdirSync(old); - writeFileSync(join(old, "result.txt"), "x\n"); - setAge(join(old, "result.txt"), 8 * DAY_MS); - setAge(old, 8 * DAY_MS); + seedScratchEntry(join(sandbox.scratchRoot, "old-ab12")); mkdirSync(join(sandbox.scratchRoot, "fresh-cd34")); busyChild = spawnIdle(); @@ -179,22 +241,26 @@ describe("resolveProcessCwds", () => { /** Reads that the test names per PID; a PID it does not name has `/w`. */ const reader = (probes: Record) => - (pid: number): CwdProbe => - probes[pid] ?? { kind: "cwd", path: "/w" }; + (pid: number): Effect.Effect => + Effect.succeed(probes[pid] ?? { kind: "cwd", path: "/w" }); + const resolveCwds = ( + listedRows: ReadonlyArray, + probes: Record, + ): ReadonlyArray | undefined => + Effect.runSync(resolveProcessCwds(listedRows, reader(probes))); it("drops a process that exited during the probe", () => { - const resolved = resolveProcessCwds( - [listed(10, "node"), listed(11, "node")], - reader({ 11: { kind: "exited" } }), - ); + const resolved = resolveCwds([listed(10, "node"), listed(11, "node")], { + 11: { kind: "exited" }, + }); expect(resolved?.map((row) => row.pid)).toEqual([10]); }); it("keeps an unreadable systemd row without a cwd, so that its children stay orphans", () => { - const resolved = resolveProcessCwds( + const resolved = resolveCwds( [listed(2005, "systemd"), listed(2021, "(sd-pam)", 2005), listed(3000, "node", 2005)], - reader({ 2005: { kind: "unreadable" }, 2021: { kind: "unreadable" } }), + { 2005: { kind: "unreadable" }, 2021: { kind: "unreadable" } }, ); expect(resolved).toBeDefined(); @@ -206,20 +272,17 @@ describe("resolveProcessCwds", () => { it.each(["ssh-agent", "gpg-agent", "/usr/bin/ssh-agent"])( "keeps an unreadable %s row without a cwd", (comm) => { - const resolved = resolveProcessCwds( - [listed(40, comm)], - reader({ 40: { kind: "unreadable" } }), - ); + const resolved = resolveCwds([listed(40, comm)], { 40: { kind: "unreadable" } }); expect(resolved).toEqual([{ ...listed(40, comm), cwd: undefined }]); }, ); it("returns undefined when any other live process has an unreadable cwd", () => { - const resolved = resolveProcessCwds( - [listed(2005, "systemd"), listed(50, "node", 2005)], - reader({ 2005: { kind: "unreadable" }, 50: { kind: "unreadable" } }), - ); + const resolved = resolveCwds([listed(2005, "systemd"), listed(50, "node", 2005)], { + 2005: { kind: "unreadable" }, + 50: { kind: "unreadable" }, + }); expect(resolved).toBeUndefined(); }); @@ -265,7 +328,7 @@ describe("isLocalDockerEndpoint", () => { describe("planTidy", () => { it("removes the merged idle worktree and keeps every other worktree with its reason", async () => { calls.length = 0; - const plan = await planTidy(inputs, stubHost()); + const tidyPlan = await plan(inputs, stubHost()); const { merged, wip, dirty, recent, busy } = sandbox.worktrees; expect(dockerCalls().length).toBeGreaterThan(0); @@ -273,7 +336,7 @@ describe("planTidy", () => { expect(call.startsWith(`docker --host ${LOCAL_ENDPOINT} `)).toBe(true); } - expect(kinds(plan, "remove-worktree")).toEqual([ + expect(kinds(tidyPlan, "remove-worktree")).toEqual([ { kind: "remove-worktree", path: merged, @@ -283,12 +346,12 @@ describe("planTidy", () => { reason: "merged into origin/main, idle 48 h", }, ]); - expect(keptReason(plan, `worktree ${wip}`)).toBe("not merged into origin/main"); - expect(keptReason(plan, `worktree ${dirty}`)).toBe("has changes"); - expect(keptReason(plan, `worktree ${recent}`)).toBe("active 0 h ago"); - expect(keptReason(plan, `worktree ${busy}`)).toBe("in use by a running process"); + expect(keptReason(tidyPlan, `worktree ${wip}`)).toBe("not merged into origin/main"); + expect(keptReason(tidyPlan, `worktree ${dirty}`)).toBe("has changes"); + expect(keptReason(tidyPlan, `worktree ${recent}`)).toBe("active 0 h ago"); + expect(keptReason(tidyPlan, `worktree ${busy}`)).toBe("in use by a running process"); - expect(kinds(plan, "stop-process")).toEqual([ + expect(kinds(tidyPlan, "stop-process")).toEqual([ { kind: "stop-process", pid: wipOrphan.pid, @@ -299,11 +362,11 @@ describe("planTidy", () => { ]); // The orphan in wip uses that worktree, so its container keeps running. - expect(kinds(plan, "stop-containers")).toEqual([]); - expect(keptReason(plan, `containers of proj-wip in ${wip}`)).toBe( + expect(kinds(tidyPlan, "stop-containers")).toEqual([]); + expect(keptReason(tidyPlan, `containers of proj-wip in ${wip}`)).toBe( "in use by a running process", ); - expect(kinds(plan, "remove-containers")).toEqual([ + expect(kinds(tidyPlan, "remove-containers")).toEqual([ { kind: "remove-containers", project: "proj-gone", @@ -312,40 +375,42 @@ describe("planTidy", () => { reason: "directory is gone", }, ]); - expect(JSON.stringify(plan)).not.toContain("c-other"); + expect(JSON.stringify(tidyPlan)).not.toContain("c-other"); - expect(kinds(plan, "remove-scratch")).toEqual([ + expect(kinds(tidyPlan, "remove-scratch")).toEqual([ { kind: "remove-scratch", path: join(sandbox.scratchRoot, "old-ab12"), reason: "idle 8 d", }, ]); - expect(keptReason(plan, `scratch ${join(sandbox.scratchRoot, "fresh-cd34")}`)).toBe( + expect(keptReason(tidyPlan, `scratch ${join(sandbox.scratchRoot, "fresh-cd34")}`)).toBe( "active 0 h ago", ); }); it("keeps every in-use-dependent candidate when the process list is unavailable", async () => { - const plan = await planTidy(inputs, stubHost({ processes: async () => undefined })); + const tidyPlan = await plan(inputs, stubHost({ processes: () => Effect.succeed(undefined) })); - expect(plan.actions.map((action) => action.kind)).toEqual(["remove-containers"]); - expect(keptReason(plan, `worktree ${sandbox.worktrees.merged}`)).toBe( + expect(tidyPlan.actions.map((action) => action.kind)).toEqual(["remove-containers"]); + expect(keptReason(tidyPlan, `worktree ${sandbox.worktrees.merged}`)).toBe( "process list unavailable", ); - expect(keptReason(plan, `scratch ${join(sandbox.scratchRoot, "old-ab12")}`)).toBe( + expect(keptReason(tidyPlan, `scratch ${join(sandbox.scratchRoot, "old-ab12")}`)).toBe( "process list unavailable", ); - expect(plan.notes).toContain( + expect(tidyPlan.notes).toContain( "process list unavailable; kept every candidate that a running process could use", ); }); it("refuses a root that contains the home directory", async () => { - const plan = await planTidy({ ...inputs, worktreeRoot: sandbox.base }, stubHost()); + const tidyPlan = await plan({ ...inputs, worktreeRoot: sandbox.base }, stubHost()); - expect(plan.notes).toContain(`refusing root ${sandbox.base}: it contains the home directory`); - expect(kinds(plan, "remove-worktree")).toEqual([]); + expect(tidyPlan.notes).toContain( + `refusing root ${sandbox.base}: it contains the home directory`, + ); + expect(kinds(tidyPlan, "remove-worktree")).toEqual([]); }); it.skipIf(!CAN_DENY)("keeps the containers of a directory that it cannot check", async () => { @@ -355,11 +420,11 @@ describe("planTidy", () => { chmodSync(sealed, 0o000); try { const ps = ok(`c-sealed\texited\tproj-sealed\t${workingDir}\n`); - const plan = await planTidy(inputs, stubHost({ ps })); + const tidyPlan = await plan(inputs, stubHost({ ps })); // `existsSync` reports false for EACCES; only ENOENT or ENOTDIR means gone. - expect(kinds(plan, "remove-containers")).toEqual([]); - expect(plan.notes).toContain(`cannot check ${workingDir}: EACCES`); + expect(kinds(tidyPlan, "remove-containers")).toEqual([]); + expect(tidyPlan.notes).toContain(`cannot check ${workingDir}: EACCES`); } finally { chmodSync(sealed, 0o700); rmSync(sealed, { recursive: true, force: true }); @@ -372,13 +437,13 @@ describe("planTidy", () => { setAge(sealed, 8 * DAY_MS); chmodSync(sealed, 0o000); try { - const plan = await planTidy(inputs, stubHost()); + const tidyPlan = await plan(inputs, stubHost()); - const removed = plan.actions.some( + const removed = tidyPlan.actions.some( (action) => action.kind === "remove-scratch" && action.path === sealed, ); expect(removed).toBe(false); - expect(keptReason(plan, `scratch ${sealed}`)).toBe(`cannot check ${sealed}: EACCES`); + expect(keptReason(tidyPlan, `scratch ${sealed}`)).toBe(`cannot check ${sealed}: EACCES`); } finally { chmodSync(sealed, 0o700); rmSync(sealed, { recursive: true, force: true }); @@ -392,12 +457,27 @@ describe("planTidy", () => { ageAdminFiles(accent, 48 * HOUR_MS); const ps = ok(`c-accent\trunning\tproj-accent\t${accent}\n`); - const plan = await planTidy(inputs, stubHost({ ps })); + const tidyPlan = await plan(inputs, stubHost({ ps })); // Plain porcelain quotes the name as "caf\303\251.ts"; `-z` keeps it as is. - expect(keptReason(plan, `worktree ${accent}`)).toBe("has changes"); - expect(kinds(plan, "stop-containers")).toEqual([]); - expect(keptReason(plan, `containers of proj-accent in ${accent}`)).toBe("active 0 h ago"); + expect(keptReason(tidyPlan, `worktree ${accent}`)).toBe("has changes"); + expect(kinds(tidyPlan, "stop-containers")).toEqual([]); + expect(keptReason(tidyPlan, `containers of proj-accent in ${accent}`)).toBe("active 0 h ago"); + }); + + it("lists a linked worktree outside the worktree root with --repo", async () => { + const outside = join(sandbox.base, "outside-wt"); + sandbox.git(sandbox.main, "worktree", "add", "-q", "--detach", outside, "main"); + try { + const scanned = await plan(inputs, stubHost({ ps: ok("") })); + const listed = await plan({ ...inputs, repo: sandbox.main }, stubHost({ ps: ok("") })); + + // The scan of the worktree root never reaches it; the --repo listing does. + expect(keptReason(scanned, `worktree ${outside}`)).toBeUndefined(); + expect(keptReason(listed, `worktree ${outside}`)).toBe("active 0 h ago"); + } finally { + sandbox.git(sandbox.main, "worktree", "remove", "--force", outside); + } }); }); @@ -416,17 +496,17 @@ describe("planTidy without a verified local Docker endpoint", () => { }, ])("$shown: no container action, and every removable worktree stays", async (row) => { calls.length = 0; - const plan = await planTidy(inputs, stubHost({ endpoint: row.endpoint })); + const tidyPlan = await plan(inputs, stubHost({ endpoint: row.endpoint })); // The orphan and scratch rules do not use Docker. - expect(plan.actions.map((action) => action.kind).sort()).toEqual([ + expect(tidyPlan.actions.map((action) => action.kind).sort()).toEqual([ "remove-scratch", "stop-process", ]); - expect(keptReason(plan, `worktree ${sandbox.worktrees.merged}`)).toBe( + expect(keptReason(tidyPlan, `worktree ${sandbox.worktrees.merged}`)).toBe( "docker endpoint not local", ); - expect(plan.notes).toContain( + expect(tidyPlan.notes).toContain( `docker endpoint ${row.shown} is not local; skipped container rules`, ); expect(dockerCalls()).toEqual([]); @@ -435,28 +515,28 @@ describe("planTidy without a verified local Docker endpoint", () => { it("keeps the worktree rule when docker is not installed", async () => { calls.length = 0; const missing = { code: null, stdout: "", stderr: "spawn docker ENOENT", missing: true }; - const plan = await planTidy(inputs, stubHost({ endpoint: missing })); + const tidyPlan = await plan(inputs, stubHost({ endpoint: missing })); - expect(kinds(plan, "remove-worktree")).toEqual([ + expect(kinds(tidyPlan, "remove-worktree")).toEqual([ expect.objectContaining({ path: sandbox.worktrees.merged, containerIds: [] }), ]); - expect(kinds(plan, "remove-containers")).toEqual([]); - expect(plan.notes).toContain("docker unavailable: spawn docker ENOENT"); + expect(kinds(tidyPlan, "remove-containers")).toEqual([]); + expect(tidyPlan.notes).toContain("docker unavailable: spawn docker ENOENT"); expect(dockerCalls()).toEqual([]); }); it("keeps every removable worktree when the local daemon cannot list containers", async () => { const down = { code: 1, stdout: "", stderr: "Cannot connect to the daemon", missing: false }; - const plan = await planTidy(inputs, stubHost({ ps: down })); + const tidyPlan = await plan(inputs, stubHost({ ps: down })); - expect(plan.actions.map((action) => action.kind).sort()).toEqual([ + expect(tidyPlan.actions.map((action) => action.kind).sort()).toEqual([ "remove-scratch", "stop-process", ]); - expect(keptReason(plan, `worktree ${sandbox.worktrees.merged}`)).toBe( + expect(keptReason(tidyPlan, `worktree ${sandbox.worktrees.merged}`)).toBe( "container list unavailable", ); - expect(plan.notes).toContain("docker unavailable: Cannot connect to the daemon"); + expect(tidyPlan.notes).toContain("docker unavailable: Cannot connect to the daemon"); }); }); @@ -468,21 +548,30 @@ describe("planTidy without a verified local Docker endpoint", () => { * options: { readonly apply: boolean; readonly report: boolean }, * inputs: TidyInputs, * host: TidyHost, - * ): Effect.Effect + * ): Effect.Effect * * `tidyCommand` resolves `--repo` into `inputs.repo` and then runs * `runTidy({ apply, report }, inputs, defaultTidyHost())`. With `apply`, - * `runTidy` takes `/tidy-lock.db` through - * `acquireKitLock(path, { waitMs: 0 })` before `planTidy`, and releases it - * after the apply. When another holder has the lock, it prints only - * `another docks-kit tidy run holds ` and leaves `process.exitCode` - * unset. A dry run takes no lock. Each line goes out through `Console.log`. + * `runTidy` takes `/tidy-lock.db` through one + * `tryAcquireKitLock(path, { privateDirectory: true })` before `planTidy`, and + * releases it after the apply. When another holder has the lock, it prints + * only `another docks-kit tidy run holds ` and leaves + * `process.exitCode` unset. A dry run takes no lock. Each line goes out + * through `Console.log`. */ describe("runTidy", () => { function tidyLock(home: string): string { return join(kitCacheDir(home), "tidy-lock.db"); } + /** `held` when another connection holds `lock`; the probe gives a free lock back at once. */ + function lockState(lock: string): "held" | "acquired" { + const probe = tryAcquireKitLock(lock, { privateDirectory: true }); + if (probe === undefined) return "held"; + releaseKitLock(probe); + return "acquired"; + } + /** Run `runTidy`, and return the printed lines and the exit code that it set. */ async function run( options: { readonly apply: boolean; readonly report: boolean }, @@ -493,7 +582,7 @@ describe("runTidy", () => { process.exitCode = undefined; const log = vi.spyOn(console, "log").mockImplementation(() => undefined); try { - await Effect.runPromise(runTidy(options, tidyInputs, host)); + await runWithServices(runTidy(options, tidyInputs, host)); return { lines: log.mock.calls.map((args) => args.map(String).join(" ")), exitCode: process.exitCode, @@ -510,10 +599,11 @@ describe("runTidy", () => { if (held.kind !== "acquired") throw new Error(`expected a free lock at ${lock}`); let listings = 0; const host = stubHost({ - processes: async () => { - listings += 1; - return rows; - }, + processes: () => + Effect.sync(() => { + listings += 1; + return rows; + }), }); calls.length = 0; @@ -550,60 +640,42 @@ describe("runTidy", () => { }); it("plans only under the lock", async () => { - // A separate home with empty roots and no containers, so the plan is empty - // and the apply changes nothing in the shared sandbox. - const quiet = join(sandbox.base, "quiet"); - const quietInputs: TidyInputs = { - home: join(quiet, "home"), - worktreeRoot: join(quiet, "worktrees"), - scratchRoot: join(quiet, "scratch"), - }; - for (const directory of Object.values(quietInputs)) mkdirSync(directory, { recursive: true }); - const lock = tidyLock(quietInputs.home); + const quiet = quietInputs("quiet"); + const lock = tidyLock(quiet.home); const duringPlan: Array = []; const host = stubHost({ ps: ok(""), - processes: async () => { - const probe = await acquireKitLock(lock, { waitMs: 0 }); - if (probe.kind === "acquired") releaseKitLock(probe.lock); - duringPlan.push(probe.kind); - return []; - }, + processes: () => + Effect.sync(() => { + duringPlan.push(lockState(lock)); + return []; + }), }); - const result = await run({ apply: true, report: false }, quietInputs, host); + const result = await run({ apply: true, report: false }, quiet, host); expect(duringPlan).toEqual(["held"]); expect(result.lines).toContain("Nothing to tidy."); expect(result.exitCode ?? 0).toBe(0); - const after = await acquireKitLock(lock, { waitMs: 0 }); - expect(after.kind).toBe("acquired"); - if (after.kind === "acquired") releaseKitLock(after.lock); + expect(lockState(lock)).toBe("acquired"); }); // The report reads the process list only on Linux and macOS (buildTidyReport). it.skipIf(process.platform === "win32")("releases the lock before the report runs", async () => { - const quiet = join(sandbox.base, "quiet-report"); - const quietInputs: TidyInputs = { - home: join(quiet, "home"), - worktreeRoot: join(quiet, "worktrees"), - scratchRoot: join(quiet, "scratch"), - }; - for (const directory of Object.values(quietInputs)) mkdirSync(directory, { recursive: true }); - const lock = tidyLock(quietInputs.home); + const quiet = quietInputs("quiet-report"); + const lock = tidyLock(quiet.home); // planTidy reads the processes once, and the report reads them once after it. const lockStates: Array = []; const host = stubHost({ ps: ok(""), - processes: async () => { - const probe = await acquireKitLock(lock, { waitMs: 0 }); - if (probe.kind === "acquired") releaseKitLock(probe.lock); - lockStates.push(probe.kind); - return []; - }, + processes: () => + Effect.sync(() => { + lockStates.push(lockState(lock)); + return []; + }), }); - await run({ apply: true, report: true }, quietInputs, host); + await run({ apply: true, report: true }, quiet, host); expect(lockStates).toEqual(["held", "acquired"]); }); @@ -612,18 +684,18 @@ describe("runTidy", () => { describe("applyTidy", () => { it("fails each container action when the plan carries no local endpoint", async () => { const host = stubHost(); - const plan = await planTidy(inputs, host); + const tidyPlan = await plan(inputs, host); // A plan whose endpoint changed after the check: `localDocker` checks again. const tampered: TidyPlan = { - ...plan, - actions: plan.actions.filter( + ...tidyPlan, + actions: tidyPlan.actions.filter( (action) => action.kind === "remove-worktree" || action.kind === "remove-containers", ), docker: { kind: "local", endpoint: "ssh://prod" }, }; calls.length = 0; - const outcome = await applyTidy(tampered, inputs, host); + const outcome = await apply(tampered, inputs, host); expect(outcome.failures).toBe(2); expect(outcome.lines).toContain( @@ -633,12 +705,94 @@ describe("applyTidy", () => { expect(existsSync(sandbox.worktrees.merged)).toBe(true); }); + it("removes the compose networks of a removed worktree through the verified endpoint", async () => { + const quiet = quietInputs("networks"); + const worktree = join(quiet.worktreeRoot, "repo", "stack"); + const host: TidyHost = { + ...stubHost({ networks: ok("net-a\nnet-b\n") }), + // The worktree removal itself is not under test here; git answers success. + git: (args) => + Effect.sync(() => { + calls.push(`git ${args.join(" ")}`); + return ok(); + }), + }; + calls.length = 0; + + const outcome = await apply( + planOf([ + { + kind: "remove-worktree", + path: worktree, + repo: sandbox.main, + containerIds: ["c-stack"], + projects: ["proj-stack"], + reason: "merged into origin/main, idle 48 h", + }, + ]), + quiet, + host, + ); + + expect(outcome.failures).toBe(0); + expect(calls).toEqual([ + `docker --host ${LOCAL_ENDPOINT} rm --force --volumes c-stack`, + `docker --host ${LOCAL_ENDPOINT} network ls -q --filter label=com.docker.compose.project=proj-stack`, + `docker --host ${LOCAL_ENDPOINT} network rm net-a net-b`, + `git -C ${sandbox.main} worktree remove -- ${worktree}`, + `git -C ${sandbox.main} worktree prune`, + ]); + }); + + it("moves a tidy.log past the rotation size to tidy.log.1 before the append", async () => { + const quiet = quietInputs("rotation"); + const entry = join(quiet.scratchRoot, "old-entry"); + seedScratchEntry(entry); + const log = tidyLogPath(quiet.home); + mkdirSync(kitCacheDir(quiet.home), { recursive: true, mode: 0o700 }); + const old = "2026-01-01T00:00:00.000Z removed scratch /old\n".repeat( + Math.ceil((LOG_ROTATE_BYTES + 1) / 45), + ); + writeFileSync(log, old); + + const outcome = await apply( + planOf([{ kind: "remove-scratch", path: entry, reason: "idle 8 d" }]), + quiet, + stubHost(), + ); + + expect(outcome.lines).toEqual([`removed scratch ${entry}`]); + expect(readFileSync(`${log}.1`, "utf8")).toBe(old); + expect(readFileSync(log, "utf8")).toMatch( + new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\S+ removed scratch ${RegExp.escape(entry)}\\n$`), + ); + }); + + it("keeps a scratch entry that became active after the plan, with its keep line", async () => { + const quiet = quietInputs("refreshed"); + const entry = join(quiet.scratchRoot, "old-entry"); + seedScratchEntry(entry); + const host = stubHost({ ps: ok(""), processes: () => Effect.succeed([]) }); + const tidyPlan = await plan(quiet, host); + expect(kinds(tidyPlan, "remove-scratch")).toEqual([ + { kind: "remove-scratch", path: entry, reason: "idle 8 d" }, + ]); + + // An agent writes into the entry between the plan and the apply. + writeFileSync(join(entry, "result.txt"), "y\n"); + const outcome = await apply(tidyPlan, quiet, host); + + expect(outcome.failures).toBe(0); + expect(outcome.lines).toEqual([`kept scratch ${entry}: active 0 h ago`]); + expect(existsSync(entry)).toBe(true); + }); + it("performs the plan: containers first, then the worktree, and only the selected PID", async () => { const host = stubHost(); - const plan = await planTidy(inputs, host); + const tidyPlan = await plan(inputs, host); calls.length = 0; - const outcome = await applyTidy(plan, inputs, host); + const outcome = await apply(tidyPlan, inputs, host); expect(outcome.failures).toBe(0); expect(existsSync(sandbox.worktrees.merged)).toBe(false); @@ -672,7 +826,419 @@ describe("applyTidy", () => { }); }); -describe("spawned docks-kit tidy --apply", () => { +// ------------------------------------------------------ spawned CLI cases ---- + +/** + * Spawned `docks-kit tidy` runs. Each case has one fixture root in the system + * temporary folder with the working folder, the home, the Bun caches, and a + * stub folder that is the whole PATH of the CLI: `ps`, which prints valid + * rows only for its parent process (the CLI, which `joinRows` drops as its + * own process), `lsof`, which prints nothing, and the stubs or the links to + * the real tools that a case needs. No case puts a real `docker` on it. + * + * A signal case asks the CLI to raise SIGTERM on itself through the request + * file that `cli/test/lib/signalSelfPreload.ts` watches; no process of these + * cases signals another process. Each stub run holds a ticket in the root + * while it runs and renames it to its exit record on every exit path; a + * waiting stub also ends on its own once its parent is gone, or after a hard + * lifetime past every bound of the case. A root goes only after the CLI has + * exited and the ticket folder could be closed with a non-recursive `rmdir`, + * which fails while a stub holds a ticket; after it, no stub can start its + * body there. + */ +const SIGNAL_PRELOAD = join(REPO_DIR, "cli", "test", "lib", "signalSelfPreload.ts"); +/** The hard lifetime of a waiting stub, past the exit bound and the case timeout. */ +const STUB_MAX_LIFETIME_MS = 90_000; +/** How long a signalled CLI may take to exit; a wait for a waiting stub would never end. */ +const EXIT_BOUND_MS = 10_000; +/** How long the teardown waits for the CLI and the stubs of a root. */ +const TEARDOWN_BOUND_MS = 10_000; + +interface Ending { + readonly code: number | null; + readonly signal: NodeJS.Signals | null; +} + +interface Launch { + readonly ended: Promise; + readonly stdout: () => string; + readonly stderr: () => string; + readonly running: () => boolean; + /** End the CLI child that this test spawned, when it still runs. */ + readonly stop: () => void; +} + +interface Fixture { + readonly root: string; + readonly work: string; + readonly home: string; + readonly stubs: string; + readonly tickets: string; + readonly records: string; + readonly request: string; + readonly env: Record; + readonly launches: Array; +} + +const caseFixtures = new Set(); + +/** The real path of `name` on the PATH of the test run. */ +function realTool(name: string): string { + for (const directory of (process.env["PATH"] ?? "").split(delimiter)) { + const candidate = join(directory, name); + if (directory !== "" && existsSync(candidate)) return realpathSync(candidate); + } + throw new Error(`${name} is not on PATH`); +} + +function shQuote(text: string): string { + return `'${text.replaceAll("'", `'\\''`)}'`; +} + +function makeFixture(): Fixture { + const root = realpathSync.native(mkdtempSync(join(tmpdir(), "docks-kit-tidy-fixture-"))); + const folder = (name: string): string => join(root, name); + const fixture: Fixture = { + root, + work: folder("work"), + home: folder("home"), + stubs: folder("stubs"), + tickets: folder("active"), + records: folder("stub-records"), + request: folder("signal-request"), + env: { + HOME: folder("home"), + USERPROFILE: folder("home"), + XDG_DATA_HOME: "", + DOCKS_KIT_ENGINE: "", + PATH: folder("stubs"), + LC_ALL: "C", + BUN_INSTALL_CACHE_DIR: folder("bun-cache"), + BUN_RUNTIME_TRANSPILER_CACHE_PATH: folder("bun-transpiler"), + SIGNAL_REQUEST_FILE: folder("signal-request"), + }, + launches: [], + }; + for (const name of ["work", "home", "stubs", "active", "stub-records"]) { + mkdirSync(folder(name), { mode: 0o700 }); + } + caseFixtures.add(fixture); + return fixture; +} + +/** + * A POSIX stub `name` whose sh `body` runs while it holds a ticket of the + * root. `before` runs first, without a ticket, for a branch that hands the + * run to a waiting stub with `exec`. + */ +function writeShStub(fixture: Fixture, name: string, body: string, before = ""): void { + const mv = realTool("mv"); + // The paths go into double quotes inside the single-quoted trap text. + for (const path of [mv, fixture.tickets, fixture.records]) { + if (/["'$`\\]/.test(path)) throw new Error(`unsupported character in stub path ${path}`); + } + const ticket = `"${fixture.tickets}/${name}-$$"`; + const record = `"${fixture.records}/${name}-$$.exited"`; + const path = join(fixture.stubs, name); + writeFileSync( + path, + `#!/bin/sh +${before} +if ! (set -C; : > ${ticket}) 2>/dev/null; then exit 1; fi +trap '"${mv}" -f ${ticket} ${record}' EXIT +${body} +`, + ); + chmodSync(path, 0o755); +} + +/** + * The Bun runner of a waiting stub: it takes its ticket, asks the CLI to raise + * SIGTERM on itself through the request file, and waits until its parent is + * gone or its hard lifetime ends. Its exit record is the renamed ticket. + */ +function writeWaitingRunner(fixture: Fixture): string { + const runner = join(fixture.stubs, "waiting-stub.mjs"); + writeFileSync( + runner, + `import { closeSync, openSync, renameSync, writeFileSync } from "node:fs" +import { join } from "node:path" +const name = process.argv[2] +const ticket = join(${JSON.stringify(fixture.tickets)}, \`\${name}-\${process.pid}\`) +try { + closeSync(openSync(ticket, "wx")) +} catch (error) { + process.stderr.write(\`waiting stub: no ticket in a closed fixture: \${String(error)}\\n\`) + process.exit(1) +} +process.on("exit", () => { + try { + renameSync(ticket, join(${JSON.stringify(fixture.records)}, \`\${name}-\${process.pid}.exited\`)) + } catch (error) { + process.stderr.write(\`waiting stub: the ticket \${ticket} stays: \${String(error)}\\n\`) + } +}) +setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) +const parent = process.ppid +const parentGone = () => { + if (process.ppid !== parent) return true + try { + process.kill(parent, 0) + return false + } catch { + return true + } +} +// The CLI raises the signal on itself; the request appears whole, by rename. +const request = process.env["SIGNAL_REQUEST_FILE"] +writeFileSync(\`\${request}.pending\`, "SIGTERM") +renameSync(\`\${request}.pending\`, request) +// A watch, not a delay: the stub waits until its CLI ends. +setInterval(() => { + if (parentGone()) process.exit(0) +}, 50) +`, + ); + return runner; +} + +/** The `ps` and `lsof` stubs of every POSIX case. */ +function writeProcessStubs(fixture: Fixture): void { + writeShStub( + fixture, + "ps", + `case "$*" in + *"pid=,comm="*) printf '%s bun\\n' "$PPID" ;; + *"etimes="*) printf '%s 1 60 1024 bun tidy\\n' "$PPID" ;; + *) printf '%s 1 01:00 1024 bun tidy\\n' "$PPID" ;; +esac`, + ); + writeShStub(fixture, "lsof", ":"); +} + +/** A `du` stub that waits on `waitPath` and prints 4 KiB for any other path. */ +function writeWaitingDu(fixture: Fixture, waitPath: string): void { + const runner = writeWaitingRunner(fixture); + writeShStub( + fixture, + "du", + `printf '4\\t%s\\n' "$2"`, + `if [ "$2" = ${shQuote(waitPath)} ]; then exec ${shQuote(process.execPath)} ${shQuote(runner)} du-wait "$@"; fi`, + ); +} + +/** Start `docks-kit tidy ` in the fixture with the self-signal preload and `preloads`. */ +function launchTidy( + fixture: Fixture, + args: ReadonlyArray, + options: { + readonly preloads?: ReadonlyArray; + readonly env?: Record; + } = {}, +): Launch { + // The entry may come relative from DOCKS_KIT_TEST_CLI_ENTRY; the CLI runs in the fixture folder. + const entry = resolve(cliEntry()); + // A preload that wraps `node:fs` goes first: Bun fixes the ESM bindings of + // `node:fs` at its first ESM import, and the self-signal preload makes one. + const preloads = [...(options.preloads ?? []), SIGNAL_PRELOAD]; + const child = spawn( + BUN_RUNTIME, + [ + "--no-env-file", + ...preloads.flatMap((preload) => ["--preload", preload]), + entry, + "tidy", + ...args, + ], + { + cwd: fixture.work, + env: childEnv({ ...fixture.env, ...options.env }), + stdio: ["ignore", "pipe", "pipe"], + }, + ); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk: string) => { + stdout += chunk; + }); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { + stderr += chunk; + }); + const closed = Promise.withResolvers(); + child.once("close", (code, signal) => closed.resolve({ code, signal })); + child.once("error", () => closed.resolve({ code: null, signal: null })); + const ended = closed.promise; + let open = true; + void ended.then(() => { + open = false; + }); + const launch: Launch = { + ended, + stdout: () => stdout, + stderr: () => stderr, + running: () => open, + stop: () => { + if (open) child.kill(); + }, + }; + fixture.launches.push(launch); + return launch; +} + +/** The ending of `run`, or `timed out` when it runs past `boundMs`. */ +async function endingWithin(run: Launch, boundMs: number): Promise { + const { promise, resolve: timeOut } = Promise.withResolvers<"timed out">(); + // The bound only caps a CLI that waits; a prompt exit resolves first. + const timer = setTimeout(() => timeOut("timed out"), boundMs); + try { + return await Promise.race([run.ended, promise]); + } finally { + clearTimeout(timer); + } +} + +/** Wait until the request file asks for SIGTERM; fail when the CLI ends first. */ +async function signalRequested(fixture: Fixture, run: Launch): Promise { + const deadline = performance.now() + SPAWN_TIMEOUT_MS / 2; + const asked = (): boolean => + existsSync(fixture.request) && readFileSync(fixture.request, "utf8").trim() === "SIGTERM"; + while (!asked()) { + if (!run.running()) { + throw new Error(`the CLI ended before it asked for a signal: ${run.stdout()}${run.stderr()}`); + } + if (performance.now() > deadline) throw new Error("no signal request appeared"); + await sleep(20); + } +} + +/** The exit records of the waiting stub `name`. */ +function exitRecords(fixture: Fixture, name: string): Array { + return readdirSync(fixture.records).filter( + (record) => record.startsWith(`${name}-`) && record.endsWith(".exited"), + ); +} + +/** + * Wait until every launch of the fixture has ended and its ticket folder can + * be closed, then remove the root. Return a problem line when the root stays. + */ +async function removeFixture(fixture: Fixture): Promise { + const deadline = performance.now() + TEARDOWN_BOUND_MS; + for (const run of fixture.launches) run.stop(); + for (const run of fixture.launches) { + if ((await endingWithin(run, TEARDOWN_BOUND_MS)) === "timed out") { + return `a CLI of ${fixture.root} did not exit; the root stays`; + } + } + for (;;) { + try { + // It fails while a stub holds a ticket; after it, no ticket can be created. + rmdirSync(fixture.tickets); + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") break; + if (performance.now() > deadline) { + return `a stub of ${fixture.root} still holds a ticket; the root stays`; + } + await sleep(20); + } + } + rmSync(fixture.root, { recursive: true, force: true }); + return undefined; +} + +afterEach(async () => { + const problems: Array = []; + for (const fixture of caseFixtures) { + const problem = await removeFixture(fixture); + if (problem !== undefined) problems.push(problem); + } + caseFixtures.clear(); + if (problems.length > 0) throw new Error(`teardown:\n${problems.join("\n")}`); +}, TEARDOWN_BOUND_MS * 3); + +/** The lines of the report section `title`, up to the next section. */ +function reportSection(stdout: string, title: string): Array { + const lines = stdout.split("\n"); + const start = lines.indexOf(`== ${title}`); + if (start < 0) return []; + const end = lines.findIndex((line, index) => index > start && line.startsWith("== ")); + return lines.slice(start + 1, end < 0 ? undefined : end); +} + +describe("spawned docks-kit tidy", () => { + it( + "lists a seeded idle scratch entry", + async () => { + const fixture = makeFixture(); + if (POSIX) writeProcessStubs(fixture); + const entry = join(scratchRoot(fixture.home), "idle-entry"); + seedScratchEntry(entry); + + const run = launchTidy(fixture, []); + + expect(await run.ended).toEqual({ code: 0, signal: null }); + const lines = run.stdout().split("\n"); + if (POSIX) { + expect(lines).toContain(`remove scratch ${entry}: idle 8 d`); + expect(lines).toContain( + "Dry run: 1 actions. Run 'docks-kit tidy --apply' to perform them.", + ); + } else { + // Windows has no tidy process list, so the entry stays. + expect(lines).toContain(`keep scratch ${entry}: process list unavailable`); + } + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "prints the measured entry of a seeded .npm folder in the package cache section of --report", + async () => { + const fixture = makeFixture(); + if (POSIX) { + writeProcessStubs(fixture); + symlinkSync(realTool("du"), join(fixture.stubs, "du")); + } + const npm = join(fixture.home, ".npm"); + mkdirSync(npm); + writeFileSync(join(npm, "index.json"), "{}\n"); + + const run = launchTidy(fixture, ["--report"]); + + expect(await run.ended).toEqual({ code: 0, signal: null }); + if (POSIX) { + const caches = reportSection(run.stdout(), "Package and tool caches"); + expect(caches).toContainEqual( + expect.stringMatching(new RegExp(`^\\d+\\.\\d (MB|GB) {2}${RegExp.escape(npm)}$`)), + ); + expect(caches).toContain("hint: npm cache verify"); + } else { + expect(reportSection(run.stdout(), "Report")).toContain( + "docks-kit tidy --report supports Linux and macOS", + ); + } + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "prints the error and exits 2 for a --repo folder that is not a git repository", + async () => { + const fixture = makeFixture(); + if (POSIX) symlinkSync(realTool("git"), join(fixture.stubs, "git")); + const folder = join(fixture.work, "plain"); + mkdirSync(folder); + + const run = launchTidy(fixture, ["--repo", folder]); + + expect(await run.ended).toEqual({ code: 2, signal: null }); + expect(run.stderr()).toContain(`--repo ${folder} is not a git repository`); + expect(run.stdout()).toBe(""); + }, + SPAWN_TIMEOUT_MS, + ); + it( "prints the held line, exits 0, and changes nothing while another tidy run holds its lock", async () => { @@ -683,6 +1249,8 @@ describe("spawned docks-kit tidy --apply", () => { const scratch = join(kitCacheDir(home), "scratch", "old-entry"); mkdirSync(scratch, { recursive: true }); setAge(scratch, 8 * DAY_MS); + // An empty PATH folder outside the listed home: no real docker is reachable. + const bin = mkdtempSync(join(tmpdir(), "tidy-held-bin-")); const lockPath = tidyApplyLockPath(home); const held = await acquireKitLock(lockPath, { waitMs: 0 }); if (held.kind !== "acquired") throw new Error(`expected a free lock at ${lockPath}`); @@ -698,6 +1266,7 @@ describe("spawned docks-kit tidy --apply", () => { USERPROFILE: home, XDG_DATA_HOME: "", DOCKS_KIT_ENGINE: "", + PATH: bin, }), timeout: SPAWN_TIMEOUT_MS, }); @@ -707,6 +1276,7 @@ describe("spawned docks-kit tidy --apply", () => { expect(listing()).toEqual(before); } finally { releaseKitLock(held.lock); + rmSync(bin, { recursive: true, force: true }); } } finally { rmSync(created, { recursive: true, force: true }); @@ -714,4 +1284,183 @@ describe("spawned docks-kit tidy --apply", () => { }, SPAWN_TIMEOUT_MS, ); + + describe.skipIf(!POSIX)( + "signals (skipped on Windows: process.kill force-terminates the process there instead of delivering the signal)", + () => { + it( + "exits 130 on one SIGTERM while a du of --report waits", + async () => { + const fixture = makeFixture(); + writeProcessStubs(fixture); + const npm = join(fixture.home, ".npm"); + mkdirSync(npm); + writeWaitingDu(fixture, npm); + + const run = launchTidy(fixture, ["--report"]); + await signalRequested(fixture, run); + + expect(await endingWithin(run, EXIT_BOUND_MS)).toEqual({ code: 130, signal: null }); + expect(run.stdout()).not.toContain("== Package and tool caches"); + // The waiting stub sees its parent gone and records its exit; the teardown waits for it. + await removeFixtureAfterRecord(fixture, "du-wait"); + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "exits 130 within the bound on one SIGTERM while docker rm of --apply waits", + async () => { + const fixture = makeFixture(); + writeProcessStubs(fixture); + const worktreeRoot = join(fixture.home, ".local", "share", "agent-worktrees"); + mkdirSync(worktreeRoot, { recursive: true }); + const gone = join(worktreeRoot, "repo", "gone-app"); + const runner = writeWaitingRunner(fixture); + writeShStub( + fixture, + "docker", + `case "$*" in + "context inspect"*) printf '%s\\n' ${shQuote(LOCAL_ENDPOINT)} ;; + *" ps "*) printf 'c-gone\\texited\\tproj-gone\\t%s\\n' ${shQuote(gone)} ;; +esac`, + `case "$*" in *" rm "*) exec ${shQuote(process.execPath)} ${shQuote(runner)} docker-wait "$@" ;; esac`, + ); + + const run = launchTidy(fixture, ["--apply"]); + await signalRequested(fixture, run); + + expect(await endingWithin(run, EXIT_BOUND_MS)).toEqual({ code: 130, signal: null }); + expect(run.stdout()).toContain( + `remove 1 container of proj-gone in ${gone}: directory is gone`, + ); + await removeFixtureAfterRecord(fixture, "docker-wait"); + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "removes the scratch entry of --apply --report, then exits 130 on one SIGTERM while a du of the report waits", + async () => { + const fixture = makeFixture(); + writeProcessStubs(fixture); + const entry = join(scratchRoot(fixture.home), "idle-entry"); + seedScratchEntry(entry); + const npm = join(fixture.home, ".npm"); + mkdirSync(npm); + writeWaitingDu(fixture, npm); + + const run = launchTidy(fixture, ["--apply", "--report"]); + await signalRequested(fixture, run); + + expect(await endingWithin(run, EXIT_BOUND_MS)).toEqual({ code: 130, signal: null }); + expect(run.stdout().split("\n")).toContain(`removed scratch ${entry}`); + expect(existsSync(entry)).toBe(false); + await removeFixtureAfterRecord(fixture, "du-wait"); + }, + SPAWN_TIMEOUT_MS, + ); + + /** + * A test preload of the CLI wraps one file operation: when it is + * reached, it asks for SIGTERM through the request file and holds the + * result of that operation until the signal has reached the process. + * The apply defers the signal exit, so the run still prints every line + * and writes the log, and exits 130 after it. + */ + for (const point of ["recheck", "rotation"] as const) { + it( + `defers a SIGTERM at the ${point === "recheck" ? "recheck of the second scratch entry" : "log rotation, before the append"} until the apply has printed its lines`, + async () => { + const fixture = makeFixture(); + writeProcessStubs(fixture); + const first = join(scratchRoot(fixture.home), "a-entry"); + const second = join(scratchRoot(fixture.home), "b-entry"); + seedScratchEntry(first); + seedScratchEntry(second); + const log = tidyLogPath(fixture.home); + const old = "2026-01-01T00:00:00.000Z removed scratch /old\n".repeat( + Math.ceil((LOG_ROTATE_BYTES + 1) / 45), + ); + writeFileSync(log, old); + const preload = join(fixture.root, "signal-at-file-operation.mjs"); + writeFileSync(preload, FILE_OPERATION_SIGNAL_PRELOAD); + + const run = launchTidy(fixture, ["--apply"], { + preloads: [preload], + env: { + TIDY_SIGNAL_POINT: point, + TIDY_SIGNAL_TARGET: point === "recheck" ? second : log, + TIDY_SIGNAL_AFTER_REMOVAL: first, + }, + }); + await signalRequested(fixture, run); + + expect(await endingWithin(run, EXIT_BOUND_MS)).toEqual({ code: 130, signal: null }); + const lines = run.stdout().split("\n"); + expect(lines).toContain(`removed scratch ${first}`); + expect(lines).toContain(`removed scratch ${second}`); + expect(readFileSync(`${log}.1`, "utf8")).toBe(old); + const logged = readFileSync(log, "utf8").split("\n").filter(Boolean); + expect(logged.map((line) => line.replace(/^\S+ /, ""))).toEqual([ + `removed scratch ${first}`, + `removed scratch ${second}`, + ]); + }, + SPAWN_TIMEOUT_MS, + ); + } + }, + ); }); + +/** + * Wait for the exit record of the waiting stub `name` after the CLI exited; + * the teardown then closes the ticket folder and removes the root. + */ +async function removeFixtureAfterRecord(fixture: Fixture, name: string): Promise { + const deadline = performance.now() + TEARDOWN_BOUND_MS; + while (exitRecords(fixture, name).length === 0) { + if (performance.now() > deadline) throw new Error(`the ${name} stub recorded no exit`); + await sleep(20); + } +} + +/** + * The test preload of the deferral cases. `TIDY_SIGNAL_POINT` `recheck` + * wraps `lstat`: the first `lstat` of `TIDY_SIGNAL_TARGET` after + * `TIDY_SIGNAL_AFTER_REMOVAL` is gone, which is the apply-time recheck of the + * second scratch entry. `rotation` wraps `rename`: the rename of + * `TIDY_SIGNAL_TARGET`, the log, to `tidy.log.1`, so the signal comes between + * the rotation and the append. At that point it asks for SIGTERM through the + * request file of `signalSelfPreload.ts` and gives the result of the + * operation back only once the signal has reached the process. + */ +const FILE_OPERATION_SIGNAL_PRELOAD = `import { createRequire } from "node:module" +const fs = createRequire(import.meta.url)("node:fs") +const point = process.env["TIDY_SIGNAL_POINT"] +const target = process.env["TIDY_SIGNAL_TARGET"] +const removed = process.env["TIDY_SIGNAL_AFTER_REMOVAL"] +let asked = false +const askThenResume = (resume) => { + asked = true + process.once("SIGTERM", () => setImmediate(resume)) + const request = process.env["SIGNAL_REQUEST_FILE"] + fs.writeFileSync(\`\${request}.pending\`, "SIGTERM") + fs.renameSync(\`\${request}.pending\`, request) +} +if (point === "recheck") { + const lstat = fs.lstat + fs.lstat = function (path, ...rest) { + if (asked || String(path) !== target || fs.existsSync(removed)) return lstat.call(this, path, ...rest) + const done = rest.pop() + return lstat.call(this, path, ...rest, (...result) => askThenResume(() => done(...result))) + } +} else if (point === "rotation") { + const rename = fs.rename + fs.rename = function (from, to, done) { + if (asked || String(from) !== target) return rename.call(this, from, to, done) + return rename.call(this, from, to, (...result) => askThenResume(() => done(...result))) + } +} +`; diff --git a/cli/test/unit/tidyReport.test.ts b/cli/test/unit/tidyReport.test.ts index f9d25b73..cd774edb 100644 --- a/cli/test/unit/tidyReport.test.ts +++ b/cli/test/unit/tidyReport.test.ts @@ -1,4 +1,6 @@ import { resolve } from "node:path"; +import { BunServices } from "@effect/platform-bun"; +import { Effect } from "effect"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { @@ -64,17 +66,25 @@ function stubHost(processes: ReadonlyArray | undefined): TidyHost { const missing = { code: null, stdout: "", stderr: "", missing: true }; return { git: real.git, - docker: async (args) => { - dockerCalls.push(args); - return { code: 0, stdout: "Build Cache\t8.9GB\t5.2GB\n", stderr: "", missing: false }; - }, - dockerEndpoint: async () => missing, - run: async () => missing, - processes: async () => processes, + docker: (args) => + Effect.sync(() => { + dockerCalls.push(args); + return { code: 0, stdout: "Build Cache\t8.9GB\t5.2GB\n", stderr: "", missing: false }; + }), + dockerEndpoint: () => Effect.succeed(missing), + run: () => Effect.succeed(missing), + processes: () => Effect.succeed(processes), now: () => Date.now(), }; } +/** Build the report with the Bun services, as the CLI does. */ +function report(host: TidyHost, docker: DockerAccess): Promise> { + return Effect.runPromise( + buildTidyReport(inputs, host, docker).pipe(Effect.provide(BunServices.layer)), + ); +} + function sectionLines( sections: ReadonlyArray, title: string, @@ -97,7 +107,7 @@ afterAll(() => { describe("buildTidyReport", () => { it.runIf(WINDOWS)("reports that Windows is not supported", async () => { - expect(await buildTidyReport(inputs, stubHost(ROWS), NO_DOCKER)).toEqual([ + expect(await report(stubHost(ROWS), NO_DOCKER)).toEqual([ { title: "Report", lines: ["docks-kit tidy --report supports Linux and macOS"] }, ]); }); @@ -105,7 +115,7 @@ describe("buildTidyReport", () => { it.skipIf(WINDOWS)( "lists old orphaned tools and old processes in temporary directories", async () => { - const sections = await buildTidyReport(inputs, stubHost(ROWS), NO_DOCKER); + const sections = await report(stubHost(ROWS), NO_DOCKER); const lines = sectionLines(sections, "Processes"); const pids = lines.map((line) => line.split(" ")[0]); @@ -124,7 +134,7 @@ describe("buildTidyReport", () => { ); it.skipIf(WINDOWS)("says when the process list is unavailable", async () => { - const sections = await buildTidyReport(inputs, stubHost(undefined), NO_DOCKER); + const sections = await report(stubHost(undefined), NO_DOCKER); expect(sectionLines(sections, "Processes")).toEqual(["unavailable: process list unavailable"]); expect(sectionLines(sections, "Memory")).toContain("unavailable: process list unavailable"); @@ -133,7 +143,7 @@ describe("buildTidyReport", () => { it.skipIf(WINDOWS)( "lists merged branches without a branch that a worktree checks out", async () => { - const lines = sectionLines(await buildTidyReport(inputs, stubHost([]), NO_DOCKER), "Git"); + const lines = sectionLines(await report(stubHost([]), NO_DOCKER), "Git"); expect(lines).toContain( `${sandbox.main}: local branches merged into origin/main (1): ${sandbox.doneBranch}`, @@ -145,7 +155,7 @@ describe("buildTidyReport", () => { it.skipIf(WINDOWS)("never calls Docker through an endpoint that is not local", async () => { dockerCalls.length = 0; const remote: DockerAccess = { kind: "not-local", endpoint: "ssh://prod" }; - const sections = await buildTidyReport(inputs, stubHost([]), remote); + const sections = await report(stubHost([]), remote); expect(sectionLines(sections, "Docker")).toEqual([ "unavailable: docker endpoint ssh://prod is not local", @@ -156,7 +166,7 @@ describe("buildTidyReport", () => { it.skipIf(WINDOWS)("puts the verified endpoint first on each Docker call", async () => { dockerCalls.length = 0; const local: DockerAccess = { kind: "local", endpoint: LOCAL_ENDPOINT }; - const sections = await buildTidyReport(inputs, stubHost([]), local); + const sections = await report(stubHost([]), local); expect(sectionLines(sections, "Docker")).toEqual([ "Build Cache: 8.9GB, reclaimable 5.2GB", From 9939bb6c4c4b4bcf1d50544badeed7d117927c4f Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:47:39 -0300 Subject: [PATCH 2/3] Point the tidy guidance to the Effect apply lock and signal rules Step guidance of #295: tidy-context names the scoped tryAcquireKitLock, the signal exit and deferral of the apply, the section failure rule, the runBounded gotcha, the paths that stay untested, and the new source line ranges. Verified: git grep -n -e 'a throw becomes' -e 'acquireUseRelease' -e 'Network removal, log rotation' -- .agents/skills/tidy-context; bun x --no-install vitest run cli/test/unit/skillMetadata.test.ts --- .agents/skills/tidy-context/SKILL.md | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/.agents/skills/tidy-context/SKILL.md b/.agents/skills/tidy-context/SKILL.md index 399fd397..82a16721 100644 --- a/.agents/skills/tidy-context/SKILL.md +++ b/.agents/skills/tidy-context/SKILL.md @@ -6,9 +6,9 @@ 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 @@ -16,17 +16,17 @@ metadata: - 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 @@ -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` | @@ -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`) @@ -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 `, 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 `, 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 -- `; 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: @@ -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: `; 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: `; 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`. @@ -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 From b7c4936326395e64c9bf931c14d614dc72353a46 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:02:18 -0300 Subject: [PATCH 3/3] Match the tidy log and cache lines without RegExp.escape Full CI failed on Ubuntu and Windows: RegExp.escape is not a function in the Node of the runners. The two assertions now compare the path part as a string. Verified: bun x --no-install vitest run cli/test/unit/tidy.test.ts; bun run lint; bun run format --- cli/test/unit/tidy.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cli/test/unit/tidy.test.ts b/cli/test/unit/tidy.test.ts index c2b59ce0..36cf8ee4 100644 --- a/cli/test/unit/tidy.test.ts +++ b/cli/test/unit/tidy.test.ts @@ -763,9 +763,9 @@ describe("applyTidy", () => { expect(outcome.lines).toEqual([`removed scratch ${entry}`]); expect(readFileSync(`${log}.1`, "utf8")).toBe(old); - expect(readFileSync(log, "utf8")).toMatch( - new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\S+ removed scratch ${RegExp.escape(entry)}\\n$`), - ); + const written = readFileSync(log, "utf8"); + expect(written).toMatch(/^\d{4}-\d{2}-\d{2}T\S+ /); + expect(written.replace(/^\S+ /, "")).toBe(`removed scratch ${entry}\n`); }); it("keeps a scratch entry that became active after the plan, with its keep line", async () => { @@ -1209,9 +1209,9 @@ describe("spawned docks-kit tidy", () => { expect(await run.ended).toEqual({ code: 0, signal: null }); if (POSIX) { const caches = reportSection(run.stdout(), "Package and tool caches"); - expect(caches).toContainEqual( - expect.stringMatching(new RegExp(`^\\d+\\.\\d (MB|GB) {2}${RegExp.escape(npm)}$`)), - ); + const npmLines = caches.filter((line) => line.endsWith(` ${npm}`)); + expect(npmLines).toHaveLength(1); + expect(npmLines[0]!.slice(0, -` ${npm}`.length)).toMatch(/^\d+\.\d (MB|GB)$/); expect(caches).toContain("hint: npm cache verify"); } else { expect(reportSection(run.stdout(), "Report")).toContain(