benignswarm 0.12.143 → 0.12.145
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 +44 -5
- package/dist/client.js +3 -1
- package/dist/commands/admin.js +18 -0
- package/dist/commands/agent.js +2 -0
- package/dist/commands/codex-start.js +12 -8
- package/dist/commands/join.js +1 -0
- package/dist/commands/machine-admin.js +6 -1
- package/dist/commands/machine.js +10 -1
- package/dist/commands/watch.js +115 -13
- package/dist/commands/worktrees.js +38 -1
- package/dist/commands/wu.js +74 -6
- package/dist/git.js +58 -0
- package/dist/harness.js +2 -0
- package/dist/help.js +5 -1
- package/dist/sandbox-probe.js +37 -3
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/antigravity.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import {
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
|
|
3
4
|
import { homedir } from "node:os";
|
|
4
|
-
import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
5
6
|
import { configRoot } from "./config.js";
|
|
6
7
|
import { repoDirectory } from "./directories.js";
|
|
7
8
|
import { CliError } from "./errors.js";
|
|
8
9
|
import { gitSandboxDeniedPaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
|
|
9
10
|
export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
|
|
11
|
+
export function isAntigravityWorkspaceWrite(env = process.env) {
|
|
12
|
+
return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
|
|
13
|
+
}
|
|
10
14
|
export function antigravityTotalTokens(usage) {
|
|
11
15
|
if (!usage)
|
|
12
16
|
return null;
|
|
@@ -53,7 +57,7 @@ export function antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin
|
|
|
53
57
|
allow.push(`read_file(${nodeModules})`);
|
|
54
58
|
if (skillRoot) {
|
|
55
59
|
allow.push(`read_file(${join(skillRoot, "identity.json")})`);
|
|
56
|
-
for (const file of ["SKILL.md", "references/api.md", "references/watchers.md", "references/process.md", "references/continuity.md"]) {
|
|
60
|
+
for (const file of ["SKILL.md", "references/api.md", "references/watchers.md", "references/process.md", "references/continuity.md", "references/agent-guide.md"]) {
|
|
57
61
|
allow.push(`read_file(${join(skillRoot, file)})`);
|
|
58
62
|
}
|
|
59
63
|
allow.push(`read_file(${join(dirname(skillRoot), ".agents", "rules", "bschat.md")})`);
|
|
@@ -148,13 +152,48 @@ export function recordAntigravityTurn(path, record) {
|
|
|
148
152
|
export function antigravityPath(b9sBin, path = process.env.PATH ?? "") {
|
|
149
153
|
return [...new Set([dirname(b9sBin), dirname(process.execPath), ...path.split(delimiter).filter(Boolean)])].join(delimiter);
|
|
150
154
|
}
|
|
151
|
-
|
|
155
|
+
/** A private scratch directory inside the checkout Antigravity is explicitly allowed to write. */
|
|
156
|
+
export function antigravitySessionTmpDir(cwd, agent, sessionKey) {
|
|
157
|
+
if (!sessionKey.trim())
|
|
158
|
+
throw new CliError("usage", "Antigravity session scratch requires a session key");
|
|
159
|
+
const folder = createHash("sha256").update(`${agent}\0${sessionKey}`).digest("hex").slice(0, 20);
|
|
160
|
+
return join(resolve(cwd), ".b9s-tmp", folder);
|
|
161
|
+
}
|
|
162
|
+
/** Read current watcher settings and derive scratch for persisted configs written before scratch was added. */
|
|
163
|
+
export function parseAntigravityTurnRuntime(text, cwd, agent, session) {
|
|
164
|
+
const value = JSON.parse(text);
|
|
165
|
+
const tmpSessionKey = value.tmpSessionKey ?? session;
|
|
166
|
+
const tmpDir = value.tmpDir ?? antigravitySessionTmpDir(cwd, agent, tmpSessionKey);
|
|
167
|
+
if (value.sandbox !== "workspace-write" || typeof value.apiHost !== "string" || typeof value.b9sBin !== "string" || typeof value.nodeBin !== "string"
|
|
168
|
+
|| typeof tmpSessionKey !== "string" || !tmpSessionKey.trim() || typeof tmpDir !== "string"
|
|
169
|
+
|| tmpDir !== antigravitySessionTmpDir(cwd, agent, tmpSessionKey)
|
|
170
|
+
|| !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")) {
|
|
171
|
+
throw new Error("invalid Antigravity turn runtime fields");
|
|
172
|
+
}
|
|
173
|
+
return { sandbox: value.sandbox, apiHost: value.apiHost, b9sBin: value.b9sBin, nodeBin: value.nodeBin, writableRoots: value.writableRoots, tmpSessionKey, tmpDir };
|
|
174
|
+
}
|
|
175
|
+
export function cleanupAntigravitySessionTmpDir(cwd, agent, sessionKey) {
|
|
176
|
+
rmSync(antigravitySessionTmpDir(cwd, agent, sessionKey), { recursive: true, force: true });
|
|
177
|
+
}
|
|
178
|
+
export function finishAntigravityScratchCleanup(cwd, agent, sessionKey, log, remove = cleanupAntigravitySessionTmpDir) {
|
|
179
|
+
try {
|
|
180
|
+
remove(cwd, agent, sessionKey);
|
|
181
|
+
log("removed Antigravity session scratch after the turn ended");
|
|
182
|
+
}
|
|
183
|
+
catch (e) {
|
|
184
|
+
log(`Antigravity session scratch cleanup failed; watcher turn finalization continues: ${e.message}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export function antigravityTurnEnv(sandbox, b9sBin, tmpDir, inheritedEnv = process.env) {
|
|
152
188
|
if (sandbox !== "workspace-write")
|
|
153
189
|
return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
|
|
190
|
+
if (!tmpDir || !isAbsolute(tmpDir))
|
|
191
|
+
throw new CliError("usage", "Antigravity workspace-write needs an absolute per-session writable TMPDIR inside the checkout");
|
|
154
192
|
const path = b9sBin ? antigravityPath(b9sBin) : [...new Set([dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean)])].join(delimiter);
|
|
155
193
|
// Antigravity supplies its restricted outbound proxy to sandboxed commands. Node's fetch
|
|
156
194
|
// ignores the proxy environment unless opted in; b9s uses fetch for authenticated API calls.
|
|
157
|
-
|
|
195
|
+
const noProxy = [...new Set([...(inheritedEnv.NO_PROXY ?? "").split(","), ...(inheritedEnv.no_proxy ?? "").split(",")].map((host) => host.trim()).filter(Boolean).concat(["127.0.0.1", "localhost", "::1"]))].join(",");
|
|
196
|
+
return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, NODE_USE_ENV_PROXY: "1", NO_PROXY: noProxy, no_proxy: noProxy, TMPDIR: tmpDir, TMP: tmpDir, TEMP: tmpDir, PATH: path };
|
|
158
197
|
}
|
|
159
198
|
export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
|
|
160
199
|
const started = new Date().toISOString();
|
package/dist/client.js
CHANGED
|
@@ -102,7 +102,7 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
102
102
|
? ["context_decision.reason"]
|
|
103
103
|
: [];
|
|
104
104
|
}
|
|
105
|
-
if (action === "assign" || action === "kind" || action === "mandatory-reviewer" || action === "required-class")
|
|
105
|
+
if (action === "assign" || action === "kind" || action === "mandatory-reviewer" || action === "required-class" || action === "head")
|
|
106
106
|
return strings("reason");
|
|
107
107
|
if (action === "take")
|
|
108
108
|
return strings("reason");
|
|
@@ -284,6 +284,8 @@ function expectedStoredText(method, path, body, response) {
|
|
|
284
284
|
const route = path.split("?", 1)[0];
|
|
285
285
|
const verb = method.toUpperCase();
|
|
286
286
|
const stored = {};
|
|
287
|
+
if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/head$/.test(route) && typeof fields.reason === "string")
|
|
288
|
+
stored.reason = fields.reason.trim();
|
|
287
289
|
if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route) && typeof fields.answer === "string" && fields.answer.trim()) {
|
|
288
290
|
const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
|
|
289
291
|
if (!receipts.some((receipt) => receipt?.field === "answer"))
|
package/dist/commands/admin.js
CHANGED
|
@@ -6,6 +6,7 @@ import { DEFAULT_URL, forgetAdmin, loadAdmin, resolveAdminName, saveAdmin } from
|
|
|
6
6
|
import { hostname } from "node:os";
|
|
7
7
|
import { spawnSync } from "node:child_process";
|
|
8
8
|
import { CliError } from "../errors.js";
|
|
9
|
+
import { verifyUnitHeadOnOrigin } from "../git.js";
|
|
9
10
|
import { table } from "../output.js";
|
|
10
11
|
import { milestoneWith, milestonesWith } from "./wu.js";
|
|
11
12
|
import { awayUntil } from "./agent.js";
|
|
@@ -553,6 +554,23 @@ async function role(action, rest, p, out) {
|
|
|
553
554
|
throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
|
|
554
555
|
}
|
|
555
556
|
async function workUnitAdmin(action, rest, p, out) {
|
|
557
|
+
if (action === "head" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
|
|
558
|
+
const project = rest[0];
|
|
559
|
+
const number = Number(rest[1]);
|
|
560
|
+
const sha = rest[2];
|
|
561
|
+
const reason = str(p.flags, "reason");
|
|
562
|
+
if (!sha || !/^[0-9a-f]{40}$/.test(sha) || !reason?.trim())
|
|
563
|
+
throw new CliError("usage", 'b9s-admin wu head <project> <n> <full-sha> --reason "why"');
|
|
564
|
+
const client = adminClient(p);
|
|
565
|
+
const base = `/projects/${encodeURIComponent(project)}/work-units/${number}`;
|
|
566
|
+
const detail = await client.call("GET", `${base}/head-verification`);
|
|
567
|
+
if (typeof detail.branch !== "string" || !detail.branch || typeof detail.repository_identity !== "string" || typeof detail.repository_url !== "string")
|
|
568
|
+
throw new CliError("origin_verification_failed", `WU #${number} did not provide its branch and project repository identity`);
|
|
569
|
+
const proof = verifyUnitHeadOnOrigin(detail.branch, sha, detail.repository_identity, detail.repository_url);
|
|
570
|
+
const result = await client.call("POST", `${base}/head`, { sha, reason, ...proof });
|
|
571
|
+
out.print(`WU #${number} recorded head corrected to ${sha}.`, result);
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
556
574
|
if (action === "merged-sha" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
|
|
557
575
|
const project = rest[0];
|
|
558
576
|
const number = Number(rest[1]);
|
package/dist/commands/agent.js
CHANGED
|
@@ -429,12 +429,14 @@ export async function skill(p, out) {
|
|
|
429
429
|
const watchers = await fetchText("/skill/references/watchers.md");
|
|
430
430
|
const processGuide = await fetchText("/skill/references/process.md");
|
|
431
431
|
const continuity = await fetchText("/skill/references/continuity.md");
|
|
432
|
+
const agentGuide = await fetchText("/skill/references/agent-guide.md");
|
|
432
433
|
mkdirSync(join(dir, "references"), { recursive: true });
|
|
433
434
|
writeFileSync(join(dir, "SKILL.md"), main);
|
|
434
435
|
writeFileSync(join(dir, "references", "api.md"), api);
|
|
435
436
|
writeFileSync(join(dir, "references", "watchers.md"), watchers);
|
|
436
437
|
writeFileSync(join(dir, "references", "process.md"), processGuide);
|
|
437
438
|
writeFileSync(join(dir, "references", "continuity.md"), continuity);
|
|
439
|
+
writeFileSync(join(dir, "references", "agent-guide.md"), agentGuide);
|
|
438
440
|
if (resolve(dir) === resolve(process.cwd(), ".claude", "skills", "b9s"))
|
|
439
441
|
rmSync(join(process.cwd(), ".claude", "skills", "bschat"), { recursive: true, force: true });
|
|
440
442
|
out.print(`Installed skill to ${dir}`, { dir });
|
|
@@ -19,7 +19,7 @@ import { claudeTurnEnv } from "../providers.js";
|
|
|
19
19
|
import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
|
|
20
20
|
import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS } from "../turn.js";
|
|
21
21
|
import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS } from "../startup-jitter.js";
|
|
22
|
-
import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
|
|
22
|
+
import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySessionTmpDir, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
|
|
23
23
|
import { configureGitCredentialForWorktree } from "./git-credential.js";
|
|
24
24
|
import { checkAndRecordHarnessBinary } from "../machine-binary.js";
|
|
25
25
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
@@ -203,6 +203,10 @@ export async function harnessStart(p, out, harness) {
|
|
|
203
203
|
const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
|
|
204
204
|
const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
|
|
205
205
|
const adopt = requestedAdopt ?? rememberedSession ?? undefined;
|
|
206
|
+
const antigravityTmpSessionKey = harness === "antigravity" && sandbox === "workspace-write" ? adopt ?? randomUUID() : undefined;
|
|
207
|
+
const antigravityTmp = antigravityTmpSessionKey ? antigravitySessionTmpDir(process.cwd(), ref, antigravityTmpSessionKey) : undefined;
|
|
208
|
+
if (antigravityTmp)
|
|
209
|
+
mkdirSync(antigravityTmp, { recursive: true, mode: 0o700 });
|
|
206
210
|
if (inContainer)
|
|
207
211
|
provisionContainerInstallRecord();
|
|
208
212
|
const install = requireInstall();
|
|
@@ -244,7 +248,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
244
248
|
lines.push(`Adopted Antigravity conversation ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one conversation conflict.`);
|
|
245
249
|
}
|
|
246
250
|
if (harness === "antigravity" && sandbox === "workspace-write")
|
|
247
|
-
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
|
|
251
|
+
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
|
|
248
252
|
}
|
|
249
253
|
}
|
|
250
254
|
else {
|
|
@@ -280,12 +284,12 @@ export async function harnessStart(p, out, harness) {
|
|
|
280
284
|
lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
|
|
281
285
|
}
|
|
282
286
|
else if (harness === "antigravity") {
|
|
283
|
-
const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin));
|
|
287
|
+
const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin, antigravityTmp));
|
|
284
288
|
session = started.conversation;
|
|
285
289
|
await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
|
|
286
290
|
lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
|
|
287
291
|
if (sandbox === "workspace-write")
|
|
288
|
-
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
|
|
292
|
+
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin, antigravityTmp), unproductivePerHour);
|
|
289
293
|
}
|
|
290
294
|
else {
|
|
291
295
|
// Claude Code takes the session id from us, so nothing has to be read back from its output.
|
|
@@ -340,14 +344,14 @@ export async function harnessStart(p, out, harness) {
|
|
|
340
344
|
// work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
|
|
341
345
|
// from ronald, whose root volume filled with agents' builds under /tmp (46 GB) while the work
|
|
342
346
|
// volume had 750 GB free, and which empties /tmp at every boot.
|
|
343
|
-
const tmp = sessionTmpDir(process.cwd(), creds.agent);
|
|
347
|
+
const tmp = antigravityTmp ?? sessionTmpDir(process.cwd(), creds.agent);
|
|
344
348
|
mkdirSync(tmp, { recursive: true });
|
|
345
349
|
const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
|
|
346
350
|
const prune = bool(p.flags, "prune");
|
|
347
|
-
watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
351
|
+
watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
348
352
|
const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
|
|
349
353
|
...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd } } : {}),
|
|
350
|
-
...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable } } : {}),
|
|
354
|
+
...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable, tmpSessionKey: antigravityTmpSessionKey, tmpDir: antigravityTmp } } : {}),
|
|
351
355
|
...(machineSessionId ? { machineSessionId } : {}) };
|
|
352
356
|
if (inContainer) {
|
|
353
357
|
const sess = sessionOfExec(exec);
|
|
@@ -646,7 +650,7 @@ export function assertAntigravitySelfCheck(output) {
|
|
|
646
650
|
}
|
|
647
651
|
}
|
|
648
652
|
/** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
|
|
649
|
-
export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
653
|
+
export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write", undefined, antigravitySessionTmpDir(cwd, ref, session)), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
650
654
|
const diagnostic = [];
|
|
651
655
|
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "antigravity", probeFor("antigravity", session, ref)))) {
|
|
652
656
|
throw new CliError("turn_mode_fault", refusalReason(diagnostic));
|
package/dist/commands/join.js
CHANGED
|
@@ -28,6 +28,7 @@ async function fetchSkill(url) {
|
|
|
28
28
|
watchers: await get("/skill/references/watchers.md"),
|
|
29
29
|
process: await get("/skill/references/process.md"),
|
|
30
30
|
continuity: await get("/skill/references/continuity.md"),
|
|
31
|
+
agentGuide: await get("/skill/references/agent-guide.md"),
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
function harnessList(p, vendor) {
|
|
@@ -808,7 +808,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
|
|
|
808
808
|
`${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour${pool.quota_substitution ? "; quota substitution enabled" : ""}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
|
|
809
809
|
...(pool.adaptive ? [` adaptive target ${pool.adaptive.target} (min ${pool.adaptive.min}, max ${pool.adaptive.max}); ${pool.adaptive.snapshot?.decision?.kind ?? "state unknown"}: ${pool.adaptive.snapshot?.decision?.reason ?? "no snapshot"}; queued ${pool.adaptive.snapshot?.queuedWork ?? "unknown"}, idle ${pool.adaptive.snapshot?.usableIdleSlots ?? "unknown"}, oldest ${pool.adaptive.snapshot?.oldestQueuedAgeSeconds == null ? "unknown" : `${Math.floor(pool.adaptive.snapshot.oldestQueuedAgeSeconds / 60)}m`}`] : []),
|
|
810
810
|
...(pool.adaptive?.paused ? [" scaling paused by operator"] : []),
|
|
811
|
-
...(pool.slots ?? []).map((slot) =>
|
|
811
|
+
...(pool.slots ?? []).map((slot) => {
|
|
812
|
+
const state = slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}`
|
|
813
|
+
: slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}`
|
|
814
|
+
: slot.placement_state ?? slot.desired ?? "unplaced";
|
|
815
|
+
return ` ${slot.slot}: ${state}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.recovery_source_machine ? `; recovery source on ${slot.recovery_source_machine}` : ""}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`;
|
|
816
|
+
}),
|
|
812
817
|
...(pool.slots ? [] : (pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`)),
|
|
813
818
|
...(pool.status?.unplaced ?? []).map((x) => /^moving to /i.test(x.reason ?? "")
|
|
814
819
|
? ` ${x.agent.padEnd(32)} ${x.reason}`
|
package/dist/commands/machine.js
CHANGED
|
@@ -1647,6 +1647,13 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1647
1647
|
? (isContainerRunning(runningContainerRuntime, runningContainerName, runner) ? "active" : "inactive")
|
|
1648
1648
|
: (w && serviceActive(w) ? "active" : "inactive");
|
|
1649
1649
|
const th = state.sessions[s.id].thread;
|
|
1650
|
+
// The watcher keeps polling through a worktree obstruction. Surface its durable fault as
|
|
1651
|
+
// a session error while it retries; successful preparation clears it without a restart.
|
|
1652
|
+
const worktreeFault = readState(s.agent, agentStateEnv).worktree_fault;
|
|
1653
|
+
if (worktreeFault) {
|
|
1654
|
+
out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: worktreeFault.message });
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1650
1657
|
// A watcher that exits at every start (a corrupt state file after the disk filled) is
|
|
1651
1658
|
// restarted by systemd forever and looked "running" here; report it as the error it is.
|
|
1652
1659
|
const fault = containerMode ? null : watcherFault(s.agent);
|
|
@@ -2510,6 +2517,8 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
2510
2517
|
let work = null;
|
|
2511
2518
|
try {
|
|
2512
2519
|
work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
|
|
2520
|
+
const sessionTmp = join(work, ".b9s-tmp", "machine-probe");
|
|
2521
|
+
mkdirSync(sessionTmp, { recursive: true, mode: 0o700 });
|
|
2513
2522
|
const marker = join(work, ".b9s-sandbox-probe");
|
|
2514
2523
|
const meOutputPath = join(work, ".b9s-sandbox-probe-me");
|
|
2515
2524
|
const meErrorPath = join(work, ".b9s-sandbox-probe-me-error");
|
|
@@ -2523,7 +2532,7 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
2523
2532
|
const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
|
|
2524
2533
|
const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
|
|
2525
2534
|
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
|
|
2526
|
-
env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
|
|
2535
|
+
env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin, sessionTmp), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
|
|
2527
2536
|
});
|
|
2528
2537
|
const parsed = parseAntigravityJson(r.stdout ?? "");
|
|
2529
2538
|
let wroteMarker = false;
|
package/dist/commands/watch.js
CHANGED
|
@@ -3,7 +3,7 @@ import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
|
|
|
3
3
|
import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
|
|
4
4
|
import { drainingUntil } from "../maintenance.js";
|
|
5
5
|
import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
|
|
6
|
-
import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySettings } from "../antigravity.js";
|
|
6
|
+
import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySessionTmpDir, antigravitySettings, finishAntigravityScratchCleanup, parseAntigravityTurnRuntime } from "../antigravity.js";
|
|
7
7
|
import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
|
|
8
8
|
import { applyAck } from "./wake.js";
|
|
9
9
|
import { launchdSessionTypeXml, lingerEnabled, machineDaemonPath, plistLaunchdDomain, loadSystemdUnit, readInstall, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
@@ -15,7 +15,7 @@ import { bool, str } from "../args.js";
|
|
|
15
15
|
import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
|
|
16
16
|
import { Client } from "../client.js";
|
|
17
17
|
import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
|
|
18
|
-
import { scanProject, unitWorktrees } from "./worktrees.js";
|
|
18
|
+
import { cleanupDeferredUnitWorktree, scanProject, unitWorktrees } from "./worktrees.js";
|
|
19
19
|
import { branchAndHead, formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
|
|
20
20
|
import { CliError } from "../errors.js";
|
|
21
21
|
import { claudeTurnEnv } from "../providers.js";
|
|
@@ -134,12 +134,7 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
134
134
|
if (harness !== "antigravity")
|
|
135
135
|
throw new CliError("usage", "--turn-antigravity-runtime is only valid with --harness antigravity");
|
|
136
136
|
try {
|
|
137
|
-
|
|
138
|
-
if (value.sandbox !== "workspace-write" || typeof value.apiHost !== "string" || typeof value.b9sBin !== "string" || typeof value.nodeBin !== "string"
|
|
139
|
-
|| !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")) {
|
|
140
|
-
throw new Error("invalid Antigravity turn runtime fields");
|
|
141
|
-
}
|
|
142
|
-
antigravityRuntime = { sandbox: value.sandbox, apiHost: value.apiHost, b9sBin: value.b9sBin, nodeBin: value.nodeBin, writableRoots: value.writableRoots };
|
|
137
|
+
antigravityRuntime = parseAntigravityTurnRuntime(antigravityRuntimeText, process.cwd(), name, session);
|
|
143
138
|
}
|
|
144
139
|
catch (error) {
|
|
145
140
|
throw new CliError("usage", `--turn-antigravity-runtime must be valid Antigravity runtime JSON: ${error.message}`);
|
|
@@ -349,7 +344,7 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
349
344
|
const wakeDependencies = { ...dependencies.wakeOnceDependencies, ...(turn?.claudeRuntime ? { claudeRuntime: turn.claudeRuntime } : {}), ...(turn?.antigravityRuntime ? { antigravityRuntime: turn.antigravityRuntime } : {}) };
|
|
350
345
|
const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, wakeDependencies);
|
|
351
346
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
352
|
-
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
|
|
347
|
+
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness, currentWatcherOomKillCount, turn?.antigravityRuntime?.sandbox);
|
|
353
348
|
else {
|
|
354
349
|
const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
|
|
355
350
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
@@ -366,7 +361,10 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
366
361
|
finish(0);
|
|
367
362
|
return stoppingCode;
|
|
368
363
|
}
|
|
369
|
-
|
|
364
|
+
if (e.code === "unit_worktree_diverged" && !once)
|
|
365
|
+
log(e.message);
|
|
366
|
+
else
|
|
367
|
+
throw e;
|
|
370
368
|
}
|
|
371
369
|
if (stopping)
|
|
372
370
|
return stoppingCode;
|
|
@@ -484,7 +482,7 @@ export function withAgentEnv(ref, work) {
|
|
|
484
482
|
}
|
|
485
483
|
}
|
|
486
484
|
/** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
|
|
487
|
-
async function prepareTurnWorktree(name, binding, allowSuperseded = false, dependencies = {}) {
|
|
485
|
+
export async function prepareTurnWorktree(name, binding, allowSuperseded = false, dependencies = {}) {
|
|
488
486
|
const creds = loadAgent(name);
|
|
489
487
|
const project = binding.project ?? creds.project;
|
|
490
488
|
if (!project)
|
|
@@ -493,20 +491,30 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false, depen
|
|
|
493
491
|
throw new CliError("unit_worktree_prepare_failed", `cannot prepare WU #${binding.work_unit_number}: server project ${project} does not match ${name}'s project ${creds.project}`);
|
|
494
492
|
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
495
493
|
const base = `/projects/${encodeURIComponent(project)}/work-units/${binding.work_unit_number}`;
|
|
494
|
+
const clearWorktreeFault = () => updateState(name, (state) => {
|
|
495
|
+
if (state.worktree_fault?.project !== project || state.worktree_fault.unit !== binding.work_unit_number || state.worktree_fault.assignment !== binding.assignment_event_id)
|
|
496
|
+
return;
|
|
497
|
+
const { worktree_fault: _resolved, ...rest } = state;
|
|
498
|
+
return rest;
|
|
499
|
+
});
|
|
496
500
|
try {
|
|
497
501
|
const record = await client.call("GET", base);
|
|
498
502
|
const unit = record.unit;
|
|
499
503
|
if (!unit || unit.number !== binding.work_unit_number)
|
|
500
504
|
throw new Error("the server did not return the requested work unit");
|
|
501
505
|
if (unit.owner_name !== creds.agent) {
|
|
506
|
+
clearWorktreeFault();
|
|
502
507
|
if (allowSuperseded)
|
|
503
508
|
return null;
|
|
504
509
|
throw new Error(`WU #${binding.work_unit_number} is now owned by ${unit.owner_name ?? "no agent"}, not ${creds.agent}`);
|
|
505
510
|
}
|
|
506
|
-
if (!["assigned", "open", "changes_requested"].includes(unit.status))
|
|
511
|
+
if (!["assigned", "open", "changes_requested"].includes(unit.status)) {
|
|
512
|
+
clearWorktreeFault();
|
|
507
513
|
return null;
|
|
514
|
+
}
|
|
508
515
|
const activeAssignment = currentAssignmentEvent(record.events ?? [], unit.owner_agent_id, creds.agent);
|
|
509
516
|
if (activeAssignment?.id !== binding.assignment_event_id) {
|
|
517
|
+
clearWorktreeFault();
|
|
510
518
|
if (allowSuperseded)
|
|
511
519
|
return null;
|
|
512
520
|
throw new Error(`assignment event ${binding.assignment_event_id} is no longer current`);
|
|
@@ -538,14 +546,63 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false, depen
|
|
|
538
546
|
if (verified.unit?.status !== "open" || verified.unit?.branch !== location.branch || verified.unit?.head !== location.head || verified.unit?.worktree !== prepared.path) {
|
|
539
547
|
throw new Error("server did not persist the prepared branch, commit and worktree exactly; refusing to launch the turn");
|
|
540
548
|
}
|
|
549
|
+
clearWorktreeFault();
|
|
541
550
|
return { number: binding.work_unit_number, path: prepared.path, branch: location.branch, status: verified.unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: false };
|
|
542
551
|
}
|
|
552
|
+
clearWorktreeFault();
|
|
543
553
|
return { number: binding.work_unit_number, path: prepared.path, branch: prepared.branch, status: unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: prepared.needsRecord };
|
|
544
554
|
}
|
|
545
555
|
catch (error) {
|
|
556
|
+
if (error.code === "unit_worktree_diverged") {
|
|
557
|
+
const fault = error;
|
|
558
|
+
updateState(name, (state) => {
|
|
559
|
+
const prior = state.worktree_fault;
|
|
560
|
+
if (prior?.project === project && prior.unit === binding.work_unit_number && prior.assignment === binding.assignment_event_id && prior.message === fault.message)
|
|
561
|
+
return;
|
|
562
|
+
return { ...state, worktree_fault: { project, unit: binding.work_unit_number, assignment: binding.assignment_event_id, message: fault.message, at: new Date().toISOString() } };
|
|
563
|
+
});
|
|
564
|
+
try {
|
|
565
|
+
await client.call("POST", `${base}/head-divergence`, { recorded_head: fault.recordedHead, branch: fault.branch, branch_head: fault.branchHead, message: fault.message });
|
|
566
|
+
}
|
|
567
|
+
catch (reportError) {
|
|
568
|
+
throw new CliError("unit_worktree_prepare_failed", `${fault.message} Could not record the divergence fault: ${reportError.message}`);
|
|
569
|
+
}
|
|
570
|
+
throw fault;
|
|
571
|
+
}
|
|
546
572
|
throw new CliError("unit_worktree_prepare_failed", `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${error.message}`);
|
|
547
573
|
}
|
|
548
574
|
}
|
|
575
|
+
/** Recheck the fault's own assignment even when the wake has no current unit binding. */
|
|
576
|
+
export async function reconcileWorktreeFault(name, log) {
|
|
577
|
+
const fault = readState(name).worktree_fault;
|
|
578
|
+
if (!fault)
|
|
579
|
+
return;
|
|
580
|
+
try {
|
|
581
|
+
const creds = loadAgent(name);
|
|
582
|
+
if (creds.project && creds.project !== fault.project)
|
|
583
|
+
throw new Error("fault project does not match the agent credential");
|
|
584
|
+
const record = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${encodeURIComponent(fault.project)}/work-units/${fault.unit}`);
|
|
585
|
+
const unit = record.unit;
|
|
586
|
+
if (!unit || unit.number !== fault.unit || typeof unit.status !== "string" || !(typeof unit.owner_name === "string" || unit.owner_name === null) || !Array.isArray(record.events))
|
|
587
|
+
throw new Error("unit or assignment history is incomplete");
|
|
588
|
+
const assignment = currentAssignmentEvent(record.events, unit.owner_agent_id, creds.agent);
|
|
589
|
+
if (unit.owner_name === creds.agent && ["assigned", "open", "changes_requested"].includes(unit.status)) {
|
|
590
|
+
if (!assignment)
|
|
591
|
+
throw new Error("current assignment event is unavailable");
|
|
592
|
+
if (assignment.id === fault.assignment)
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
updateState(name, (state) => {
|
|
596
|
+
if (JSON.stringify(state.worktree_fault) !== JSON.stringify(fault))
|
|
597
|
+
return;
|
|
598
|
+
const { worktree_fault: _resolved, ...rest } = state;
|
|
599
|
+
return rest;
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
catch (error) {
|
|
603
|
+
log(`could not recheck WU #${fault.unit}'s worktree fault: ${error.message}; keeping the fault`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
549
606
|
const CODEX_THREAD_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
550
607
|
/** Follow a Codex exec that opens a new thread, as soon as the session hook records its id. */
|
|
551
608
|
export function followCurrentCodexProbe(name, initialThread) {
|
|
@@ -633,6 +690,8 @@ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, bef
|
|
|
633
690
|
export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
|
|
634
691
|
const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
|
|
635
692
|
log(`debug poll: ${message}`); };
|
|
693
|
+
if (turnSink)
|
|
694
|
+
await reconcileWorktreeFault(name, log);
|
|
636
695
|
const state = readState(name);
|
|
637
696
|
const pending = state.watch_pending;
|
|
638
697
|
if (pending) {
|
|
@@ -828,6 +887,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
828
887
|
}
|
|
829
888
|
if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
|
|
830
889
|
const runtime = dependencies.antigravityRuntime;
|
|
890
|
+
mkdirSync(runtime.tmpDir, { recursive: true, mode: 0o700 });
|
|
831
891
|
const args = antigravitySettings(runtime.sandbox, process.cwd(), configRoot(), runtime.apiHost, [...runtime.writableRoots, ...(preparedWorktree ? [preparedWorktree.path] : [])], runtime.b9sBin, runtime.nodeBin, name, preparedWorktree ?? undefined);
|
|
832
892
|
turnExec = turnExec.replace(ANTIGRAVITY_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
|
|
833
893
|
}
|
|
@@ -1043,7 +1103,7 @@ function diskFloorAllowsTurn(log, env) {
|
|
|
1043
1103
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
1044
1104
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
1045
1105
|
*/
|
|
1046
|
-
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness, oomKillCounter = currentWatcherOomKillCount) {
|
|
1106
|
+
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness, oomKillCounter = currentWatcherOomKillCount, antigravitySandbox) {
|
|
1047
1107
|
const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
|
|
1048
1108
|
log(`debug poll: ${message}`); };
|
|
1049
1109
|
const turn = ctl.turn;
|
|
@@ -1106,6 +1166,44 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
1106
1166
|
ctl.failedAt = Date.now();
|
|
1107
1167
|
}
|
|
1108
1168
|
if (harness === "antigravity") {
|
|
1169
|
+
if (antigravitySandbox === "workspace-write") {
|
|
1170
|
+
try {
|
|
1171
|
+
const pending = readState(name, env).watcher_worktree_cleanups ?? [];
|
|
1172
|
+
const completed = [];
|
|
1173
|
+
for (const closure of pending) {
|
|
1174
|
+
try {
|
|
1175
|
+
const cleanup = await cleanupDeferredUnitWorktree(loadAgent(name), closure, process.cwd());
|
|
1176
|
+
if (cleanup.retry) {
|
|
1177
|
+
log(`Antigravity turn cleanup kept WU #${closure.work_unit_number} for retry: ${cleanup.reason}`);
|
|
1178
|
+
}
|
|
1179
|
+
else {
|
|
1180
|
+
log(cleanup.removed
|
|
1181
|
+
? `Antigravity turn cleanup WU #${closure.work_unit_number}: ${cleanup.reason}`
|
|
1182
|
+
: `Antigravity turn cleanup did not remove WU #${closure.work_unit_number}: ${cleanup.reason}`);
|
|
1183
|
+
completed.push(closure.id);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
catch (e) {
|
|
1187
|
+
log(`Antigravity turn worktree cleanup failed outside the session sandbox for WU #${closure.work_unit_number}: ${e.message}`);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
if (completed.length) {
|
|
1191
|
+
const finished = new Set(completed);
|
|
1192
|
+
try {
|
|
1193
|
+
updateState(name, (state) => ({
|
|
1194
|
+
...state,
|
|
1195
|
+
watcher_worktree_cleanups: (state.watcher_worktree_cleanups ?? []).filter((closure) => !finished.has(closure.id)),
|
|
1196
|
+
}), env);
|
|
1197
|
+
}
|
|
1198
|
+
catch (e) {
|
|
1199
|
+
log(`Antigravity turn cleanup receipts could not be cleared from watcher state: ${e.message}`);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
catch (e) {
|
|
1204
|
+
log(`Antigravity turn cleanup queue could not be read outside the session sandbox: ${e.message}`);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1109
1207
|
try {
|
|
1110
1208
|
const removed = cleanupAntigravitySandboxProbeRefs(process.cwd(), agentRef(loadAgent(name)), env);
|
|
1111
1209
|
if (removed.length)
|
|
@@ -1114,6 +1212,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
1114
1212
|
catch (e) {
|
|
1115
1213
|
log(`Antigravity sandbox probe ref cleanup failed outside the session sandbox: ${e.message}`);
|
|
1116
1214
|
}
|
|
1215
|
+
const tmpSessionKey = env.BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY;
|
|
1216
|
+
if (tmpSessionKey && env.TMPDIR === antigravitySessionTmpDir(process.cwd(), name, tmpSessionKey)) {
|
|
1217
|
+
finishAntigravityScratchCleanup(process.cwd(), name, tmpSessionKey, log);
|
|
1218
|
+
}
|
|
1117
1219
|
}
|
|
1118
1220
|
ctl.turn = null;
|
|
1119
1221
|
await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
|
|
@@ -4,13 +4,47 @@ import { Client } from "../client.js";
|
|
|
4
4
|
import { loadAgent, resolveAgentName } from "../config.js";
|
|
5
5
|
import { CliError } from "../errors.js";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
7
|
-
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
|
|
7
|
+
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, removeWorktreeIfClean, worktreeState, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
|
|
8
8
|
import { table } from "../output.js";
|
|
9
9
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
10
10
|
import { sweepClosedHarnessServers } from "../harness-server-sweep.js";
|
|
11
|
+
import { isAntigravityWorkspaceWrite } from "../antigravity.js";
|
|
11
12
|
const CLOSED = ["done", "abandoned", "superseded"];
|
|
12
13
|
const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
|
|
13
14
|
const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
|
|
15
|
+
/** Remove only the exact clean worktree recorded for a successful close, outside the Antigravity sandbox. */
|
|
16
|
+
export async function cleanupDeferredUnitWorktree(creds, closure, cwd = process.cwd()) {
|
|
17
|
+
const number = closure.work_unit_number;
|
|
18
|
+
if (closure.keep_worktree)
|
|
19
|
+
return { removed: false, retry: false, reason: "--keep-worktree was requested" };
|
|
20
|
+
const record = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${encodeURIComponent(closure.project)}/work-units/${number}`);
|
|
21
|
+
const unit = record.unit;
|
|
22
|
+
if (unit?.number !== number)
|
|
23
|
+
return { removed: false, retry: false, reason: "the server returned a different work unit" };
|
|
24
|
+
if (unit.status !== "done")
|
|
25
|
+
return { removed: false, retry: false, reason: `WU #${number} is ${unit.status}, not done` };
|
|
26
|
+
if (typeof unit.worktree !== "string" || !unit.worktree)
|
|
27
|
+
return { removed: false, retry: false, reason: "the unit has no recorded worktree" };
|
|
28
|
+
if (!existsSync(unit.worktree))
|
|
29
|
+
return { removed: false, retry: false, reason: "the recorded worktree path no longer exists" };
|
|
30
|
+
const path = realpathSync(unit.worktree);
|
|
31
|
+
const expectedPath = existsSync(closure.worktree) ? realpathSync(closure.worktree) : null;
|
|
32
|
+
if (path !== expectedPath)
|
|
33
|
+
return { removed: false, retry: false, reason: "the unit worktree no longer matches the exact deferred closure" };
|
|
34
|
+
if ((unit.branch ?? null) !== closure.branch)
|
|
35
|
+
return { removed: false, retry: false, reason: "the unit branch no longer matches the exact deferred closure" };
|
|
36
|
+
if (path === realpathSync(cwd))
|
|
37
|
+
return { removed: false, retry: false, reason: "the worktree is the watcher checkout" };
|
|
38
|
+
const state = worktreeState(path, cwd);
|
|
39
|
+
if (state.state !== "ready")
|
|
40
|
+
return { removed: false, retry: false, reason: state.state === "partial" ? state.reason : "the recorded path is not a linked worktree" };
|
|
41
|
+
if (state.branch !== closure.branch)
|
|
42
|
+
return { removed: false, retry: false, reason: `the linked worktree is on ${state.branch ?? "a detached head"}, not ${closure.branch ?? "the recorded detached head"}` };
|
|
43
|
+
const result = removeWorktreeIfClean(path, cwd);
|
|
44
|
+
return result.removed
|
|
45
|
+
? { removed: true, retry: false, reason: "removed the clean closed unit worktree; its branch was kept" }
|
|
46
|
+
: { removed: false, retry: true, reason: result.reason ?? "Git refused removal" };
|
|
47
|
+
}
|
|
14
48
|
async function timedClientCall(client, method, path, body, timeoutMs, operation) {
|
|
15
49
|
const controller = new AbortController();
|
|
16
50
|
let timedOut = false;
|
|
@@ -112,6 +146,9 @@ export async function pruneProjectWorktrees(creds, project, cwd, protection, log
|
|
|
112
146
|
*/
|
|
113
147
|
export async function worktrees(p, out, timeouts = {}) {
|
|
114
148
|
const sub = p.positionals[1];
|
|
149
|
+
if (sub === "prune" && isAntigravityWorkspaceWrite()) {
|
|
150
|
+
throw new CliError("antigravity_cleanup_owner", "b9s worktrees prune is refused in Antigravity workspace-write because the shared Git worktree registry is read-only; the watcher processes queued wu done worktrees at turn finalization, and retained or abandoned worktrees must be pruned from an unrestricted checkout");
|
|
151
|
+
}
|
|
115
152
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
116
153
|
const creds = loadAgent(name);
|
|
117
154
|
const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
|
package/dist/commands/wu.js
CHANGED
|
@@ -10,7 +10,7 @@ import { readState, updateState } from "../state.js";
|
|
|
10
10
|
import { codexRollout, sessionsOf } from "../sessions.js";
|
|
11
11
|
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
|
|
12
12
|
import { CliError, WrittenReceiptMismatchError } from "../errors.js";
|
|
13
|
-
import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch, worktreeState } from "../git.js";
|
|
13
|
+
import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
|
|
14
14
|
import { join, resolve } from "node:path";
|
|
15
15
|
import { formatStepRules, table } from "../output.js";
|
|
16
16
|
import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
|
|
@@ -20,6 +20,7 @@ import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompac
|
|
|
20
20
|
import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
|
|
21
21
|
import { formatStandingRuleSet } from "../standing-rules.js";
|
|
22
22
|
import { projectOf } from "./agent.js";
|
|
23
|
+
import { isAntigravityWorkspaceWrite } from "../antigravity.js";
|
|
23
24
|
/** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
|
|
24
25
|
export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
|
|
25
26
|
return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
|
|
@@ -1102,7 +1103,12 @@ export async function wu(p, out) {
|
|
|
1102
1103
|
? await telemetryFromEvents(name, Array.isArray(doneRecord.events) ? doneRecord.events : [])
|
|
1103
1104
|
: null;
|
|
1104
1105
|
const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged, ...(telemetry ? { context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason } : {}), ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: noCommitsBeyondTarget } : {}) });
|
|
1105
|
-
|
|
1106
|
+
const keepWorktree = !!p.flags["keep-worktree"];
|
|
1107
|
+
const antigravityWorkspaceWrite = isAntigravityWorkspaceWrite();
|
|
1108
|
+
const deferredCleanupError = antigravityWorkspaceWrite && !keepWorktree && r.unit.worktree
|
|
1109
|
+
? recordDeferredWorktreeCleanup(name, { id: randomUUID(), project, work_unit_number: r.unit.number, worktree: r.unit.worktree, branch: r.unit.branch ?? null, keep_worktree: false })
|
|
1110
|
+
: null;
|
|
1111
|
+
out.print(withRuleText(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, keepWorktree, antigravityWorkspaceWrite, "done", !deferredCleanupError && !keepWorktree, deferredCleanupError), r, "close"), r);
|
|
1106
1112
|
return;
|
|
1107
1113
|
}
|
|
1108
1114
|
case "merge": {
|
|
@@ -1126,7 +1132,9 @@ export async function wu(p, out) {
|
|
|
1126
1132
|
case "abandon": {
|
|
1127
1133
|
const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
|
|
1128
1134
|
// Same as done: a clean worktree goes (its branch, and every commit on it, stays).
|
|
1129
|
-
|
|
1135
|
+
const keepWorktree = !!p.flags["keep-worktree"];
|
|
1136
|
+
const antigravityWorkspaceWrite = isAntigravityWorkspaceWrite();
|
|
1137
|
+
out.print(fmt(r.unit) + cleanupUnitWorktree(r.unit.worktree, await processDef(), keepWorktree, antigravityWorkspaceWrite, "abandon"), r);
|
|
1130
1138
|
return;
|
|
1131
1139
|
}
|
|
1132
1140
|
case "evidence": {
|
|
@@ -1152,6 +1160,20 @@ export async function wu(p, out) {
|
|
|
1152
1160
|
out.print(fmt(r.unit), r);
|
|
1153
1161
|
return;
|
|
1154
1162
|
}
|
|
1163
|
+
case "head": {
|
|
1164
|
+
const sha = p.positionals[3];
|
|
1165
|
+
const reason = str(p.flags, "reason");
|
|
1166
|
+
if (!sha || !/^[0-9a-f]{40}$/.test(sha) || !reason?.trim())
|
|
1167
|
+
throw new CliError("usage", 'wu head <n> <full-40-character-lowercase-sha> --reason "why"');
|
|
1168
|
+
const number = num();
|
|
1169
|
+
const detail = await client.call("GET", `${base}/${number}/head-verification`);
|
|
1170
|
+
if (typeof detail.branch !== "string" || !detail.branch || typeof detail.repository_identity !== "string" || typeof detail.repository_url !== "string")
|
|
1171
|
+
throw new CliError("origin_verification_failed", `WU #${number} did not provide its branch and project repository identity`);
|
|
1172
|
+
const proof = verifyUnitHeadOnOrigin(detail.branch, sha, detail.repository_identity, detail.repository_url);
|
|
1173
|
+
const result = await client.call("POST", `${base}/${number}/head`, { sha, reason, ...proof });
|
|
1174
|
+
out.print(fmt(result.unit), result);
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1155
1177
|
case "target": {
|
|
1156
1178
|
// Move where the unit lands, before review. "default" restores the process target.
|
|
1157
1179
|
const t = p.positionals[3];
|
|
@@ -1361,9 +1383,18 @@ export async function processCmd(p, out) {
|
|
|
1361
1383
|
}
|
|
1362
1384
|
/** Per agent per tag, what real units have shown. */
|
|
1363
1385
|
/** A closed unit's worktree goes when it is clean and we are not standing in it; the branch and its commits stay. */
|
|
1364
|
-
function cleanupUnitWorktree(wt, def, keep) {
|
|
1365
|
-
if (!wt
|
|
1386
|
+
function cleanupUnitWorktree(wt, def, keep, antigravityWorkspaceWrite = false, action = "done", deferredRecorded = false, deferredError = null) {
|
|
1387
|
+
if (!wt)
|
|
1366
1388
|
return "";
|
|
1389
|
+
if (keep)
|
|
1390
|
+
return `\nWorktree ${wt} kept by --keep-worktree.`;
|
|
1391
|
+
if (antigravityWorkspaceWrite) {
|
|
1392
|
+
return action === "done"
|
|
1393
|
+
? deferredRecorded
|
|
1394
|
+
? `\nWorktree ${wt} queued for watcher cleanup outside Antigravity workspace-write at turn finalization; the exact closed worktree will be checked for ownership and cleanliness. Its branch is kept.`
|
|
1395
|
+
: `\nWorktree ${wt} was not queued for watcher cleanup${deferredError ? ` (${deferredError})` : ""}; remove it from an unrestricted checkout. Its branch is kept.`
|
|
1396
|
+
: `\nWorktree ${wt} left in place; the watcher removes only explicitly queued completed worktrees. Prune this abandoned worktree from an unrestricted checkout.`;
|
|
1397
|
+
}
|
|
1367
1398
|
if (resolve(process.cwd()).startsWith(resolve(wt)))
|
|
1368
1399
|
return `\nWorktree ${wt} left in place (you are in it); remove it from elsewhere: git worktree remove ${wt}`;
|
|
1369
1400
|
if (wt === repoParent() || worktreeForBranch(def.merge.target_branch) === wt)
|
|
@@ -1375,6 +1406,18 @@ function cleanupUnitWorktree(wt, def, keep) {
|
|
|
1375
1406
|
return `\nWorktree ${wt} kept: it has uncommitted files that are not on the branch. Commit them to the branch if they belong to the record, or run b9s worktrees prune --archive --yes to save them to an archive branch and remove the worktree.`;
|
|
1376
1407
|
return `\nWorktree ${wt} kept: ${res.reason}.`;
|
|
1377
1408
|
}
|
|
1409
|
+
function recordDeferredWorktreeCleanup(agent, closure) {
|
|
1410
|
+
try {
|
|
1411
|
+
updateState(agent, (onDisk) => ({
|
|
1412
|
+
...onDisk,
|
|
1413
|
+
watcher_worktree_cleanups: [...(onDisk.watcher_worktree_cleanups ?? []).filter((item) => item.id !== closure.id), closure],
|
|
1414
|
+
}));
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
catch (error) {
|
|
1418
|
+
return error.message;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1378
1421
|
/**
|
|
1379
1422
|
* One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
|
|
1380
1423
|
* continues existing work in its own worktree; --here uses the current checkout (single-agent repos).
|
|
@@ -1387,6 +1430,29 @@ function assertNotShaBranch(branch, flag = "--branch") {
|
|
|
1387
1430
|
throw new CliError("usage", `refusing ${flag} ${branch}: never name a branch after a commit SHA`, "Pass a descriptive branch name like wu/123-fix or omit --branch to create one from origin's target.");
|
|
1388
1431
|
}
|
|
1389
1432
|
}
|
|
1433
|
+
export function divergentUnitHeadMessage(n, recordedHead, branch, branchHead, cwd = process.cwd()) {
|
|
1434
|
+
const subject = spawnSync("git", ["show", "-s", "--format=%s", recordedHead], { cwd, encoding: "utf8" });
|
|
1435
|
+
const history = spawnSync("git", ["log", "-n", "2000", "--format=%H%x09%s", branchHead, "--"], { cwd, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
|
|
1436
|
+
let match;
|
|
1437
|
+
if (subject.status !== 0 || history.status !== 0 || !subject.stdout.trim())
|
|
1438
|
+
match = "Matching commit subject could not be checked.";
|
|
1439
|
+
else {
|
|
1440
|
+
const found = history.stdout.split(/\r?\n/).map((line) => line.split("\t", 2)).find(([sha, title]) => sha !== recordedHead && title === subject.stdout.trim());
|
|
1441
|
+
match = found ? `A commit with the same subject appears on the branch: ${found[0]}; this is not proof of the same change.` : "No commit with the same subject appears in the first 2000 branch commits.";
|
|
1442
|
+
}
|
|
1443
|
+
return `WU #${n}: recorded head ${recordedHead} and local branch ${branch} at ${branchHead} diverge; refusing to guess which committed work belongs to the unit. ${match} After inspecting and pushing the intended branch, an operator or assigner can record its head with: b9s wu head ${n} ${branchHead} --reason "explain the verified head"`;
|
|
1444
|
+
}
|
|
1445
|
+
export class UnitWorktreeDiverged extends CliError {
|
|
1446
|
+
recordedHead;
|
|
1447
|
+
branch;
|
|
1448
|
+
branchHead;
|
|
1449
|
+
constructor(recordedHead, branch, branchHead, message) {
|
|
1450
|
+
super("unit_worktree_diverged", message);
|
|
1451
|
+
this.recordedHead = recordedHead;
|
|
1452
|
+
this.branch = branch;
|
|
1453
|
+
this.branchHead = branchHead;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1390
1456
|
export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
|
|
1391
1457
|
if (unit.branch && isShaBranchName(unit.branch))
|
|
1392
1458
|
throw new CliError("no_branch", `recorded branch ${unit.branch} is a commit identifier, not a branch`, "Record and push the unit branch before retrying.");
|
|
@@ -1426,6 +1492,8 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
|
|
|
1426
1492
|
const recoveryRequired = homeCheckoutRecorded || recordedWorktreeMissing || startedUnitWithoutRecordedWorktree || adoptedExistingWorktree;
|
|
1427
1493
|
const recordedHead = recoveryRequired && typeof unit.head === "string" ? fullSha(unit.head) : null;
|
|
1428
1494
|
const recordedBranchTip = recoveryRequired && typeof unit.branch === "string" && !isShaBranchName(unit.branch) ? fullSha(`refs/heads/${unit.branch}`) : null;
|
|
1495
|
+
if (recoveryRequired && unit.head && !recordedHead)
|
|
1496
|
+
throw new CliError("unit_worktree_prepare_failed", `recorded head ${unit.head} is unavailable in this checkout; fetch it before preparing WU #${n}`);
|
|
1429
1497
|
let recoveryBase = recordedHead ?? recordedBranchTip;
|
|
1430
1498
|
if (recordedHead && recordedBranchTip) {
|
|
1431
1499
|
const headIsOnBranch = isAncestor(recordedHead, recordedBranchTip, home);
|
|
@@ -1433,7 +1501,7 @@ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
|
|
|
1433
1501
|
if (headIsOnBranch === true)
|
|
1434
1502
|
recoveryBase = recordedBranchTip;
|
|
1435
1503
|
else if (branchIsOnHead !== true) {
|
|
1436
|
-
throw new
|
|
1504
|
+
throw new UnitWorktreeDiverged(recordedHead, unit.branch, recordedBranchTip, divergentUnitHeadMessage(n, recordedHead, unit.branch, recordedBranchTip, home));
|
|
1437
1505
|
}
|
|
1438
1506
|
}
|
|
1439
1507
|
if (adoptedExistingWorktree) {
|
package/dist/git.js
CHANGED
|
@@ -677,6 +677,64 @@ export function fetchRemoteBranch(branch, remote = "origin", cwd = process.cwd()
|
|
|
677
677
|
}
|
|
678
678
|
return { ok: true, ref: trackingRef };
|
|
679
679
|
}
|
|
680
|
+
/** Compare supported Git URL forms by host and repository path, without exposing user info. */
|
|
681
|
+
export function normalizedRepositoryUrl(value) {
|
|
682
|
+
const scp = /^([^@/:\s]+)@([^/:\s]+):(.+)$/.exec(value);
|
|
683
|
+
const candidate = scp ? `ssh://${scp[2]}/${scp[3]}` : value;
|
|
684
|
+
let parsed;
|
|
685
|
+
try {
|
|
686
|
+
parsed = new URL(candidate);
|
|
687
|
+
}
|
|
688
|
+
catch {
|
|
689
|
+
throw new CliError("origin_verification_failed", "repository URL cannot be normalized safely");
|
|
690
|
+
}
|
|
691
|
+
if (!["https:", "ssh:"].includes(parsed.protocol) || !parsed.hostname || parsed.search || parsed.hash)
|
|
692
|
+
throw new CliError("origin_verification_failed", "repository URL cannot be normalized safely");
|
|
693
|
+
const path = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
|
|
694
|
+
if (!path)
|
|
695
|
+
throw new CliError("origin_verification_failed", "repository URL has no repository path");
|
|
696
|
+
const port = parsed.port && !(parsed.protocol === "ssh:" && parsed.port === "22") ? `${parsed.protocol.slice(0, -1)}:${parsed.port}@` : "";
|
|
697
|
+
return `${port}${parsed.hostname.toLowerCase()}/${path}`;
|
|
698
|
+
}
|
|
699
|
+
/** Verify the selected commit against a freshly fetched, consistently advertised origin branch. */
|
|
700
|
+
export function verifyUnitHeadOnOrigin(branch, sha, repositoryIdentity, repositoryUrl, cwd = process.cwd()) {
|
|
701
|
+
if (!/^[0-9a-f]{40}$/.test(sha))
|
|
702
|
+
throw new CliError("usage", "head must be a full 40-character lowercase commit SHA");
|
|
703
|
+
if (!/^[0-9a-f]{64}$/.test(repositoryIdentity))
|
|
704
|
+
throw new CliError("origin_verification_failed", "the project did not provide a valid repository identity");
|
|
705
|
+
const configured = spawnSync("git", ["config", "--get-all", "remote.origin.url"], { cwd, encoding: "utf8" });
|
|
706
|
+
const effective = spawnSync("git", ["remote", "get-url", "--all", "origin"], { cwd, encoding: "utf8" });
|
|
707
|
+
const urls = (text) => text.trim().split(/\r?\n/).filter(Boolean);
|
|
708
|
+
const configuredUrls = urls(configured.stdout ?? "");
|
|
709
|
+
const effectiveUrls = urls(effective.stdout ?? "");
|
|
710
|
+
if (configured.status !== 0 || effective.status !== 0 || configuredUrls.length !== 1 || effectiveUrls.length !== 1)
|
|
711
|
+
throw new CliError("origin_verification_failed", "origin must have exactly one configured URL");
|
|
712
|
+
const expected = normalizedRepositoryUrl(repositoryUrl);
|
|
713
|
+
const configuredOrigin = normalizedRepositoryUrl(configuredUrls[0]);
|
|
714
|
+
const effectiveOrigin = normalizedRepositoryUrl(effectiveUrls[0]);
|
|
715
|
+
if (configuredOrigin !== expected || effectiveOrigin !== expected)
|
|
716
|
+
throw new CliError("origin_verification_failed", `this checkout's origin ${configuredOrigin}${effectiveOrigin !== configuredOrigin ? ` (effective ${effectiveOrigin})` : ""} does not match the selected project's configured repository ${expected}`);
|
|
717
|
+
const remoteRef = `refs/heads/${branch}`;
|
|
718
|
+
if (spawnSync("git", ["check-ref-format", remoteRef], { cwd }).status !== 0)
|
|
719
|
+
throw new CliError("no_branch", "the recorded branch is not a valid Git branch");
|
|
720
|
+
const fetched = fetchRemoteBranch(branch, "origin", cwd);
|
|
721
|
+
if (!fetched.ok)
|
|
722
|
+
throw new CliError("origin_verification_failed", `cannot fetch the recorded branch from origin: ${fetched.reason}`);
|
|
723
|
+
const fetchedTip = fullSha(`refs/remotes/origin/${branch}`, cwd);
|
|
724
|
+
const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", remoteRef], { cwd, encoding: "utf8", timeout: 120_000 });
|
|
725
|
+
if (listed.status !== 0)
|
|
726
|
+
throw new CliError("origin_verification_failed", `cannot read the recorded branch from origin: ${listed.error?.message || listed.stderr?.trim() || `git ls-remote exited ${listed.status ?? "without a status"}`}`);
|
|
727
|
+
const lines = listed.stdout.trim().split(/\r?\n/).map((line) => line.split(/\s+/));
|
|
728
|
+
if (lines.length !== 1 || lines[0]?.[1] !== remoteRef || !/^[0-9a-f]{40}$/.test(lines[0]?.[0] ?? ""))
|
|
729
|
+
throw new CliError("origin_verification_failed", "origin did not advertise exactly the recorded branch and a full SHA");
|
|
730
|
+
const remoteTip = lines[0][0];
|
|
731
|
+
if (!fetchedTip || fetchedTip !== remoteTip)
|
|
732
|
+
throw new CliError("origin_verification_failed", "the origin branch changed while it was being verified; fetch and try again");
|
|
733
|
+
const onBranch = isAncestor(sha, fetchedTip, cwd);
|
|
734
|
+
if (onBranch !== true)
|
|
735
|
+
throw new CliError("origin_verification_failed", onBranch === false ? `${sha} is not on origin/${branch}` : `cannot verify ${sha} against origin/${branch}`);
|
|
736
|
+
return { branch, remote_tip: remoteTip, repository_identity: repositoryIdentity };
|
|
737
|
+
}
|
|
680
738
|
/** Check a merge against the local target, then the freshly fetched origin target when needed. */
|
|
681
739
|
export function verifyMergedCommit(merged, target, cwd = process.cwd()) {
|
|
682
740
|
const local = isAncestor(merged, target, cwd);
|
package/dist/harness.js
CHANGED
|
@@ -153,6 +153,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
|
|
|
153
153
|
writeFileSync(join(neutral, "references", "watchers.md"), files.watchers);
|
|
154
154
|
writeFileSync(join(neutral, "references", "process.md"), files.process);
|
|
155
155
|
writeFileSync(join(neutral, "references", "continuity.md"), files.continuity);
|
|
156
|
+
writeFileSync(join(neutral, "references", "agent-guide.md"), files.agentGuide);
|
|
156
157
|
written.push(join(neutral, "SKILL.md"));
|
|
157
158
|
switch (harness) {
|
|
158
159
|
case "claude-code": {
|
|
@@ -163,6 +164,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
|
|
|
163
164
|
writeFileSync(join(dir, "references", "watchers.md"), files.watchers);
|
|
164
165
|
writeFileSync(join(dir, "references", "process.md"), files.process);
|
|
165
166
|
writeFileSync(join(dir, "references", "continuity.md"), files.continuity);
|
|
167
|
+
writeFileSync(join(dir, "references", "agent-guide.md"), files.agentGuide);
|
|
166
168
|
written.push(join(dir, "SKILL.md"));
|
|
167
169
|
rmSync(join(root, ".claude", "skills", "bschat"), { recursive: true, force: true });
|
|
168
170
|
const sp = join(root, ".claude", "settings.local.json");
|
package/dist/help.js
CHANGED
|
@@ -175,6 +175,7 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
175
175
|
b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
|
|
176
176
|
b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
|
|
177
177
|
b9s wu target <n> <branch|default> [--summary "reviewed work summary"] owner, assigner or operator: change where this unit lands
|
|
178
|
+
b9s wu head <n> <full-sha> --reason "why" assigner or operator: record a commit verified on the unit's branch
|
|
178
179
|
b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."] [--milestone <key> | --unit <n>] [--question <text>]
|
|
179
180
|
b9s ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] [--question <text>] amend your own open ask
|
|
180
181
|
b9s ask-operator withdraw <key> --note "why it no longer needs an operator answer" withdraw your own ask, a steward-raised declared-wait ask, or an ask if you are a project assigner
|
|
@@ -190,6 +191,7 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
190
191
|
wu release <n> [--note ..] lifts it earlier
|
|
191
192
|
b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
|
|
192
193
|
b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; checks its branch has no commits beyond the target for no-source; requires a passing lock-run gate receipt for the commit or matching tree
|
|
194
|
+
Antigravity workspace-write queues the exact closed worktree for cleanup outside the sandbox at turn finalization; branches are kept
|
|
193
195
|
b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
|
|
194
196
|
b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
|
|
195
197
|
b9s wu show <n> [--scope-only] show the full unit (including route/review explanation when recorded) or only its scope for scripts
|
|
@@ -198,7 +200,8 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
198
200
|
b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
|
|
199
201
|
b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
|
|
200
202
|
b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
|
|
201
|
-
--archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it
|
|
203
|
+
--archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
|
|
204
|
+
refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
|
|
202
205
|
b9s worktrees [scan] the project's worktree registry (machine, path, branch, dirty, merged, who);
|
|
203
206
|
scan reports every linked worktree of the repo you are in (watchers do this hourly)
|
|
204
207
|
b9s goal [set "<text>" [--state s] | achieved | paused | stalled | abandoned | clear]
|
|
@@ -402,6 +405,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
|
|
|
402
405
|
b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
|
|
403
406
|
b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
|
|
404
407
|
b9s-admin wu merged-sha <project> <n> --sha <full-40-character-lowercase-sha> --reason "why" operator: correct a legacy abbreviated merged SHA with an audited reason
|
|
408
|
+
b9s-admin wu head <project> <n> <full-sha> --reason "why" operator: record a commit verified on the unit's branch
|
|
405
409
|
b9s-admin wu required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why" set or clear an operator hard routing-class lock
|
|
406
410
|
b9s-admin routing show <project> [--mode build|review] [--tag <tag>] inspect confidence matrix, exploration spend, and recent decisions
|
|
407
411
|
b9s-admin routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason "why"]
|
package/dist/sandbox-probe.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { createServer } from "node:http";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { homedir } from "node:os";
|
|
@@ -11,7 +12,8 @@ export const PROBE_CHECKS = [
|
|
|
11
12
|
"cwd_is_checkout", "origin_is_https",
|
|
12
13
|
"tool_node", "tool_npm", "tool_npx", "tool_git", "tool_b9s",
|
|
13
14
|
"git_branch", "git_branch_delete", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
|
|
14
|
-
"net_api", "net_other_host",
|
|
15
|
+
"net_api", "net_other_host", "net_loopback",
|
|
16
|
+
"tmpdir_writable", "system_tmpdir_refused",
|
|
15
17
|
"write_checkout", "write_checkout_parent", "write_unit_worktree", "write_sibling_checkout", "git_commit", "git_fetch", "write_b9s_home",
|
|
16
18
|
"write_git_config", "write_git_hooks", "write_home", "write_node_install",
|
|
17
19
|
];
|
|
@@ -186,6 +188,30 @@ async function reach(url, timeoutMs = 10_000) {
|
|
|
186
188
|
return { ok: false, detail: clip(cause ? `${e.message}: ${cause}` : e.message) };
|
|
187
189
|
}
|
|
188
190
|
}
|
|
191
|
+
async function reachLoopback() {
|
|
192
|
+
const server = createServer((_request, response) => { response.end("b9s-loopback-ok"); });
|
|
193
|
+
try {
|
|
194
|
+
await new Promise((resolve, reject) => {
|
|
195
|
+
server.once("error", reject);
|
|
196
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
197
|
+
});
|
|
198
|
+
const address = server.address();
|
|
199
|
+
if (!address || typeof address === "string")
|
|
200
|
+
throw new Error("loopback server did not report its bound address");
|
|
201
|
+
const response = await fetch(`http://127.0.0.1:${address.port}/probe`, { signal: AbortSignal.timeout(5_000), redirect: "manual" });
|
|
202
|
+
const body = await response.text();
|
|
203
|
+
if (response.status !== 200 || body !== "b9s-loopback-ok")
|
|
204
|
+
throw new Error(`loopback response was HTTP ${response.status} with unexpected body`);
|
|
205
|
+
return { ok: true, value: `127.0.0.1:${address.port}`, detail: "local HTTP server reached directly" };
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
return { ok: false, detail: clip(error.message) };
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
if (server.listening)
|
|
212
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
189
215
|
export async function runSandboxProbe(options) {
|
|
190
216
|
const env = options.env ?? process.env;
|
|
191
217
|
const cwd = options.cwd ?? process.cwd();
|
|
@@ -214,6 +240,9 @@ export async function runSandboxProbe(options) {
|
|
|
214
240
|
checks.tool_npx = tool("npx", ["--version"], cwd, env);
|
|
215
241
|
checks.tool_git = tool("git", ["--version"], cwd, env);
|
|
216
242
|
checks.tool_b9s = tool("b9s", null, cwd, env);
|
|
243
|
+
checks.tmpdir_writable = env.TMPDIR ? createAndRemove(env.TMPDIR, nonce) : { ok: false, detail: "TMPDIR is not set" };
|
|
244
|
+
checks.system_tmpdir_refused = createAndRemove("/tmp", nonce);
|
|
245
|
+
checks.net_loopback = await reachLoopback();
|
|
217
246
|
if (toplevel) {
|
|
218
247
|
const agent = env.BSCHAT_AGENT;
|
|
219
248
|
const watcherCleansRef = options.harness === "antigravity" && options.sandbox === "workspace-write";
|
|
@@ -387,7 +416,8 @@ export function expectedFor(harness, sandbox, result) {
|
|
|
387
416
|
cwd_is_checkout: works, origin_is_https: { expected: "any", note: UNMEASURED },
|
|
388
417
|
tool_node: works, tool_npm: works, tool_npx: works, tool_git: works, tool_b9s: works,
|
|
389
418
|
git_branch: works, git_branch_delete: works, git_object: works, git_worktree: works, git_other_worktree: result?.checks.git_other_worktree?.not_applicable ? otherWorktree : { expected: "any", note: UNMEASURED }, git_remote_read: works,
|
|
390
|
-
net_api: works, net_other_host: { expected: "any", note: UNMEASURED },
|
|
419
|
+
net_api: works, net_other_host: { expected: "any", note: UNMEASURED }, net_loopback: { expected: "any", note: UNMEASURED },
|
|
420
|
+
tmpdir_writable: { expected: "any", note: UNMEASURED }, system_tmpdir_refused: { expected: "any", note: UNMEASURED },
|
|
391
421
|
write_checkout: works, write_checkout_parent: works, write_unit_worktree: { expected: "any", note: "requires --unit-worktree" }, write_sibling_checkout: { expected: "any", note: "requires --sibling-checkout" }, git_commit: { expected: "any", note: "requires --unit-worktree" }, git_fetch: { expected: "any", note: "requires --unit-worktree" }, write_b9s_home: works,
|
|
392
422
|
write_git_config: { expected: "any", note: ACCEPTED_GIT }, write_git_hooks: { expected: "any", note: ACCEPTED_GIT },
|
|
393
423
|
write_home: { expected: "any", note: UNMEASURED }, write_node_install: { expected: "any", note: UNMEASURED },
|
|
@@ -404,6 +434,9 @@ export function expectedFor(harness, sandbox, result) {
|
|
|
404
434
|
return {
|
|
405
435
|
...base,
|
|
406
436
|
origin_is_https: works,
|
|
437
|
+
net_loopback: { expected: "works", note: "Antigravity workspace-write must reach an explicitly bound local test server; loopback bypass is limited to localhost, 127.0.0.1 and ::1" },
|
|
438
|
+
tmpdir_writable: { expected: "works", note: "b9s start sets a checkout-local per-agent scratch directory for Antigravity workspace-write" },
|
|
439
|
+
system_tmpdir_refused: { expected: "refused", note: "Antigravity workspace-write remains scoped to checkout grants; system /tmp is not granted" },
|
|
407
440
|
git_branch_delete: { expected: "refused", note: ANTIGRAVITY_REF_CLEANUP },
|
|
408
441
|
git_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
|
|
409
442
|
write_checkout_parent: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
|
|
@@ -476,7 +509,8 @@ const LABEL = {
|
|
|
476
509
|
origin_is_https: "origin is reached over HTTPS",
|
|
477
510
|
tool_node: "node runs", tool_npm: "npm runs", tool_npx: "npx runs", tool_git: "git runs", tool_b9s: "b9s is on PATH",
|
|
478
511
|
git_branch: "git can create a probe branch", git_branch_delete: "git can delete a branch from inside the session", git_object: "git can write a commit object", git_worktree: "git can add its reserved sandbox probe worktree", git_other_worktree: "another agent's Git worktree metadata is writable", git_remote_read: "git can read origin",
|
|
479
|
-
net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable",
|
|
512
|
+
net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable", net_loopback: "a local test server is reachable through loopback",
|
|
513
|
+
tmpdir_writable: "the configured TMPDIR accepts a temporary file", system_tmpdir_refused: "the system /tmp directory is refused",
|
|
480
514
|
write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_unit_worktree: "the active unit worktree is writable", write_sibling_checkout: "a sibling checkout is writable", git_commit: "git commit works in the active unit worktree", git_fetch: "git fetch works in the active unit worktree", write_b9s_home: "b9s's own folder is writable",
|
|
481
515
|
write_git_config: "the clone's git config is writable", write_git_hooks: "the clone's git hooks are writable",
|
|
482
516
|
write_home: "the home folder is writable", write_node_install: "the Node installation is writable",
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.145";
|