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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions .agents/skills/tidy-context/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
---
name: tidy-context
description: "Use when modifying the docks-kit agent-leftover sweep or checked temporary-path removal: tidy.ts planTidy, applyTidy, agentRoots, checkWorktree, isLocalDockerEndpoint, localDocker, resolveProcessCwds, or isProtectedProcess; kitLock.ts acquireKitLock and the tidy-lock.db apply lock; processes.ts processExited; tidyReport.ts buildTidyReport; scratch.ts createScratchDir, allowedRemovalRoots, or removeTemporaryPath; commands tidy.ts runTidy and scratch.ts (docks-kit tidy --apply, --repo, --report; docks-kit scratch new and remove); or the omp extension hygiene.ts with scratch_new, scratch_remove, tidy_report, detectResources, claimSweep over tidy.stamp.claim, and its Windows EPERM probe. Not for agent cleanup conduct inside a session (use workspace-hygiene) or deployment and linking of the docks-kit-omp plugin (use omp-sync-context)."
description: "Use when modifying the docks-kit agent-leftover sweep or checked temporary-path removal: tidy.ts planTidy, applyTidy, agentRoots, checkWorktree, isLocalDockerEndpoint, localDocker, resolveProcessCwds, or isProtectedProcess; kitLock.ts tryAcquireKitLock, which takes the tidy-lock.db apply lock (the Promise poll acquireKitLock is test-only); processes.ts processExited; tidyReport.ts buildTidyReport; scratch.ts createScratchDir, allowedRemovalRoots, or removeTemporaryPath; commands tidy.ts runTidy and scratch.ts (docks-kit tidy --apply, --repo, --report; docks-kit scratch new and remove); or the omp extension hygiene.ts with scratch_new, scratch_remove, tidy_report, detectResources, claimSweep over tidy.stamp.claim, and its Windows EPERM probe. Not for agent cleanup conduct inside a session (use workspace-hygiene) or deployment and linking of the docks-kit-omp plugin (use omp-sync-context)."
user-invocable: false
metadata:
pattern: tool-wrapper
source_files:
- path: cli/src/engine-native/tidy.ts
lines: "1-1427"
lines: "1-1487"
- path: cli/src/engine-native/tidyReport.ts
lines: "1-589"
lines: "1-586"
- path: cli/src/engine-native/kitLock.ts
lines: "1-121"
lines: "1-162"
- path: cli/src/engine-native/processes.ts
lines: "1-16"
- path: cli/src/engine-native/scratch.ts
Expand All @@ -22,18 +22,18 @@ metadata:
- path: SoT/.omp/plugin/extensions/hygiene.ts
lines: "1-2291"
- path: cli/test/unit/tidy.test.ts
lines: "1-1466"
lines: "1-1802"
- path: cli/test/unit/kitLock.test.ts
lines: "1-398"
- path: cli/test/unit/tidyReport.test.ts
lines: "1-178"
lines: "1-196"
- path: cli/test/unit/scratch.test.ts
lines: "1-187"
- path: cli/test/unit/ompKitPluginExtension.test.ts
lines: "1-1520"
- path: cli/test/lib/gitSandbox.ts
lines: "1-181"
updated: "2026-11-19"
updated: "2026-12-02"
---

# Tidy, Scratch, and Hygiene Context
Expand Down Expand Up @@ -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` — `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/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` is test-only: only tests call it. It imports only `node:` modules, so a test child can load it alone (verify: `grep -n 'from "' cli/src/engine-native/kitLock.ts`)
- `cli/src/engine-native/processes.ts` — `processExited` — true only when `process.kill(pid, 0)` throws ESRCH. `tidy.ts darwinProcesses` (the macOS cwd probe) uses it to tell an exited PID from an unreadable cwd. Unprobed: no unit test runs the macOS probe (verify: `grep -n "processExited(pid)" cli/src/engine-native/tidy.ts`)
- `cli/src/engine-native/tidyReport.ts` — `buildTidyReport` — read-only sections; reuses `tidy.ts` helpers (verify: `grep -n 'from "./tidy"' cli/src/engine-native/tidyReport.ts`)
- `cli/src/engine-native/scratch.ts` — `kitCacheDir`, `scratchRoot`, `tidyApplyLockPath`, `syncLockPath` — owner of `~/.cache/docks-kit`, its `scratch/` child, and the lock files `tidy-lock.db` and `sync-lock.db` (verify: `grep -n -e "export function kitCacheDir" -e "LockPath(home" cli/src/engine-native/scratch.ts`)
Expand Down Expand Up @@ -98,7 +98,7 @@ Pointers here name concepts, not coordinates — if a path or symbol moved, trus
4. `git status --porcelain -z` fails or lists a path: keep.
5. No `origin/HEAD`, `origin/main`, or `origin/master` (`defaultBranchRef`): keep.
6. `HEAD` is not an ancestor of that ref: keep `not merged into <ref>`.
7. Admin `HEAD`, `index`, `logs/HEAD` are younger than the worktree idle threshold: keep `active N h ago`.
7. The newest activity of the two metadata scans (admin `HEAD`, `index`, `logs/HEAD`; the second scan also reads the changed paths) is younger than the worktree idle threshold: keep `active N h ago`. A write that only the second scan sees keeps the worktree.
8. A process cwd is inside: keep `in use by a running process`; no process list: keep `process list unavailable`.
9. `worktreeRepository` cannot prove a linked worktree of `<common>/worktrees`: keep.

Expand Down Expand Up @@ -128,9 +128,9 @@ Probe: `bunx vitest run cli/test/unit/tidy.test.ts -t "removes the merged idle w

### Scratch rule

- Each first-level entry of the scratch root: a symbolic link is kept; activity is the latest `lstat` mtime of the entry and its immediate children (`entryActivity`).
- Each first-level entry of the scratch root: a symbolic link is kept; activity is the latest `lstat` mtime of the entry and its immediate children (`entryActivity`), read one after another. The entry itself is read again after its children: a changed mtime or inode of the entry, or an entry that is gone by then, keeps it with `cannot check <path>: changed during the check`. The recheck sees a change of the entry itself, such as a child that is created, removed, or renamed; it does not see a write to an existing child after that child was read.
- Idle past the scratch threshold and no process cwd inside: `remove-scratch`.
- `applyTidy` checks activity again before removal and removes through `removeTemporaryPath(path, [scratchRoot], home)`.
- `applyTidy` checks activity again before removal and removes through `removeTemporaryPath(path, [scratchRoot], home)` only on a positive idle result; an entry that is missing at that check is not removed and gets `failed scratch <path>: does not exist`.
- Probe: `bunx vitest run cli/test/unit/tidy.test.ts -t "keeps an old scratch entry whose children it cannot list"`.

### Apply order
Expand All @@ -144,7 +144,7 @@ Probe: `bunx vitest run cli/test/unit/tidy.test.ts -t "removes the merged idle w

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"`.
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`; each `git` and `docker` call of the apply runs in `signalExitPoint`. A signal that arrives during a waiting `git` or `docker` call exits 130 at once. A signal recorded during a plain apply step has one of two outcomes: when a later `git` or `docker` call of the apply remains, the CLI exits 130 before it starts the next `git` or `docker` call, and the lines of the apply are not printed; when no such call remains, the apply prints its lines and writes the log, and the CLI then exits 130. 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

Expand All @@ -167,7 +167,8 @@ Probes: `bunx vitest run cli/test/unit/scratch.test.ts -t "refuses a symbolic li

### Lock

- `kitLock.ts acquireKitLock(path, { waitMs })` makes the directory (mode 0700), opens `DatabaseSync(path)`, and sets `busy_timeout = 0`. It tries `BEGIN IMMEDIATE` every `POLL_MS` until it succeeds or `waitMs` ends. It returns `{ kind: "acquired", lock }` or `{ kind: "held" }`.
- `kitLock.ts tryAcquireKitLock(path, { privateDirectory })` takes the production locks, `tidy-lock.db` included. It makes the directory (mode 0700) unless `privateDirectory` is false, opens `DatabaseSync(path)`, sets `busy_timeout = 0`, and tries `BEGIN IMMEDIATE` once. It returns the lock, or `undefined` when another connection holds it; a caller that waits polls it between its own sleeps.
- `kitLock.ts acquireKitLock(path, { waitMs, pollMs })` is test-only: a Promise poll that tries `BEGIN IMMEDIATE`, then sleeps `pollMs` (default `KIT_LOCK_POLL_MS`), capped at the time left of `waitMs`, and tries again until it succeeds or `waitMs` ends. It returns `{ kind: "acquired", lock }` or `{ kind: "held" }`.
- The lock is the RESERVED lock of that transaction, and only one connection can hold RESERVED. `BEGIN EXCLUSIVE` is wrong here: two racers that each hold SHARED while they move up can both fail at `waitMs: 0`.
- At most one connection, in any process, holds the lock. The OS releases it when the holder process ends for any reason. A paused holder keeps it. No staleness rule and no takeover exist.
- A module-level set keeps each held connection, so the garbage collector cannot close a lock that a caller dropped.
Expand All @@ -192,7 +193,7 @@ Re-derive before you rely on a value.
|---|---|---|
| `WORKTREE_IDLE_MS`, `STACK_IDLE_MS`, `SCRATCH_IDLE_MS` | Worktree, container/orphan, and scratch idle thresholds | `grep -n -e "WORKTREE_IDLE_MS =" -e "STACK_IDLE_MS =" -e "SCRATCH_IDLE_MS =" cli/src/engine-native/tidy.ts` |
| `LOG_ROTATE_BYTES` | `tidy.log` size that triggers rotation | `grep -n "LOG_ROTATE_BYTES =" cli/src/engine-native/tidy.ts` |
| `POLL_MS` | Time between two lock tries | `grep -n "POLL_MS =" cli/src/engine-native/kitLock.ts` |
| `KIT_LOCK_POLL_MS` | Default sleep between two tries of the test-only `acquireKitLock` | `grep -n "KIT_LOCK_POLL_MS =" cli/src/engine-native/kitLock.ts` |
| `REPORT_PROCESS_AGE_MS`, `RECENT_MS` | Report process age and "recent" window | `grep -n -e "REPORT_PROCESS_AGE_MS =" -e "RECENT_MS =" cli/src/engine-native/tidyReport.ts` |
| `SWEEP_INTERVAL_MS`, `CLAIM_STALE_MS` | Background sweep interval and claim staleness | `grep -n -e "SWEEP_INTERVAL_MS =" -e "CLAIM_STALE_MS =" SoT/.omp/plugin/extensions/hygiene.ts` |

Expand All @@ -217,7 +218,7 @@ Re-derive before you rely on a value.
| Worktree activity ignores git-ignored files | A stack that writes only to an ignored `dist/` does not refresh activity; a merged clean worktree is removed | `checkWorktree` runs `git status --porcelain -z` without `--ignored`: `grep -n -e '"--porcelain", "-z"' cli/src/engine-native/tidy.ts` |
| Containers in a removable worktree skip the container idle rule | A running container with an anonymous volume is removed with `docker rm --force --volumes` | Docker documents `--force` as SIGKILL and `--volumes` as anonymous-volume removal: https://docs.docker.com/reference/cli/docker/container/rm |
| `missing` docker is not `containersUnknown` | With no `docker` CLI, worktrees are still removed | `bunx vitest run cli/test/unit/tidy.test.ts -t "keeps the worktree rule when docker is not installed"` |
| Silent skips | A container group outside the territory, a stopped group in a present directory, a vanished scratch entry, or an orphan with no cwd gets no `keep` line | Read `planTidy` before you claim "everything is listed" |
| Silent skips | A container group outside the territory, a stopped group in a present directory, a scratch entry that is missing at the first read of its check, or an orphan with no cwd gets no `keep` line | Read `planTidy` before you claim "everything is listed" |
| Windows has no process list | Every worktree and scratch entry stays, and the orphan rule is off | `grep -n "process.platform ===" cli/src/engine-native/tidy.ts` |
| A held lock exits 0 | A script reads "another docks-kit tidy run holds" as success | `runTidy` leaves the exit code unset when the lock is held; `bunx vitest run cli/test/unit/tidy.test.ts -t "prints the held line and plans nothing while another run holds the lock"` |
| `applyTidy` does not take the lock | A new caller that skips `runTidy` applies a plan with no lock, next to a running sweep | Call `applyTidy` only through `runTidy`: `grep -rn "applyTidy(" cli/src` |
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 2026-12-02 - docks-kit 0.32.3: tidy keeps a scratch directory that changes during its check

`docks-kit tidy` and `docks-kit tidy --apply` now look at an idle scratch
directory itself again after they read the dates of its files
(DocksDocks/docks-kit#302). When the directory itself changed during that
check, because a file or folder in it was created, removed, or renamed, tidy
keeps it and prints
`keep scratch <path>: cannot check <path>: changed during the check` in the
plan, or `kept scratch <path>: ...` in the result of `--apply`. The next run
checks it again. Before, `--apply` could remove a directory in which an
agent had just created a file. A write to a file that already existed, after
tidy read that file, does not change the directory and stays unseen.

`docks-kit tidy --apply` no longer removes a scratch directory that is
missing when it checks the directory again; it reports
`failed scratch <path>: does not exist`, as before, also when the directory
reappears before the removal.

## 2026-12-01 - docks-kit 0.32.2: fast toggles refuse a retargeted or replaced config

`docks-kit --fast` and `docks-kit --ultrafast` now also leave `config.yml`
Expand Down
2 changes: 1 addition & 1 deletion SoT/.omp/plugin/extensions/talk.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion cli/src/commands/tidy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const report = Flag.Boolean("report").pipe(
);

/** The try of the tidy lock failed; `cause` is the error of the lock primitive. */
export class TidyLockFailed extends Schema.TaggedError<
class TidyLockFailed extends Schema.TaggedError<
TidyLockFailed,
{ readonly brand: unique symbol }
>()("TidyLockFailed", {
Expand Down
6 changes: 4 additions & 2 deletions cli/src/engine-native/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,10 @@ normalization injectable for tests. These direct reads remain:

Two cross-platform primitives need no platform branch:

- `kitLock.ts` `acquireKitLock`: an SQLite `BEGIN IMMEDIATE` lock. The OS
releases it when the holder process ends, on POSIX and on Windows.
- `kitLock.ts` `tryAcquireKitLock`: an SQLite `BEGIN IMMEDIATE` lock, which
the tidy apply lock and the sync locks take. The OS releases it when the
holder process ends, on POSIX and on Windows. The Promise poll
`acquireKitLock` is test-only.
- `processes.ts` `processExited`: `process.kill(pid, 0)` throws ESRCH for an
exited PID on every host (`kill(2)` on POSIX, libuv `uv_kill` on Windows).

Expand Down
13 changes: 10 additions & 3 deletions cli/src/engine-native/syncConcurrency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,16 @@ export const runBounded = <A, E, R>(
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);
// The exit callback records the outcome before it returns, so no
// scheduler yield lets a sibling take a queued task after a failure.
yield* tasks[index]!.pipe(
Effect.onExit((exit) => {
if (Exit.isSuccess(exit)) results[index] = exit.value;
else pool.state = drainAfterFailure(pool.state, index, exit.cause);
return Effect.void;
}),
Effect.exit,
);
}
});
const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker);
Expand Down
Loading
Loading