benignswarm 0.12.93 → 0.12.94
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 +167 -46
- package/dist/args.js +1 -1
- package/dist/brief.js +1 -1
- package/dist/client.js +20 -0
- package/dist/commands/codex-start.js +119 -22
- package/dist/commands/machine-admin.js +7 -7
- package/dist/commands/watch.js +8 -11
- package/dist/commands/wu.js +188 -5
- package/dist/git.js +1 -1
- package/dist/harnesses.js +7 -6
- package/dist/help.js +8 -6
- package/dist/index.js +1 -1
- package/dist/recovery-archive.js +149 -0
- package/dist/turn-guard.js +2 -0
- package/dist/usage.js +6 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -211,8 +211,8 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
211
211
|
if (sub === "add") {
|
|
212
212
|
const turnTimeout = str(p.flags, "turn-timeout");
|
|
213
213
|
const turnsPerHour = str(p.flags, "turns-per-hour");
|
|
214
|
-
if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) >
|
|
215
|
-
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to
|
|
214
|
+
if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 60))
|
|
215
|
+
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
|
|
216
216
|
const body = {
|
|
217
217
|
project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
|
|
218
218
|
model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
|
|
@@ -240,7 +240,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
240
240
|
}
|
|
241
241
|
if (sub === "limit") {
|
|
242
242
|
const value = str(p.flags, "turns-per-hour");
|
|
243
|
-
if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) >
|
|
243
|
+
if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 60)
|
|
244
244
|
throw new CliError("usage", "machine session limit <machine> <project>/<agent> --turns-per-hour <1..20>");
|
|
245
245
|
const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turns_per_hour: Number(value) });
|
|
246
246
|
return out.print(`${ref} on ${machineName}: turn limit set to ${value} per hour; the daemon applies it within 30 s.`, r);
|
|
@@ -273,7 +273,7 @@ export function repeated(argv, flag) {
|
|
|
273
273
|
return out;
|
|
274
274
|
}
|
|
275
275
|
/**
|
|
276
|
-
* pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..
|
|
276
|
+
* pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]
|
|
277
277
|
* pool list [project] | show <project>/<name> | remove <project>/<name>
|
|
278
278
|
*/
|
|
279
279
|
export async function poolAdmin(action, rest, p, out, argv) {
|
|
@@ -288,12 +288,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
|
|
|
288
288
|
const variants = repeated(argv, "variant").map(parseVariant);
|
|
289
289
|
const count = Number(str(p.flags, "count"));
|
|
290
290
|
if (!project || !name || !variants.length || !Number.isInteger(count))
|
|
291
|
-
throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..
|
|
291
|
+
throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]");
|
|
292
292
|
const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
|
|
293
293
|
const tt = str(p.flags, "turn-timeout");
|
|
294
294
|
const tph = str(p.flags, "turns-per-hour");
|
|
295
|
-
if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) >
|
|
296
|
-
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to
|
|
295
|
+
if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 60))
|
|
296
|
+
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
|
|
297
297
|
const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}) });
|
|
298
298
|
return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
|
|
299
299
|
}
|
package/dist/commands/watch.js
CHANGED
|
@@ -22,7 +22,7 @@ import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
|
|
|
22
22
|
import { readState, writeState } from "../state.js";
|
|
23
23
|
import { probeCapabilities } from "../capabilities.js";
|
|
24
24
|
import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
|
|
25
|
-
import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
|
|
25
|
+
import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
|
|
26
26
|
import { sessionUsage } from "../usage.js";
|
|
27
27
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
28
28
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
@@ -70,8 +70,8 @@ export async function watch(p, out) {
|
|
|
70
70
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
71
71
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
72
72
|
const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
|
|
73
|
-
if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour >
|
|
74
|
-
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${
|
|
73
|
+
if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
|
|
74
|
+
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
|
|
75
75
|
if (!turnMode && p.flags["turns-per-hour"] !== undefined)
|
|
76
76
|
throw new CliError("usage", "--turns-per-hour is only used with --turn");
|
|
77
77
|
const thread = exec ? threadOfExec(exec) : null;
|
|
@@ -87,7 +87,7 @@ export async function watch(p, out) {
|
|
|
87
87
|
throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
|
|
88
88
|
const named = str(p.flags, "harness") ?? (thread ? "codex" : undefined);
|
|
89
89
|
if (!named)
|
|
90
|
-
throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh> and --session <id> (a Codex exec resume command names its thread itself)");
|
|
90
|
+
throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh|antigravity> and --session <id> (a Codex exec resume command names its thread itself)");
|
|
91
91
|
const harness = turnHarness(named);
|
|
92
92
|
const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
|
|
93
93
|
if (!session)
|
|
@@ -581,7 +581,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
581
581
|
ctl.failedAt = Date.now();
|
|
582
582
|
}
|
|
583
583
|
ctl.turn = null;
|
|
584
|
-
await completePendingTurnGuard(name, probe, log, undefined, env);
|
|
584
|
+
await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
|
|
585
585
|
return;
|
|
586
586
|
}
|
|
587
587
|
if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
|
|
@@ -612,7 +612,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
612
612
|
}
|
|
613
613
|
if ("missing" in ph) {
|
|
614
614
|
if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
615
|
-
await completePendingTurnGuard(name, probe, log, undefined, env);
|
|
615
|
+
await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
|
|
616
616
|
if (readState(name, env).turn_guard?.fault)
|
|
617
617
|
return;
|
|
618
618
|
}
|
|
@@ -620,7 +620,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
620
620
|
return;
|
|
621
621
|
}
|
|
622
622
|
if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
623
|
-
await completePendingTurnGuard(name, probe, log, undefined, env);
|
|
623
|
+
await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
|
|
624
624
|
if (readState(name, env).turn_guard?.fault)
|
|
625
625
|
return;
|
|
626
626
|
}
|
|
@@ -712,10 +712,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
|
|
|
712
712
|
}
|
|
713
713
|
return true;
|
|
714
714
|
}
|
|
715
|
-
export async function completePendingTurnGuard(name, probe, log, outputOverride,
|
|
716
|
-
// The watcher passes its isolated environment; start-turn callers may pass measured tokens.
|
|
717
|
-
const env = tokenOverrideOrEnv !== null && typeof tokenOverrideOrEnv === "object" ? tokenOverrideOrEnv : envOverride;
|
|
718
|
-
const tokenOverride = tokenOverrideOrEnv === null || typeof tokenOverrideOrEnv === "number" ? tokenOverrideOrEnv : undefined;
|
|
715
|
+
export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
|
|
719
716
|
const current = readState(name, env);
|
|
720
717
|
const guard = current.turn_guard;
|
|
721
718
|
const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
|
package/dist/commands/wu.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { bool, str } from "../args.js";
|
|
4
4
|
import { Client } from "../client.js";
|
|
5
5
|
import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
@@ -8,12 +8,22 @@ import { codexRollout, sessionsOf } from "../sessions.js";
|
|
|
8
8
|
import { sessionUsage, watcherClaudeUsage } from "../usage.js";
|
|
9
9
|
import { CliError } from "../errors.js";
|
|
10
10
|
import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
11
|
-
import { resolve } from "node:path";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
12
|
import { table } from "../output.js";
|
|
13
|
+
import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
|
|
14
|
+
import { createRecoveryArchive } from "../recovery-archive.js";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
13
16
|
/** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
|
|
14
17
|
export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
|
|
15
18
|
return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
|
|
16
19
|
}
|
|
20
|
+
/** Antigravity has an independent sandbox marker; never infer it from Claude's environment. */
|
|
21
|
+
export function shouldInheritAntigravitySandboxUrlRewrites(env = process.env) {
|
|
22
|
+
return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
|
|
23
|
+
}
|
|
24
|
+
export function shouldInheritSandboxUrlRewrites(env = process.env) {
|
|
25
|
+
return shouldInheritClaudeSandboxUrlRewrites(env) || shouldInheritAntigravitySandboxUrlRewrites(env);
|
|
26
|
+
}
|
|
17
27
|
export function scopeEditFromArgs(p) {
|
|
18
28
|
const replacement = bool(p.flags, "replace");
|
|
19
29
|
const append = str(p.flags, "append");
|
|
@@ -78,6 +88,111 @@ function retrospectiveEventDetail(event) {
|
|
|
78
88
|
return ` [send-back retrospective finalized: ${data.retrospective.send_backs.length} recorded]`;
|
|
79
89
|
return "";
|
|
80
90
|
}
|
|
91
|
+
const GIT_FILE_LIMIT = 50 * 1024 * 1024;
|
|
92
|
+
const RECOVERY_LIMIT = 1024 * 1024 * 1024;
|
|
93
|
+
const regenerablePath = (path) => /(^|\/)(node_modules|target|dist|build|coverage|\.cache|\.next|\.turbo|__pycache__)(\/|$)/i.test(path);
|
|
94
|
+
function gitRun(cwd, args, extraEnv = {}) {
|
|
95
|
+
const result = spawnSync("git", args, { cwd, env: { ...process.env, ...extraEnv }, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
96
|
+
if (result.status !== 0)
|
|
97
|
+
throw new CliError("recovery_git_failed", `git ${args[0]} failed: ${result.stderr?.trim() || "unknown Git error"}`);
|
|
98
|
+
return result.stdout;
|
|
99
|
+
}
|
|
100
|
+
/** Pushes the branch tip even when there was no dirty work to turn into a WIP commit. */
|
|
101
|
+
export function pushCutoffBranch(cwd, branch) {
|
|
102
|
+
const pushed = spawnSync("git", ["push", "origin", `HEAD:refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 2 * 1024 * 1024 });
|
|
103
|
+
if (pushed.status === 0)
|
|
104
|
+
return null;
|
|
105
|
+
return (pushed.stderr?.trim() || "git push failed").replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, "https://[redacted]@").slice(0, 1000);
|
|
106
|
+
}
|
|
107
|
+
export function saveWipCommit(cwd, branch) {
|
|
108
|
+
const head = gitRun(cwd, ["rev-parse", "HEAD"]).trim();
|
|
109
|
+
const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-index-"));
|
|
110
|
+
const index = join(temp, "index");
|
|
111
|
+
const extra = { GIT_INDEX_FILE: index };
|
|
112
|
+
try {
|
|
113
|
+
gitRun(cwd, ["read-tree", "HEAD"], extra);
|
|
114
|
+
gitRun(cwd, ["add", "-A"], extra);
|
|
115
|
+
const staged = gitRun(cwd, ["diff", "--cached", "--name-only", "-z"], extra).split("\0").filter(Boolean);
|
|
116
|
+
const oversized = staged.filter((path) => {
|
|
117
|
+
try {
|
|
118
|
+
return lstatSync(resolve(cwd, path)).isFile() && lstatSync(resolve(cwd, path)).size > GIT_FILE_LIMIT;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
for (const path of oversized)
|
|
125
|
+
gitRun(cwd, ["update-index", "--force-remove", "--", path], extra);
|
|
126
|
+
if (spawnSync("git", ["diff", "--cached", "--quiet"], { cwd, env: { ...process.env, ...extra } }).status === 0)
|
|
127
|
+
return { commit: null, oversized };
|
|
128
|
+
const tree = gitRun(cwd, ["write-tree"], extra).trim();
|
|
129
|
+
const commit = gitRun(cwd, ["-c", "user.name=BenignSwarm cutoff", "-c", "user.email=cutoff@benignswarm.invalid", "commit-tree", tree, "-p", head, "-m", `Forced cutoff WIP save for ${branch}`]).trim();
|
|
130
|
+
gitRun(cwd, ["update-ref", `refs/heads/${branch}`, commit, head]);
|
|
131
|
+
return { commit, oversized };
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
rmSync(temp, { recursive: true, force: true });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function createCutoffBundle(cwd, branch, oversized, pushError) {
|
|
138
|
+
const ignored = gitRun(cwd, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]).split("\0").filter(Boolean);
|
|
139
|
+
const candidates = [...new Set([...ignored, ...oversized])].sort();
|
|
140
|
+
const files = [];
|
|
141
|
+
const omitted = [];
|
|
142
|
+
const skipped = [];
|
|
143
|
+
let total = 0;
|
|
144
|
+
for (const path of candidates) {
|
|
145
|
+
if (regenerablePath(path)) {
|
|
146
|
+
skipped.push({ path, reason: "regenerable build/cache output" });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const stat = lstatSync(resolve(cwd, path));
|
|
151
|
+
if (!stat.isFile()) {
|
|
152
|
+
omitted.push({ path, reason: "not a regular file; operator must inspect it on the source volume" });
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (total + stat.size > RECOVERY_LIMIT) {
|
|
156
|
+
omitted.push({ path, reason: "recovery bundle reached the 1 GiB uncompressed safety bound" });
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const bytes = new Uint8Array(readFileSync(resolve(cwd, path)));
|
|
160
|
+
files.push({ path, bytes });
|
|
161
|
+
total += bytes.length;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
omitted.push({ path, reason: "file could not be read at cutoff" });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (pushError) {
|
|
168
|
+
const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-bundle-"));
|
|
169
|
+
try {
|
|
170
|
+
const bundle = join(temp, "local.bundle");
|
|
171
|
+
const made = spawnSync("git", ["bundle", "create", bundle, `refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 1024 * 1024 });
|
|
172
|
+
if (made.status === 0) {
|
|
173
|
+
const bytes = new Uint8Array(readFileSync(bundle));
|
|
174
|
+
if (total + bytes.length <= RECOVERY_LIMIT) {
|
|
175
|
+
files.push({ path: "recovery/local.bundle", bytes });
|
|
176
|
+
total += bytes.length;
|
|
177
|
+
}
|
|
178
|
+
else
|
|
179
|
+
omitted.push({ path: "recovery/local.bundle", reason: "local Git bundle exceeded the 1 GiB recovery bound" });
|
|
180
|
+
}
|
|
181
|
+
else
|
|
182
|
+
omitted.push({ path: "recovery/local.bundle", reason: `git bundle failed: ${made.stderr?.trim().slice(0, 250) || "unknown Git error"}` });
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
rmSync(temp, { recursive: true, force: true });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
let archive = createRecoveryArchive(files);
|
|
189
|
+
while (archive.length > RECOVERY_LIMIT && files.length) {
|
|
190
|
+
const removed = files.pop();
|
|
191
|
+
omitted.push({ path: removed.path, reason: "compressed recovery bundle exceeded the 1 GiB limit" });
|
|
192
|
+
archive = createRecoveryArchive(files);
|
|
193
|
+
}
|
|
194
|
+
return { archive, manifest: { captured: files.map(({ path, bytes }) => ({ path, size: bytes.length })), omitted, skipped } };
|
|
195
|
+
}
|
|
81
196
|
export function assignmentDisposition(unit, to) {
|
|
82
197
|
if (unit.status !== "queued")
|
|
83
198
|
return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
|
|
@@ -739,6 +854,72 @@ export async function wu(p, out) {
|
|
|
739
854
|
out.print(`${fmt(unit)}${context ? `\n${context}` : ""}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (b9s evidence get <id>)\nVerdict: b9s wu approve ${n} --note "..." | b9s wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote, measure_context: reviewDetail.measure_context });
|
|
740
855
|
return;
|
|
741
856
|
}
|
|
857
|
+
case "recovery": {
|
|
858
|
+
if (p.positionals[2] === "save") {
|
|
859
|
+
const n = Number(p.positionals[3]);
|
|
860
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
861
|
+
throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
|
|
862
|
+
const reason = str(p.flags, "reason");
|
|
863
|
+
if (!reason?.trim())
|
|
864
|
+
throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
|
|
865
|
+
const cwd = process.cwd();
|
|
866
|
+
const { branch } = branchAndHead(cwd);
|
|
867
|
+
if (!branch)
|
|
868
|
+
throw new CliError("recovery_branch_missing", "run recovery save from the unit's own branch worktree");
|
|
869
|
+
const existing = await client.call("GET", `${base}/${n}`);
|
|
870
|
+
if (existing.unit.branch !== branch)
|
|
871
|
+
throw new CliError("recovery_branch_mismatch", `current branch ${branch} does not match WU #${n}'s pinned branch ${existing.unit.branch}`);
|
|
872
|
+
const begun = await client.call("POST", `${base}/${n}/recovery`, { cutoff_reason: reason.trim(), branch });
|
|
873
|
+
const id = begun.recovery.id;
|
|
874
|
+
try {
|
|
875
|
+
const saved = saveWipCommit(cwd, branch);
|
|
876
|
+
// A clean worktree can still have a local-only HEAD; always prove its ref reached origin.
|
|
877
|
+
const pushError = pushCutoffBranch(cwd, branch);
|
|
878
|
+
const { archive, manifest } = createCutoffBundle(cwd, branch, saved.oversized, pushError);
|
|
879
|
+
const manifestText = JSON.stringify(manifest);
|
|
880
|
+
if (manifestText.length > 200_000)
|
|
881
|
+
throw new CliError("recovery_manifest_too_large", "the omitted-file manifest exceeds the API limit; keep this volume and ask the operator to resolve it");
|
|
882
|
+
const response = await client.raw("POST", `${base}/${n}/recovery/${id}/upload`, archive.buffer.slice(archive.byteOffset, archive.byteOffset + archive.byteLength), {
|
|
883
|
+
"content-type": "application/octet-stream", "x-bschat-sha256": recoverySha256(archive),
|
|
884
|
+
"x-bschat-recovery-manifest": manifestText, "x-bschat-cutoff-reason": reason.trim(),
|
|
885
|
+
...(saved.commit ? { "x-bschat-wip-commit": saved.commit } : {}), ...(pushError ? { "x-bschat-push-error": pushError } : {}),
|
|
886
|
+
});
|
|
887
|
+
const result = await response.json();
|
|
888
|
+
out.print(`Recovery bundle ${result.recovery.status}; WIP commit ${saved.commit ?? "not needed"}${pushError ? `; push failed: ${pushError}` : ""}. Keep the source volume until the API reports safe_to_delete.`, result);
|
|
889
|
+
}
|
|
890
|
+
catch (error) {
|
|
891
|
+
try {
|
|
892
|
+
await client.call("POST", `${base}/${n}/recovery/${id}/failure`, { failure: error.message.slice(0, 1500) });
|
|
893
|
+
}
|
|
894
|
+
catch { /* the original recovery error is the useful one */ }
|
|
895
|
+
throw error;
|
|
896
|
+
}
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (p.positionals[2] !== "restore")
|
|
900
|
+
throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\" | restore <unit>");
|
|
901
|
+
const n = Number(p.positionals[3]);
|
|
902
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
903
|
+
throw new CliError("usage", "wu recovery restore <unit>");
|
|
904
|
+
const metadata = await client.call("GET", `${base}/${n}/recovery`);
|
|
905
|
+
const recovery = metadata.recovery;
|
|
906
|
+
if (!recovery?.available)
|
|
907
|
+
throw new CliError("recovery_unavailable", `no verified recovery bundle is available for WU #${n}`);
|
|
908
|
+
if (!recovery.id || !recovery.sha256)
|
|
909
|
+
throw new CliError("bad_response", "recovery metadata is missing its identifier or checksum");
|
|
910
|
+
const unitResult = await client.call("GET", `${base}/${n}`);
|
|
911
|
+
const worktree = worktreeForBranch(unitResult.unit.branch);
|
|
912
|
+
if (!worktree)
|
|
913
|
+
throw new CliError("recovery_worktree_missing", `the worktree for ${unitResult.unit.branch} is not checked out; start WU #${n} with b9s wu start ${n} --branch ${unitResult.unit.branch}`);
|
|
914
|
+
const response = await client.raw("GET", `${base}/${n}/recovery/${recovery.id}/content`);
|
|
915
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
916
|
+
const digest = recoverySha256(bytes);
|
|
917
|
+
if (digest !== recovery.sha256)
|
|
918
|
+
throw new CliError("recovery_checksum_mismatch", `downloaded recovery checksum is ${digest}; expected ${recovery.sha256}; no files were restored`);
|
|
919
|
+
const restored = await restoreRecoveryArchive(bytes, worktree);
|
|
920
|
+
out.print(`Restored ${restored.length} recovery file(s) into ${worktree}${recovery.manifest?.omitted?.length ? `\nUncaptured files remain: ${recovery.manifest.omitted.length}; the source volume must stay protected.` : ""}`, { restored, worktree, recovery });
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
742
923
|
case "show": {
|
|
743
924
|
const r = await client.call("GET", `${base}/${num()}`);
|
|
744
925
|
const onlyScope = scopeOnlyOutput(r.unit, bool(p.flags, "scope-only"));
|
|
@@ -749,7 +930,9 @@ export async function wu(p, out) {
|
|
|
749
930
|
const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}${e.data?.to && Array.isArray(e.data.to) ? ` -> ${e.data.to.join(", ")}` : ""}${retrospectiveEventDetail(e)}`).join("\n");
|
|
750
931
|
const lessons = [...r.events].reverse().filter((e) => typeof e.data?.lesson === "string").map((e) => ` ${e.actor_name}: ${e.data.lesson}`).join("\n");
|
|
751
932
|
const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
|
|
752
|
-
|
|
933
|
+
const recovery = r.unit.recovery;
|
|
934
|
+
const recoveryText = recovery ? `\nRecovery: ${recovery.available ? `available (${recovery.size ?? "?"} bytes, sha256 ${recovery.sha256 ?? "?"})` : "not verified"}${recovery.expires_at ? `; expires ${recovery.expires_at}` : ""}${recovery.manifest?.skipped?.length ? `; skipped ${recovery.manifest.skipped.length} regenerable path(s)` : ""}${recovery.manifest?.omitted?.length ? `; ${recovery.manifest.omitted.length} uncaptured path(s), source volume remains protected` : ""}${recovery.available ? `; restore: b9s wu recovery restore ${r.unit.number}` : ""}` : "";
|
|
935
|
+
out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
|
|
753
936
|
return;
|
|
754
937
|
}
|
|
755
938
|
case "list":
|
|
@@ -870,7 +1053,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
|
|
|
870
1053
|
branchCreated = true;
|
|
871
1054
|
log(`created ${pinned} from origin/${pinned}`);
|
|
872
1055
|
}
|
|
873
|
-
const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude,
|
|
1056
|
+
const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites()) : { created: false };
|
|
874
1057
|
return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
|
|
875
1058
|
}
|
|
876
1059
|
const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
|
|
@@ -884,7 +1067,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
|
|
|
884
1067
|
baseRef = at;
|
|
885
1068
|
}
|
|
886
1069
|
const branchCreated = fullSha(branch) === null;
|
|
887
|
-
const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude,
|
|
1070
|
+
const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
|
|
888
1071
|
return { mode: "fresh", path, branch, created: result.created, branchCreated };
|
|
889
1072
|
}
|
|
890
1073
|
/** Select the replay commit from the same target ref used to create its worktree. */
|
package/dist/git.js
CHANGED
|
@@ -162,7 +162,7 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
|
|
|
162
162
|
else
|
|
163
163
|
applyFullCheckout(path);
|
|
164
164
|
// Git copies config.worktree into linked worktrees. Strip inherited URL rewrites first so a
|
|
165
|
-
//
|
|
165
|
+
// sandbox-specific proxy workarounds never leak into Codex or full-access worktrees.
|
|
166
166
|
clearWorktreeUrlRewrites(path);
|
|
167
167
|
if (inheritUrlRewrites)
|
|
168
168
|
copyWorktreeUrlRewrites(cwd, path);
|
package/dist/harnesses.js
CHANGED
|
@@ -7,21 +7,22 @@ import { configRoot } from "./config.js";
|
|
|
7
7
|
import { readState, writeState } from "./state.js";
|
|
8
8
|
import { codexArchivedRollout, codexRollout } from "./sessions.js";
|
|
9
9
|
import { codexTurnPhase, usageLimitUntil } from "./turn.js";
|
|
10
|
+
import { antigravityProbe } from "./antigravity.js";
|
|
10
11
|
/**
|
|
11
12
|
* Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
|
|
12
13
|
* Each adapter says how to start a session, what one turn's command is, whether a turn is running in
|
|
13
14
|
* that session (by anyone: an app, a terminal, a turn left by a watcher that restarted), and how the
|
|
14
|
-
* last turn ended. Antigravity
|
|
15
|
-
*
|
|
15
|
+
* last turn ended. Antigravity uses its `agy` CLI and cached login; Gemini CLI no longer accepts
|
|
16
|
+
* personal logins (Google moved individuals to Antigravity).
|
|
16
17
|
*/
|
|
17
|
-
export const TURN_HARNESSES = ["codex", "claude-code", "dsh"];
|
|
18
|
+
export const TURN_HARNESSES = ["codex", "claude-code", "dsh", "antigravity"];
|
|
18
19
|
export function turnHarness(h) {
|
|
19
20
|
if (TURN_HARNESSES.includes(h))
|
|
20
21
|
return h;
|
|
21
22
|
throw new CliError("unsupported", `harness ${h} cannot run headless turns; supported: ${TURN_HARNESSES.join(", ")}`);
|
|
22
23
|
}
|
|
23
|
-
export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
|
|
24
|
-
export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
|
|
24
|
+
export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness", antigravity: "Antigravity" };
|
|
25
|
+
export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh", antigravity: "agy" };
|
|
25
26
|
/** Node's fetch ignores the sandbox's HTTP(S)_PROXY unless this opt-in is present. */
|
|
26
27
|
export function claudeSandboxEnv(sandbox) {
|
|
27
28
|
return sandbox === "workspace-write" ? { NODE_USE_ENV_PROXY: "1", BSCHAT_CLAUDE_SANDBOX: "workspace-write" } : {};
|
|
@@ -117,7 +118,7 @@ export function assertClaudeSelfCheck(stdout) {
|
|
|
117
118
|
throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${error}`);
|
|
118
119
|
}
|
|
119
120
|
export function probeFor(harness, session, ref) {
|
|
120
|
-
return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
|
|
121
|
+
return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : harness === "dsh" ? dshProbe(session, ref) : antigravityProbe(session, ref);
|
|
121
122
|
}
|
|
122
123
|
export const dshTurnLog = (ref) => join(configRoot(), "logs", `turn.${ref.replace("/", ".")}.jsonl`);
|
|
123
124
|
/** The first session event identifies a newly-created DeepSeek Harness session. */
|
package/dist/help.js
CHANGED
|
@@ -20,7 +20,7 @@ GET /account/usage reports used and allowed micro-dollars, uncertain calls and t
|
|
|
20
20
|
Session/admin clients can use GET /assistant/conversations, GET /assistant/conversations/:id/messages (paged history with saved tool notices), POST /assistant/conversations/:id/messages (SSE), and DELETE /assistant/conversations/:id. Old assistant messages report notices_available=false. The assistant can draft changes; POST /assistant/proposals/:id/apply or /discard is the operator's explicit action. See the agent/operator skill API reference for events and tools.
|
|
21
21
|
Free and paid accounts without a live Stripe subscription use the UTC calendar month; subscribed paid accounts reset at current_period_end.
|
|
22
22
|
|
|
23
|
-
GitHub repository links are managed by the account owner through the browser session API: POST /github/connect, GET /github/callback, GET /github/repositories, and POST/GET/DELETE /projects/:p/github-link. App setup steps are in the operator skill (packages/skill-admin/references/setup.md). Hosted merge remains disabled
|
|
23
|
+
GitHub repository links are managed by the account owner through the browser session API: POST /github/connect, GET /github/callback, GET /github/repositories, and POST/GET/DELETE /projects/:p/github-link. Hosted merge execution and status are served at POST/GET /projects/:p/work-units/:n/merge (role-checked against merge.merged_by, operator-hold checked, target-serialized in MergeTargetDO, with idempotent reconciliation and manual wu done disabled for enabled linked targets). App setup steps are in the operator skill (packages/skill-admin/references/setup.md). Hosted merge remains disabled per project (hosted_merge_enabled = 0) until the live GitHub bypass-change check completes and the operator enables it.
|
|
24
24
|
|
|
25
25
|
Agent commands
|
|
26
26
|
b9s login --as <name> --key <bs_agent_...> [--url <api>] [--label <machine-label>]
|
|
@@ -133,6 +133,8 @@ Agent commands
|
|
|
133
133
|
b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
|
|
134
134
|
b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; no-source closes an evidence-only unit without a merge SHA and checks its branch has no commits beyond the target
|
|
135
135
|
b9s wu show <n> [--scope-only] show the full unit or only its scope for scripts
|
|
136
|
+
b9s wu recovery save <n> --reason "..." save a WIP branch commit and encrypted cutoff bundle; keep the source volume until safe_to_delete
|
|
137
|
+
b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
|
|
136
138
|
b9s wu abandon <n> [--note ..] wu list [--all] for state and timeline
|
|
137
139
|
b9s worktrees prune [--yes] [--archive] remove clean worktrees whose work landed or whose unit is closed (dry run without --yes);
|
|
138
140
|
--archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it
|
|
@@ -150,9 +152,9 @@ Agent commands
|
|
|
150
152
|
--env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
|
|
151
153
|
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
|
|
152
154
|
--service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
|
|
153
|
-
itself (--harness codex|claude-code|dsh --session <id>); 3 consecutive turns without an
|
|
155
|
+
itself (--harness codex|claude-code|dsh|antigravity --session <id>); 3 consecutive turns without an
|
|
154
156
|
agent-key call stop it and report a machine error; max 20 turns/hour (lower with
|
|
155
|
-
--turns-per-hour 1..
|
|
157
|
+
--turns-per-hour 1..60). A fault persists across watcher restarts; an operator or
|
|
156
158
|
assigner resumes it with b9s-admin machine session resume.
|
|
157
159
|
Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
|
|
158
160
|
b9s update the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
|
|
@@ -162,7 +164,7 @@ Agent commands
|
|
|
162
164
|
b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
|
|
163
165
|
hook and instructions, each watcher's plist versus what launchd runs), with fixes
|
|
164
166
|
b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
|
|
165
|
-
b9s start --harness codex|claude-code|dsh --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..
|
|
167
|
+
b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--dsh path] [--agy path]
|
|
166
168
|
run an agent headless: enroll, start or adopt its session, turn-mode watcher
|
|
167
169
|
Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
|
|
168
170
|
(b9s codex start is the same with --harness codex)
|
|
@@ -288,7 +290,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
|
|
|
288
290
|
b9s-admin machine maintenance <name> --at <ISO | HH:MM> --for <30m | 2h> | --cancel a window: no new turns from
|
|
289
291
|
15 min before, its agents away until the machine reports back after booting
|
|
290
292
|
b9s-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access> [--harness codex|claude-code] [--provider anthropic|deepseek]
|
|
291
|
-
[--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..
|
|
293
|
+
[--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..60]
|
|
292
294
|
b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
|
|
293
295
|
b9s-admin machine session stop|start|resume|limit|remove <machine> <project>/<agent> resume a latched turn fault or set a lower per-session hourly limit
|
|
294
296
|
(change its count/settings, pause scaling, pin, or bench the agent)
|
|
@@ -305,7 +307,7 @@ Pools (a role, variants and a count; the server names the agents and places them
|
|
|
305
307
|
b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
|
|
306
308
|
b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
|
|
307
309
|
b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...]
|
|
308
|
-
--count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..
|
|
310
|
+
--count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]
|
|
309
311
|
slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
|
|
310
312
|
b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
|
|
311
313
|
b9s-admin delete-account --confirm "delete everything"
|
package/dist/index.js
CHANGED
|
@@ -73,7 +73,7 @@ const COMMANDS = {
|
|
|
73
73
|
start: async (p, out) => {
|
|
74
74
|
const h = str(p.flags, "harness");
|
|
75
75
|
if (!h)
|
|
76
|
-
throw new CliError("usage", "start needs --harness <codex|claude-code>");
|
|
76
|
+
throw new CliError("usage", "start needs --harness <codex|claude-code|dsh|antigravity>");
|
|
77
77
|
return harnessStart(p, out, turnHarness(h));
|
|
78
78
|
},
|
|
79
79
|
unpause: async (p, out) => unpause(p, out),
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { open, mkdir, lstat, realpath } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, resolve, sep } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
5
|
+
import { CliError } from "./errors.js";
|
|
6
|
+
const MAGIC = new TextEncoder().encode("BSRECOV1");
|
|
7
|
+
function safePath(root, path) {
|
|
8
|
+
if (!path || path.length > 4096 || isAbsolute(path) || path.includes("\\") || path.includes("\0") || path.split("/").some((part) => !part || part === "." || part === ".."))
|
|
9
|
+
throw new CliError("unsafe_recovery", `unsafe recovery path ${JSON.stringify(path)}`);
|
|
10
|
+
const target = resolve(root, path);
|
|
11
|
+
if (target !== root && !target.startsWith(root + sep))
|
|
12
|
+
throw new CliError("unsafe_recovery", `recovery path escapes worktree: ${path}`);
|
|
13
|
+
return target;
|
|
14
|
+
}
|
|
15
|
+
/** Restores the simple length-prefixed regular-file format emitted by b9s recovery save. */
|
|
16
|
+
export async function restoreRecoveryArchive(data, worktree) {
|
|
17
|
+
try {
|
|
18
|
+
data = gunzipSync(data, { maxOutputLength: 1024 * 1024 * 1024 + 16 * 1024 * 1024 + 12 });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new CliError("bad_recovery_archive", "recovery bundle is not valid gzip data or expands beyond the 1 GiB recovery limit");
|
|
22
|
+
}
|
|
23
|
+
if (data.length < 12 || !MAGIC.every((v, i) => data[i] === v))
|
|
24
|
+
throw new CliError("bad_recovery_archive", "recovery bundle has an unsupported archive format");
|
|
25
|
+
const manifestSize = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(8);
|
|
26
|
+
if (manifestSize > 16 * 1024 * 1024 || 12 + manifestSize > data.length)
|
|
27
|
+
throw new CliError("bad_recovery_archive", "recovery archive manifest is truncated or too large");
|
|
28
|
+
let files;
|
|
29
|
+
try {
|
|
30
|
+
files = JSON.parse(new TextDecoder().decode(data.subarray(12, 12 + manifestSize)));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw new CliError("bad_recovery_archive", "recovery archive manifest is invalid JSON");
|
|
34
|
+
}
|
|
35
|
+
if (!Array.isArray(files) || files.length > 100_000)
|
|
36
|
+
throw new CliError("bad_recovery_archive", "recovery archive file list is invalid");
|
|
37
|
+
let archiveSize = 0;
|
|
38
|
+
let archiveOffset = 12 + manifestSize;
|
|
39
|
+
const archivePaths = new Set();
|
|
40
|
+
for (const entry of files) {
|
|
41
|
+
if (!entry || typeof entry.path !== "string" || !Number.isSafeInteger(entry.size) || entry.size < 0 || archivePaths.has(entry.path))
|
|
42
|
+
throw new CliError("bad_recovery_archive", "recovery archive contains an invalid or duplicate file entry");
|
|
43
|
+
safePath(worktree, entry.path);
|
|
44
|
+
archivePaths.add(entry.path);
|
|
45
|
+
archiveSize += entry.size;
|
|
46
|
+
if (!Number.isSafeInteger(archiveSize) || archiveSize > 1024 * 1024 * 1024)
|
|
47
|
+
throw new CliError("bad_recovery_archive", "recovery archive file data exceeds the 1 GiB recovery limit");
|
|
48
|
+
archiveOffset += entry.size;
|
|
49
|
+
}
|
|
50
|
+
if (archiveOffset > data.length)
|
|
51
|
+
throw new CliError("bad_recovery_archive", "recovery archive file data is truncated");
|
|
52
|
+
if (archiveOffset !== data.length)
|
|
53
|
+
throw new CliError("bad_recovery_archive", "recovery archive has trailing bytes");
|
|
54
|
+
const root = await realpath(worktree);
|
|
55
|
+
let offset = 12 + manifestSize;
|
|
56
|
+
const restored = [];
|
|
57
|
+
const seen = new Set();
|
|
58
|
+
// Validate all existing paths first so a later symlink cannot cause a partial restore.
|
|
59
|
+
for (const entry of files) {
|
|
60
|
+
const target = safePath(root, entry.path);
|
|
61
|
+
let parent = root;
|
|
62
|
+
for (const part of entry.path.split("/").slice(0, -1)) {
|
|
63
|
+
parent = resolve(parent, part);
|
|
64
|
+
try {
|
|
65
|
+
const stat = await lstat(parent);
|
|
66
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
67
|
+
throw new CliError("unsafe_recovery", `recovery path crosses a symlink or non-directory: ${entry.path}`);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
if (error.code === "ENOENT")
|
|
71
|
+
break;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const stat = await lstat(target);
|
|
77
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
78
|
+
throw new CliError("unsafe_recovery", `refusing to replace a symlink or non-file: ${entry.path}`);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (error.code !== "ENOENT")
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (const entry of files) {
|
|
86
|
+
if (!entry || typeof entry.path !== "string" || !Number.isSafeInteger(entry.size) || entry.size < 0 || seen.has(entry.path))
|
|
87
|
+
throw new CliError("bad_recovery_archive", "recovery archive contains an invalid or duplicate file entry");
|
|
88
|
+
seen.add(entry.path);
|
|
89
|
+
const target = safePath(root, entry.path);
|
|
90
|
+
if (offset + entry.size > data.length)
|
|
91
|
+
throw new CliError("bad_recovery_archive", `recovery archive is truncated at ${entry.path}`);
|
|
92
|
+
const parts = entry.path.split("/");
|
|
93
|
+
let parent = root;
|
|
94
|
+
for (const part of parts.slice(0, -1)) {
|
|
95
|
+
parent = resolve(parent, part);
|
|
96
|
+
try {
|
|
97
|
+
const stat = await lstat(parent);
|
|
98
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
99
|
+
throw new CliError("unsafe_recovery", `recovery path crosses a symlink or non-directory: ${entry.path}`);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.code !== "ENOENT")
|
|
103
|
+
throw error;
|
|
104
|
+
await mkdir(parent);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const stat = await lstat(target);
|
|
109
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
110
|
+
throw new CliError("unsafe_recovery", `refusing to replace a symlink or non-file: ${entry.path}`);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
if (error.code !== "ENOENT")
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
const file = await open(target, "w", 0o600);
|
|
117
|
+
try {
|
|
118
|
+
await file.write(data.subarray(offset, offset + entry.size));
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
await file.close();
|
|
122
|
+
}
|
|
123
|
+
offset += entry.size;
|
|
124
|
+
restored.push(entry.path);
|
|
125
|
+
}
|
|
126
|
+
if (offset !== data.length)
|
|
127
|
+
throw new CliError("bad_recovery_archive", "recovery archive has trailing bytes");
|
|
128
|
+
return restored;
|
|
129
|
+
}
|
|
130
|
+
export function sha256(data) { return createHash("sha256").update(data).digest("hex"); }
|
|
131
|
+
export function recoveryArchiveHeader(files) {
|
|
132
|
+
const json = new TextEncoder().encode(JSON.stringify(files));
|
|
133
|
+
const header = new Uint8Array(12 + json.length);
|
|
134
|
+
header.set(MAGIC);
|
|
135
|
+
new DataView(header.buffer).setUint32(8, json.length);
|
|
136
|
+
header.set(json, 12);
|
|
137
|
+
return header;
|
|
138
|
+
}
|
|
139
|
+
export function createRecoveryArchive(files) {
|
|
140
|
+
const header = recoveryArchiveHeader(files.map(({ path, bytes }) => ({ path, size: bytes.length })));
|
|
141
|
+
const raw = new Uint8Array(header.length + files.reduce((n, entry) => n + entry.bytes.length, 0));
|
|
142
|
+
raw.set(header);
|
|
143
|
+
let offset = header.length;
|
|
144
|
+
for (const entry of files) {
|
|
145
|
+
raw.set(entry.bytes, offset);
|
|
146
|
+
offset += entry.bytes.length;
|
|
147
|
+
}
|
|
148
|
+
return gzipSync(raw, { level: 6 });
|
|
149
|
+
}
|