docks-kit 0.20.10 → 0.21.0
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 +8 -2
- package/README.md +15 -8
- package/cli/docs/command-guards.md +20 -5
- package/cli/docs/flags.md +11 -0
- package/cli/src/argv.ts +4 -0
- package/cli/src/commands/omp.ts +2 -1
- 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/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 +138 -0
- package/cli/src/engine-native/tidyReport.ts +509 -0
- package/cli/src/generated/sotPayload.ts +13 -5
- package/cli/src/main.ts +6 -0
- package/cli/tsconfig.json +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `docks-kit tidy --apply` lock. Only `node:` imports, so that a test child
|
|
3
|
+
* process can load this module alone.
|
|
4
|
+
*
|
|
5
|
+
* - The lock holds `<pid> <ISO time> <token>`, written with `wx`.
|
|
6
|
+
* - A lock is stale when its mtime is older than 1 h or its PID is dead.
|
|
7
|
+
* - Stale takeover runs only under the takeover mutex `<lock>.takeover`, and
|
|
8
|
+
* the holder checks staleness again before it removes the lock. Thus two
|
|
9
|
+
* runs never both remove a stale lock and both create a new one.
|
|
10
|
+
* - A run removes the lock and the mutex only while they still hold its token.
|
|
11
|
+
*/
|
|
12
|
+
import { randomBytes } from "node:crypto";
|
|
13
|
+
import {
|
|
14
|
+
closeSync,
|
|
15
|
+
lstatSync,
|
|
16
|
+
openSync,
|
|
17
|
+
readFileSync,
|
|
18
|
+
unlinkSync,
|
|
19
|
+
writeSync,
|
|
20
|
+
type Stats,
|
|
21
|
+
} from "node:fs";
|
|
22
|
+
|
|
23
|
+
export const LOCK_STALE_MS = 3_600_000;
|
|
24
|
+
/** A takeover mutex lives for microseconds; one older than this belongs to a dead run. */
|
|
25
|
+
export const TAKEOVER_STALE_MS = 60_000;
|
|
26
|
+
|
|
27
|
+
export interface TidyLock {
|
|
28
|
+
readonly path: string;
|
|
29
|
+
readonly token: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function errorCode(cause: unknown): string | undefined {
|
|
33
|
+
return cause instanceof Error && "code" in cause && typeof cause.code === "string"
|
|
34
|
+
? cause.code
|
|
35
|
+
: undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Create `path` with `wx` and write `text`; false when the path exists. */
|
|
39
|
+
function createExclusive(path: string, text: string): boolean {
|
|
40
|
+
let fd: number;
|
|
41
|
+
try {
|
|
42
|
+
fd = openSync(path, "wx", 0o600);
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
if (errorCode(cause) === "EEXIST") return false;
|
|
45
|
+
throw cause;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
writeSync(fd, text);
|
|
49
|
+
} finally {
|
|
50
|
+
closeSync(fd);
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `lstat`, `undefined` when absent; any other error throws. */
|
|
56
|
+
function lstatIfPresent(path: string): Stats | undefined {
|
|
57
|
+
try {
|
|
58
|
+
return lstatSync(path);
|
|
59
|
+
} catch (cause) {
|
|
60
|
+
const code = errorCode(cause);
|
|
61
|
+
if (code === "ENOENT" || code === "ENOTDIR") return undefined;
|
|
62
|
+
throw cause;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readText(path: string): string | undefined {
|
|
67
|
+
try {
|
|
68
|
+
return readFileSync(path, "utf8");
|
|
69
|
+
} catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function unlinkIfPresent(path: string): void {
|
|
75
|
+
try {
|
|
76
|
+
unlinkSync(path);
|
|
77
|
+
} catch (cause) {
|
|
78
|
+
if (errorCode(cause) !== "ENOENT") throw cause;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Remove `path` only while its third field is still `token`. */
|
|
83
|
+
function releaseOwned(path: string, token: string): void {
|
|
84
|
+
if (readText(path)?.trim().split(/\s+/)[2] !== token) return;
|
|
85
|
+
try {
|
|
86
|
+
unlinkSync(path);
|
|
87
|
+
} catch {
|
|
88
|
+
// The path is already gone.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** True when the lock is absent, older than 1 h, or names a dead PID. */
|
|
93
|
+
function lockIsStale(path: string, now: number): boolean {
|
|
94
|
+
const stats = lstatIfPresent(path);
|
|
95
|
+
if (stats === undefined) return true;
|
|
96
|
+
if (now - stats.mtimeMs > LOCK_STALE_MS) return true;
|
|
97
|
+
const pid = Number.parseInt(readText(path)?.trim().split(/\s+/)[0] ?? "", 10);
|
|
98
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
99
|
+
try {
|
|
100
|
+
process.kill(pid, 0);
|
|
101
|
+
return false;
|
|
102
|
+
} catch (cause) {
|
|
103
|
+
return errorCode(cause) === "ESRCH";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Take the takeover mutex; remove a mutex older than 60 s once, then try once more. */
|
|
108
|
+
function acquireMutex(mutex: string, text: string, now: number): boolean {
|
|
109
|
+
if (createExclusive(mutex, text)) return true;
|
|
110
|
+
const seen = readText(mutex);
|
|
111
|
+
const stats = lstatIfPresent(mutex);
|
|
112
|
+
if (stats !== undefined && now - stats.mtimeMs <= TAKEOVER_STALE_MS) return false;
|
|
113
|
+
// Remove the stale mutex only while it still holds the text that this run saw.
|
|
114
|
+
if (stats !== undefined && readText(mutex) === seen) unlinkIfPresent(mutex);
|
|
115
|
+
return createExclusive(mutex, text);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Take the lock, or `undefined` when another run holds it. */
|
|
119
|
+
export function acquireTidyLock(path: string, now: number): TidyLock | undefined {
|
|
120
|
+
const token = randomBytes(16).toString("hex");
|
|
121
|
+
const text = `${process.pid} ${new Date(now).toISOString()} ${token}\n`;
|
|
122
|
+
if (createExclusive(path, text)) return { path, token };
|
|
123
|
+
if (!lockIsStale(path, now)) return undefined;
|
|
124
|
+
const mutex = `${path}.takeover`;
|
|
125
|
+
if (!acquireMutex(mutex, text, now)) return undefined;
|
|
126
|
+
try {
|
|
127
|
+
// Another run may have taken the lock over between the first check and the mutex.
|
|
128
|
+
if (!lockIsStale(path, now)) return undefined;
|
|
129
|
+
unlinkIfPresent(path);
|
|
130
|
+
return createExclusive(path, text) ? { path, token } : undefined;
|
|
131
|
+
} finally {
|
|
132
|
+
releaseOwned(mutex, token);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function releaseTidyLock(lock: TidyLock): void {
|
|
137
|
+
releaseOwned(lock.path, lock.token);
|
|
138
|
+
}
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only report of disk and memory use that `docks-kit tidy --apply` does
|
|
3
|
+
* not remove. The report runs only listing and measuring commands. Each
|
|
4
|
+
* section runs on its own; a failure becomes one `unavailable: <message>` line.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
import { isSameOrInside } from "./scratch";
|
|
10
|
+
import { runBounded } from "./syncConcurrency";
|
|
11
|
+
import {
|
|
12
|
+
agentRoots,
|
|
13
|
+
commandName,
|
|
14
|
+
DAY_MS,
|
|
15
|
+
defaultBranchRef,
|
|
16
|
+
errorMessage,
|
|
17
|
+
firstLine,
|
|
18
|
+
HOUR_MS,
|
|
19
|
+
listWorktreeCandidates,
|
|
20
|
+
isProtectedProcess,
|
|
21
|
+
lstatOrUndefined,
|
|
22
|
+
localDocker,
|
|
23
|
+
mainRepository,
|
|
24
|
+
normalizePath,
|
|
25
|
+
notLocalMessage,
|
|
26
|
+
orphanParents,
|
|
27
|
+
PROCESS_LIST_UNAVAILABLE,
|
|
28
|
+
repositoryWorktrees,
|
|
29
|
+
shorten,
|
|
30
|
+
shortRef,
|
|
31
|
+
sortedEntries,
|
|
32
|
+
worktreeRepository,
|
|
33
|
+
type DockerAccess,
|
|
34
|
+
type ProcessRow,
|
|
35
|
+
type TidyHost,
|
|
36
|
+
type TidyInputs,
|
|
37
|
+
} from "./tidy";
|
|
38
|
+
|
|
39
|
+
export interface TidyReportSection {
|
|
40
|
+
readonly title: string;
|
|
41
|
+
readonly lines: ReadonlyArray<string>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const REPORT_PROCESS_AGE_MS = 12 * HOUR_MS;
|
|
45
|
+
const RECENT_MS = 30 * DAY_MS;
|
|
46
|
+
const TEMP_ENTRY_COUNT = 5;
|
|
47
|
+
const TEMP_ROOTS = ["/tmp", "/var/tmp"] as const;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Development tools, servers, and tunnels. The report tests it against the
|
|
51
|
+
* file name of each argument, so a directory such as `/opt/google/chrome/`
|
|
52
|
+
* does not match. The lookahead rejects a longer name, so `ssh-agent` and
|
|
53
|
+
* `chrome_crashpad_handler` do not match.
|
|
54
|
+
*/
|
|
55
|
+
const DEV_PROCESS =
|
|
56
|
+
/\b(node|bun|deno|npm|pnpm|yarn|npx|bunx|python[0-9.]*|php|ruby|java|cargo|vite|next|webpack|esbuild|tsc|vitest|jest|playwright|chrome|chromium|mysqld|postgres|redis-server|mongod|ssh|kubectl|cloudflared|ngrok|tail|watch)(?![-\w])/;
|
|
57
|
+
|
|
58
|
+
const DOCKER_HINTS: Readonly<Record<string, string>> = {
|
|
59
|
+
"Build Cache": "docker builder prune --filter until=168h",
|
|
60
|
+
Images: "docker image prune (dangling images only)",
|
|
61
|
+
Containers: "docks-kit tidy --apply removes agent leftovers",
|
|
62
|
+
"Local Volumes": "review named volumes; never prune them blindly",
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Package and tool caches, home-relative unless absolute; a hint names the prune command. */
|
|
66
|
+
const CACHES: ReadonlyArray<{ readonly path: string; readonly hint?: string }> = [
|
|
67
|
+
{ path: ".npm", hint: "npm cache verify" },
|
|
68
|
+
{ path: ".bun/install/cache", hint: "bun pm cache rm" },
|
|
69
|
+
{ path: ".cache/pnpm", hint: "pnpm store prune" },
|
|
70
|
+
{ path: ".local/share/pnpm/store", hint: "pnpm store prune" },
|
|
71
|
+
{ path: "/tmp/.pnpm-store", hint: "pnpm store prune" },
|
|
72
|
+
{ path: ".cache/uv", hint: "uv cache prune" },
|
|
73
|
+
{ path: ".cache/pip", hint: "pip cache purge" },
|
|
74
|
+
{ path: ".cache/composer", hint: "composer clear-cache" },
|
|
75
|
+
{ path: ".cache/go-build", hint: "go clean -cache" },
|
|
76
|
+
{ path: ".cache/ms-playwright" },
|
|
77
|
+
{ path: ".cache/puppeteer" },
|
|
78
|
+
{ path: ".cache/huggingface" },
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
const HISTORIES: ReadonlyArray<{ readonly path: string; readonly hint?: string }> = [
|
|
82
|
+
{ path: ".omp/agent/sessions", hint: "omp gc --apply" },
|
|
83
|
+
{ path: ".claude/projects" },
|
|
84
|
+
{ path: ".codex/sessions" },
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
function formatKb(kb: number): string {
|
|
88
|
+
return kb >= 1024 * 1024 ? `${(kb / 1024 / 1024).toFixed(1)} GB` : `${(kb / 1024).toFixed(1)} MB`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function formatAge(ms: number): string {
|
|
92
|
+
return ms < 2 * DAY_MS ? `${Math.floor(ms / HOUR_MS)} h` : `${Math.floor(ms / DAY_MS)} d`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Disk use of one path in KiB, from `du -sk`. A partial read (exit 1) still counts. */
|
|
96
|
+
async function sizeKb(path: string, host: TidyHost): Promise<number> {
|
|
97
|
+
const result = await host.run("du", ["-sk", path]);
|
|
98
|
+
const kb = Number.parseInt(result.stdout.trim().split(/\s+/)[0] ?? "", 10);
|
|
99
|
+
if (Number.isFinite(kb)) return kb;
|
|
100
|
+
throw new Error(result.missing ? "du is not on PATH" : `du ${path}: ${firstLine(result)}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** `<size> <path>` lines for the paths that exist, plus their hints in order. */
|
|
104
|
+
async function sizeLines(
|
|
105
|
+
entries: ReadonlyArray<{ readonly path: string; readonly hint?: string }>,
|
|
106
|
+
home: string,
|
|
107
|
+
host: TidyHost,
|
|
108
|
+
): Promise<Array<string>> {
|
|
109
|
+
const present = entries
|
|
110
|
+
.map((entry) => ({
|
|
111
|
+
...entry,
|
|
112
|
+
path: entry.path.startsWith("/") ? entry.path : join(home, entry.path),
|
|
113
|
+
}))
|
|
114
|
+
.filter((entry) => lstatOrUndefined(entry.path)?.isDirectory() === true);
|
|
115
|
+
const sizes = await runBounded(
|
|
116
|
+
present.map((entry) => () => sizeKb(entry.path, host)),
|
|
117
|
+
3,
|
|
118
|
+
);
|
|
119
|
+
const hints = [
|
|
120
|
+
...new Set(present.flatMap((entry) => (entry.hint === undefined ? [] : [entry.hint]))),
|
|
121
|
+
];
|
|
122
|
+
return [
|
|
123
|
+
...present.map((entry, index) => `${formatKb(sizes[index]!)} ${entry.path}`),
|
|
124
|
+
...hints.map((hint) => `hint: ${hint}`),
|
|
125
|
+
];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// --------------------------------------------------------------- sections ----
|
|
129
|
+
|
|
130
|
+
async function memorySection(
|
|
131
|
+
rows: ReadonlyArray<ProcessRow> | undefined,
|
|
132
|
+
host: TidyHost,
|
|
133
|
+
): Promise<Array<string>> {
|
|
134
|
+
const lines: Array<string> = [];
|
|
135
|
+
if (process.platform === "linux") {
|
|
136
|
+
const meminfo = readFileSync("/proc/meminfo", "utf8");
|
|
137
|
+
const field = (name: string): number | undefined => {
|
|
138
|
+
const match = new RegExp(`^${name}:\\s+(\\d+) kB`, "m").exec(meminfo);
|
|
139
|
+
return match === null ? undefined : Number(match[1]);
|
|
140
|
+
};
|
|
141
|
+
const total = field("SwapTotal");
|
|
142
|
+
const free = field("SwapFree");
|
|
143
|
+
if (total !== undefined && free !== undefined) {
|
|
144
|
+
lines.push(`swap: ${formatKb(total - free)} used of ${formatKb(total)}`);
|
|
145
|
+
}
|
|
146
|
+
const mounts = ["/tmp", "/dev/shm"].filter((path) => lstatOrUndefined(path) !== undefined);
|
|
147
|
+
const df = await host.run("df", ["-kP", ...mounts]);
|
|
148
|
+
if (df.code !== 0) lines.push(`unavailable: df: ${firstLine(df)}`);
|
|
149
|
+
else {
|
|
150
|
+
const dfRows = df.stdout
|
|
151
|
+
.split("\n")
|
|
152
|
+
.slice(1)
|
|
153
|
+
.filter((line) => line.trim() !== "");
|
|
154
|
+
dfRows.forEach((line, index) => {
|
|
155
|
+
const fields = line.trim().split(/\s+/);
|
|
156
|
+
const size = Number(fields[1]);
|
|
157
|
+
const used = Number(fields[2]);
|
|
158
|
+
const mount = mounts[index];
|
|
159
|
+
if (mount !== undefined && Number.isFinite(size) && Number.isFinite(used)) {
|
|
160
|
+
lines.push(`${mount}: ${formatKb(used)} used of ${formatKb(size)} (${fields[0]})`);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (rows === undefined) {
|
|
166
|
+
lines.push(`unavailable: ${PROCESS_LIST_UNAVAILABLE}`);
|
|
167
|
+
return lines;
|
|
168
|
+
}
|
|
169
|
+
const omp = rows.filter((row) => commandName(row.comm) === "omp");
|
|
170
|
+
if (omp.length > 0) {
|
|
171
|
+
const rss = omp.reduce((sum, row) => sum + row.rssKb, 0);
|
|
172
|
+
lines.push(`omp processes: ${omp.length}, ${formatKb(rss)} resident`);
|
|
173
|
+
lines.push("hint: close idle omp sessions");
|
|
174
|
+
}
|
|
175
|
+
return lines;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function temporarySection(host: TidyHost, now: number): Promise<Array<string>> {
|
|
179
|
+
const uid = process.getuid?.();
|
|
180
|
+
const roots = [...new Set(TEMP_ROOTS.map((root) => normalizePath(root)))];
|
|
181
|
+
const entries: Array<{
|
|
182
|
+
readonly path: string;
|
|
183
|
+
readonly ageMs: number;
|
|
184
|
+
readonly directory: boolean;
|
|
185
|
+
readonly kb: number;
|
|
186
|
+
}> = [];
|
|
187
|
+
for (const root of roots) {
|
|
188
|
+
for (const name of sortedEntries(root)) {
|
|
189
|
+
const path = join(root, name);
|
|
190
|
+
const stats = lstatOrUndefined(path);
|
|
191
|
+
if (stats === undefined || (uid !== undefined && stats.uid !== uid)) continue;
|
|
192
|
+
entries.push({
|
|
193
|
+
path,
|
|
194
|
+
ageMs: now - stats.mtimeMs,
|
|
195
|
+
directory: stats.isDirectory(),
|
|
196
|
+
kb: Math.ceil((stats.blocks * 512) / 1024),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const directories = entries.filter((entry) => entry.directory);
|
|
201
|
+
const sizes = await runBounded(
|
|
202
|
+
directories.map((entry) => () => sizeKb(entry.path, host)),
|
|
203
|
+
3,
|
|
204
|
+
);
|
|
205
|
+
const measured = [
|
|
206
|
+
...entries.filter((entry) => !entry.directory),
|
|
207
|
+
...directories.map((entry, index) => ({ ...entry, kb: sizes[index]! })),
|
|
208
|
+
];
|
|
209
|
+
const largest = measured.sort((a, b) => b.kb - a.kb).slice(0, TEMP_ENTRY_COUNT);
|
|
210
|
+
if (largest.length === 0) return [];
|
|
211
|
+
return [
|
|
212
|
+
...largest.map(
|
|
213
|
+
(entry) => `${formatKb(entry.kb)} ${formatAge(entry.ageMs)} old ${entry.path}`,
|
|
214
|
+
),
|
|
215
|
+
"hint: docks-kit scratch remove <path> removes an entry that an agent created",
|
|
216
|
+
];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Listening TCP ports per PID, from `ss -ltnpH`. */
|
|
220
|
+
async function listeningPorts(host: TidyHost): Promise<Map<number, Set<string>>> {
|
|
221
|
+
const ports = new Map<number, Set<string>>();
|
|
222
|
+
const result = await host.run("ss", ["-ltnpH"]);
|
|
223
|
+
if (result.code !== 0) return ports;
|
|
224
|
+
for (const line of result.stdout.split("\n")) {
|
|
225
|
+
const local = line.trim().split(/\s+/)[3];
|
|
226
|
+
const port = local?.slice(local.lastIndexOf(":") + 1);
|
|
227
|
+
if (port === undefined || port === "") continue;
|
|
228
|
+
for (const match of line.matchAll(/pid=(\d+)/g)) {
|
|
229
|
+
const pid = Number(match[1]);
|
|
230
|
+
ports.set(pid, (ports.get(pid) ?? new Set()).add(port));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return ports;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function processSection(
|
|
237
|
+
rows: ReadonlyArray<ProcessRow> | undefined,
|
|
238
|
+
territory: ReadonlyArray<string>,
|
|
239
|
+
host: TidyHost,
|
|
240
|
+
): Promise<Array<string>> {
|
|
241
|
+
if (rows === undefined) return [`unavailable: ${PROCESS_LIST_UNAVAILABLE}`];
|
|
242
|
+
const parents = orphanParents(rows);
|
|
243
|
+
const selected = rows.filter((row) => {
|
|
244
|
+
// The report never suggests `kill` for the agent harness, its launcher, or the kit.
|
|
245
|
+
if (row.ageMs < REPORT_PROCESS_AGE_MS || isProtectedProcess(row)) return false;
|
|
246
|
+
const names = row.args
|
|
247
|
+
.split(/\s+/)
|
|
248
|
+
.map((word) => word.slice(word.lastIndexOf("/") + 1))
|
|
249
|
+
.join(" ");
|
|
250
|
+
const devOrphan = parents.has(row.ppid) && DEV_PROCESS.test(names);
|
|
251
|
+
if (devOrphan) return true;
|
|
252
|
+
if (row.cwd === undefined) return false;
|
|
253
|
+
const cwd = normalizePath(row.cwd);
|
|
254
|
+
return territory.some((root) => isSameOrInside(root, cwd));
|
|
255
|
+
});
|
|
256
|
+
if (selected.length === 0) return [];
|
|
257
|
+
const ports =
|
|
258
|
+
process.platform === "linux" ? await listeningPorts(host) : new Map<number, Set<string>>();
|
|
259
|
+
return [
|
|
260
|
+
...selected.map((row) => {
|
|
261
|
+
const listening = [...(ports.get(row.pid) ?? [])];
|
|
262
|
+
const suffix = listening.length === 0 ? "" : ` ports ${listening.join(",")}`;
|
|
263
|
+
return `${row.pid} ${Math.floor(row.ageMs / HOUR_MS)} h ${formatKb(row.rssKb)} ${row.cwd ?? "?"} ${shorten(row.args, 100)}${suffix}`;
|
|
264
|
+
}),
|
|
265
|
+
"hint: kill <pid> after you confirm that nothing uses it",
|
|
266
|
+
];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function dockerSection(host: TidyHost, docker: DockerAccess): Promise<Array<string>> {
|
|
270
|
+
if (docker.kind === "missing") throw new Error("docker is not on PATH");
|
|
271
|
+
const runDocker = localDocker(host, docker);
|
|
272
|
+
if (runDocker === undefined) throw new Error(notLocalMessage(docker.endpoint));
|
|
273
|
+
const result = await runDocker([
|
|
274
|
+
"system",
|
|
275
|
+
"df",
|
|
276
|
+
"--format",
|
|
277
|
+
"{{.Type}}\\t{{.Size}}\\t{{.Reclaimable}}",
|
|
278
|
+
]);
|
|
279
|
+
if (result.code !== 0) throw new Error(`docker system df: ${firstLine(result)}`);
|
|
280
|
+
return result.stdout
|
|
281
|
+
.split("\n")
|
|
282
|
+
.filter((line) => line.trim() !== "")
|
|
283
|
+
.flatMap((line) => {
|
|
284
|
+
const [type = "", size = "", reclaimable = ""] = line.trim().split("\t");
|
|
285
|
+
const hint = DOCKER_HINTS[type];
|
|
286
|
+
return [
|
|
287
|
+
`${type}: ${size}, reclaimable ${reclaimable}`,
|
|
288
|
+
...(hint === undefined ? [] : [`hint: ${hint}`]),
|
|
289
|
+
];
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async function trashSection(home: string, host: TidyHost): Promise<Array<string>> {
|
|
294
|
+
if (process.platform === "darwin") return sizeLines([{ path: ".Trash" }], home, host);
|
|
295
|
+
const files = join(home, ".local", "share", "Trash", "files");
|
|
296
|
+
const lines = await sizeLines([{ path: files }], home, host);
|
|
297
|
+
if (lines.length === 0) return [];
|
|
298
|
+
const info = join(home, ".local", "share", "Trash", "info");
|
|
299
|
+
let oldest: string | undefined;
|
|
300
|
+
for (const name of sortedEntries(info)) {
|
|
301
|
+
if (!name.endsWith(".trashinfo")) continue;
|
|
302
|
+
try {
|
|
303
|
+
const date = /^DeletionDate=(.+)$/m.exec(readFileSync(join(info, name), "utf8"))?.[1]?.trim();
|
|
304
|
+
if (date !== undefined && (oldest === undefined || date < oldest)) oldest = date;
|
|
305
|
+
} catch {
|
|
306
|
+
// An unreadable entry does not change the oldest date.
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (oldest !== undefined) lines.push(`oldest item deleted ${oldest}`);
|
|
310
|
+
const setting = await host.run("gsettings", [
|
|
311
|
+
"get",
|
|
312
|
+
"org.gnome.desktop.privacy",
|
|
313
|
+
"remove-old-trash-files",
|
|
314
|
+
]);
|
|
315
|
+
if (setting.code === 0 && setting.stdout.trim() === "false") {
|
|
316
|
+
lines.push("hint: gsettings set org.gnome.desktop.privacy remove-old-trash-files true");
|
|
317
|
+
}
|
|
318
|
+
return lines;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function gitSection(
|
|
322
|
+
inputs: TidyInputs,
|
|
323
|
+
worktreeRoot: string | undefined,
|
|
324
|
+
host: TidyHost,
|
|
325
|
+
): Promise<Array<string>> {
|
|
326
|
+
const repos = new Set<string>();
|
|
327
|
+
if (inputs.repo !== undefined) {
|
|
328
|
+
const repo = await mainRepository(inputs.repo, host);
|
|
329
|
+
if (repo !== undefined) repos.add(repo);
|
|
330
|
+
} else {
|
|
331
|
+
const listing = await listWorktreeCandidates(inputs, host);
|
|
332
|
+
for (const candidate of listing.candidates) {
|
|
333
|
+
if (candidate.admin === undefined) continue;
|
|
334
|
+
const repo = await worktreeRepository(candidate.path, candidate.admin, host);
|
|
335
|
+
if (repo !== undefined) repos.add(repo);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const lines: Array<string> = [];
|
|
339
|
+
for (const repo of [...repos].sort()) {
|
|
340
|
+
const worktrees = (await repositoryWorktrees(repo, host)) ?? [];
|
|
341
|
+
const ref = await defaultBranchRef(repo, host);
|
|
342
|
+
if (ref !== undefined) {
|
|
343
|
+
const defaultBranch = ref.replace(/^refs\/remotes\/[^/]+\//, "");
|
|
344
|
+
const checkedOut = new Set(
|
|
345
|
+
worktrees.flatMap((entry) => (entry.branch === undefined ? [] : [shortRef(entry.branch)])),
|
|
346
|
+
);
|
|
347
|
+
const merged = await host.git([
|
|
348
|
+
"-C",
|
|
349
|
+
repo,
|
|
350
|
+
"branch",
|
|
351
|
+
"--merged",
|
|
352
|
+
ref,
|
|
353
|
+
"--format=%(refname:short)",
|
|
354
|
+
]);
|
|
355
|
+
const branches = merged.stdout
|
|
356
|
+
.split("\n")
|
|
357
|
+
.map((line) => line.trim())
|
|
358
|
+
.filter((branch) => branch !== "" && branch !== defaultBranch && !checkedOut.has(branch));
|
|
359
|
+
if (merged.code === 0 && branches.length > 0) {
|
|
360
|
+
lines.push(
|
|
361
|
+
`${repo}: local branches merged into ${shortRef(ref)} (${branches.length}): ${branches.join(", ")}`,
|
|
362
|
+
);
|
|
363
|
+
lines.push("hint: git branch -d <branch>");
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const stash = await host.git(["-C", repo, "stash", "list"]);
|
|
367
|
+
const stashes = stash.stdout.split("\n").filter((line) => line.trim() !== "").length;
|
|
368
|
+
if (stash.code === 0 && stashes > 0) lines.push(`${repo}: stash entries: ${stashes}`);
|
|
369
|
+
const outside = worktrees
|
|
370
|
+
.slice(1)
|
|
371
|
+
.filter(
|
|
372
|
+
(entry) => worktreeRoot === undefined || !isSameOrInside(worktreeRoot, entry.path),
|
|
373
|
+
).length;
|
|
374
|
+
if (outside > 0) {
|
|
375
|
+
lines.push(
|
|
376
|
+
`${repo}: linked worktrees outside ${worktreeRoot ?? "the agent worktree root"}: ${outside}`,
|
|
377
|
+
);
|
|
378
|
+
lines.push(`hint: docks-kit tidy --repo ${repo}`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return lines;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Names in `directory` whose entry changed in the last 30 days. */
|
|
385
|
+
function recentNames(
|
|
386
|
+
directory: string,
|
|
387
|
+
now: number,
|
|
388
|
+
keep: (name: string) => boolean,
|
|
389
|
+
): Array<string> {
|
|
390
|
+
return sortedEntries(directory).filter((name) => {
|
|
391
|
+
if (!keep(name)) return false;
|
|
392
|
+
const stats = lstatOrUndefined(join(directory, name));
|
|
393
|
+
return stats !== undefined && now - stats.mtimeMs <= RECENT_MS;
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function scheduledSection(home: string, host: TidyHost, now: number): Promise<Array<string>> {
|
|
398
|
+
const lines: Array<string> = [];
|
|
399
|
+
const crontab = await host.run("crontab", ["-l"]);
|
|
400
|
+
if (crontab.code === 0) {
|
|
401
|
+
const entries = crontab.stdout
|
|
402
|
+
.split("\n")
|
|
403
|
+
.map((line) => line.trim())
|
|
404
|
+
.filter((line) => line !== "" && !line.startsWith("#")).length;
|
|
405
|
+
if (entries > 0) lines.push(`crontab: ${entries} entries`);
|
|
406
|
+
}
|
|
407
|
+
const units =
|
|
408
|
+
process.platform === "darwin"
|
|
409
|
+
? recentNames(join(home, "Library", "LaunchAgents"), now, (name) => name.endsWith(".plist"))
|
|
410
|
+
: recentNames(join(home, ".config", "systemd", "user"), now, (name) =>
|
|
411
|
+
/\.(service|timer|path)$/.test(name),
|
|
412
|
+
);
|
|
413
|
+
if (units.length > 0) {
|
|
414
|
+
const label = process.platform === "darwin" ? "launch agents" : "systemd user units";
|
|
415
|
+
lines.push(`${label} changed in the last 30 days: ${units.join(", ")}`);
|
|
416
|
+
}
|
|
417
|
+
return lines;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Bun keeps the packages that `bun add -g` installed in the dependencies of
|
|
422
|
+
* its global `package.json`; its `node_modules` also holds their dependencies.
|
|
423
|
+
*/
|
|
424
|
+
function bunGlobalPackages(home: string): Array<string> {
|
|
425
|
+
try {
|
|
426
|
+
const manifest: unknown = JSON.parse(
|
|
427
|
+
readFileSync(join(home, ".bun", "install", "global", "package.json"), "utf8"),
|
|
428
|
+
);
|
|
429
|
+
const dependencies =
|
|
430
|
+
typeof manifest === "object" && manifest !== null && "dependencies" in manifest
|
|
431
|
+
? manifest.dependencies
|
|
432
|
+
: undefined;
|
|
433
|
+
return typeof dependencies === "object" && dependencies !== null
|
|
434
|
+
? Object.keys(dependencies).sort()
|
|
435
|
+
: [];
|
|
436
|
+
} catch {
|
|
437
|
+
return [];
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async function globalSection(home: string, host: TidyHost, now: number): Promise<Array<string>> {
|
|
442
|
+
const keep = (name: string): boolean => name !== ".bin" && name !== ".cache";
|
|
443
|
+
const lines: Array<string> = [];
|
|
444
|
+
const bunModules = join(home, ".bun", "install", "global", "node_modules");
|
|
445
|
+
const bun = bunGlobalPackages(home).filter((name) => {
|
|
446
|
+
const stats = lstatOrUndefined(join(bunModules, name));
|
|
447
|
+
return stats !== undefined && now - stats.mtimeMs <= RECENT_MS;
|
|
448
|
+
});
|
|
449
|
+
if (bun.length > 0)
|
|
450
|
+
lines.push(`bun global installs changed in the last 30 days: ${bun.join(", ")}`);
|
|
451
|
+
const npmRoot = await host.run("npm", ["root", "-g"]);
|
|
452
|
+
const root = npmRoot.code === 0 ? npmRoot.stdout.trim() : "";
|
|
453
|
+
if (root !== "") {
|
|
454
|
+
const npm = recentNames(root, now, keep);
|
|
455
|
+
if (npm.length > 0)
|
|
456
|
+
lines.push(`npm global installs changed in the last 30 days: ${npm.join(", ")}`);
|
|
457
|
+
}
|
|
458
|
+
return lines;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function section(
|
|
462
|
+
title: string,
|
|
463
|
+
build: () => Promise<ReadonlyArray<string>>,
|
|
464
|
+
): Promise<TidyReportSection | undefined> {
|
|
465
|
+
try {
|
|
466
|
+
const lines = await build();
|
|
467
|
+
return lines.length === 0 ? undefined : { title, lines };
|
|
468
|
+
} catch (cause) {
|
|
469
|
+
return { title, lines: [`unavailable: ${errorMessage(cause)}`] };
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Build the report sections in their fixed order; a section with no lines is
|
|
475
|
+
* left out. `docker` is the access that the plan of the same run resolved.
|
|
476
|
+
*/
|
|
477
|
+
export async function buildTidyReport(
|
|
478
|
+
inputs: TidyInputs,
|
|
479
|
+
host: TidyHost,
|
|
480
|
+
docker: DockerAccess,
|
|
481
|
+
): Promise<ReadonlyArray<TidyReportSection>> {
|
|
482
|
+
if (process.platform === "win32") {
|
|
483
|
+
return [{ title: "Report", lines: ["docks-kit tidy --report supports Linux and macOS"] }];
|
|
484
|
+
}
|
|
485
|
+
const now = host.now();
|
|
486
|
+
const home = normalizePath(inputs.home);
|
|
487
|
+
const roots = agentRoots(inputs);
|
|
488
|
+
const rows = await host.processes().catch(() => undefined);
|
|
489
|
+
// A process cwd keeps the spelling that it has when the path is gone, so
|
|
490
|
+
// each temporary root counts in both its typed and its real spelling.
|
|
491
|
+
const territory = [
|
|
492
|
+
roots.worktreeRoot,
|
|
493
|
+
roots.scratchRoot,
|
|
494
|
+
...TEMP_ROOTS.flatMap((root) => [root, normalizePath(root)]),
|
|
495
|
+
].filter((path): path is string => path !== undefined);
|
|
496
|
+
const sections = await Promise.all([
|
|
497
|
+
section("Memory", () => memorySection(rows, host)),
|
|
498
|
+
section("Temporary directories", () => temporarySection(host, now)),
|
|
499
|
+
section("Processes", () => processSection(rows, territory, host)),
|
|
500
|
+
section("Docker", () => dockerSection(host, docker)),
|
|
501
|
+
section("Package and tool caches", () => sizeLines(CACHES, home, host)),
|
|
502
|
+
section("Trash", () => trashSection(home, host)),
|
|
503
|
+
section("Git", () => gitSection(inputs, roots.worktreeRoot, host)),
|
|
504
|
+
section("Agent histories", () => sizeLines(HISTORIES, home, host)),
|
|
505
|
+
section("Scheduled jobs and services", () => scheduledSection(home, host, now)),
|
|
506
|
+
section("Global installs", () => globalSection(home, host, now)),
|
|
507
|
+
]);
|
|
508
|
+
return sections.filter((entry): entry is TidyReportSection => entry !== undefined);
|
|
509
|
+
}
|