benignswarm 0.12.164 → 0.12.166

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/dist/model.js CHANGED
@@ -2,6 +2,28 @@ import { existsSync, openSync, readFileSync, readSync, statSync } from "node:fs"
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { detectVendor } from "./vendor.js";
5
+ /** Canonical provider inferred only from an explicit provider value or recognizable harness/model. */
6
+ export function inferProvider(model, harness, explicit) {
7
+ const raw = explicit?.trim().toLowerCase();
8
+ if (raw && raw !== "unknown")
9
+ return raw;
10
+ const value = `${harness ?? ""} ${model ?? ""}`.toLowerCase();
11
+ if (/deepseek/.test(value))
12
+ return "deepseek";
13
+ if (/claude|anthropic/.test(value))
14
+ return "anthropic";
15
+ if (/gemini|hydrogen|neon|google/.test(value))
16
+ return "google";
17
+ if (/\b(?:gpt|o[13]|codex)\b/.test(value))
18
+ return "openai";
19
+ return null;
20
+ }
21
+ function knownObservation(value) {
22
+ if (typeof value !== "string")
23
+ return null;
24
+ const normalized = value.trim();
25
+ return normalized && normalized.toLowerCase() !== "unknown" ? normalized : null;
26
+ }
5
27
  /**
6
28
  * Model id from Claude Code's transcript JSONL: the last assistant message's `message.model`.
7
29
  * Reads only the tail of the file, since transcripts can be large.
@@ -48,7 +70,7 @@ export function modelFromHarnessConfig(vendor, cwd = process.cwd(), env = proces
48
70
  return m[1];
49
71
  }
50
72
  }
51
- else if (vendor === "gemini-cli" || vendor === "antigravity") {
73
+ else if (vendor === "gemini-cli") {
52
74
  const p = join(home, ".gemini", "settings.json");
53
75
  if (existsSync(p)) {
54
76
  const j = JSON.parse(readFileSync(p, "utf8"));
@@ -79,11 +101,13 @@ export function modelFromHarnessConfig(vendor, cwd = process.cwd(), env = proces
79
101
  * Reasoning effort: --effort, BSCHAT_EFFORT, then what the harness itself exposes (Claude Code's
80
102
  * CLAUDE_EFFORT, Codex's model_reasoning_effort in config.toml), else "unknown". Never a guess.
81
103
  */
82
- export function resolveEffort(flag, env = process.env, vendor = null, cwd = process.cwd()) {
83
- if (flag)
84
- return flag;
85
- if (env.BSCHAT_EFFORT)
86
- return env.BSCHAT_EFFORT;
104
+ export function resolveEffort(flag, env = process.env, vendor = null, cwd = process.cwd(), observedEffort) {
105
+ const explicit = knownObservation(flag) ?? knownObservation(env.BSCHAT_EFFORT);
106
+ if (explicit)
107
+ return explicit;
108
+ const observed = knownObservation(observedEffort);
109
+ if (observed)
110
+ return observed;
87
111
  const v = detectVendor(env) ?? vendor;
88
112
  try {
89
113
  if (v === "claude-code" && env.CLAUDE_EFFORT)
@@ -111,19 +135,23 @@ export function resolveEffort(flag, env = process.env, vendor = null, cwd = proc
111
135
  */
112
136
  export function resolveModelDetailed(opts) {
113
137
  const env = opts.env ?? process.env;
114
- if (opts.flag)
115
- return { model: opts.flag, source: "flag" };
116
- if (env.BSCHAT_MODEL)
117
- return { model: env.BSCHAT_MODEL, source: "env" };
118
- if (opts.hookModel)
119
- return { model: opts.hookModel, source: "hook" };
138
+ const flag = knownObservation(opts.flag);
139
+ if (flag)
140
+ return { model: flag, source: "flag" };
141
+ const fromEnv = knownObservation(env.BSCHAT_MODEL);
142
+ if (fromEnv)
143
+ return { model: fromEnv, source: "env" };
144
+ const fromHook = knownObservation(opts.hookModel);
145
+ if (fromHook)
146
+ return { model: fromHook, source: "hook" };
120
147
  // Env-based vendor detection can fail inside a harness's sandboxed shell; the vendor saved at
121
148
  // join time is the stable fallback so the config lookup does not flap between a value and unknown.
122
149
  const cfg = modelFromHarnessConfig(detectVendor(env) ?? opts.vendor ?? null, opts.cwd, env);
123
150
  if (cfg)
124
151
  return { model: cfg, source: "config" };
125
- if (opts.identityModel)
126
- return { model: opts.identityModel, source: "identity" };
152
+ const fromIdentity = knownObservation(opts.identityModel);
153
+ if (fromIdentity)
154
+ return { model: fromIdentity, source: "identity" };
127
155
  return { model: "unknown", source: "unknown" };
128
156
  }
129
157
  /**
package/dist/output.js CHANGED
@@ -65,6 +65,7 @@ export function fmtMessage(m) {
65
65
  export function fmtStatus(s) {
66
66
  const parts = [
67
67
  `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
68
+ s.agent_state ? `agent_state=${s.agent_state} (${s.agent_state_source ?? "source unavailable"}: ${s.agent_state_reason ?? "reason unavailable"})${s.agent_state_fix ? `; fix=${s.agent_state_fix}` : ""}` : null,
68
69
  `state=${s.state ?? "-"}`,
69
70
  s.watcher_state ? `watcher=${s.watcher_state}${s.watcher_state === "errored" && s.watcher?.last_error ? `(${s.watcher.last_error})` : ""}` : null,
70
71
  s.goal ? `goal="${s.goal}"` : null,
@@ -0,0 +1,468 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync } from "node:fs";
3
+ import { platform, tmpdir } from "node:os";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { measurePath, parseLsofOutput } from "./build-caches.js";
6
+ import { linuxProcessEnded, readLinuxProcessOrigin, uninspectableExclusion } from "./machine-processes.js";
7
+ export const STALE_VITEST_SCRATCH_AGE_MS = 2 * 60 * 60_000;
8
+ export const MAX_SCRATCH_CLEANUPS_PER_PASS = 100;
9
+ const LSOF_PID_BATCH_SIZE = 200;
10
+ /** Matches apps/api/src/machine-headroom.ts home_volume_below_floor / work_volume_below_floor logic. */
11
+ export function detectLocalDiskPressure(spaces, floorPct) {
12
+ const reasons = [];
13
+ for (const space of spaces) {
14
+ if (!space || space.totalBytes <= 0 || space.freeBytes < 0 || space.freeBytes > space.totalBytes)
15
+ continue;
16
+ const freePct = (space.freeBytes / space.totalBytes) * 100;
17
+ if (freePct < floorPct) {
18
+ reasons.push(space.label === "home" ? "home_volume_below_floor" : "work_volume_below_floor");
19
+ }
20
+ }
21
+ return { underPressure: reasons.length > 0, reasons, floorPct };
22
+ }
23
+ function realpathSafe(target) {
24
+ try {
25
+ return realpathSync(target);
26
+ }
27
+ catch {
28
+ const stripped = target.replace(/ \(deleted\)$/, "");
29
+ const dir = dirname(stripped);
30
+ if (dir && dir !== stripped) {
31
+ try {
32
+ return join(realpathSync(dir), basename(stripped));
33
+ }
34
+ catch { /* fall back */ }
35
+ }
36
+ return resolve(stripped);
37
+ }
38
+ }
39
+ function isSameOrInside(candidate, parent) {
40
+ return candidate === parent || candidate.startsWith(parent === "/" ? "/" : `${parent}/`);
41
+ }
42
+ function referencesPath(command, target) {
43
+ let from = 0;
44
+ while (true) {
45
+ const at = command.indexOf(target, from);
46
+ if (at < 0)
47
+ return false;
48
+ const after = command[at + target.length];
49
+ if (after === undefined || !/[A-Za-z0-9_-]/.test(after))
50
+ return true;
51
+ from = at + target.length;
52
+ }
53
+ }
54
+ function isPermissionError(error) {
55
+ const err = error;
56
+ return err?.code === "EPERM" || err?.code === "EACCES" || /operation not permitted|permission denied|sandbox/i.test(err?.message ?? "");
57
+ }
58
+ function isDisappearedError(error) {
59
+ const code = error?.code;
60
+ return code === "ENOENT" || code === "ESRCH" || code === "EBADF";
61
+ }
62
+ function defaultPidNamespace(os) {
63
+ if (os !== "linux")
64
+ return "host";
65
+ try {
66
+ return readlinkSync("/proc/self/ns/pid");
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ function defaultIdentifyProcess(pid) {
73
+ let pidNamespace;
74
+ try {
75
+ pidNamespace = readlinkSync(`/proc/${pid}/ns/pid`);
76
+ }
77
+ catch (error) {
78
+ if (error.code === "ENOENT")
79
+ return { method: "linux-process-gone" };
80
+ return null;
81
+ }
82
+ try {
83
+ const bootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
84
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
85
+ const close = stat.lastIndexOf(")");
86
+ if (close < 0)
87
+ return null;
88
+ const startTime = stat.slice(close + 1).trim().split(/\s+/)[19];
89
+ if (!bootId || !startTime)
90
+ return null;
91
+ return { method: "linux-process-token", pidNamespace, bootId, startTime };
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ function defaultProcessRows(os) {
98
+ if (os !== "linux" && os !== "darwin") {
99
+ throw new Error(`process-table inspection is unsupported on ${os}`);
100
+ }
101
+ const args = os === "linux"
102
+ ? ["-ww", "-axo", "pid=,ppid=,euid=,command="]
103
+ : ["-ww", "-axo", "pid=,ppid=,uid=,command="];
104
+ const res = spawnSync("ps", args, { encoding: "utf8", timeout: 10_000, maxBuffer: 16 * 1024 * 1024 });
105
+ if (res.error || res.status !== 0) {
106
+ const detail = res.error?.message ?? res.stderr ?? `ps exited ${res.status}`;
107
+ const err = new Error(`cannot inspect process table: ${detail}`);
108
+ err.code = res.error?.code ?? (/operation not permitted|permission denied|sandbox/i.test(detail) ? "EPERM" : undefined);
109
+ throw err;
110
+ }
111
+ const rows = [];
112
+ for (const line of res.stdout.split(/\r?\n/)) {
113
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
114
+ if (!match)
115
+ continue;
116
+ const pid = Number(match[1]);
117
+ const ppid = Number(match[2]);
118
+ const uid = Number(match[3]);
119
+ if (Number.isSafeInteger(pid) && pid > 0)
120
+ rows.push({ pid, ppid, uid, command: match[4] });
121
+ }
122
+ return rows;
123
+ }
124
+ const defaultProcFs = {
125
+ readlink: (path) => readlinkSync(path),
126
+ readdir: (path) => readdirSync(path),
127
+ readOrigin: readLinuxProcessOrigin,
128
+ isEnded: linuxProcessEnded,
129
+ };
130
+ /**
131
+ * Affirmatively inspects `/proc/<pid>/cwd` and `/proc/<pid>/fd` across all Linux processes.
132
+ * Disappeared/zombie processes are skipped. Same-UID permission failures fail closed unless allowed
133
+ * by `uninspectableExclusion`; other-UID permission failures are recorded in `uninspectedProcesses`
134
+ * so any candidate accessible to those UIDs is preserved.
135
+ */
136
+ export function probeLinuxProcessPaths(rows, fsOps = defaultProcFs, selfUid = process.getuid?.()) {
137
+ const pathsByPid = new Map();
138
+ const uninspectedProcesses = [];
139
+ const handleError = (row, error, context) => {
140
+ if (isDisappearedError(error) || fsOps.isEnded(row.pid))
141
+ return "skip";
142
+ const isSameUid = row.uid === undefined || (selfUid !== undefined && row.uid === selfUid);
143
+ if (isSameUid && isPermissionError(error) && row.ppid !== undefined) {
144
+ if (uninspectableExclusion(fsOps.readOrigin(row.pid, row.ppid)) !== null)
145
+ return "skip";
146
+ }
147
+ if (!isSameUid && isPermissionError(error)) {
148
+ uninspectedProcesses.push({ pid: row.pid, uid: row.uid });
149
+ return "uninspected";
150
+ }
151
+ return {
152
+ pathsByPid,
153
+ probeFailed: true,
154
+ uninspectedProcesses,
155
+ reason: `cannot inspect ${context} for process ${row.pid}: ${error.message}`,
156
+ };
157
+ };
158
+ for (const row of rows) {
159
+ const paths = [];
160
+ try {
161
+ const cwd = fsOps.readlink(`/proc/${row.pid}/cwd`);
162
+ if (cwd.startsWith("/"))
163
+ paths.push(cwd);
164
+ }
165
+ catch (error) {
166
+ const outcome = handleError(row, error, "working directory");
167
+ if (outcome === "skip" || outcome === "uninspected")
168
+ continue;
169
+ return outcome;
170
+ }
171
+ let fds;
172
+ try {
173
+ fds = fsOps.readdir(`/proc/${row.pid}/fd`);
174
+ }
175
+ catch (error) {
176
+ const outcome = handleError(row, error, "file descriptors");
177
+ if (outcome === "skip" || outcome === "uninspected")
178
+ continue;
179
+ return outcome;
180
+ }
181
+ let skippedPid = false;
182
+ for (const fd of fds) {
183
+ try {
184
+ const target = fsOps.readlink(`/proc/${row.pid}/fd/${fd}`);
185
+ if (target.startsWith("/"))
186
+ paths.push(target);
187
+ }
188
+ catch (error) {
189
+ if (isDisappearedError(error) || fsOps.isEnded(row.pid))
190
+ continue;
191
+ const outcome = handleError(row, error, `fd ${fd}`);
192
+ if (outcome === "skip" || outcome === "uninspected") {
193
+ skippedPid = true;
194
+ break;
195
+ }
196
+ return outcome;
197
+ }
198
+ }
199
+ if (!skippedPid)
200
+ pathsByPid.set(row.pid, paths);
201
+ }
202
+ return { pathsByPid, probeFailed: false, ...(uninspectedProcesses.length ? { uninspectedProcesses } : {}) };
203
+ }
204
+ /**
205
+ * Affirmatively inspects `cwd` and open file descriptors for candidate macOS processes via `lsof`.
206
+ * Fails closed on `lsof` timeouts/signals/errors (never trusting partial output on timeout) and
207
+ * preserves candidates if any surviving live process lacks affirmative coverage.
208
+ */
209
+ export function probeDarwinProcessPaths(rows, execCommand = (cmd, args, opts) => execFileSync(cmd, args, opts), probePid = (pid, signal) => process.kill(pid, signal), selfUid = process.getuid?.()) {
210
+ const pathsByPid = new Map();
211
+ const uninspectedProcesses = [];
212
+ if (rows.length === 0)
213
+ return { pathsByPid, probeFailed: false };
214
+ const alive = (pid) => {
215
+ try {
216
+ probePid(pid, 0);
217
+ return true;
218
+ }
219
+ catch (error) {
220
+ return error?.code !== "ESRCH";
221
+ }
222
+ };
223
+ for (let i = 0; i < rows.length; i += LSOF_PID_BATCH_SIZE) {
224
+ const batch = rows.slice(i, i + LSOF_PID_BATCH_SIZE);
225
+ let stdout = "";
226
+ let fatalError = null;
227
+ try {
228
+ stdout = execCommand("lsof", ["-w", "-n", "-P", "-F", "pcn", "-p", batch.map((r) => r.pid).join(",")], {
229
+ encoding: "utf8",
230
+ timeout: 10_000,
231
+ stdio: ["ignore", "pipe", "pipe"],
232
+ });
233
+ }
234
+ catch (error) {
235
+ const err = error;
236
+ const cleanPartialExit = err.code !== "ETIMEDOUT" && !err.signal && err.status === 1;
237
+ if (cleanPartialExit && typeof err.stdout === "string" && err.stdout.trim()) {
238
+ stdout = err.stdout;
239
+ }
240
+ else if (cleanPartialExit && batch.every((row) => !alive(row.pid))) {
241
+ continue;
242
+ }
243
+ else {
244
+ fatalError = err.message ?? (err.code ? `lsof ${err.code}` : "lsof failed");
245
+ }
246
+ }
247
+ if (fatalError) {
248
+ return { pathsByPid, probeFailed: true, reason: `cannot inspect process cwd/open files via lsof: ${fatalError}` };
249
+ }
250
+ if (stdout) {
251
+ for (const [pid, paths] of parseLsofOutput(stdout)) {
252
+ pathsByPid.set(pid, paths);
253
+ }
254
+ }
255
+ for (const row of batch) {
256
+ const inspected = pathsByPid.get(row.pid);
257
+ if ((!inspected || inspected.length === 0) && alive(row.pid)) {
258
+ const isOtherUid = row.uid !== undefined && selfUid !== undefined && row.uid !== selfUid;
259
+ if (isOtherUid) {
260
+ uninspectedProcesses.push({ pid: row.pid, uid: row.uid });
261
+ continue;
262
+ }
263
+ return {
264
+ pathsByPid,
265
+ probeFailed: true,
266
+ uninspectedProcesses,
267
+ reason: `lsof did not return cwd or open file paths for live process ${row.pid}`,
268
+ };
269
+ }
270
+ }
271
+ }
272
+ return { pathsByPid, probeFailed: false, ...(uninspectedProcesses.length ? { uninspectedProcesses } : {}) };
273
+ }
274
+ function ownerIsAliveOrUnverified(scratch, os, pidNamespace, probePid, identifyProcess) {
275
+ const ownerFile = join(scratch, ".b9s-vitest-owner");
276
+ let contents;
277
+ try {
278
+ contents = readFileSync(ownerFile, "utf8");
279
+ }
280
+ catch (error) {
281
+ // Missing owner file means no recorded PID lock; still guarded by affirmative live process scan.
282
+ if (error.code === "ENOENT")
283
+ return false;
284
+ return true;
285
+ }
286
+ let owner;
287
+ try {
288
+ owner = JSON.parse(contents);
289
+ }
290
+ catch {
291
+ const legacyPid = Number(contents);
292
+ owner = { pid: Number.isSafeInteger(legacyPid) ? legacyPid : undefined };
293
+ }
294
+ const ownerPid = owner?.pid;
295
+ if (typeof ownerPid !== "number" || !Number.isSafeInteger(ownerPid) || ownerPid <= 1)
296
+ return true;
297
+ if (typeof owner.pidNamespace !== "string" || !pidNamespace || owner.pidNamespace !== pidNamespace)
298
+ return true;
299
+ if (os === "linux" && owner.method === "linux-process-token" && typeof owner.bootId === "string" && typeof owner.startTime === "string") {
300
+ const observed = identifyProcess(ownerPid);
301
+ if (!observed)
302
+ return true;
303
+ if (observed.method === "linux-process-gone")
304
+ return false;
305
+ if (observed.pidNamespace !== owner.pidNamespace)
306
+ return true;
307
+ return observed.bootId === owner.bootId && observed.startTime === owner.startTime;
308
+ }
309
+ if (os !== "linux" && owner.method === "host-pid" && owner.pidNamespace === "host") {
310
+ try {
311
+ probePid(ownerPid, 0);
312
+ return true;
313
+ }
314
+ catch (error) {
315
+ if (isPermissionError(error))
316
+ return true;
317
+ if (error.code === "ESRCH")
318
+ return false;
319
+ return true;
320
+ }
321
+ }
322
+ return true;
323
+ }
324
+ /**
325
+ * Boundedly removes abandoned `b9s-vitest-*` directories in `os.tmpdir()` older than 2 hours
326
+ * meeting the send-back ruling liveness standard: owned by the daemon's user with mode 0700,
327
+ * complete same-user cwd/open-file coverage, no live owner token, and no inspectable holder.
328
+ */
329
+ export function cleanupStaleVitestScratchDirs(ops = {}) {
330
+ const dir = ops.tempDir ?? tmpdir();
331
+ const now = ops.now ?? Date.now();
332
+ const maxAgeMs = ops.maxAgeMs ?? STALE_VITEST_SCRATCH_AGE_MS;
333
+ const maxRemovals = ops.maxRemovals ?? MAX_SCRATCH_CLEANUPS_PER_PASS;
334
+ const os = ops.runtimePlatform ?? platform();
335
+ const pidNamespace = ops.pidNamespace !== undefined ? ops.pidNamespace : defaultPidNamespace(os);
336
+ const probePid = ops.probePid ?? ((pid, signal) => process.kill(pid, signal));
337
+ const identifyProcess = ops.identifyProcess ?? defaultIdentifyProcess;
338
+ const readProcessRows = ops.readProcessRows ?? (() => defaultProcessRows(os));
339
+ const selfUid = ops.uid !== undefined ? ops.uid : process.getuid?.();
340
+ let names;
341
+ try {
342
+ names = readdirSync(dir);
343
+ }
344
+ catch (error) {
345
+ if (error.code === "ENOENT") {
346
+ return { tmpdir: dir, disk_pressure: true, removed_dirs: 0, reclaimed_bytes: 0, skipped_active: 0, skipped_recent: 0, errors: 0, capped: false };
347
+ }
348
+ return { tmpdir: dir, disk_pressure: true, removed_dirs: 0, reclaimed_bytes: 0, skipped_active: 0, skipped_recent: 0, errors: 1, capped: false, aborted_reason: error.message };
349
+ }
350
+ const candidates = [];
351
+ let skippedRecent = 0;
352
+ for (const name of names.sort()) {
353
+ if (!name.startsWith("b9s-vitest-"))
354
+ continue;
355
+ const scratch = join(dir, name);
356
+ let info;
357
+ try {
358
+ info = lstatSync(scratch);
359
+ }
360
+ catch {
361
+ continue;
362
+ }
363
+ if (info.isSymbolicLink() || !info.isDirectory())
364
+ continue;
365
+ const measured = measurePath(scratch);
366
+ const mtimeMs = Math.max(measured.mtimeMs, info.mtimeMs);
367
+ if (!Number.isFinite(mtimeMs) || now - mtimeMs <= maxAgeMs) {
368
+ skippedRecent += 1;
369
+ continue;
370
+ }
371
+ candidates.push({ path: scratch, realPath: realpathSafe(scratch), bytes: measured.bytes, uid: info.uid, mode: info.mode });
372
+ }
373
+ if (candidates.length === 0) {
374
+ return { tmpdir: dir, disk_pressure: true, removed_dirs: 0, reclaimed_bytes: 0, skipped_active: 0, skipped_recent: skippedRecent, errors: 0, capped: false };
375
+ }
376
+ let rows;
377
+ try {
378
+ rows = readProcessRows();
379
+ }
380
+ catch (error) {
381
+ return {
382
+ tmpdir: dir,
383
+ disk_pressure: true,
384
+ removed_dirs: 0,
385
+ reclaimed_bytes: 0,
386
+ skipped_active: candidates.length,
387
+ skipped_recent: skippedRecent,
388
+ errors: 0,
389
+ capped: false,
390
+ aborted_reason: error.message,
391
+ };
392
+ }
393
+ let probeResult;
394
+ try {
395
+ if (ops.probeProcessPaths) {
396
+ probeResult = ops.probeProcessPaths(rows);
397
+ }
398
+ else if (ops.readProcessPaths) {
399
+ probeResult = { pathsByPid: ops.readProcessPaths(rows.map((r) => r.pid)), probeFailed: false };
400
+ }
401
+ else if (os === "linux") {
402
+ probeResult = probeLinuxProcessPaths(rows, ops.procFs, selfUid);
403
+ }
404
+ else if (os === "darwin") {
405
+ probeResult = probeDarwinProcessPaths(rows, ops.execCommand, probePid, selfUid);
406
+ }
407
+ else {
408
+ probeResult = { pathsByPid: new Map(), probeFailed: true, reason: `cwd/open-file inspection is unsupported on ${os}` };
409
+ }
410
+ }
411
+ catch (error) {
412
+ probeResult = { pathsByPid: new Map(), probeFailed: true, reason: error.message };
413
+ }
414
+ if (probeResult.probeFailed) {
415
+ return {
416
+ tmpdir: dir,
417
+ disk_pressure: true,
418
+ removed_dirs: 0,
419
+ reclaimed_bytes: 0,
420
+ skipped_active: candidates.length,
421
+ skipped_recent: skippedRecent,
422
+ errors: 0,
423
+ capped: false,
424
+ aborted_reason: probeResult.reason ?? "process cwd and open-file inspection failed",
425
+ };
426
+ }
427
+ const isDaemonOwned0700 = (candidate) => selfUid !== undefined && candidate.uid === selfUid && (candidate.mode & 0o777) === 0o700;
428
+ const openTargets = [...probeResult.pathsByPid.values()].flat().map((target) => {
429
+ const stripped = target.replace(/ \(deleted\)$/, "");
430
+ return { raw: stripped, real: realpathSafe(stripped) };
431
+ });
432
+ let removedDirs = 0;
433
+ let reclaimedBytes = 0;
434
+ let skippedActive = 0;
435
+ let errors = 0;
436
+ let capped = false;
437
+ for (const candidate of candidates) {
438
+ if (removedDirs >= maxRemovals) {
439
+ capped = true;
440
+ break;
441
+ }
442
+ const referencedInCommand = rows.some((row) => referencesPath(row.command, candidate.path) || referencesPath(row.command, candidate.realPath));
443
+ const heldByOpenPath = openTargets.some((target) => isSameOrInside(target.raw, candidate.path) || isSameOrInside(target.real, candidate.realPath));
444
+ const heldByOwner = ownerIsAliveOrUnverified(candidate.path, os, pidNamespace, probePid, identifyProcess);
445
+ if (!isDaemonOwned0700(candidate) || referencedInCommand || heldByOpenPath || heldByOwner) {
446
+ skippedActive += 1;
447
+ continue;
448
+ }
449
+ try {
450
+ rmSync(candidate.path, { recursive: true, force: true });
451
+ removedDirs += 1;
452
+ reclaimedBytes += candidate.bytes;
453
+ }
454
+ catch {
455
+ errors += 1;
456
+ }
457
+ }
458
+ return {
459
+ tmpdir: dir,
460
+ disk_pressure: true,
461
+ removed_dirs: removedDirs,
462
+ reclaimed_bytes: reclaimedBytes,
463
+ skipped_active: skippedActive,
464
+ skipped_recent: skippedRecent,
465
+ errors,
466
+ capped,
467
+ };
468
+ }