docks-kit 0.20.10 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +14 -7
- package/README.md +19 -10
- package/cli/docs/command-guards.md +30 -12
- package/cli/docs/flags.md +34 -5
- package/cli/docs/omp-models.md +96 -44
- package/cli/src/argv.ts +4 -0
- package/cli/src/commands/omp.ts +95 -23
- package/cli/src/commands/scratch.ts +75 -0
- package/cli/src/commands/tidy.ts +91 -0
- package/cli/src/engine-native/ompKitPlugin.ts +94 -0
- package/cli/src/engine-native/ompOverlay.ts +96 -26
- package/cli/src/engine-native/ompPlugins.ts +41 -8
- package/cli/src/engine-native/ompSync.ts +7 -4
- package/cli/src/engine-native/scratch.ts +188 -0
- package/cli/src/engine-native/tidy.ts +1296 -0
- package/cli/src/engine-native/tidyLock.ts +163 -0
- package/cli/src/engine-native/tidyReport.ts +509 -0
- package/cli/src/generated/sotPayload.ts +14 -6
- package/cli/src/main.ts +8 -0
- package/cli/tsconfig.json +1 -1
- package/docks-kit +2 -2
- package/docks-kit.ps1 +2 -2
- package/package.json +3 -3
|
@@ -0,0 +1,1296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe sweep of agent leftovers. `planTidy` lists what can go: merged idle
|
|
3
|
+
* linked worktrees and their containers, containers of gone or idle agent
|
|
4
|
+
* directories, orphaned processes in agent directories, and idle scratch
|
|
5
|
+
* entries. `applyTidy` performs a plan under a lock file. Each check fails
|
|
6
|
+
* closed: a candidate that a check cannot prove safe stays, with its reason.
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
appendFileSync,
|
|
10
|
+
lstatSync,
|
|
11
|
+
readdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
readlinkSync,
|
|
14
|
+
realpathSync,
|
|
15
|
+
renameSync,
|
|
16
|
+
statSync,
|
|
17
|
+
type Stats,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
20
|
+
|
|
21
|
+
import { spawnProcess, type AsyncProcessResult } from "./exec";
|
|
22
|
+
import { ensureDirectory } from "./ompFileDeploy";
|
|
23
|
+
import { isSameOrInside, kitCacheDir, removeTemporaryPath } from "./scratch";
|
|
24
|
+
import { runBounded } from "./syncConcurrency";
|
|
25
|
+
import { acquireTidyLock, releaseTidyLock } from "./tidyLock";
|
|
26
|
+
|
|
27
|
+
export const HOUR_MS = 3_600_000;
|
|
28
|
+
export const DAY_MS = 24 * HOUR_MS;
|
|
29
|
+
const WORKTREE_IDLE_MS = 24 * HOUR_MS;
|
|
30
|
+
/** Idle time of an agent directory before tidy stops its containers; also the orphan age. */
|
|
31
|
+
const STACK_IDLE_MS = 24 * HOUR_MS;
|
|
32
|
+
const SCRATCH_IDLE_MS = 7 * DAY_MS;
|
|
33
|
+
const LOG_ROTATE_BYTES = 262_144;
|
|
34
|
+
|
|
35
|
+
export const PROCESS_LIST_UNAVAILABLE = "process list unavailable";
|
|
36
|
+
const PROCESS_LIST_UNAVAILABLE_NOTE =
|
|
37
|
+
"process list unavailable; kept every candidate that a running process could use";
|
|
38
|
+
const IN_USE = "in use by a running process";
|
|
39
|
+
const DOCKER_PS_FORMAT =
|
|
40
|
+
'{{.ID}}\\t{{.State}}\\t{{.Label "com.docker.compose.project"}}\\t{{.Label "com.docker.compose.project.working_dir"}}';
|
|
41
|
+
/** Process names that tidy never stops: the agent harness, its launcher, and the kit. */
|
|
42
|
+
const PROTECTED_NAMES = ["omp", "tern", "docks-kit"] as const;
|
|
43
|
+
|
|
44
|
+
// ----------------------------------------------------------------- paths ----
|
|
45
|
+
|
|
46
|
+
/** The plan-lifecycle worktree root: `$XDG_DATA_HOME/agent-worktrees`. */
|
|
47
|
+
export function agentWorktreeRoot(home: string, env: NodeJS.ProcessEnv): string {
|
|
48
|
+
const xdg = env["XDG_DATA_HOME"];
|
|
49
|
+
const dataHome =
|
|
50
|
+
xdg !== undefined && xdg !== "" && isAbsolute(xdg) ? xdg : join(home, ".local", "share");
|
|
51
|
+
return join(dataHome, "agent-worktrees");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function tidyLockPath(home: string): string {
|
|
55
|
+
return join(kitCacheDir(home), "tidy.lock");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function tidyLogPath(home: string): string {
|
|
59
|
+
return join(kitCacheDir(home), "tidy.log");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolve a path, then take its real path when it exists. Tidy compares only
|
|
64
|
+
* these forms, so macOS `/private` and Windows drive spellings agree.
|
|
65
|
+
*/
|
|
66
|
+
export function normalizePath(path: string): string {
|
|
67
|
+
const resolved = resolve(path);
|
|
68
|
+
try {
|
|
69
|
+
return realpathSync(resolved);
|
|
70
|
+
} catch {
|
|
71
|
+
return resolved;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ------------------------------------------------------------------ host ----
|
|
76
|
+
|
|
77
|
+
export interface TidyProcess {
|
|
78
|
+
readonly code: number | null;
|
|
79
|
+
readonly stdout: string;
|
|
80
|
+
readonly stderr: string;
|
|
81
|
+
readonly missing: boolean;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface ProcessRow {
|
|
85
|
+
readonly pid: number;
|
|
86
|
+
readonly ppid: number;
|
|
87
|
+
readonly ageMs: number;
|
|
88
|
+
readonly rssKb: number;
|
|
89
|
+
readonly comm: string;
|
|
90
|
+
readonly args: string;
|
|
91
|
+
readonly cwd: string | undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface TidyHost {
|
|
95
|
+
readonly git: (args: ReadonlyArray<string>) => Promise<TidyProcess>;
|
|
96
|
+
/**
|
|
97
|
+
* Runs `docker <args>`. Tidy calls it only through `localDocker`, which puts
|
|
98
|
+
* `--host <verified local endpoint>` first.
|
|
99
|
+
*/
|
|
100
|
+
readonly docker: (args: ReadonlyArray<string>) => Promise<TidyProcess>;
|
|
101
|
+
/**
|
|
102
|
+
* Prints the endpoint that a plain docker command uses, after `DOCKER_HOST`,
|
|
103
|
+
* `DOCKER_CONTEXT`, and the current context apply. It does not connect.
|
|
104
|
+
*/
|
|
105
|
+
readonly dockerEndpoint: () => Promise<TidyProcess>;
|
|
106
|
+
readonly run: (command: string, args: ReadonlyArray<string>) => Promise<TidyProcess>;
|
|
107
|
+
/** `undefined` when the host cannot list processes with their working directories. */
|
|
108
|
+
readonly processes: () => Promise<ReadonlyArray<ProcessRow> | undefined>;
|
|
109
|
+
readonly now: () => number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function errorCode(cause: unknown): string | undefined {
|
|
113
|
+
return cause instanceof Error && "code" in cause && typeof cause.code === "string"
|
|
114
|
+
? cause.code
|
|
115
|
+
: undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function errorMessage(cause: unknown): string {
|
|
119
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function isMissingCommand(result: AsyncProcessResult): boolean {
|
|
123
|
+
const error = result.error;
|
|
124
|
+
if (error === undefined) return false;
|
|
125
|
+
return errorCode(error) === "ENOENT" || error.message.startsWith("command not found on PATH");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function runTool(command: string, args: ReadonlyArray<string>): Promise<TidyProcess> {
|
|
129
|
+
const result = await spawnProcess(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
130
|
+
const stderr =
|
|
131
|
+
result.stderr === "" && result.error !== undefined ? result.error.message : result.stderr;
|
|
132
|
+
return {
|
|
133
|
+
code: result.exitCode,
|
|
134
|
+
stdout: result.stdout,
|
|
135
|
+
stderr,
|
|
136
|
+
missing: isMissingCommand(result),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** First non-empty output line of a failed command, for a one-line reason. */
|
|
141
|
+
export function firstLine(result: TidyProcess): string {
|
|
142
|
+
const line = [...result.stderr.split("\n"), ...result.stdout.split("\n")]
|
|
143
|
+
.map((text) => text.trim())
|
|
144
|
+
.find((text) => text !== "");
|
|
145
|
+
if (line !== undefined) return line;
|
|
146
|
+
return result.missing ? "command not found" : `exit ${String(result.code)}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The file name of `comm`; macOS `ps` prints the full executable path there. */
|
|
150
|
+
export function commandName(comm: string): string {
|
|
151
|
+
return comm.split("/").at(-1) ?? comm;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
interface PsFields {
|
|
155
|
+
readonly ppid: number;
|
|
156
|
+
readonly ageMs: number;
|
|
157
|
+
readonly rssKb: number;
|
|
158
|
+
readonly args: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Parse `pid ppid age rss args` rows; `undefined` when a row does not parse. */
|
|
162
|
+
function parsePsFields(
|
|
163
|
+
stdout: string,
|
|
164
|
+
parseAge: (text: string) => number | undefined,
|
|
165
|
+
): Map<number, PsFields> | undefined {
|
|
166
|
+
const rows = new Map<number, PsFields>();
|
|
167
|
+
for (const line of stdout.split("\n")) {
|
|
168
|
+
if (line.trim() === "") continue;
|
|
169
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)(?:\s+(.*))?$/.exec(line);
|
|
170
|
+
if (match === null) return undefined;
|
|
171
|
+
const ageMs = parseAge(match[3]!);
|
|
172
|
+
if (ageMs === undefined) return undefined;
|
|
173
|
+
rows.set(Number(match[1]), {
|
|
174
|
+
ppid: Number(match[2]),
|
|
175
|
+
ageMs,
|
|
176
|
+
rssKb: Number(match[4]),
|
|
177
|
+
args: (match[5] ?? "").trim(),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
return rows.size === 0 ? undefined : rows;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Parse `pid comm` rows; `comm` is the last column, so it may hold spaces. */
|
|
184
|
+
function parsePsNames(stdout: string): Map<number, string> | undefined {
|
|
185
|
+
const names = new Map<number, string>();
|
|
186
|
+
for (const line of stdout.split("\n")) {
|
|
187
|
+
if (line.trim() === "") continue;
|
|
188
|
+
const match = /^\s*(\d+)\s(.*)$/.exec(line);
|
|
189
|
+
if (match === null) return undefined;
|
|
190
|
+
names.set(Number(match[1]), match[2]!.trim());
|
|
191
|
+
}
|
|
192
|
+
return names.size === 0 ? undefined : names;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Parse the macOS `etime` form `[[dd-]hh:]mm:ss` into milliseconds. */
|
|
196
|
+
export function parseElapsed(text: string): number | undefined {
|
|
197
|
+
const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(text);
|
|
198
|
+
if (match === null) return undefined;
|
|
199
|
+
const [d, h, m, s] = [match[1], match[2], match[3], match[4]].map((part) =>
|
|
200
|
+
part === undefined ? 0 : Number(part),
|
|
201
|
+
);
|
|
202
|
+
return (((d! * 24 + h!) * 60 + m!) * 60 + s!) * 1000;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function parseSeconds(text: string): number | undefined {
|
|
206
|
+
return /^\d+$/.test(text) ? Number(text) * 1000 : undefined;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Parse `lsof -Fpn` output: a `p<pid>` line, then the `n<path>` line of its cwd. */
|
|
210
|
+
function parseLsofCwd(stdout: string): Map<number, string> | undefined {
|
|
211
|
+
const cwds = new Map<number, string>();
|
|
212
|
+
let pid: number | undefined;
|
|
213
|
+
for (const line of stdout.split("\n")) {
|
|
214
|
+
if (line.startsWith("p")) {
|
|
215
|
+
if (!/^p\d+$/.test(line)) return undefined;
|
|
216
|
+
pid = Number(line.slice(1));
|
|
217
|
+
} else if (line.startsWith("n") && pid !== undefined) {
|
|
218
|
+
cwds.set(pid, line.slice(1));
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return cwds;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A `ps` row before its working directory is read. */
|
|
225
|
+
export type ListedProcess = Omit<ProcessRow, "cwd">;
|
|
226
|
+
|
|
227
|
+
/** One read of a process working directory. */
|
|
228
|
+
export type CwdProbe =
|
|
229
|
+
| { readonly kind: "cwd"; readonly path: string }
|
|
230
|
+
| { readonly kind: "exited" }
|
|
231
|
+
| { readonly kind: "unreadable" };
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Processes that the kernel often keeps from a `cwd` read (the user service
|
|
235
|
+
* manager and setgid agents). They never work in an agent directory.
|
|
236
|
+
*/
|
|
237
|
+
const UNREADABLE_CWD_NAMES: ReadonlyArray<string> = [
|
|
238
|
+
"systemd",
|
|
239
|
+
"(sd-pam)",
|
|
240
|
+
"ssh-agent",
|
|
241
|
+
"gpg-agent",
|
|
242
|
+
];
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Attach each working directory. A process that exited during the probe is
|
|
246
|
+
* dropped. A known agent or service manager with an unreadable cwd stays with
|
|
247
|
+
* `cwd: undefined`: it keeps its PID, so `orphanParents` still finds the
|
|
248
|
+
* `systemd` subreaper, and it protects no directory. Any other unreadable cwd
|
|
249
|
+
* returns `undefined`, because that process could use an agent directory.
|
|
250
|
+
*/
|
|
251
|
+
export function resolveProcessCwds(
|
|
252
|
+
rows: ReadonlyArray<ListedProcess>,
|
|
253
|
+
readCwd: (pid: number) => CwdProbe,
|
|
254
|
+
): ReadonlyArray<ProcessRow> | undefined {
|
|
255
|
+
const resolved: Array<ProcessRow> = [];
|
|
256
|
+
for (const row of rows) {
|
|
257
|
+
const probe = readCwd(row.pid);
|
|
258
|
+
if (probe.kind === "exited") continue;
|
|
259
|
+
if (probe.kind === "cwd") {
|
|
260
|
+
resolved.push({ ...row, cwd: probe.path });
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
// Linux `comm` is the name cut to 15 characters; macOS `comm` is the full path.
|
|
264
|
+
const known =
|
|
265
|
+
UNREADABLE_CWD_NAMES.includes(row.comm) ||
|
|
266
|
+
UNREADABLE_CWD_NAMES.includes(commandName(row.comm));
|
|
267
|
+
if (!known) return undefined;
|
|
268
|
+
resolved.push({ ...row, cwd: undefined });
|
|
269
|
+
}
|
|
270
|
+
return resolved;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Join the two `ps` reads by PID. Two reads keep `comm` unambiguous: as the
|
|
275
|
+
* last column it may hold spaces (Linux `omp daemon brok`, a macOS app path).
|
|
276
|
+
*/
|
|
277
|
+
function joinRows(
|
|
278
|
+
fields: Map<number, PsFields> | undefined,
|
|
279
|
+
names: Map<number, string> | undefined,
|
|
280
|
+
): Array<ListedProcess> | undefined {
|
|
281
|
+
if (fields === undefined || names === undefined) return undefined;
|
|
282
|
+
const rows: Array<ListedProcess> = [];
|
|
283
|
+
for (const [pid, row] of fields) {
|
|
284
|
+
const comm = names.get(pid);
|
|
285
|
+
if (comm === undefined || pid === process.pid) continue;
|
|
286
|
+
rows.push({ pid, ...row, comm });
|
|
287
|
+
}
|
|
288
|
+
return rows;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** `readlink /proc/<pid>/cwd`; ENOENT or ESRCH means that the process exited. */
|
|
292
|
+
function readLinuxCwd(pid: number): CwdProbe {
|
|
293
|
+
try {
|
|
294
|
+
return { kind: "cwd", path: readlinkSync(`/proc/${pid}/cwd`) };
|
|
295
|
+
} catch (cause) {
|
|
296
|
+
const code = errorCode(cause);
|
|
297
|
+
return code === "ENOENT" || code === "ESRCH" ? { kind: "exited" } : { kind: "unreadable" };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function linuxProcesses(uid: number): Promise<ReadonlyArray<ProcessRow> | undefined> {
|
|
302
|
+
const user = ["-u", String(uid)];
|
|
303
|
+
const [fields, names] = await Promise.all([
|
|
304
|
+
runTool("ps", [...user, "-o", "pid=,ppid=,etimes=,rss=,args="]),
|
|
305
|
+
runTool("ps", [...user, "-o", "pid=,comm="]),
|
|
306
|
+
]);
|
|
307
|
+
if (fields.code !== 0 || names.code !== 0) return undefined;
|
|
308
|
+
const rows = joinRows(parsePsFields(fields.stdout, parseSeconds), parsePsNames(names.stdout));
|
|
309
|
+
return rows === undefined ? undefined : resolveProcessCwds(rows, readLinuxCwd);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function darwinProcesses(uid: number): Promise<ReadonlyArray<ProcessRow> | undefined> {
|
|
313
|
+
const user = ["-x", "-U", String(uid)];
|
|
314
|
+
const [fields, names, lsof] = await Promise.all([
|
|
315
|
+
runTool("ps", [...user, "-o", "pid=,ppid=,etime=,rss=,args="]),
|
|
316
|
+
runTool("ps", [...user, "-o", "pid=,comm="]),
|
|
317
|
+
runTool("lsof", ["-nP", "-a", "-u", String(uid), "-d", "cwd", "-Fpn"]),
|
|
318
|
+
]);
|
|
319
|
+
if (fields.code !== 0 || names.code !== 0 || lsof.code !== 0) return undefined;
|
|
320
|
+
const cwds = parseLsofCwd(lsof.stdout);
|
|
321
|
+
const rows = joinRows(parsePsFields(fields.stdout, parseElapsed), parsePsNames(names.stdout));
|
|
322
|
+
if (cwds === undefined || rows === undefined) return undefined;
|
|
323
|
+
// A PID without an `lsof` cwd exited (ESRCH) or is alive but unreadable (EPERM).
|
|
324
|
+
return resolveProcessCwds(rows, (pid) => {
|
|
325
|
+
const cwd = cwds.get(pid);
|
|
326
|
+
if (cwd !== undefined) return { kind: "cwd", path: cwd };
|
|
327
|
+
try {
|
|
328
|
+
process.kill(pid, 0);
|
|
329
|
+
} catch (cause) {
|
|
330
|
+
if (errorCode(cause) === "ESRCH") return { kind: "exited" };
|
|
331
|
+
}
|
|
332
|
+
return { kind: "unreadable" };
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async function listProcesses(): Promise<ReadonlyArray<ProcessRow> | undefined> {
|
|
337
|
+
const uid = process.getuid?.();
|
|
338
|
+
if (uid === undefined) return undefined;
|
|
339
|
+
if (process.platform === "linux") return linuxProcesses(uid);
|
|
340
|
+
if (process.platform === "darwin") return darwinProcesses(uid);
|
|
341
|
+
return undefined;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function defaultTidyHost(): TidyHost {
|
|
345
|
+
return {
|
|
346
|
+
git: (args) => runTool("git", args),
|
|
347
|
+
docker: (args) => runTool("docker", args),
|
|
348
|
+
dockerEndpoint: () =>
|
|
349
|
+
runTool("docker", ["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"]),
|
|
350
|
+
run: runTool,
|
|
351
|
+
processes: listProcesses,
|
|
352
|
+
now: () => Date.now(),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** PIDs that adopt orphans: init (1) and each user `systemd` subreaper. */
|
|
357
|
+
export function orphanParents(rows: ReadonlyArray<ProcessRow>): ReadonlySet<number> {
|
|
358
|
+
const parents = new Set<number>([1]);
|
|
359
|
+
for (const row of rows) if (commandName(row.comm) === "systemd") parents.add(row.pid);
|
|
360
|
+
return parents;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ---------------------------------------------------------------- docker ----
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* True only for a local daemon socket: `unix:///<absolute path>`, or the
|
|
367
|
+
* Windows pipe `npipe:////./pipe/<name>` on the local server `.`. A compose
|
|
368
|
+
* label inside agent territory does not prove a local daemon, because
|
|
369
|
+
* `DOCKER_HOST` or a context can send a plain docker command to another host.
|
|
370
|
+
*/
|
|
371
|
+
export function isLocalDockerEndpoint(value: string): boolean {
|
|
372
|
+
for (const char of value) {
|
|
373
|
+
const code = char.codePointAt(0) ?? 0;
|
|
374
|
+
if (code < 0x20 || code === 0x7f || char === "\\") return false;
|
|
375
|
+
}
|
|
376
|
+
return /^unix:\/\/\/.+$/.test(value) || /^npipe:\/\/\/\/\.\/pipe\/[^/]+$/.test(value);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** How tidy may reach Docker in one run. Only `local` permits a Docker call. */
|
|
380
|
+
export type DockerAccess =
|
|
381
|
+
| { readonly kind: "local"; readonly endpoint: string }
|
|
382
|
+
| { readonly kind: "missing"; readonly reason: string }
|
|
383
|
+
| { readonly kind: "not-local"; readonly endpoint: string };
|
|
384
|
+
|
|
385
|
+
/** Resolve the effective endpoint once per run; the plan carries it to the apply. */
|
|
386
|
+
export async function resolveDockerAccess(host: TidyHost): Promise<DockerAccess> {
|
|
387
|
+
const result = await host.dockerEndpoint();
|
|
388
|
+
if (result.missing) return { kind: "missing", reason: firstLine(result) };
|
|
389
|
+
const endpoint = result.code === 0 ? result.stdout.trim() : "";
|
|
390
|
+
return isLocalDockerEndpoint(endpoint)
|
|
391
|
+
? { kind: "local", endpoint }
|
|
392
|
+
: { kind: "not-local", endpoint };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function notLocalMessage(endpoint: string): string {
|
|
396
|
+
return `docker endpoint ${endpoint === "" ? "<empty>" : endpoint} is not local`;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export type DockerRunner = (args: ReadonlyArray<string>) => Promise<TidyProcess>;
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* The only path from tidy to a Docker call. It checks the endpoint again and
|
|
403
|
+
* puts `--host <endpoint>` first; `undefined` unless the endpoint is local.
|
|
404
|
+
*/
|
|
405
|
+
export function localDocker(host: TidyHost, access: DockerAccess): DockerRunner | undefined {
|
|
406
|
+
if (access.kind !== "local" || !isLocalDockerEndpoint(access.endpoint)) return undefined;
|
|
407
|
+
const endpoint = access.endpoint;
|
|
408
|
+
return (args) => host.docker(["--host", endpoint, ...args]);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ------------------------------------------------------------ plan model ----
|
|
412
|
+
|
|
413
|
+
export type TidyAction =
|
|
414
|
+
| {
|
|
415
|
+
readonly kind: "remove-worktree";
|
|
416
|
+
readonly path: string;
|
|
417
|
+
readonly repo: string;
|
|
418
|
+
readonly containerIds: ReadonlyArray<string>;
|
|
419
|
+
readonly projects: ReadonlyArray<string>;
|
|
420
|
+
readonly reason: string;
|
|
421
|
+
}
|
|
422
|
+
| {
|
|
423
|
+
readonly kind: "stop-containers";
|
|
424
|
+
readonly project: string;
|
|
425
|
+
readonly workingDir: string;
|
|
426
|
+
readonly ids: ReadonlyArray<string>;
|
|
427
|
+
readonly reason: string;
|
|
428
|
+
}
|
|
429
|
+
| {
|
|
430
|
+
readonly kind: "remove-containers";
|
|
431
|
+
readonly project: string;
|
|
432
|
+
readonly workingDir: string;
|
|
433
|
+
readonly ids: ReadonlyArray<string>;
|
|
434
|
+
readonly reason: string;
|
|
435
|
+
}
|
|
436
|
+
| {
|
|
437
|
+
readonly kind: "stop-process";
|
|
438
|
+
readonly pid: number;
|
|
439
|
+
readonly args: string;
|
|
440
|
+
readonly cwd: string;
|
|
441
|
+
readonly reason: string;
|
|
442
|
+
}
|
|
443
|
+
| { readonly kind: "remove-scratch"; readonly path: string; readonly reason: string };
|
|
444
|
+
|
|
445
|
+
export interface TidyKept {
|
|
446
|
+
readonly subject: string;
|
|
447
|
+
readonly reason: string;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export interface TidyPlan {
|
|
451
|
+
readonly actions: ReadonlyArray<TidyAction>;
|
|
452
|
+
readonly kept: ReadonlyArray<TidyKept>;
|
|
453
|
+
readonly notes: ReadonlyArray<string>;
|
|
454
|
+
/** The Docker access that listed the containers; `applyTidy` uses the same endpoint. */
|
|
455
|
+
readonly docker: DockerAccess;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export interface TidyInputs {
|
|
459
|
+
readonly home: string;
|
|
460
|
+
readonly worktreeRoot: string;
|
|
461
|
+
readonly scratchRoot: string;
|
|
462
|
+
readonly repo?: string;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export function shorten(text: string, max: number): string {
|
|
466
|
+
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function plural(count: number, noun: string): string {
|
|
470
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** The word that a plan line starts with: `remove` or `stop`. */
|
|
474
|
+
export function actionVerb(action: TidyAction): "remove" | "stop" {
|
|
475
|
+
return action.kind === "stop-containers" || action.kind === "stop-process" ? "stop" : "remove";
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export function actionSubject(action: TidyAction): string {
|
|
479
|
+
switch (action.kind) {
|
|
480
|
+
case "remove-worktree":
|
|
481
|
+
return action.containerIds.length === 0
|
|
482
|
+
? `worktree ${action.path}`
|
|
483
|
+
: `worktree ${action.path} with ${plural(action.containerIds.length, "container")}`;
|
|
484
|
+
case "stop-containers":
|
|
485
|
+
case "remove-containers":
|
|
486
|
+
return `${plural(action.ids.length, "container")} of ${action.project || "(no project)"} in ${action.workingDir}`;
|
|
487
|
+
case "stop-process":
|
|
488
|
+
return `process ${action.pid} (${shorten(action.args, 80)}) in ${action.cwd}`;
|
|
489
|
+
case "remove-scratch":
|
|
490
|
+
return `scratch ${action.path}`;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// ------------------------------------------------------------ roots guard ----
|
|
495
|
+
|
|
496
|
+
interface AgentRoots {
|
|
497
|
+
readonly worktreeRoot: string | undefined;
|
|
498
|
+
readonly scratchRoot: string | undefined;
|
|
499
|
+
readonly home: string;
|
|
500
|
+
readonly notes: ReadonlyArray<string>;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Normalize both roots and drop a root that equals or contains the home directory. */
|
|
504
|
+
export function agentRoots(inputs: TidyInputs): AgentRoots {
|
|
505
|
+
const home = normalizePath(inputs.home);
|
|
506
|
+
const notes: Array<string> = [];
|
|
507
|
+
const guard = (root: string): string | undefined => {
|
|
508
|
+
const path = normalizePath(root);
|
|
509
|
+
if (!isSameOrInside(path, home)) return path;
|
|
510
|
+
notes.push(`refusing root ${path}: it contains the home directory`);
|
|
511
|
+
return undefined;
|
|
512
|
+
};
|
|
513
|
+
return {
|
|
514
|
+
worktreeRoot: guard(inputs.worktreeRoot),
|
|
515
|
+
scratchRoot: guard(inputs.scratchRoot),
|
|
516
|
+
home,
|
|
517
|
+
notes,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// -------------------------------------------------------------- worktrees ----
|
|
522
|
+
|
|
523
|
+
export interface WorktreeCandidate {
|
|
524
|
+
readonly path: string;
|
|
525
|
+
/** The admin directory that the `.git` file names; `undefined` when it names none. */
|
|
526
|
+
readonly admin: string | undefined;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export interface WorktreeListing {
|
|
530
|
+
readonly candidates: ReadonlyArray<WorktreeCandidate>;
|
|
531
|
+
readonly kept: ReadonlyArray<TidyKept>;
|
|
532
|
+
readonly notes: ReadonlyArray<string>;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export function lstatOrUndefined(path: string): Stats | undefined {
|
|
536
|
+
try {
|
|
537
|
+
return lstatSync(path);
|
|
538
|
+
} catch {
|
|
539
|
+
return undefined;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
export function sortedEntries(directory: string): Array<string> {
|
|
544
|
+
try {
|
|
545
|
+
return readdirSync(directory).sort();
|
|
546
|
+
} catch {
|
|
547
|
+
return [];
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** The admin directory from a `gitdir: <path>` file at `<worktree>/.git`. */
|
|
552
|
+
function adminDirectory(worktree: string): string | undefined {
|
|
553
|
+
try {
|
|
554
|
+
const text = readFileSync(join(worktree, ".git"), "utf8");
|
|
555
|
+
if (!text.startsWith("gitdir: ")) return undefined;
|
|
556
|
+
return normalizePath(resolve(worktree, text.slice("gitdir: ".length).trim()));
|
|
557
|
+
} catch {
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Scan `<root>/<a>` and `<root>/<a>/<b>` with `lstat`. Never follow a symbolic
|
|
564
|
+
* link, and never descend into a directory that has a `.git` entry.
|
|
565
|
+
*/
|
|
566
|
+
function scanWorktreeRoot(root: string): {
|
|
567
|
+
readonly candidates: Array<WorktreeCandidate>;
|
|
568
|
+
readonly kept: Array<TidyKept>;
|
|
569
|
+
} {
|
|
570
|
+
const candidates: Array<WorktreeCandidate> = [];
|
|
571
|
+
const kept: Array<TidyKept> = [];
|
|
572
|
+
const visit = (directory: string, depth: number): void => {
|
|
573
|
+
for (const entry of sortedEntries(directory)) {
|
|
574
|
+
const path = join(directory, entry);
|
|
575
|
+
if (lstatOrUndefined(path)?.isDirectory() !== true) continue;
|
|
576
|
+
const marker = lstatOrUndefined(join(path, ".git"));
|
|
577
|
+
if (marker === undefined) {
|
|
578
|
+
if (depth === 0) visit(path, 1);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const admin = marker.isFile() ? adminDirectory(path) : undefined;
|
|
582
|
+
if (admin === undefined)
|
|
583
|
+
kept.push({ subject: `directory ${path}`, reason: "not a linked worktree" });
|
|
584
|
+
else candidates.push({ path, admin });
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
visit(root, 0);
|
|
588
|
+
return { candidates, kept };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** One entry of `git worktree list --porcelain`. */
|
|
592
|
+
export interface WorktreeEntry {
|
|
593
|
+
readonly path: string;
|
|
594
|
+
readonly prunable: boolean;
|
|
595
|
+
/** The checked-out branch ref, `refs/heads/<name>`; `undefined` when detached or bare. */
|
|
596
|
+
readonly branch: string | undefined;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function parseWorktreeList(stdout: string): Array<WorktreeEntry> {
|
|
600
|
+
return stdout
|
|
601
|
+
.split(/\r?\n\r?\n/)
|
|
602
|
+
.map((block) => block.split(/\r?\n/).filter((line) => line !== ""))
|
|
603
|
+
.filter((lines) => lines.length > 0 && lines[0]!.startsWith("worktree "))
|
|
604
|
+
.map((lines) => ({
|
|
605
|
+
path: normalizePath(lines[0]!.slice("worktree ".length)),
|
|
606
|
+
prunable: lines.some((line) => line === "prunable" || line.startsWith("prunable ")),
|
|
607
|
+
branch: lines.find((line) => line.startsWith("branch "))?.slice("branch ".length),
|
|
608
|
+
}));
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Every worktree entry of a repository, the main worktree first. */
|
|
612
|
+
export async function repositoryWorktrees(
|
|
613
|
+
repo: string,
|
|
614
|
+
host: TidyHost,
|
|
615
|
+
): Promise<ReadonlyArray<WorktreeEntry> | undefined> {
|
|
616
|
+
const result = await host.git(["-C", repo, "worktree", "list", "--porcelain"]);
|
|
617
|
+
return result.code === 0 ? parseWorktreeList(result.stdout) : undefined;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Worktree candidates (rule 4): a scan of the worktree root by default, or the
|
|
622
|
+
* linked worktrees of `inputs.repo`, at any location.
|
|
623
|
+
*/
|
|
624
|
+
export async function listWorktreeCandidates(
|
|
625
|
+
inputs: TidyInputs,
|
|
626
|
+
host: TidyHost,
|
|
627
|
+
): Promise<WorktreeListing> {
|
|
628
|
+
if (inputs.repo !== undefined) {
|
|
629
|
+
const entries = await repositoryWorktrees(inputs.repo, host);
|
|
630
|
+
if (entries === undefined) {
|
|
631
|
+
return { candidates: [], kept: [], notes: [`git worktree list failed in ${inputs.repo}`] };
|
|
632
|
+
}
|
|
633
|
+
const candidates = entries
|
|
634
|
+
.slice(1)
|
|
635
|
+
.filter((entry) => !entry.prunable)
|
|
636
|
+
.map((entry) => ({ path: entry.path, admin: adminDirectory(entry.path) }));
|
|
637
|
+
return { candidates, kept: [], notes: [] };
|
|
638
|
+
}
|
|
639
|
+
const root = agentRoots(inputs).worktreeRoot;
|
|
640
|
+
if (root === undefined) return { candidates: [], kept: [], notes: [] };
|
|
641
|
+
if (lstatOrUndefined(root)?.isDirectory() !== true) {
|
|
642
|
+
return { candidates: [], kept: [], notes: [`worktree root ${root} does not exist`] };
|
|
643
|
+
}
|
|
644
|
+
return { ...scanWorktreeRoot(root), notes: [] };
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** The default branch ref: `origin/HEAD`, else `origin/main`, else `origin/master`. */
|
|
648
|
+
export async function defaultBranchRef(
|
|
649
|
+
directory: string,
|
|
650
|
+
host: TidyHost,
|
|
651
|
+
): Promise<string | undefined> {
|
|
652
|
+
const symbolic = await host.git([
|
|
653
|
+
"-C",
|
|
654
|
+
directory,
|
|
655
|
+
"symbolic-ref",
|
|
656
|
+
"--quiet",
|
|
657
|
+
"refs/remotes/origin/HEAD",
|
|
658
|
+
]);
|
|
659
|
+
const refs = ["refs/remotes/origin/main", "refs/remotes/origin/master"];
|
|
660
|
+
if (symbolic.code === 0 && symbolic.stdout.trim() !== "") refs.unshift(symbolic.stdout.trim());
|
|
661
|
+
for (const ref of refs) {
|
|
662
|
+
const verify = await host.git([
|
|
663
|
+
"-C",
|
|
664
|
+
directory,
|
|
665
|
+
"rev-parse",
|
|
666
|
+
"--verify",
|
|
667
|
+
"--quiet",
|
|
668
|
+
`${ref}^{commit}`,
|
|
669
|
+
]);
|
|
670
|
+
if (verify.code === 0) return ref;
|
|
671
|
+
}
|
|
672
|
+
return undefined;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
export function shortRef(ref: string): string {
|
|
676
|
+
return ref.replace(/^refs\/(remotes|heads)\//, "");
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
interface GitLocation {
|
|
680
|
+
/** The common git directory, normalized. */
|
|
681
|
+
readonly common: string;
|
|
682
|
+
/** The parent of `common`, or `common` itself for a bare repository. */
|
|
683
|
+
readonly repo: string;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
async function gitLocation(directory: string, host: TidyHost): Promise<GitLocation | undefined> {
|
|
687
|
+
const result = await host.git([
|
|
688
|
+
"-C",
|
|
689
|
+
directory,
|
|
690
|
+
"rev-parse",
|
|
691
|
+
"--path-format=absolute",
|
|
692
|
+
"--git-common-dir",
|
|
693
|
+
]);
|
|
694
|
+
if (result.code !== 0 || result.stdout.trim() === "") return undefined;
|
|
695
|
+
const common = normalizePath(result.stdout.trim());
|
|
696
|
+
return { common, repo: basename(common) === ".git" ? dirname(common) : common };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** The main repository of any checkout or worktree of it; `undefined` outside git. */
|
|
700
|
+
export async function mainRepository(
|
|
701
|
+
directory: string,
|
|
702
|
+
host: TidyHost,
|
|
703
|
+
): Promise<string | undefined> {
|
|
704
|
+
return (await gitLocation(directory, host))?.repo;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* The main repository of a linked worktree. `undefined` unless the admin
|
|
709
|
+
* directory lies in `<common>/worktrees`, so a submodule never matches.
|
|
710
|
+
*/
|
|
711
|
+
export async function worktreeRepository(
|
|
712
|
+
worktree: string,
|
|
713
|
+
admin: string,
|
|
714
|
+
host: TidyHost,
|
|
715
|
+
): Promise<string | undefined> {
|
|
716
|
+
const location = await gitLocation(worktree, host);
|
|
717
|
+
if (location === undefined) return undefined;
|
|
718
|
+
const expected = normalizePath(join(location.common, "worktrees"));
|
|
719
|
+
return normalizePath(dirname(admin)) === expected ? location.repo : undefined;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* `lstat` with three outcomes: the stats; `undefined` when the path is absent
|
|
724
|
+
* (ENOENT or ENOTDIR); or a thrown `cannot check <path>: <code>` for any other
|
|
725
|
+
* error. An unknown state never counts as absent, so it never permits an action.
|
|
726
|
+
*/
|
|
727
|
+
function lstatIfPresent(path: string): Stats | undefined {
|
|
728
|
+
try {
|
|
729
|
+
return lstatSync(path);
|
|
730
|
+
} catch (cause) {
|
|
731
|
+
const code = errorCode(cause);
|
|
732
|
+
if (code === "ENOENT" || code === "ENOTDIR") return undefined;
|
|
733
|
+
throw new Error(`cannot check ${path}: ${code ?? errorMessage(cause)}`, { cause });
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Latest `lstat` mtime of the paths that exist; `undefined` when none exists. */
|
|
738
|
+
function latestMtime(paths: ReadonlyArray<string>): number | undefined {
|
|
739
|
+
let latest: number | undefined;
|
|
740
|
+
for (const path of paths) {
|
|
741
|
+
const stats = lstatIfPresent(path);
|
|
742
|
+
if (stats !== undefined && (latest === undefined || stats.mtimeMs > latest)) {
|
|
743
|
+
latest = stats.mtimeMs;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
return latest;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** Latest mtime of a scratch entry and its immediate children; it throws when unknown. */
|
|
750
|
+
function entryActivity(path: string): number | undefined {
|
|
751
|
+
const stats = lstatIfPresent(path);
|
|
752
|
+
if (stats === undefined) return undefined;
|
|
753
|
+
if (!stats.isDirectory()) return stats.mtimeMs;
|
|
754
|
+
let children: Array<string>;
|
|
755
|
+
try {
|
|
756
|
+
children = readdirSync(path);
|
|
757
|
+
} catch (cause) {
|
|
758
|
+
throw new Error(`cannot check ${path}: ${errorCode(cause) ?? errorMessage(cause)}`, {
|
|
759
|
+
cause,
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
return latestMtime([path, ...children.map((entry) => join(path, entry))]);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Paths that `git status --porcelain -z` lists, resolved against the worktree.
|
|
767
|
+
* Each entry is `XY <path>` and a NUL; a rename or copy entry has its source
|
|
768
|
+
* path as a second NUL-terminated field. Git does not quote names in this form.
|
|
769
|
+
*/
|
|
770
|
+
function changedPaths(worktree: string, stdout: string): Array<string> {
|
|
771
|
+
const fields = stdout.split("\0");
|
|
772
|
+
const paths: Array<string> = [];
|
|
773
|
+
for (let index = 0; index < fields.length; index += 1) {
|
|
774
|
+
const entry = fields[index]!;
|
|
775
|
+
if (entry.length < 4) continue;
|
|
776
|
+
paths.push(resolve(worktree, entry.slice(3)));
|
|
777
|
+
if (/[RC]/.test(entry.slice(0, 2))) index += 1;
|
|
778
|
+
}
|
|
779
|
+
return paths;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
interface InspectedWorktree {
|
|
783
|
+
readonly path: string;
|
|
784
|
+
readonly repo: string | undefined;
|
|
785
|
+
/** Latest activity for the stack rule: admin files plus the changed paths. */
|
|
786
|
+
readonly stackActivity: number | undefined;
|
|
787
|
+
readonly verdict: { readonly remove: boolean; readonly reason: string };
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
interface PlanContext {
|
|
791
|
+
readonly home: string;
|
|
792
|
+
readonly now: number;
|
|
793
|
+
readonly inUse: ReadonlyArray<string> | undefined;
|
|
794
|
+
readonly host: TidyHost;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function hours(ms: number): number {
|
|
798
|
+
return Math.max(0, Math.floor(ms / HOUR_MS));
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function days(ms: number): number {
|
|
802
|
+
return Math.max(0, Math.floor(ms / DAY_MS));
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** Why a running process blocks `path`, or `undefined` when nothing uses it. */
|
|
806
|
+
function inUseReason(path: string, inUse: ReadonlyArray<string> | undefined): string | undefined {
|
|
807
|
+
if (inUse === undefined) return PROCESS_LIST_UNAVAILABLE;
|
|
808
|
+
return inUse.some((cwd) => isSameOrInside(path, cwd)) ? IN_USE : undefined;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Candidate checks (rule 5); a path that tidy cannot check keeps the worktree. */
|
|
812
|
+
async function inspectWorktree(
|
|
813
|
+
candidate: WorktreeCandidate,
|
|
814
|
+
context: PlanContext,
|
|
815
|
+
): Promise<InspectedWorktree> {
|
|
816
|
+
try {
|
|
817
|
+
return await checkWorktree(candidate, context);
|
|
818
|
+
} catch (cause) {
|
|
819
|
+
return {
|
|
820
|
+
path: candidate.path,
|
|
821
|
+
repo: undefined,
|
|
822
|
+
stackActivity: undefined,
|
|
823
|
+
verdict: { remove: false, reason: errorMessage(cause) },
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** The checks in order; the first failed check keeps the worktree. */
|
|
829
|
+
async function checkWorktree(
|
|
830
|
+
candidate: WorktreeCandidate,
|
|
831
|
+
context: PlanContext,
|
|
832
|
+
): Promise<InspectedWorktree> {
|
|
833
|
+
const { path, admin } = candidate;
|
|
834
|
+
const { host, now } = context;
|
|
835
|
+
const keep = (reason: string, stackActivity?: number): InspectedWorktree => ({
|
|
836
|
+
path,
|
|
837
|
+
repo: undefined,
|
|
838
|
+
stackActivity,
|
|
839
|
+
verdict: { remove: false, reason },
|
|
840
|
+
});
|
|
841
|
+
if (isSameOrInside(path, context.home)) return keep("contains the home directory");
|
|
842
|
+
if (admin === undefined || lstatIfPresent(admin) === undefined) {
|
|
843
|
+
return keep("main repository is missing");
|
|
844
|
+
}
|
|
845
|
+
const adminFiles = [join(admin, "HEAD"), join(admin, "index"), join(admin, "logs", "HEAD")];
|
|
846
|
+
const activity = latestMtime(adminFiles) ?? lstatIfPresent(path)?.mtimeMs;
|
|
847
|
+
const status = await host.git(["-C", path, "--no-optional-locks", "status", "--porcelain", "-z"]);
|
|
848
|
+
const changed = status.code === 0 ? changedPaths(path, status.stdout) : [];
|
|
849
|
+
const latest = latestMtime([...adminFiles, ...changed]) ?? activity;
|
|
850
|
+
if (lstatIfPresent(join(admin, "locked")) !== undefined) return keep("locked", latest);
|
|
851
|
+
if (status.code !== 0) return keep(`git status failed: ${firstLine(status)}`, latest);
|
|
852
|
+
if (changed.length > 0) return keep("has changes", latest);
|
|
853
|
+
const ref = await defaultBranchRef(path, host);
|
|
854
|
+
if (ref === undefined) return keep("no remote default branch", latest);
|
|
855
|
+
const merged = await host.git(["-C", path, "merge-base", "--is-ancestor", "HEAD", ref]);
|
|
856
|
+
if (merged.code !== 0) return keep(`not merged into ${shortRef(ref)}`, latest);
|
|
857
|
+
const idle = activity === undefined ? 0 : now - activity;
|
|
858
|
+
if (idle < WORKTREE_IDLE_MS) return keep(`active ${hours(idle)} h ago`, latest);
|
|
859
|
+
const blocked = inUseReason(path, context.inUse);
|
|
860
|
+
if (blocked !== undefined) return keep(blocked, latest);
|
|
861
|
+
const repo = await worktreeRepository(path, admin, host);
|
|
862
|
+
if (repo === undefined) return keep("not a linked worktree", latest);
|
|
863
|
+
return {
|
|
864
|
+
path,
|
|
865
|
+
repo,
|
|
866
|
+
stackActivity: latest,
|
|
867
|
+
verdict: { remove: true, reason: `merged into ${shortRef(ref)}, idle ${hours(idle)} h` },
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// ------------------------------------------------------------- containers ----
|
|
872
|
+
|
|
873
|
+
interface ContainerRow {
|
|
874
|
+
readonly id: string;
|
|
875
|
+
readonly state: string;
|
|
876
|
+
readonly project: string;
|
|
877
|
+
readonly workingDir: string;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function parseContainerRows(stdout: string): Array<ContainerRow> {
|
|
881
|
+
const rows: Array<ContainerRow> = [];
|
|
882
|
+
for (const line of stdout.split("\n")) {
|
|
883
|
+
const [id = "", state = "", project = "", workingDir = ""] = line.trim().split("\t");
|
|
884
|
+
if (id === "" || workingDir.trim() === "") continue;
|
|
885
|
+
rows.push({ id, state, project, workingDir: normalizePath(workingDir.trim()) });
|
|
886
|
+
}
|
|
887
|
+
return rows;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/** The first-level scratch entry that holds `path`, or `undefined`. */
|
|
891
|
+
function scratchEntryOf(scratchRoot: string | undefined, path: string): string | undefined {
|
|
892
|
+
if (scratchRoot === undefined || !isSameOrInside(scratchRoot, path)) return undefined;
|
|
893
|
+
const [first] = relative(scratchRoot, path).split(/[\\/]/);
|
|
894
|
+
return first === undefined || first === "" ? undefined : join(scratchRoot, first);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// ------------------------------------------------------------------ plan ----
|
|
898
|
+
|
|
899
|
+
/** Build the sweep plan. Read-only: it runs only listing commands. */
|
|
900
|
+
export async function planTidy(inputs: TidyInputs, host: TidyHost): Promise<TidyPlan> {
|
|
901
|
+
const roots = agentRoots(inputs);
|
|
902
|
+
const notes: Array<string> = [...roots.notes];
|
|
903
|
+
const kept: Array<TidyKept> = [];
|
|
904
|
+
const now = host.now();
|
|
905
|
+
const rows = await host.processes();
|
|
906
|
+
if (rows === undefined) notes.push(PROCESS_LIST_UNAVAILABLE_NOTE);
|
|
907
|
+
const inUse =
|
|
908
|
+
rows === undefined
|
|
909
|
+
? undefined
|
|
910
|
+
: rows.flatMap((row) => (row.cwd === undefined ? [] : [normalizePath(row.cwd)]));
|
|
911
|
+
const context: PlanContext = { home: roots.home, now, inUse, host };
|
|
912
|
+
|
|
913
|
+
const listing = await listWorktreeCandidates(inputs, host);
|
|
914
|
+
kept.push(...listing.kept);
|
|
915
|
+
notes.push(...listing.notes);
|
|
916
|
+
const inspected = await runBounded(
|
|
917
|
+
listing.candidates.map((candidate) => () => inspectWorktree(candidate, context)),
|
|
918
|
+
3,
|
|
919
|
+
);
|
|
920
|
+
const removals = new Map<
|
|
921
|
+
string,
|
|
922
|
+
{ repo: string; reason: string; containerIds: Array<string>; projects: Array<string> }
|
|
923
|
+
>();
|
|
924
|
+
for (const worktree of inspected) {
|
|
925
|
+
if (worktree.verdict.remove && worktree.repo !== undefined) {
|
|
926
|
+
removals.set(worktree.path, {
|
|
927
|
+
repo: worktree.repo,
|
|
928
|
+
reason: worktree.verdict.reason,
|
|
929
|
+
containerIds: [],
|
|
930
|
+
projects: [],
|
|
931
|
+
});
|
|
932
|
+
} else {
|
|
933
|
+
kept.push({ subject: `worktree ${worktree.path}`, reason: worktree.verdict.reason });
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
const stopContainers: Array<TidyAction> = [];
|
|
938
|
+
const removeContainers: Array<TidyAction> = [];
|
|
939
|
+
const docker = await resolveDockerAccess(host);
|
|
940
|
+
const runDocker = localDocker(host, docker);
|
|
941
|
+
// A worktree with an unknown container list stays: removing it could leave
|
|
942
|
+
// a running stack without its directory. A host without docker has no stack.
|
|
943
|
+
let containersUnknown: string | undefined;
|
|
944
|
+
if (docker.kind === "missing") {
|
|
945
|
+
notes.push(`docker unavailable: ${docker.reason}`);
|
|
946
|
+
} else if (runDocker === undefined) {
|
|
947
|
+
notes.push(`${notLocalMessage(docker.endpoint)}; skipped container rules`);
|
|
948
|
+
containersUnknown = "docker endpoint not local";
|
|
949
|
+
} else {
|
|
950
|
+
const listed = await runDocker(["ps", "-a", "--no-trunc", "--format", DOCKER_PS_FORMAT]);
|
|
951
|
+
if (listed.code !== 0) {
|
|
952
|
+
notes.push(`docker unavailable: ${firstLine(listed)}`);
|
|
953
|
+
containersUnknown = "container list unavailable";
|
|
954
|
+
}
|
|
955
|
+
const territory = [
|
|
956
|
+
roots.worktreeRoot,
|
|
957
|
+
roots.scratchRoot,
|
|
958
|
+
...(inputs.repo === undefined ? [] : listing.candidates.map((candidate) => candidate.path)),
|
|
959
|
+
].filter((path): path is string => path !== undefined);
|
|
960
|
+
const groups = new Map<string, Array<ContainerRow>>();
|
|
961
|
+
for (const row of listed.code === 0 ? parseContainerRows(listed.stdout) : []) {
|
|
962
|
+
const key = `${row.project}\0${row.workingDir}`;
|
|
963
|
+
groups.set(key, [...(groups.get(key) ?? []), row]);
|
|
964
|
+
}
|
|
965
|
+
for (const group of groups.values()) {
|
|
966
|
+
const { project, workingDir } = group[0]!;
|
|
967
|
+
const subject = `containers of ${project || "(no project)"} in ${workingDir}`;
|
|
968
|
+
const ids = group.map((row) => row.id);
|
|
969
|
+
const removal = [...removals].find(([path]) => isSameOrInside(path, workingDir))?.[1];
|
|
970
|
+
if (removal !== undefined) {
|
|
971
|
+
removal.containerIds.push(...ids);
|
|
972
|
+
if (project !== "" && !removal.projects.includes(project)) removal.projects.push(project);
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
if (!territory.some((root) => isSameOrInside(root, workingDir))) continue;
|
|
976
|
+
// Only a path that `lstat` reports absent is gone; an unknown state keeps the rows.
|
|
977
|
+
let present: boolean;
|
|
978
|
+
try {
|
|
979
|
+
present = lstatIfPresent(workingDir) !== undefined;
|
|
980
|
+
} catch (cause) {
|
|
981
|
+
notes.push(errorMessage(cause));
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
if (!present) {
|
|
985
|
+
removeContainers.push({
|
|
986
|
+
kind: "remove-containers",
|
|
987
|
+
project,
|
|
988
|
+
workingDir,
|
|
989
|
+
ids,
|
|
990
|
+
reason: "directory is gone",
|
|
991
|
+
});
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
const running = group.filter((row) => row.state === "running").map((row) => row.id);
|
|
995
|
+
if (running.length === 0) continue;
|
|
996
|
+
const worktree = inspected.find((entry) => isSameOrInside(entry.path, workingDir));
|
|
997
|
+
const owner = worktree?.path ?? scratchEntryOf(roots.scratchRoot, workingDir);
|
|
998
|
+
if (owner === undefined) {
|
|
999
|
+
kept.push({ subject, reason: "not in a linked worktree or a scratch entry" });
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
let activity: number | undefined;
|
|
1003
|
+
try {
|
|
1004
|
+
activity = worktree !== undefined ? worktree.stackActivity : entryActivity(owner);
|
|
1005
|
+
} catch (cause) {
|
|
1006
|
+
kept.push({ subject, reason: errorMessage(cause) });
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
if (activity === undefined) {
|
|
1010
|
+
kept.push({ subject, reason: "idle time unknown" });
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
const idle = now - activity;
|
|
1014
|
+
if (idle < STACK_IDLE_MS) {
|
|
1015
|
+
kept.push({ subject, reason: `active ${hours(idle)} h ago` });
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
const blocked = inUseReason(owner, inUse);
|
|
1019
|
+
if (blocked !== undefined) {
|
|
1020
|
+
kept.push({ subject, reason: blocked });
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
stopContainers.push({
|
|
1024
|
+
kind: "stop-containers",
|
|
1025
|
+
project,
|
|
1026
|
+
workingDir,
|
|
1027
|
+
ids: running,
|
|
1028
|
+
reason: `idle ${hours(idle)} h`,
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
if (containersUnknown !== undefined) {
|
|
1033
|
+
for (const path of removals.keys()) {
|
|
1034
|
+
kept.push({ subject: `worktree ${path}`, reason: containersUnknown });
|
|
1035
|
+
}
|
|
1036
|
+
removals.clear();
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
const stopProcesses: Array<TidyAction> = [];
|
|
1040
|
+
if (rows !== undefined) {
|
|
1041
|
+
const parents = orphanParents(rows);
|
|
1042
|
+
const processRoots = [roots.worktreeRoot, roots.scratchRoot].filter(
|
|
1043
|
+
(path): path is string => path !== undefined,
|
|
1044
|
+
);
|
|
1045
|
+
for (const row of rows) {
|
|
1046
|
+
if (!parents.has(row.ppid) || row.ageMs < STACK_IDLE_MS || row.cwd === undefined) continue;
|
|
1047
|
+
if (isProtectedProcess(row)) continue;
|
|
1048
|
+
const cwd = normalizePath(row.cwd);
|
|
1049
|
+
if (!processRoots.some((root) => isSameOrInside(root, cwd))) continue;
|
|
1050
|
+
stopProcesses.push({
|
|
1051
|
+
kind: "stop-process",
|
|
1052
|
+
pid: row.pid,
|
|
1053
|
+
args: row.args,
|
|
1054
|
+
cwd,
|
|
1055
|
+
reason: `orphaned for ${hours(row.ageMs)} h`,
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
const removeScratch: Array<TidyAction> = [];
|
|
1061
|
+
const scratch = roots.scratchRoot;
|
|
1062
|
+
if (scratch !== undefined && lstatOrUndefined(scratch)?.isDirectory() === true) {
|
|
1063
|
+
for (const entry of sortedEntries(scratch)) {
|
|
1064
|
+
const path = join(scratch, entry);
|
|
1065
|
+
const subject = `scratch ${path}`;
|
|
1066
|
+
let activity: number | undefined;
|
|
1067
|
+
try {
|
|
1068
|
+
if (lstatIfPresent(path)?.isSymbolicLink() === true) {
|
|
1069
|
+
kept.push({ subject, reason: "is a symbolic link" });
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
activity = entryActivity(path);
|
|
1073
|
+
} catch (cause) {
|
|
1074
|
+
kept.push({ subject, reason: errorMessage(cause) });
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
if (activity === undefined) continue;
|
|
1078
|
+
const idle = now - activity;
|
|
1079
|
+
if (idle < SCRATCH_IDLE_MS) {
|
|
1080
|
+
kept.push({ subject, reason: `active ${hours(idle)} h ago` });
|
|
1081
|
+
continue;
|
|
1082
|
+
}
|
|
1083
|
+
const blocked = inUseReason(path, inUse);
|
|
1084
|
+
if (blocked !== undefined) {
|
|
1085
|
+
kept.push({ subject, reason: blocked });
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
removeScratch.push({ kind: "remove-scratch", path, reason: `idle ${days(idle)} d` });
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
const removeWorktrees: Array<TidyAction> = [...removals].map(([path, removal]) => ({
|
|
1093
|
+
kind: "remove-worktree",
|
|
1094
|
+
path,
|
|
1095
|
+
...removal,
|
|
1096
|
+
}));
|
|
1097
|
+
return {
|
|
1098
|
+
actions: [
|
|
1099
|
+
...stopProcesses,
|
|
1100
|
+
...removeWorktrees,
|
|
1101
|
+
...stopContainers,
|
|
1102
|
+
...removeContainers,
|
|
1103
|
+
...removeScratch,
|
|
1104
|
+
],
|
|
1105
|
+
kept,
|
|
1106
|
+
notes,
|
|
1107
|
+
docker,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/**
|
|
1112
|
+
* True for the agent harness, its launcher, and the kit: by process name, and
|
|
1113
|
+
* by an argument path under `/.omp/` or `/tern/` (omp workers and plugins).
|
|
1114
|
+
*/
|
|
1115
|
+
export function isProtectedProcess(row: ProcessRow): boolean {
|
|
1116
|
+
const name = commandName(row.comm);
|
|
1117
|
+
if (
|
|
1118
|
+
PROTECTED_NAMES.some(
|
|
1119
|
+
(protectedName) => name === protectedName || name.startsWith(`${protectedName} `),
|
|
1120
|
+
)
|
|
1121
|
+
) {
|
|
1122
|
+
return true;
|
|
1123
|
+
}
|
|
1124
|
+
return row.args.includes("/.omp/") || row.args.includes("/tern/");
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// ----------------------------------------------------------------- apply ----
|
|
1128
|
+
|
|
1129
|
+
function appendLog(log: string, lines: ReadonlyArray<string>, now: number): void {
|
|
1130
|
+
if (lines.length === 0) return;
|
|
1131
|
+
try {
|
|
1132
|
+
if (statSync(log).size > LOG_ROTATE_BYTES) renameSync(log, `${log}.1`);
|
|
1133
|
+
} catch (cause) {
|
|
1134
|
+
if (errorCode(cause) !== "ENOENT") throw cause;
|
|
1135
|
+
}
|
|
1136
|
+
const stamp = new Date(now).toISOString();
|
|
1137
|
+
appendFileSync(log, lines.map((line) => `${stamp} ${line}\n`).join(""), { mode: 0o600 });
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
async function removeProjectNetworks(
|
|
1141
|
+
projects: ReadonlyArray<string>,
|
|
1142
|
+
runDocker: DockerRunner,
|
|
1143
|
+
): Promise<void> {
|
|
1144
|
+
for (const project of projects) {
|
|
1145
|
+
const list = await runDocker([
|
|
1146
|
+
"network",
|
|
1147
|
+
"ls",
|
|
1148
|
+
"-q",
|
|
1149
|
+
"--filter",
|
|
1150
|
+
`label=com.docker.compose.project=${project}`,
|
|
1151
|
+
]);
|
|
1152
|
+
const ids =
|
|
1153
|
+
list.code === 0
|
|
1154
|
+
? list.stdout
|
|
1155
|
+
.split("\n")
|
|
1156
|
+
.map((id) => id.trim())
|
|
1157
|
+
.filter((id) => id !== "")
|
|
1158
|
+
: [];
|
|
1159
|
+
// A network that another container still uses stays; that failure is not a tidy failure.
|
|
1160
|
+
if (ids.length > 0) await runDocker(["network", "rm", ...ids]);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* Perform a plan under the tidy lock. Order: stop processes, remove worktrees
|
|
1166
|
+
* (their containers first), prune each touched repository, stop containers,
|
|
1167
|
+
* remove containers, remove scratch entries. Never `git worktree remove --force`.
|
|
1168
|
+
* Every Docker call uses the endpoint that the plan verified.
|
|
1169
|
+
*/
|
|
1170
|
+
export async function applyTidy(
|
|
1171
|
+
plan: TidyPlan,
|
|
1172
|
+
inputs: TidyInputs,
|
|
1173
|
+
host: TidyHost,
|
|
1174
|
+
): Promise<{
|
|
1175
|
+
readonly locked: boolean;
|
|
1176
|
+
readonly failures: number;
|
|
1177
|
+
readonly lines: ReadonlyArray<string>;
|
|
1178
|
+
}> {
|
|
1179
|
+
ensureDirectory(kitCacheDir(inputs.home));
|
|
1180
|
+
const lockPath = tidyLockPath(inputs.home);
|
|
1181
|
+
const lock = acquireTidyLock(lockPath, host.now());
|
|
1182
|
+
if (lock === undefined) {
|
|
1183
|
+
return { locked: true, failures: 0, lines: [`another docks-kit tidy run holds ${lockPath}`] };
|
|
1184
|
+
}
|
|
1185
|
+
try {
|
|
1186
|
+
const lines: Array<string> = [];
|
|
1187
|
+
let failures = 0;
|
|
1188
|
+
const done = (outcome: "removed" | "stopped", subject: string): void => {
|
|
1189
|
+
lines.push(`${outcome} ${subject}`);
|
|
1190
|
+
};
|
|
1191
|
+
const failed = (subject: string, detail: string): void => {
|
|
1192
|
+
failures += 1;
|
|
1193
|
+
lines.push(`failed ${subject}: ${detail}`);
|
|
1194
|
+
};
|
|
1195
|
+
const byKind = <K extends TidyAction["kind"]>(kind: K) =>
|
|
1196
|
+
plan.actions.filter(
|
|
1197
|
+
(action): action is Extract<TidyAction, { kind: K }> => action.kind === kind,
|
|
1198
|
+
);
|
|
1199
|
+
|
|
1200
|
+
for (const action of byKind("stop-process")) {
|
|
1201
|
+
const subject = actionSubject(action);
|
|
1202
|
+
try {
|
|
1203
|
+
process.kill(action.pid, "SIGTERM");
|
|
1204
|
+
done("stopped", subject);
|
|
1205
|
+
} catch (cause) {
|
|
1206
|
+
if (errorCode(cause) === "ESRCH") done("stopped", subject);
|
|
1207
|
+
else failed(subject, errorMessage(cause));
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
// A container action without a verified local endpoint fails and changes nothing.
|
|
1211
|
+
const runDocker = localDocker(host, plan.docker);
|
|
1212
|
+
const noDocker =
|
|
1213
|
+
plan.docker.kind === "missing" ? "docker unavailable" : notLocalMessage(plan.docker.endpoint);
|
|
1214
|
+
|
|
1215
|
+
const touched = new Set<string>();
|
|
1216
|
+
for (const action of byKind("remove-worktree")) {
|
|
1217
|
+
const subject = actionSubject(action);
|
|
1218
|
+
if (action.containerIds.length > 0) {
|
|
1219
|
+
if (runDocker === undefined) {
|
|
1220
|
+
failed(subject, noDocker);
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const removed = await runDocker(["rm", "--force", "--volumes", ...action.containerIds]);
|
|
1224
|
+
if (removed.code !== 0) {
|
|
1225
|
+
failed(subject, `docker rm: ${firstLine(removed)}`);
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
await removeProjectNetworks(action.projects, runDocker);
|
|
1229
|
+
}
|
|
1230
|
+
touched.add(action.repo);
|
|
1231
|
+
const result = await host.git(["-C", action.repo, "worktree", "remove", "--", action.path]);
|
|
1232
|
+
if (result.code === 0) done("removed", subject);
|
|
1233
|
+
else failed(subject, firstLine(result));
|
|
1234
|
+
}
|
|
1235
|
+
for (const repo of touched) {
|
|
1236
|
+
const result = await host.git(["-C", repo, "worktree", "prune"]);
|
|
1237
|
+
if (result.code !== 0) failed(`worktree prune in ${repo}`, firstLine(result));
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
for (const action of byKind("stop-containers")) {
|
|
1241
|
+
if (runDocker === undefined) {
|
|
1242
|
+
failed(actionSubject(action), noDocker);
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
const result = await runDocker(["stop", ...action.ids]);
|
|
1246
|
+
if (result.code === 0) done("stopped", actionSubject(action));
|
|
1247
|
+
else failed(actionSubject(action), firstLine(result));
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
for (const action of byKind("remove-containers")) {
|
|
1251
|
+
if (runDocker === undefined) {
|
|
1252
|
+
failed(actionSubject(action), noDocker);
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const result = await runDocker(["rm", "--force", "--volumes", ...action.ids]);
|
|
1256
|
+
if (result.code !== 0) {
|
|
1257
|
+
failed(actionSubject(action), firstLine(result));
|
|
1258
|
+
continue;
|
|
1259
|
+
}
|
|
1260
|
+
await removeProjectNetworks(action.project === "" ? [] : [action.project], runDocker);
|
|
1261
|
+
done("removed", actionSubject(action));
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
const scratch = agentRoots(inputs).scratchRoot;
|
|
1265
|
+
for (const action of byKind("remove-scratch")) {
|
|
1266
|
+
const subject = actionSubject(action);
|
|
1267
|
+
if (scratch === undefined) {
|
|
1268
|
+
failed(subject, "the scratch root is refused");
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
let activity: number | undefined;
|
|
1272
|
+
try {
|
|
1273
|
+
activity = entryActivity(action.path);
|
|
1274
|
+
} catch (cause) {
|
|
1275
|
+
lines.push(`kept ${subject}: ${errorMessage(cause)}`);
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1278
|
+
if (activity !== undefined && host.now() - activity < SCRATCH_IDLE_MS) {
|
|
1279
|
+
lines.push(`kept ${subject}: active ${hours(host.now() - activity)} h ago`);
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
const outcome = removeTemporaryPath(action.path, [scratch], inputs.home);
|
|
1283
|
+
if (outcome.kind === "removed") done("removed", subject);
|
|
1284
|
+
else failed(subject, outcome.reason);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
try {
|
|
1288
|
+
appendLog(tidyLogPath(inputs.home), lines, host.now());
|
|
1289
|
+
} catch (cause) {
|
|
1290
|
+
failed(`log ${tidyLogPath(inputs.home)}`, errorMessage(cause));
|
|
1291
|
+
}
|
|
1292
|
+
return { locked: false, failures, lines };
|
|
1293
|
+
} finally {
|
|
1294
|
+
releaseTidyLock(lock);
|
|
1295
|
+
}
|
|
1296
|
+
}
|