benignswarm 0.12.109 → 0.12.111
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/args.js +2 -1
- package/dist/commands/machine-admin.js +128 -20
- package/dist/commands/machine.js +95 -15
- package/dist/commands/test-results.js +125 -0
- package/dist/commands/worktrees.js +10 -1
- package/dist/container.js +13 -0
- package/dist/git.js +27 -0
- package/dist/harness-server-sweep.js +78 -0
- package/dist/harnesses.js +56 -11
- package/dist/help.js +6 -0
- package/dist/index.js +2 -0
- package/dist/tail-lines.js +90 -0
- package/dist/test-results.js +418 -0
- package/dist/turn.js +51 -2
- package/dist/usage.js +48 -12
- package/dist/version.js +1 -1
- package/package.json +3 -2
|
@@ -7,6 +7,7 @@ import { spawnSync } from "node:child_process";
|
|
|
7
7
|
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
|
|
8
8
|
import { table } from "../output.js";
|
|
9
9
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
10
|
+
import { sweepClosedHarnessServers } from "../harness-server-sweep.js";
|
|
10
11
|
const CLOSED = ["done", "abandoned", "superseded"];
|
|
11
12
|
const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
|
|
12
13
|
const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
|
|
@@ -53,6 +54,7 @@ export async function unitWorktrees(creds, project, options = {}) {
|
|
|
53
54
|
clearTimeout(timer);
|
|
54
55
|
}
|
|
55
56
|
const closed = new Map();
|
|
57
|
+
const closedCheckouts = [];
|
|
56
58
|
const active = { paths: new Map(), branches: new Map() };
|
|
57
59
|
for (const u of all.units) {
|
|
58
60
|
const label = `WU #${u.number} (${u.status})`;
|
|
@@ -66,12 +68,19 @@ export async function unitWorktrees(creds, project, options = {}) {
|
|
|
66
68
|
if (!u.worktree || !existsSync(u.worktree))
|
|
67
69
|
continue;
|
|
68
70
|
closed.set(realpathSync(u.worktree), `WU #${u.number} ${u.status}`);
|
|
71
|
+
if (typeof u.closed_at === "string" && Number.isSafeInteger(u.number))
|
|
72
|
+
closedCheckouts.push({ path: realpathSync(u.worktree), number: u.number, closedAt: u.closed_at, branch: typeof u.branch === "string" ? u.branch : null });
|
|
69
73
|
}
|
|
70
|
-
return { closed, active };
|
|
74
|
+
return { closed, active, closedCheckouts };
|
|
71
75
|
}
|
|
72
76
|
export async function pruneProjectWorktrees(creds, project, cwd, protection, log) {
|
|
73
77
|
const before = await scanProject(creds, project, { cwd });
|
|
74
78
|
const units = await unitWorktrees(creds, project);
|
|
79
|
+
const linked = scanWorktrees(cwd);
|
|
80
|
+
if (!linked)
|
|
81
|
+
throw new Error("could not verify linked worktrees for harness process sweep");
|
|
82
|
+
const linkedBranches = new Map(linked.worktrees.map(worktree => [realpathSync(worktree.path), worktree.branch]));
|
|
83
|
+
await sweepClosedHarnessServers(units.closedCheckouts.filter(unit => unit.branch !== null && linkedBranches.get(unit.path) === unit.branch), units.active, protection, log);
|
|
75
84
|
const report = pruneReport(cwd, units.closed, units.active, undefined, protection);
|
|
76
85
|
const dirtyClosed = [...new Set(report.kept.flatMap((item) => {
|
|
77
86
|
const number = item.dirtyClosed ? /WU #(\d+)/.exec(item.dirtyClosed)?.[1] : undefined;
|
package/dist/container.js
CHANGED
|
@@ -179,6 +179,10 @@ export function readGitIdentity(cwd, runner = defaultRunner) {
|
|
|
179
179
|
const userEmail = emailRes.status === 0 && emailRes.stdout.trim() ? emailRes.stdout.trim() : null;
|
|
180
180
|
return { ok: Boolean(userName && userEmail), user_name: userName, user_email: userEmail };
|
|
181
181
|
}
|
|
182
|
+
export function parseContainerRuntimeVersion(stdout) {
|
|
183
|
+
const line = (stdout ?? "").split(/\r?\n/).find((item) => item.trim())?.trim() ?? "";
|
|
184
|
+
return line && !line.startsWith("{") ? line.slice(0, 120) : null;
|
|
185
|
+
}
|
|
182
186
|
function normalizeContainerArch(raw) {
|
|
183
187
|
if (!raw)
|
|
184
188
|
return null;
|
|
@@ -198,18 +202,26 @@ export function probeNestedSandbox(opts = {}) {
|
|
|
198
202
|
const readSysctl = opts.readSysctl ?? ((p) => (existsSync(p) ? readFileSync(p, "utf8").trim() : null));
|
|
199
203
|
const listDir = opts.listDir ?? ((p) => (existsSync(p) ? readdirSync(p) : []));
|
|
200
204
|
let runtime = opts.runtime ?? null;
|
|
205
|
+
let version = null;
|
|
201
206
|
if (!runtime) {
|
|
202
207
|
for (const candidate of ["podman", "docker"]) {
|
|
203
208
|
const r = runner(candidate, ["--version"]);
|
|
204
209
|
if (r.status === 0) {
|
|
205
210
|
runtime = candidate;
|
|
211
|
+
version = parseContainerRuntimeVersion(r.stdout);
|
|
206
212
|
break;
|
|
207
213
|
}
|
|
208
214
|
}
|
|
209
215
|
}
|
|
216
|
+
else {
|
|
217
|
+
const r = runner(runtime, ["--version"]);
|
|
218
|
+
if (r.status === 0)
|
|
219
|
+
version = parseContainerRuntimeVersion(r.stdout);
|
|
220
|
+
}
|
|
210
221
|
if (!runtime) {
|
|
211
222
|
return {
|
|
212
223
|
runtime: null,
|
|
224
|
+
version: null,
|
|
213
225
|
ok: false,
|
|
214
226
|
nested_sandbox_ok: false,
|
|
215
227
|
usable_without_root: false,
|
|
@@ -297,6 +309,7 @@ export function probeNestedSandbox(opts = {}) {
|
|
|
297
309
|
const ok = missing.length === 0 && usableWithoutRoot;
|
|
298
310
|
return {
|
|
299
311
|
runtime,
|
|
312
|
+
version,
|
|
300
313
|
ok,
|
|
301
314
|
nested_sandbox_ok: ok,
|
|
302
315
|
usable_without_root: usableWithoutRoot,
|
package/dist/git.js
CHANGED
|
@@ -14,6 +14,33 @@ function status(cwd, timeoutMs) {
|
|
|
14
14
|
return null;
|
|
15
15
|
return r.stdout.trim();
|
|
16
16
|
}
|
|
17
|
+
/** Local, bounded proof that a session checkout is clean and every commit is reachable from a remote. */
|
|
18
|
+
export function sessionCheckoutFacts(cwd) {
|
|
19
|
+
const statusResult = spawnSync("git", ["status", "--porcelain"], {
|
|
20
|
+
cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
|
|
21
|
+
});
|
|
22
|
+
const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], {
|
|
23
|
+
cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
|
|
24
|
+
});
|
|
25
|
+
const statusError = statusResult.error;
|
|
26
|
+
const remoteError = remoteResult.error;
|
|
27
|
+
const statusOk = statusResult.status === 0;
|
|
28
|
+
const countText = remoteResult.stdout.trim();
|
|
29
|
+
const count = remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
|
|
30
|
+
const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
|
|
31
|
+
const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
|
|
32
|
+
const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
|
|
33
|
+
const clean = statusOk ? entries.length === 0 : null;
|
|
34
|
+
const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), remoteError?.code ?? (count === null ? `git remote reachability exited ${remoteResult.status}` : null)].filter(Boolean);
|
|
35
|
+
return {
|
|
36
|
+
clean,
|
|
37
|
+
uncommitted,
|
|
38
|
+
untracked,
|
|
39
|
+
pushed: count === null ? null : count === 0,
|
|
40
|
+
unpushed_commits: count,
|
|
41
|
+
...(errors.length ? { error: errors.join("; ") } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
17
44
|
function git(args, cwd) {
|
|
18
45
|
// Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
|
|
19
46
|
// the 1 MB default made such a worktree unreadable rather than dirty.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, sep } from "node:path";
|
|
3
|
+
import { scanWorktreeProcesses } from "./machine-processes.js";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
function within(root, path) {
|
|
6
|
+
const rel = relative(root, path);
|
|
7
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
8
|
+
}
|
|
9
|
+
/** Stop only identified test servers in a verified closed and otherwise unused checkout. */
|
|
10
|
+
export async function sweepClosedHarnessServers(checkouts, active, protection, log, deps = {}) {
|
|
11
|
+
const now = deps.now ?? Date.now();
|
|
12
|
+
const scan = deps.scan ?? ((path) => scanWorktreeProcesses(path, { project_roots: [path], foreign_roots: [] }));
|
|
13
|
+
const signal = deps.signal ?? ((pid, signal) => { process.kill(pid, signal); });
|
|
14
|
+
const alive = deps.alive ?? ((pid) => {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(pid, 0);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error.code === "ESRCH")
|
|
21
|
+
return false;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
const pause = deps.pause ?? delay;
|
|
26
|
+
const attempts = deps.attempts ?? 10;
|
|
27
|
+
for (const unit of checkouts) {
|
|
28
|
+
const closed = Date.parse(unit.closedAt);
|
|
29
|
+
if (!Number.isFinite(closed) || now - closed < 30 * 60_000)
|
|
30
|
+
continue;
|
|
31
|
+
try {
|
|
32
|
+
const root = realpathSync(unit.path);
|
|
33
|
+
if (active.branches.has(unit.branch ?? "") || [...active.paths.keys()].some(path => within(root, path) || within(path, root)))
|
|
34
|
+
continue;
|
|
35
|
+
if (protection.inUse.some(use => {
|
|
36
|
+
const path = realpathSync(use.path);
|
|
37
|
+
return within(root, path) || within(path, root);
|
|
38
|
+
}))
|
|
39
|
+
continue;
|
|
40
|
+
const processes = scan(root);
|
|
41
|
+
for (const candidate of processes) {
|
|
42
|
+
if (!/(?:^|[\s/])(?:wrangler(?:\.js)?\s+dev|vite(?:\.js)?(?:\s|$)|workerd(?:\s|$))/.test(candidate.command))
|
|
43
|
+
continue;
|
|
44
|
+
const identity = () => {
|
|
45
|
+
const current = scan(root).find(p => p.pid === candidate.pid);
|
|
46
|
+
if (current)
|
|
47
|
+
return current.started_at === candidate.started_at && current.command === candidate.command && current.cwd === candidate.cwd ? "same" : "changed";
|
|
48
|
+
return alive(candidate.pid) ? "unknown" : "gone";
|
|
49
|
+
};
|
|
50
|
+
let state = identity();
|
|
51
|
+
if (state !== "same") {
|
|
52
|
+
log(`closed unit #${unit.number}: process ${candidate.pid} ${state} before signal; not stopped`);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
signal(candidate.pid, "SIGTERM");
|
|
56
|
+
for (let i = 0; i < attempts && state === "same"; i++) {
|
|
57
|
+
await pause(100);
|
|
58
|
+
state = identity();
|
|
59
|
+
}
|
|
60
|
+
if (state === "same") {
|
|
61
|
+
// The last complete scan establishes the identity immediately before escalation.
|
|
62
|
+
signal(candidate.pid, "SIGKILL");
|
|
63
|
+
for (let i = 0; i < attempts && state === "same"; i++) {
|
|
64
|
+
await pause(100);
|
|
65
|
+
state = identity();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (state === "gone")
|
|
69
|
+
log(`closed unit #${unit.number}: stopped pid ${candidate.pid}, age ${candidate.elapsed_seconds}s, command ${candidate.command}`);
|
|
70
|
+
else
|
|
71
|
+
log(`closed unit #${unit.number}: pid ${candidate.pid} exit not verified (${state}), age ${candidate.elapsed_seconds}s, command ${candidate.command}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
log(`closed unit #${unit.number}: harness process sweep could not inspect safely; no further processes stopped: ${error.message}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/harnesses.js
CHANGED
|
@@ -6,7 +6,8 @@ import { CliError } from "./errors.js";
|
|
|
6
6
|
import { configRoot } from "./config.js";
|
|
7
7
|
import { readState, writeState } from "./state.js";
|
|
8
8
|
import { codexArchivedRollout, codexRollout } from "./sessions.js";
|
|
9
|
-
import {
|
|
9
|
+
import { readTurnPhase, usageLimitUntil } from "./turn.js";
|
|
10
|
+
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
|
|
10
11
|
import { antigravityProbe } from "./antigravity.js";
|
|
11
12
|
/**
|
|
12
13
|
* Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
|
|
@@ -331,12 +332,15 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
|
|
|
331
332
|
};
|
|
332
333
|
}
|
|
333
334
|
function codexProbe(thread) {
|
|
334
|
-
const read = () => { const r = codexRollout(thread); return r ?
|
|
335
|
+
const read = () => { const r = codexRollout(thread); return r ? readTurnPhase(r) : null; };
|
|
335
336
|
return {
|
|
336
337
|
label: "Codex",
|
|
337
338
|
what: `thread ${thread}`,
|
|
338
339
|
phase() {
|
|
339
340
|
const ph = read();
|
|
341
|
+
// A reader that hit its cap without deciding never reports idle: start nothing, report unknown.
|
|
342
|
+
if (ph?.unknown)
|
|
343
|
+
return { missing: `${ph.unknown}; cannot tell whether a turn is running, so starting none`, unknown: true };
|
|
340
344
|
if (ph)
|
|
341
345
|
return { ...ph, lastErrorAt: ph.lastEventAt };
|
|
342
346
|
return {
|
|
@@ -351,17 +355,24 @@ function codexProbe(thread) {
|
|
|
351
355
|
const path = codexRollout(thread);
|
|
352
356
|
if (!path)
|
|
353
357
|
return "";
|
|
354
|
-
|
|
358
|
+
// The last 800 characters of assistant text: read from the end until that much is collected (WU #474).
|
|
359
|
+
const messages = [];
|
|
360
|
+
let collected = 0;
|
|
361
|
+
scanLinesBackward(path, (line) => {
|
|
362
|
+
let event;
|
|
355
363
|
try {
|
|
356
|
-
|
|
357
|
-
if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
|
|
358
|
-
return [];
|
|
359
|
-
const content = event.payload.message.content;
|
|
360
|
-
return typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
|
|
364
|
+
event = JSON.parse(line);
|
|
361
365
|
}
|
|
362
366
|
catch {
|
|
363
|
-
return
|
|
367
|
+
return false;
|
|
364
368
|
}
|
|
369
|
+
if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
|
|
370
|
+
return false;
|
|
371
|
+
const content = event.payload.message.content;
|
|
372
|
+
const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
|
|
373
|
+
messages.unshift(...parts);
|
|
374
|
+
collected += parts.reduce((n, t) => n + t.length + 1, 0);
|
|
375
|
+
return collected >= 800;
|
|
365
376
|
});
|
|
366
377
|
return messages.join("\n").slice(-800);
|
|
367
378
|
},
|
|
@@ -409,6 +420,37 @@ export function claudeTranscriptTimes(text) {
|
|
|
409
420
|
}
|
|
410
421
|
return { lastEventAt, promptAt };
|
|
411
422
|
}
|
|
423
|
+
/**
|
|
424
|
+
* claudeTranscriptTimes for a transcript file, read from the end to the latest user prompt (WU #474).
|
|
425
|
+
* `capped` is set when the prompt was not found within the read cap: the prompt time is then unknown.
|
|
426
|
+
*/
|
|
427
|
+
export function claudeTranscriptTimesFromFile(path, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
428
|
+
let lastEventAt = null;
|
|
429
|
+
let promptAt = null;
|
|
430
|
+
const scan = scanLinesBackward(path, (line) => {
|
|
431
|
+
let j;
|
|
432
|
+
try {
|
|
433
|
+
j = JSON.parse(line);
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
return false;
|
|
437
|
+
} // a line still being written
|
|
438
|
+
if (!j.timestamp)
|
|
439
|
+
return false;
|
|
440
|
+
if (lastEventAt === null)
|
|
441
|
+
lastEventAt = j.timestamp;
|
|
442
|
+
if (j.type === "user" && typeof j.message?.content === "string") {
|
|
443
|
+
promptAt = j.timestamp;
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
446
|
+
return false;
|
|
447
|
+
}, chunkBytes, maxBytes);
|
|
448
|
+
return scan.capped ? { lastEventAt, promptAt, capped: true } : { lastEventAt, promptAt };
|
|
449
|
+
}
|
|
450
|
+
const claudeTimesCache = new FileFactsCache();
|
|
451
|
+
function readClaudeTranscriptTimes(path) {
|
|
452
|
+
return claudeTimesCache.get(path, (p) => claudeTranscriptTimesFromFile(p));
|
|
453
|
+
}
|
|
412
454
|
/**
|
|
413
455
|
* The error a `claude -p --output-format json` run ended with, or null when it succeeded. Output
|
|
414
456
|
* that is not the result object (a missing session prints plain text) is returned as the error.
|
|
@@ -484,15 +526,18 @@ function claudeProbe(session, ref) {
|
|
|
484
526
|
const tr = claudeTranscript(session);
|
|
485
527
|
if (!tr)
|
|
486
528
|
return { missing: `no transcript for Claude Code session ${session} under ${join(claudeHome(), "projects")}; cannot tell whether a turn is running, so starting none` };
|
|
487
|
-
const times =
|
|
529
|
+
const times = readClaudeTranscriptTimes(tr);
|
|
488
530
|
// Claude Code writes no turn-ended marker, so a running turn is a process holding the session.
|
|
489
531
|
const running = sessionProcesses(session).length > 0;
|
|
532
|
+
// No process and no prompt within the read cap: the bounded read can't place the latest turn, so it never reports idle.
|
|
533
|
+
if (!running && times.capped)
|
|
534
|
+
return { missing: `no user prompt within the last ${Math.round(TAIL_MAX_BYTES / 1048576)} MB of ${tr}; cannot tell where the latest turn stands, so starting none`, unknown: true };
|
|
490
535
|
const res = lastResult();
|
|
491
536
|
return { running, startedAt: times.promptAt, lastEventAt: times.lastEventAt, lastError: running ? null : res?.error ?? null, lastErrorAt: res?.at ?? null };
|
|
492
537
|
},
|
|
493
538
|
startedSince(ms) {
|
|
494
539
|
const tr = claudeTranscript(session);
|
|
495
|
-
const p = tr ?
|
|
540
|
+
const p = tr ? readClaudeTranscriptTimes(tr).promptAt : null;
|
|
496
541
|
return !!p && Date.parse(p) >= ms - 5_000;
|
|
497
542
|
},
|
|
498
543
|
turnError: () => lastResult()?.error ?? null,
|
package/dist/help.js
CHANGED
|
@@ -258,6 +258,10 @@ Machine placement shares capacity across the account's projects: session seats a
|
|
|
258
258
|
b9s evidence info <id|sha256>
|
|
259
259
|
b9s evidence get <id|sha256> [--out path] verifies sha256 on download
|
|
260
260
|
b9s evidence verify <id> --confirmed|--refuted --note "..." named agent checks a claim; evidence authors cannot verify their own
|
|
261
|
+
b9s test-results import <junit.xml|run.json> [--metadata-file context.json] [--unit n]
|
|
262
|
+
preserve the report as test evidence, validate/import schema v1, optionally attach to a unit
|
|
263
|
+
JUnit requires context JSON (source, invocation, runner, run); JSON reports include those fields
|
|
264
|
+
b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
|
|
261
265
|
b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
|
|
262
266
|
save a RESUME or HANDOFF note, announce it, revoke this key; history stays
|
|
263
267
|
b9s handoffs [--open] [--agent a] notes left by retired agents (open = not yet picked up)
|
|
@@ -442,6 +446,8 @@ Pools (a role, variants and a count; the server names the agents and places them
|
|
|
442
446
|
slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
|
|
443
447
|
b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
|
|
444
448
|
b9s-admin pool slot stop <project>/<pool>/<slot> [--reason text] suspend one slot and stop its session
|
|
449
|
+
b9s-admin pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>]
|
|
450
|
+
verifies each source slot independently; unsafe slots stay placed with a reason
|
|
445
451
|
b9s-admin pool suggestions <project> [--status pending|accepted|rejected|superseded|all] inspect explicit non-mutating pool-weight suggestions
|
|
446
452
|
b9s-admin pool suggestion accept <project> <id> [--note "..."] apply a pending pool-weight suggestion and audit it
|
|
447
453
|
b9s-admin pool suggestion reject <project> <id> [--reason "..."] reject a pool-weight suggestion with an audit note
|
package/dist/index.js
CHANGED
|
@@ -35,6 +35,7 @@ import { agentNotice } from "./commands/notices.js";
|
|
|
35
35
|
import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
|
|
36
36
|
import { gitCredentialMain } from "./commands/git-credential.js";
|
|
37
37
|
import { templates } from "./commands/templates.js";
|
|
38
|
+
import { testResults } from "./commands/test-results.js";
|
|
38
39
|
import { environment } from "./commands/environment.js";
|
|
39
40
|
import { runCommandSafely } from "./command-runner.js";
|
|
40
41
|
const COMMANDS = {
|
|
@@ -47,6 +48,7 @@ const COMMANDS = {
|
|
|
47
48
|
resume,
|
|
48
49
|
"git-credential": async (p) => gitCredentialMain(p),
|
|
49
50
|
templates,
|
|
51
|
+
"test-results": testResults,
|
|
50
52
|
environment,
|
|
51
53
|
notice: agentNotice,
|
|
52
54
|
who: a.who,
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Reading append-only session logs (Codex rollouts, Claude Code transcripts) from the end. The daemon
|
|
4
|
+
* and the watchers need only the newest facts in these files, yet they grow for the life of a thread
|
|
5
|
+
* (120-150 MB per Codex rollout on aws1, 2026-11-17), and reading them whole every pass churned
|
|
6
|
+
* gigabytes per machine (WU #474).
|
|
7
|
+
*/
|
|
8
|
+
export const TAIL_CHUNK_BYTES = 256 * 1024;
|
|
9
|
+
/** How far back a per-pass reader may look (WU #474 scope: a hard cap). Past it the answer is "unknown", never "idle". */
|
|
10
|
+
export const TAIL_MAX_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
/** Counts scans and bytes read, so tests can prove an unchanged file is not read again and a scan stops at its cap. */
|
|
12
|
+
export const tailReadStats = { scans: 0, bytes: 0 };
|
|
13
|
+
/**
|
|
14
|
+
* Calls `visit` with each complete line of the file from the last to the first, until it returns true
|
|
15
|
+
* (stop), the file's start is reached, or `maxBytes` have been read (then `capped` is true and the
|
|
16
|
+
* piece of a line cut by the cap is never visited). Lines split on the newline byte, which never occurs
|
|
17
|
+
* inside a multi-byte UTF-8 sequence, so decoding each line separately is exact. A final line without a
|
|
18
|
+
* newline is still visited (a writer may be mid-line; callers skip what doesn't parse, as the full reads
|
|
19
|
+
* did). A single line longer than the cap is never assembled: memory stays within the cap.
|
|
20
|
+
*/
|
|
21
|
+
export function scanLinesBackward(path, visit, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
22
|
+
const fd = openSync(path, "r");
|
|
23
|
+
tailReadStats.scans++;
|
|
24
|
+
let bytesRead = 0;
|
|
25
|
+
try {
|
|
26
|
+
let pos = fstatSync(fd).size;
|
|
27
|
+
let carry = Buffer.alloc(0);
|
|
28
|
+
while (pos > 0) {
|
|
29
|
+
if (bytesRead >= maxBytes)
|
|
30
|
+
return { bytesRead, capped: true };
|
|
31
|
+
const start = Math.max(0, pos - Math.min(chunkBytes, maxBytes - bytesRead));
|
|
32
|
+
const chunk = Buffer.alloc(pos - start);
|
|
33
|
+
let got = 0;
|
|
34
|
+
while (got < chunk.length) {
|
|
35
|
+
const n = readSync(fd, chunk, got, chunk.length - got, start + got);
|
|
36
|
+
if (n === 0)
|
|
37
|
+
break;
|
|
38
|
+
got += n;
|
|
39
|
+
}
|
|
40
|
+
bytesRead += got;
|
|
41
|
+
tailReadStats.bytes += got;
|
|
42
|
+
const data = carry.length ? Buffer.concat([chunk.subarray(0, got), carry]) : chunk.subarray(0, got);
|
|
43
|
+
let end = data.length;
|
|
44
|
+
// Walk newline positions from the end; the piece before the first newline may continue in the previous chunk.
|
|
45
|
+
for (let i = data.length - 1; i >= 0; i--) {
|
|
46
|
+
if (data[i] !== 0x0a)
|
|
47
|
+
continue;
|
|
48
|
+
if (end > i + 1 && visit(data.subarray(i + 1, end).toString("utf8")))
|
|
49
|
+
return { bytesRead, capped: false };
|
|
50
|
+
end = i;
|
|
51
|
+
}
|
|
52
|
+
carry = Buffer.from(data.subarray(0, end));
|
|
53
|
+
pos = start;
|
|
54
|
+
}
|
|
55
|
+
if (carry.length && visit(carry.toString("utf8")))
|
|
56
|
+
return { bytesRead, capped: false };
|
|
57
|
+
return { bytesRead, capped: false };
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Results computed from a file, reused while the file's identity (device, inode), size and mtime are unchanged. */
|
|
64
|
+
export class FileFactsCache {
|
|
65
|
+
max;
|
|
66
|
+
entries = new Map();
|
|
67
|
+
constructor(max = 256) {
|
|
68
|
+
this.max = max;
|
|
69
|
+
}
|
|
70
|
+
get(path, compute) {
|
|
71
|
+
const fd = openSync(path, "r");
|
|
72
|
+
let key;
|
|
73
|
+
try {
|
|
74
|
+
const s = fstatSync(fd, { bigint: true });
|
|
75
|
+
key = `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}`;
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
closeSync(fd);
|
|
79
|
+
}
|
|
80
|
+
const hit = this.entries.get(path);
|
|
81
|
+
if (hit && hit.key === key)
|
|
82
|
+
return hit.value;
|
|
83
|
+
const value = compute(path);
|
|
84
|
+
this.entries.delete(path);
|
|
85
|
+
this.entries.set(path, { key, value });
|
|
86
|
+
if (this.entries.size > this.max)
|
|
87
|
+
this.entries.delete(this.entries.keys().next().value);
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
}
|