benignswarm 0.12.110 → 0.12.112
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/antigravity.js +3 -1
- package/dist/client.js +2 -2
- package/dist/commands/install.js +77 -13
- package/dist/commands/join.js +3 -5
- package/dist/commands/lists.js +2 -2
- package/dist/commands/machine-admin.js +5 -2
- package/dist/commands/machine.js +176 -34
- package/dist/commands/watch.js +3 -3
- package/dist/commands/worktrees.js +11 -2
- package/dist/commands/wu.js +4 -2
- package/dist/git.js +57 -4
- package/dist/harness-server-sweep.js +78 -0
- package/dist/harnesses.js +57 -12
- package/dist/help.js +3 -0
- package/dist/install.js +122 -24
- package/dist/lock.js +2 -1
- package/dist/log-rotation.js +65 -0
- package/dist/tail-lines.js +90 -0
- package/dist/turn.js +51 -2
- package/dist/usage.js +48 -12
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/commands/machine.js
CHANGED
|
@@ -1,25 +1,27 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
|
|
3
|
+
import { rotateLogs } from "../log-rotation.js";
|
|
2
4
|
import { createHash, createHmac } from "node:crypto";
|
|
3
5
|
import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
6
|
import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
|
|
5
7
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
8
|
import { str } from "../args.js";
|
|
7
9
|
import { Client } from "../client.js";
|
|
8
|
-
import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
10
|
+
import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
9
11
|
import { CliError } from "../errors.js";
|
|
10
12
|
import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
11
13
|
import { applySparse, sessionCheckoutFacts } from "../git.js";
|
|
12
14
|
import { drainingUntil, writeMaintenance } from "../maintenance.js";
|
|
13
|
-
import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
15
|
+
import { TURN_HARNESSES, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
14
16
|
import { readState, writeState } from "../state.js";
|
|
15
|
-
import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
17
|
+
import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
16
18
|
import { CLI_VERSION } from "../version.js";
|
|
17
19
|
import { probeCapabilities } from "../capabilities.js";
|
|
18
20
|
import { diskSpaceNotice } from "../notices.js";
|
|
19
21
|
import { verifyClaudeProvider } from "../providers.js";
|
|
20
22
|
import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
|
|
21
23
|
import { defaultWorkspaceWritableRoots } from "../start-options.js";
|
|
22
|
-
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
|
|
24
|
+
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
|
|
23
25
|
import { bootTimeMs } from "../boot-time.js";
|
|
24
26
|
import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
|
|
25
27
|
import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
|
|
@@ -852,6 +854,9 @@ export async function launchDesiredSession(opts) {
|
|
|
852
854
|
return { status: 1, stdout: "", stderr: `timed out waiting for in-container b9s start (${containerName})` };
|
|
853
855
|
}
|
|
854
856
|
/** One pass: make what runs here match what the operator declared, then report. */
|
|
857
|
+
/** Service logs are rotated by the daemon (WU #481), checked at most this often. */
|
|
858
|
+
const LOG_ROTATION_EVERY_MS = 10 * 60_000;
|
|
859
|
+
let lastLogRotationAt = 0;
|
|
855
860
|
export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
856
861
|
const client = Client.raw(m.url, m.key, {
|
|
857
862
|
requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
|
|
@@ -860,6 +865,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
860
865
|
? `request start ${event.method} ${event.path}`
|
|
861
866
|
: `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
|
|
862
867
|
});
|
|
868
|
+
if (Date.now() - lastLogRotationAt >= LOG_ROTATION_EVERY_MS) {
|
|
869
|
+
lastLogRotationAt = Date.now();
|
|
870
|
+
for (const r of rotateLogs(join(configRoot(), "logs")))
|
|
871
|
+
log(`rotated ${r.file}: ${Math.round(r.bytes_before / 1048576)} MB, kept the newest ${Math.round(r.kept_bytes / 1048576)} MB as ${r.file}.1`);
|
|
872
|
+
}
|
|
863
873
|
const me = await client.call("GET", "/machines/me");
|
|
864
874
|
const desired = me.sessions;
|
|
865
875
|
const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
|
|
@@ -1182,7 +1192,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1182
1192
|
dir: s.dir,
|
|
1183
1193
|
thread: th,
|
|
1184
1194
|
watcher: watcherState,
|
|
1185
|
-
last_turn:
|
|
1195
|
+
...((t) => ({ last_turn: t.line, ...(t.unknown_reason ? { last_turn_unknown: t.unknown_reason } : {}) }))(lastTurn(s.agent)),
|
|
1186
1196
|
turn_judgment: s.turn_judgment ?? null,
|
|
1187
1197
|
...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
|
|
1188
1198
|
...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
|
|
@@ -1626,7 +1636,7 @@ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
|
|
|
1626
1636
|
const ph = thread ? probeFor(harness, thread, agent).phase() : null;
|
|
1627
1637
|
const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
|
|
1628
1638
|
if (!thread || !ph || "missing" in ph)
|
|
1629
|
-
return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
|
|
1639
|
+
return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
|
|
1630
1640
|
const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
|
|
1631
1641
|
const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
|
|
1632
1642
|
const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
|
|
@@ -1661,16 +1671,37 @@ export function turnProcess(thread, harness = "codex", psOutput, agent) {
|
|
|
1661
1671
|
*/
|
|
1662
1672
|
const CRASH_STARTS = 5;
|
|
1663
1673
|
const CRASH_WINDOW_MS = 5 * 60_000;
|
|
1664
|
-
|
|
1674
|
+
/**
|
|
1675
|
+
* The last 64 KiB of a watcher's error log. Log rotation (WU #481) can empty the live file; then the
|
|
1676
|
+
* rotated <name>.1 supplies the rest of the window, from a line start, so a fault the guards look for
|
|
1677
|
+
* (a directory_conflict marker, a crash loop) is still seen on the pass right after a rotation.
|
|
1678
|
+
*/
|
|
1679
|
+
export function watcherLogText(ref) {
|
|
1665
1680
|
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
1666
1681
|
if (!existsSync(f))
|
|
1667
1682
|
return null;
|
|
1668
|
-
const
|
|
1669
|
-
const
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1683
|
+
const WINDOW = 65_536;
|
|
1684
|
+
const tail = (path, max) => {
|
|
1685
|
+
const size = statSync(path).size;
|
|
1686
|
+
const fd = openSync(path, "r");
|
|
1687
|
+
try {
|
|
1688
|
+
const buf = Buffer.alloc(Math.min(size, max));
|
|
1689
|
+
readSync(fd, buf, 0, buf.length, size - buf.length);
|
|
1690
|
+
return buf;
|
|
1691
|
+
}
|
|
1692
|
+
finally {
|
|
1693
|
+
closeSync(fd);
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
const live = tail(f, WINDOW);
|
|
1697
|
+
const rotated = `${f}.1`;
|
|
1698
|
+
if (live.length >= WINDOW || !existsSync(rotated))
|
|
1699
|
+
return live.toString("utf8");
|
|
1700
|
+
let earlier = tail(rotated, WINDOW - live.length);
|
|
1701
|
+
const nl = earlier.indexOf(0x0a);
|
|
1702
|
+
if (statSync(rotated).size > earlier.length && nl >= 0)
|
|
1703
|
+
earlier = earlier.subarray(nl + 1); // start at a whole line
|
|
1704
|
+
return Buffer.concat([earlier, live]).toString("utf8");
|
|
1674
1705
|
}
|
|
1675
1706
|
/** A marked startup failure is unambiguous even when it prevents the first watching banner. */
|
|
1676
1707
|
export function watcherDirectoryConflict(ref, logText) {
|
|
@@ -1736,12 +1767,44 @@ export function watcherFault(ref, logText, nowMs = Date.now()) {
|
|
|
1736
1767
|
}
|
|
1737
1768
|
}
|
|
1738
1769
|
/** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
|
|
1739
|
-
|
|
1770
|
+
const TURN_LINE = (l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l);
|
|
1771
|
+
const lastTurnCache = new FileFactsCache();
|
|
1772
|
+
/**
|
|
1773
|
+
* The latest turn line of a watcher log, read from the end (WU #481: the whole-file read ran per session
|
|
1774
|
+
* per pass over logs up to 190 MB). Within the cap it equals the whole-file answer; past it, line is null
|
|
1775
|
+
* and unknown_reason says why, so no diagnostic text is ever reported as a turn line.
|
|
1776
|
+
*/
|
|
1777
|
+
export function lastTurnFromFile(f, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
1778
|
+
let found = null;
|
|
1779
|
+
const visit = (l) => { if (TURN_LINE(l)) {
|
|
1780
|
+
found = l.slice(0, 300);
|
|
1781
|
+
return true;
|
|
1782
|
+
} return false; };
|
|
1783
|
+
const scan = scanLinesBackward(f, visit, chunkBytes, maxBytes);
|
|
1784
|
+
let read = scan.bytesRead;
|
|
1785
|
+
let capped = scan.capped;
|
|
1786
|
+
// A rotation (WU #481) may have moved the latest turn line into <name>.1 and left the live log short:
|
|
1787
|
+
// continue there with what is left of the same cap, so rotation never hides the latest turn.
|
|
1788
|
+
const rotated = `${f}.1`;
|
|
1789
|
+
if (found === null && !capped && existsSync(rotated) && statSync(rotated).size > 0) {
|
|
1790
|
+
if (read < maxBytes) {
|
|
1791
|
+
const more = scanLinesBackward(rotated, visit, chunkBytes, maxBytes - read);
|
|
1792
|
+
read += more.bytesRead;
|
|
1793
|
+
capped = more.capped;
|
|
1794
|
+
}
|
|
1795
|
+
else {
|
|
1796
|
+
capped = true; // the budget ended exactly at the live log's start; the rotated bytes went unread
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
if (found !== null)
|
|
1800
|
+
return { line: found };
|
|
1801
|
+
return capped ? { line: null, unknown_reason: `no turn line in the last ${Math.round(maxBytes / 1048576)} MB of the watcher log` } : { line: null };
|
|
1802
|
+
}
|
|
1803
|
+
export function lastTurn(ref) {
|
|
1740
1804
|
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
1741
1805
|
if (!existsSync(f))
|
|
1742
|
-
return null;
|
|
1743
|
-
|
|
1744
|
-
return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
|
|
1806
|
+
return { line: null };
|
|
1807
|
+
return lastTurnCache.get(f, (path) => lastTurnFromFile(path));
|
|
1745
1808
|
}
|
|
1746
1809
|
function volumeSpace(path, label) {
|
|
1747
1810
|
try {
|
|
@@ -1809,6 +1872,16 @@ function antigravityUsernsDenied(parsed, output) {
|
|
|
1809
1872
|
const denied = value?.denied_actions ?? error?.denied_actions;
|
|
1810
1873
|
return /Terminal sandbox unavailable/i.test(output) || (Array.isArray(denied) && denied.some((entry) => entry && typeof entry === "object" && entry.action === "command"));
|
|
1811
1874
|
}
|
|
1875
|
+
/** Resolve an authenticated identity before the probe moves into its fresh temporary cwd. */
|
|
1876
|
+
function antigravityProbeAgent(sessions = [], cwd = process.cwd()) {
|
|
1877
|
+
const session = sessions.find((item) => item.harness === "antigravity") ?? sessions[0];
|
|
1878
|
+
try {
|
|
1879
|
+
return resolveAgentName(session?.agent ?? process.env.BSCHAT_AGENT?.trim(), process.env, cwd);
|
|
1880
|
+
}
|
|
1881
|
+
catch {
|
|
1882
|
+
return null;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1812
1885
|
/** Install only an absent or byte-identical b9s profile; leave every other owner untouched. */
|
|
1813
1886
|
export function installAgyAppArmorProfile(binary, profilePath = AGY_APPARMOR_PATH, run = (args, input) => spawnSync("sudo", args, { input, encoding: "utf8", stdio: input === undefined ? "pipe" : ["pipe", "ignore", "pipe"] })) {
|
|
1814
1887
|
const profile = agyAppArmorProfile(binary);
|
|
@@ -1838,13 +1911,38 @@ function resolvedAgyBinary(path) {
|
|
|
1838
1911
|
const binary = result.status === 0 ? (result.stdout ?? "").trim() : "";
|
|
1839
1912
|
return isAbsolute(binary) ? binary : null;
|
|
1840
1913
|
}
|
|
1841
|
-
/** Runs one cached
|
|
1842
|
-
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
1843
|
-
if (
|
|
1914
|
+
/** Runs one cached authenticated API check through Antigravity's real workspace-write terminal sandbox. */
|
|
1915
|
+
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
|
|
1916
|
+
if (agent) {
|
|
1917
|
+
try {
|
|
1918
|
+
agent = resolveAgentName(agent, process.env, process.cwd());
|
|
1919
|
+
}
|
|
1920
|
+
catch {
|
|
1921
|
+
agent = null;
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
if (!agent) {
|
|
1925
|
+
const result = { ok: false, error: "authenticated sandbox probe has no project-agent identity; set BSCHAT_AGENT or run from a checkout with a b9s identity" };
|
|
1926
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
|
|
1927
|
+
return result;
|
|
1928
|
+
}
|
|
1929
|
+
let credentialFingerprint;
|
|
1930
|
+
try {
|
|
1931
|
+
const credentials = loadAgent(agent);
|
|
1932
|
+
if (agentRef(credentials) !== agent)
|
|
1933
|
+
throw new Error("saved identity does not match the selected agent");
|
|
1934
|
+
credentialFingerprint = createHash("sha256").update(credentials.key).digest("hex");
|
|
1935
|
+
}
|
|
1936
|
+
catch {
|
|
1937
|
+
const result = { ok: false, error: `authenticated sandbox probe cannot resolve saved credentials for ${agent} from the machine's b9s home` };
|
|
1938
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
|
|
1939
|
+
return result;
|
|
1940
|
+
}
|
|
1941
|
+
if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && agySandboxCache.agent === agent && agySandboxCache.credentialFingerprint === credentialFingerprint && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
|
|
1844
1942
|
return agySandboxCache.result;
|
|
1845
1943
|
if (!b9sBin) {
|
|
1846
1944
|
const result = { ok: false, error: `recorded b9s install is unavailable; expected ${join(configRoot(), "install.json")}` };
|
|
1847
|
-
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
1945
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
|
|
1848
1946
|
return result;
|
|
1849
1947
|
}
|
|
1850
1948
|
let result;
|
|
@@ -1852,11 +1950,19 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
1852
1950
|
try {
|
|
1853
1951
|
work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
|
|
1854
1952
|
const marker = join(work, ".b9s-sandbox-probe");
|
|
1953
|
+
const meOutputPath = join(work, ".b9s-sandbox-probe-me");
|
|
1954
|
+
const meErrorPath = join(work, ".b9s-sandbox-probe-me-error");
|
|
1955
|
+
const meStatusPath = join(work, ".b9s-sandbox-probe-status");
|
|
1855
1956
|
const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
|
|
1856
|
-
const
|
|
1957
|
+
const quotedMeOutput = `'${meOutputPath.replace(/'/g, `'\\''`)}'`;
|
|
1958
|
+
const quotedMeError = `'${meErrorPath.replace(/'/g, `'\\''`)}'`;
|
|
1959
|
+
const quotedMeStatus = `'${meStatusPath.replace(/'/g, `'\\''`)}'`;
|
|
1960
|
+
const command = `b9s me > ${quotedMeOutput} 2> ${quotedMeError}; me_status=$?; printf '%s' "$me_status" > ${quotedMeStatus}; if [ "$me_status" -eq 0 ]; then printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}; fi`;
|
|
1961
|
+
const prompt = `Use your terminal tool once to run this exact command and do not replace or simulate its output: ${command}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
|
|
1857
1962
|
const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
|
|
1858
1963
|
const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
|
|
1859
|
-
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
|
|
1964
|
+
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
|
|
1965
|
+
env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
|
|
1860
1966
|
});
|
|
1861
1967
|
const parsed = parseAntigravityJson(r.stdout ?? "");
|
|
1862
1968
|
let wroteMarker = false;
|
|
@@ -1864,22 +1970,39 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
1864
1970
|
wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
|
|
1865
1971
|
}
|
|
1866
1972
|
catch { /* a missing marker means the sandbox command did not run */ }
|
|
1973
|
+
let meOutput = "";
|
|
1974
|
+
let meError = "";
|
|
1975
|
+
let meStatus = "";
|
|
1976
|
+
try {
|
|
1977
|
+
meOutput = readFileSync(meOutputPath, "utf8");
|
|
1978
|
+
}
|
|
1979
|
+
catch { /* missing output means b9s me did not run */ }
|
|
1980
|
+
try {
|
|
1981
|
+
meError = readFileSync(meErrorPath, "utf8");
|
|
1982
|
+
}
|
|
1983
|
+
catch { /* missing stderr means b9s me did not run */ }
|
|
1984
|
+
try {
|
|
1985
|
+
meStatus = readFileSync(meStatusPath, "utf8");
|
|
1986
|
+
}
|
|
1987
|
+
catch { /* missing status means b9s me did not run */ }
|
|
1988
|
+
const authenticatedMe = meStatus === "0" && /^agent:\s+\S+/m.test(meOutput);
|
|
1989
|
+
const meDiagnostic = meError.trim().replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/(https?:\/\/)[^/\s@]+@/gi, "$1[redacted]@").slice(0, 300);
|
|
1867
1990
|
const output = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
|
|
1868
|
-
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
|
|
1991
|
+
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker && authenticatedMe
|
|
1869
1992
|
? { ok: true, error: null }
|
|
1870
1993
|
: { ok: false, error: antigravityUsernsDenied(parsed, output)
|
|
1871
1994
|
? AGY_USERNS_FIX
|
|
1872
|
-
: `sandbox
|
|
1995
|
+
: `sandbox authenticated API check failed (b9s me exit ${meStatus || "unknown"}; agy exit ${r.status ?? "unknown"})${meDiagnostic ? `: ${meDiagnostic}` : meOutput && !authenticatedMe ? `: ${meOutput.trim().slice(0, 300)}` : ""}; verify the API host is allowed and the recorded b9s install ${b9sBin} and Node runtime ${process.execPath} are usable inside the sandbox` };
|
|
1873
1996
|
}
|
|
1874
1997
|
catch (error) {
|
|
1875
1998
|
const detail = error instanceof Error ? error.message : String(error);
|
|
1876
|
-
result = { ok: false, error: `sandbox could not prepare b9s
|
|
1999
|
+
result = { ok: false, error: `sandbox could not prepare authenticated b9s me probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
|
|
1877
2000
|
}
|
|
1878
2001
|
finally {
|
|
1879
2002
|
if (work)
|
|
1880
2003
|
rmSync(work, { recursive: true, force: true });
|
|
1881
2004
|
}
|
|
1882
|
-
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
2005
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
|
|
1883
2006
|
return result;
|
|
1884
2007
|
}
|
|
1885
2008
|
function antigravityLoginFacts(path) {
|
|
@@ -1896,11 +2019,11 @@ function antigravityLoginFacts(path) {
|
|
|
1896
2019
|
};
|
|
1897
2020
|
}
|
|
1898
2021
|
/** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
|
|
1899
|
-
export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
2022
|
+
export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
|
|
1900
2023
|
const facts = antigravityLoginFacts(path);
|
|
1901
2024
|
return {
|
|
1902
2025
|
...facts,
|
|
1903
|
-
sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
|
|
2026
|
+
sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin, agent) : null,
|
|
1904
2027
|
};
|
|
1905
2028
|
}
|
|
1906
2029
|
/** Linux's MemAvailable; Darwin is supplied by vm_stat, never approximated by free pages. */
|
|
@@ -1913,12 +2036,24 @@ function memAvailable() {
|
|
|
1913
2036
|
}
|
|
1914
2037
|
return platform() === "darwin" ? null : freemem();
|
|
1915
2038
|
}
|
|
2039
|
+
/**
|
|
2040
|
+
* On a headless Mac, a Claude Code sign-in kept in the login keychain can't be read, and 'claude auth status'
|
|
2041
|
+
* then reports no stored login, which looks the same as never having signed in. The observed status is kept;
|
|
2042
|
+
* when it is "not logged in" there, with no file credential, the report adds the keychain as a possible cause
|
|
2043
|
+
* and its fix as a readiness gap (WU #478). A rejected stored login or any other failure is left as observed.
|
|
2044
|
+
*/
|
|
2045
|
+
export function claudeKeychainGap(f, headlessMac, fileCredentials) {
|
|
2046
|
+
if (!headlessMac || fileCredentials || f.logged_in || f.login !== "not logged in")
|
|
2047
|
+
return f;
|
|
2048
|
+
return { ...f, readiness_gap: "possible cause: this Mac has no desktop session, and a Claude Code sign-in kept in the login keychain can't be read without one. If Claude Code is signed in at the desktop, sign in there (or enable automatic sign-in), or store a file credential with 'claude setup-token'" };
|
|
2049
|
+
}
|
|
1916
2050
|
/** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
|
|
1917
2051
|
let claudeSandboxCache = null;
|
|
1918
2052
|
function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
|
|
1919
|
-
const
|
|
1920
|
-
if (!
|
|
2053
|
+
const found = claudeFacts(undefined, path);
|
|
2054
|
+
if (!found)
|
|
1921
2055
|
return null;
|
|
2056
|
+
const f = claudeKeychainGap(found, process.platform === "darwin" && launchdSessionNow() === "headless", existsSync(join(claudeHome(), ".credentials.json")));
|
|
1922
2057
|
if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
|
|
1923
2058
|
claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
|
|
1924
2059
|
const providers = {};
|
|
@@ -1945,7 +2080,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1945
2080
|
return codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null;
|
|
1946
2081
|
})();
|
|
1947
2082
|
const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
|
|
1948
|
-
const
|
|
2083
|
+
const probeAgent = antigravityProbeAgent(sessions);
|
|
2084
|
+
const antigravity = probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
|
|
1949
2085
|
const homeSpace = volumeSpace(homedir(), "home");
|
|
1950
2086
|
const readTelemetryFile = (path) => { try {
|
|
1951
2087
|
return readFileSync(path, "utf8");
|
|
@@ -1987,6 +2123,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1987
2123
|
booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
|
|
1988
2124
|
booted_at_exact: bootedAt === null ? null : new Date(bootedAt).toISOString(),
|
|
1989
2125
|
daemon_path: path,
|
|
2126
|
+
// macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
|
|
2127
|
+
...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
|
|
1990
2128
|
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
1991
2129
|
git_identity: gitIdentity,
|
|
1992
2130
|
on_ec2: onEc2,
|
|
@@ -2122,6 +2260,8 @@ export function prepare(opts = {}) {
|
|
|
2122
2260
|
const daemonPath = machineDaemonPath();
|
|
2123
2261
|
const daemonEnv = { ...process.env, PATH: daemonPath };
|
|
2124
2262
|
steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
|
|
2263
|
+
if (platform() === "darwin")
|
|
2264
|
+
steps.push({ step: "launchd", result: "ok", detail: launchdGuidance() });
|
|
2125
2265
|
if (platform() === "darwin")
|
|
2126
2266
|
steps.push(...macReadinessSteps(macReadiness({ path: daemonPath })).map((step) => ({ ...step, result: step.result })));
|
|
2127
2267
|
const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
|
|
@@ -2611,7 +2751,8 @@ export async function machine(p, out) {
|
|
|
2611
2751
|
const bin = requireInstall().bin;
|
|
2612
2752
|
const daemonPath = machineDaemonPath();
|
|
2613
2753
|
const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: daemonPath, HOME: homedir() }, "machine");
|
|
2614
|
-
|
|
2754
|
+
const launchd = process.platform === "darwin" ? { ...launchdFacts(), guidance: launchdGuidance() } : null;
|
|
2755
|
+
return out.print([`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run with PATH ${daemonPath}. Logs: ~/.b9s/logs/machine.*.log`, ...(launchd ? [launchd.guidance] : [])].join("\n"), { path, label: MACHINE_LABEL, daemon_path: daemonPath, ...(launchd ? { launchd } : {}) });
|
|
2615
2756
|
}
|
|
2616
2757
|
const m = loadMachine();
|
|
2617
2758
|
const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
|
|
@@ -2623,7 +2764,8 @@ export async function machine(p, out) {
|
|
|
2623
2764
|
const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
|
|
2624
2765
|
return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
|
|
2625
2766
|
});
|
|
2626
|
-
|
|
2767
|
+
const launchd = process.platform === "darwin" ? launchdFacts() : null;
|
|
2768
|
+
return out.print([`machine ${m.name} (${m.url})`, ...(launchd ? [launchdFactsLine(launchd)] : []), ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state, ...(launchd ? { launchd } : {}) });
|
|
2627
2769
|
}
|
|
2628
2770
|
if (sub === "once") {
|
|
2629
2771
|
const r = await reconcile(m, log);
|
package/dist/commands/watch.js
CHANGED
|
@@ -4,7 +4,7 @@ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTu
|
|
|
4
4
|
import { drainingUntil } from "../maintenance.js";
|
|
5
5
|
import { probeFor, turnHarness } from "../harnesses.js";
|
|
6
6
|
import { applyAck } from "./wake.js";
|
|
7
|
-
import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
7
|
+
import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
8
8
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
10
|
import { homedir, userInfo } from "node:os";
|
|
@@ -1369,7 +1369,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
1369
1369
|
<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
|
|
1370
1370
|
<key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
|
|
1371
1371
|
<key>RunAtLoad</key><true/>
|
|
1372
|
-
<key>KeepAlive</key><true
|
|
1372
|
+
<key>KeepAlive</key><true/>${launchdSessionTypeXml()}
|
|
1373
1373
|
<key>StandardOutPath</key><string>${join(logDir, `watch.${slug}.out.log`)}</string>
|
|
1374
1374
|
<key>StandardErrorPath</key><string>${join(logDir, `watch.${slug}.err.log`)}</string>
|
|
1375
1375
|
</dict></plist>
|
|
@@ -1383,7 +1383,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
1383
1383
|
const sess = sessionOfExec(exec);
|
|
1384
1384
|
if (sess)
|
|
1385
1385
|
bindSession(sess.kind, sess.id, name);
|
|
1386
|
-
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout
|
|
1386
|
+
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout ${plistLaunchdDomain(path)}/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
|
|
1387
1387
|
}
|
|
1388
1388
|
export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
|
|
1389
1389
|
function escapeXml(s) {
|
|
@@ -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;
|
|
@@ -195,7 +204,7 @@ export async function scanProject(creds, project, options = {}) {
|
|
|
195
204
|
const scan = scanWorktrees(options.cwd ?? process.cwd(), options);
|
|
196
205
|
if (!scan)
|
|
197
206
|
throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
|
|
198
|
-
const machine =
|
|
207
|
+
const machine = defaultMachine();
|
|
199
208
|
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
200
209
|
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
201
210
|
options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
|
package/dist/commands/wu.js
CHANGED
|
@@ -8,7 +8,7 @@ import { readState, writeState } from "../state.js";
|
|
|
8
8
|
import { codexRollout, sessionsOf } from "../sessions.js";
|
|
9
9
|
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
|
|
10
10
|
import { CliError, WrittenReceiptMismatchError } from "../errors.js";
|
|
11
|
-
import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
11
|
+
import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
12
12
|
import { join, resolve } from "node:path";
|
|
13
13
|
import { table } from "../output.js";
|
|
14
14
|
import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
|
|
@@ -1608,9 +1608,11 @@ export async function lock(p, out) {
|
|
|
1608
1608
|
out.print(r.lock.holder_name ? `${lockName} released; now held by ${r.lock.holder_name}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}.` : `${lockName} released; free.`, r);
|
|
1609
1609
|
return;
|
|
1610
1610
|
}
|
|
1611
|
+
if (str(p.flags, "machine") !== undefined)
|
|
1612
|
+
throw new CliError("usage", "lock acquisition is scoped to the host running the CLI; --machine is only for unlock");
|
|
1611
1613
|
const unit = str(p.flags, "unit");
|
|
1612
1614
|
// Scoped to this machine unless --shared: the resource is this box's CPU and disk.
|
|
1613
|
-
const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared"), machine:
|
|
1615
|
+
const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared"), machine: defaultMachine() });
|
|
1614
1616
|
out.print(r.maintenance
|
|
1615
1617
|
? `${lockName} is not handed out now: ${r.maintenance}. You are #${r.position} in line and will be @mentioned when it is yours after the window; do not poll. Leave the queue: b9s unlock ${lockName}`
|
|
1616
1618
|
: r.acquired
|
package/dist/git.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
1
|
+
import { copyFileSync, existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
4
|
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
5
5
|
import { CliError } from "./errors.js";
|
|
6
|
+
import { configDirectory } from "./directories.js";
|
|
6
7
|
export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
|
|
7
8
|
function status(cwd, timeoutMs) {
|
|
8
9
|
const r = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
|
|
@@ -108,9 +109,61 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
|
108
109
|
});
|
|
109
110
|
return { repo, worktrees };
|
|
110
111
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
112
|
+
function registeredMachineLabel(env) {
|
|
113
|
+
let path;
|
|
114
|
+
try {
|
|
115
|
+
path = join(configDirectory(env), "machine.json");
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
const detail = error instanceof Error ? `: ${error.message}` : "";
|
|
119
|
+
throw new CliError("machine_identity_unavailable", `cannot resolve the machine registration directory${detail}; fix the .bschat/.b9s directory conflict before using host-scoped locks or status`);
|
|
120
|
+
}
|
|
121
|
+
let raw;
|
|
122
|
+
try {
|
|
123
|
+
raw = readFileSync(path, "utf8");
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const code = error.code;
|
|
127
|
+
if (code === "ENOENT") {
|
|
128
|
+
try {
|
|
129
|
+
lstatSync(path);
|
|
130
|
+
}
|
|
131
|
+
catch (statError) {
|
|
132
|
+
if (statError.code === "ENOENT")
|
|
133
|
+
return undefined;
|
|
134
|
+
throw new CliError("machine_identity_unavailable", `cannot inspect machine registration ${path}; fix its permissions or path before using host-scoped locks or status`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new CliError("machine_identity_unavailable", `cannot read machine registration ${path} (${code ?? "unknown error"}); fix its permissions or registration before using host-scoped locks or status`);
|
|
138
|
+
}
|
|
139
|
+
let value;
|
|
140
|
+
try {
|
|
141
|
+
value = JSON.parse(raw);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
throw new CliError("machine_identity_unavailable", `machine registration ${path} is malformed; repair or remove it only if this host is unregistered before using host-scoped locks or status`);
|
|
145
|
+
}
|
|
146
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.name !== "string" || !value.name.trim()) {
|
|
147
|
+
throw new CliError("machine_identity_unavailable", `machine registration ${path} has no valid name; repair or remove it only if this host is unregistered before using host-scoped locks or status`);
|
|
148
|
+
}
|
|
149
|
+
return value.name.trim();
|
|
150
|
+
}
|
|
151
|
+
/** The machine shared by every CLI identity running on this host. Saved agent machine fields are not identity. */
|
|
152
|
+
export function defaultMachine(label, env = process.env, host = hostname()) {
|
|
153
|
+
const h = host.trim();
|
|
154
|
+
const registered = registeredMachineLabel(env);
|
|
155
|
+
const resolvedLabel = registered ?? label?.trim();
|
|
156
|
+
return resolvedLabel ? `${h}/${resolvedLabel}` : h;
|
|
157
|
+
}
|
|
158
|
+
/** Use the current host for status and locks; retain a copied identity's machine field only as a diagnostic label. */
|
|
159
|
+
const warnedMachineMismatches = new Set();
|
|
160
|
+
export function machineIdentityForAgent(savedMachine, env = process.env, host = hostname(), warn = (line) => process.stderr.write(`${line}\n`)) {
|
|
161
|
+
const current = defaultMachine(undefined, env, host);
|
|
162
|
+
if (savedMachine && savedMachine !== current && !warnedMachineMismatches.has(`${savedMachine}\0${current}`)) {
|
|
163
|
+
warnedMachineMismatches.add(`${savedMachine}\0${current}`);
|
|
164
|
+
warn(`[b9s] saved machine label "${savedMachine}" differs from this host "${current}"; using the host identity`);
|
|
165
|
+
}
|
|
166
|
+
return current;
|
|
114
167
|
}
|
|
115
168
|
/** True when `ancestor` is reachable from `ref` in the repo at cwd; null when either is unknown to git. */
|
|
116
169
|
export function isAncestor(ancestor, ref, cwd = process.cwd()) {
|
|
@@ -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
|
+
}
|