benignswarm 0.12.92 → 0.12.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -2,8 +2,8 @@ import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  // These options accept comma-separated collections, so repeating them should
4
4
  // append another collection instead of discarding earlier values.
5
- export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks"];
6
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
5
+ export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "writable-root", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks", "confirm-causes"];
6
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "writable-root", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes"];
7
7
  export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source", "allow-lower-tier"];
8
8
  export function parse(argv) {
9
9
  const options = {};
@@ -25,7 +25,15 @@ export function parse(argv) {
25
25
  }
26
26
  const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
27
27
  const flags = values;
28
- return { positionals, flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])) };
28
+ const repeatValues = {};
29
+ for (const [key, value] of Object.entries(flags))
30
+ if (Array.isArray(value))
31
+ repeatValues[key] = value;
32
+ return {
33
+ positionals,
34
+ flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])),
35
+ repeated: repeatValues,
36
+ };
29
37
  }
30
38
  catch (e) {
31
39
  if (e instanceof CliError)
@@ -37,6 +45,9 @@ export function str(flags, k) {
37
45
  const v = flags[k];
38
46
  return typeof v === "string" ? v : undefined;
39
47
  }
48
+ export function repeated(parsed, k) {
49
+ return parsed.repeated?.[k] ?? [];
50
+ }
40
51
  export function bool(flags, k) {
41
52
  return flags[k] === true;
42
53
  }
@@ -2,8 +2,9 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join as joinPath } from "node:path";
5
- import { bool, str } from "../args.js";
6
- import { agentRef, configRoot, loadAgent } from "../config.js";
5
+ import { bool, repeated, str } from "../args.js";
6
+ import { configRoot } from "../config.js";
7
+ import { startAgentIdentity, startEnrollmentIdentity, startWritableRoots } from "../start-options.js";
7
8
  import { CliError } from "../errors.js";
8
9
  import { requireInstall } from "../install.js";
9
10
  import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
@@ -16,6 +17,7 @@ import { randomUUID } from "node:crypto";
16
17
  import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
17
18
  import { claudeTurnEnv } from "../providers.js";
18
19
  import { DEFAULT_TURNS_PER_HOUR } from "../turn-guard.js";
20
+ import { configureGitCredentialForWorktree } from "./git-credential.js";
19
21
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
20
22
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
21
23
  /**
@@ -32,6 +34,22 @@ export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
32
34
  export async function codexStart(p, out) {
33
35
  return harnessStart(p, out, "codex");
34
36
  }
37
+ /** Builds the token enrollment call used by start; the token supplies project scope. */
38
+ export function startJoinArgs(p, harness, model) {
39
+ const identity = startEnrollmentIdentity(str(p.flags, "as") ?? "");
40
+ return {
41
+ parsed: {
42
+ ...p,
43
+ flags: {
44
+ ...p.flags,
45
+ as: identity.name,
46
+ vendor: harness,
47
+ model,
48
+ },
49
+ },
50
+ ...(identity.project ? { expectedProject: identity.project } : {}),
51
+ };
52
+ }
35
53
  export async function harnessStart(p, out, harness) {
36
54
  const label = HARNESS_LABEL[harness];
37
55
  const cmd = harness === "codex" ? "codex start" : "start";
@@ -79,10 +97,12 @@ export async function harnessStart(p, out, harness) {
79
97
  if (harness === "dsh" && !existsSync(bin))
80
98
  throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
81
99
  const effort = str(p.flags, "effort");
82
- // The machine's toolchain and job folders a sandboxed agent may also write (b9s-admin machine writable).
83
- const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
84
- if (writable.some((w) => !w.startsWith("/")))
85
- throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
100
+ const requestedAdopt = str(p.flags, "thread") ?? str(p.flags, "session");
101
+ // Machine-configured folders and explicit extra roots are combined with existing package caches
102
+ // only for workspace-write. Full-access sessions keep their previous root settings.
103
+ const machineWritable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean);
104
+ const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
105
+ const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
86
106
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
87
107
  const settings = harness === "codex"
88
108
  ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
@@ -90,20 +110,21 @@ export async function harnessStart(p, out, harness) {
90
110
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
91
111
  : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
92
112
  const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
93
- if (harness === "claude-code" && sandbox === "workspace-write")
94
- configureHttpsOriginForWorktree(process.cwd());
95
113
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
96
114
  const lines = [];
97
115
  const token = str(p.flags, "token");
98
116
  if (token) {
99
117
  const joined = [];
100
- await join({ ...p, flags: { ...p.flags, vendor: harness, model } }, { json: false, print: (h) => joined.push(h) });
118
+ const enrollment = startJoinArgs(p, harness, model);
119
+ await join(enrollment.parsed, { json: false, print: (h) => joined.push(h) }, enrollment.expectedProject);
101
120
  lines.push(joined.join("\n").split("\n")[0]);
102
121
  }
103
- const creds = loadAgent(name);
122
+ const { credentials: creds, ref } = startAgentIdentity(name);
123
+ if (harness === "claude-code" && sandbox === "workspace-write")
124
+ configureHttpsOriginForWorktree(process.cwd());
125
+ await configureGitCredentialForWorktree(process.cwd(), creds);
104
126
  if (creds.vendor && creds.vendor !== harness)
105
- throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not ${harness}`);
106
- const ref = agentRef(creds);
127
+ throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
107
128
  const priorState = readState(ref);
108
129
  if (priorState.turn_guard?.fault) {
109
130
  const fault = priorState.turn_guard.fault;
@@ -111,7 +132,7 @@ export async function harnessStart(p, out, harness) {
111
132
  }
112
133
  const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
113
134
  const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
114
- const adopt = str(p.flags, "thread") ?? str(p.flags, "session") ?? rememberedSession ?? undefined;
135
+ const adopt = requestedAdopt ?? rememberedSession ?? undefined;
115
136
  requireInstall();
116
137
  // 2. Its session: adopt one, or start one headless with an onboarding turn.
117
138
  let session;
@@ -0,0 +1,128 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { Client } from "../client.js";
3
+ import { loadAgent, resolveAgentName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ import { requireInstall } from "../install.js";
6
+ function credentialInput(input) {
7
+ const result = {};
8
+ for (const line of input.split(/\r?\n/)) {
9
+ if (!line)
10
+ break;
11
+ const i = line.indexOf("=");
12
+ if (i < 0)
13
+ continue;
14
+ const key = line.slice(0, i);
15
+ if (key === "protocol" || key === "host" || key === "path")
16
+ result[key] = line.slice(i + 1);
17
+ }
18
+ return result;
19
+ }
20
+ function repositoryPath(path) {
21
+ if (!path)
22
+ return null;
23
+ const normalized = path.replace(/^\//, "").replace(/\.git$/i, "");
24
+ return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalized) ? normalized.toLowerCase() : null;
25
+ }
26
+ export async function credentialResponse(input, api) {
27
+ const request = credentialInput(input);
28
+ if (request.protocol !== "https" || request.host?.toLowerCase() !== "github.com")
29
+ return "";
30
+ const wanted = repositoryPath(request.path);
31
+ if (!wanted)
32
+ return "";
33
+ const metadata = await api("GET", "");
34
+ if (!metadata.linked || !metadata.repository) {
35
+ throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
36
+ }
37
+ const linked = `${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase();
38
+ if (wanted !== linked)
39
+ return "";
40
+ const credential = await api("POST", "", {});
41
+ return `username=${credential.username}\npassword=${credential.password}\n\n`;
42
+ }
43
+ export async function gitCredentialOperation(operation, input, api) {
44
+ if (operation === "store" || operation === "erase")
45
+ return "";
46
+ if (operation !== "get")
47
+ throw new CliError("usage", "git-credential get|store|erase");
48
+ return credentialResponse(input, api);
49
+ }
50
+ export async function gitCredential(p) {
51
+ const operation = p.positionals[1];
52
+ const chunks = [];
53
+ for await (const chunk of process.stdin)
54
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
55
+ const input = Buffer.concat(chunks).toString("utf8");
56
+ if (operation === "store" || operation === "erase")
57
+ return;
58
+ if (operation !== "get")
59
+ throw new CliError("usage", "git-credential get|store|erase");
60
+ const agent = loadAgent(resolveAgentName(undefined));
61
+ if (!agent.project)
62
+ throw new CliError("github_not_connected", "GitHub credential helper requires a project-scoped agent identity.");
63
+ const client = Client.forAgent(agent, undefined, { presence: false });
64
+ const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
65
+ const result = await gitCredentialOperation(operation, input, (method, _path, body) => client.call(method, base, body));
66
+ if (result)
67
+ process.stdout.write(result);
68
+ }
69
+ function remoteRepository(url) {
70
+ const scp = /^git@github\.com:([^?#]+)$/i.exec(url);
71
+ const ssh = /^ssh:\/\/(?:git@)?github\.com\/([^?#]+)$/i.exec(url);
72
+ const https = /^https:\/\/github\.com\/([^?#]+)$/i.exec(url);
73
+ const match = scp ?? ssh ?? https;
74
+ if (!match)
75
+ return null;
76
+ const credentialPath = match[1].replace(/^\//, "");
77
+ const path = repositoryPath(credentialPath);
78
+ if (!path)
79
+ return null;
80
+ return { sshPrefix: scp ? "git@github.com:" : ssh ? "ssh://git@github.com/" : null, path, credentialPath };
81
+ }
82
+ function gitConfig(cwd, args) {
83
+ const result = spawnSync("git", ["config", ...args], { cwd, encoding: "utf8" });
84
+ if (result.status !== 0)
85
+ throw new CliError("git_credential_config", (result.stderr ?? "").trim() || "could not configure the worktree Git credential helper");
86
+ }
87
+ function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
88
+ /** Adds the exact repo helper only when origin is the repository linked to this project. */
89
+ export async function configureGitCredentialForWorktree(cwd, creds, lookup, installBin) {
90
+ if (!creds.project)
91
+ return;
92
+ const client = Client.forAgent(creds, undefined, { presence: false });
93
+ const metadata = lookup
94
+ ? await lookup()
95
+ : await client.call("GET", `/projects/${encodeURIComponent(creds.project)}/git-credentials`);
96
+ if (!metadata.linked || !metadata.repository)
97
+ return;
98
+ // Read the configured value, not `remote get-url`: that command expands existing insteadOf
99
+ // rewrites and would hide the SSH origin when this startup runs a second time.
100
+ const remote = spawnSync("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8" });
101
+ if (remote.status !== 0)
102
+ throw new CliError("git_origin", `cannot read origin in ${cwd}: ${(remote.stderr ?? "").trim() || "git remote get-url origin failed"}`);
103
+ const parsed = remoteRepository(remote.stdout.trim());
104
+ if (!parsed)
105
+ return;
106
+ if (`${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase() !== parsed.path)
107
+ return;
108
+ const enabled = spawnSync("git", ["config", "extensions.worktreeConfig", "true"], { cwd, encoding: "utf8" });
109
+ if (enabled.status !== 0)
110
+ throw new CliError("git_credential_config", (enabled.stderr ?? "").trim() || "could not enable per-worktree Git configuration");
111
+ if (parsed.sshPrefix) {
112
+ const rewriteKey = `url.https://github.com/${parsed.credentialPath}.insteadOf`;
113
+ const sshOrigin = `${parsed.sshPrefix}${parsed.credentialPath}`;
114
+ const existing = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd, encoding: "utf8" });
115
+ if (!(existing.stdout ?? "").split(/\r?\n/).includes(sshOrigin))
116
+ gitConfig(cwd, ["--worktree", "--add", rewriteKey, sshOrigin]);
117
+ }
118
+ // useHttpPath makes Git send this exact remote path (including an optional .git suffix).
119
+ // Matching the remote spelling and suffix keeps this helper out of other repositories.
120
+ const repoUrl = `https://github.com/${parsed.credentialPath}`;
121
+ const helperKey = `credential.${repoUrl}.helper`;
122
+ gitConfig(cwd, ["--worktree", "--replace-all", helperKey, ""]);
123
+ gitConfig(cwd, ["--worktree", "--add", helperKey, `!${shellQuote(installBin ?? requireInstall().bin)} git-credential`]);
124
+ gitConfig(cwd, ["--worktree", "credential.https://github.com.useHttpPath", "true"]);
125
+ }
126
+ export async function gitCredentialMain(p) {
127
+ return gitCredential(p);
128
+ }
@@ -11,6 +11,7 @@ import { codexHooksPath } from "./codex.js";
11
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
12
  import { detectVendor } from "../vendor.js";
13
13
  import { CLI_VERSION } from "../version.js";
14
+ import { assertEnrolledStartProject } from "../start-options.js";
14
15
  function repoRoot() {
15
16
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
16
17
  return r.status === 0 ? r.stdout.trim() : process.cwd();
@@ -64,7 +65,7 @@ export async function setup(p, out) {
64
65
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
65
66
  out.print(`b9s ${inst.version} for this machine: ${inst.bin}\nRecorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { install: inst, identity: idPath, written: uniq, hook_verified: !!selfTest });
66
67
  }
67
- export async function join(p, out) {
68
+ export async function join(p, out, expectedProject) {
68
69
  const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
69
70
  if (!name)
70
71
  throw new CliError("usage", "join needs --as <agent-name> (the name you were given)");
@@ -107,6 +108,9 @@ export async function join(p, out) {
107
108
  if (!res.ok)
108
109
  throw new CliError(json.error ?? `http_${res.status}`, json.message ?? "join failed");
109
110
  const project = json.project ? json.project.name : null;
111
+ // Used internally by `b9s start --as project/name --token ...`: enrollment always
112
+ // submits the bare name, then verifies the token was actually scoped to that project.
113
+ assertEnrolledStartProject(expectedProject, project);
110
114
  const ref = agentRef({ project, agent: name });
111
115
  const path = saveAgent({ url, key: json.key, account: json.project ? json.project.id : "", project, agent: name, vendor, machine });
112
116
  const idPath = noBind ? null : writeIdentity(root, vendor, name, model, bool(p.flags, "replace"), project);
@@ -231,6 +231,13 @@ export async function machineAdmin(action, rest, p, out) {
231
231
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { resume_turns: true });
232
232
  return out.print(`${ref} on ${machineName}: turn mode resumed explicitly; its daemon applies the request within 30 s.`, r);
233
233
  }
234
+ if (sub === "thread") {
235
+ const thread = rest[3];
236
+ if (thread === undefined)
237
+ throw new CliError("usage", "machine session thread <machine> <project>/<agent> <thread-id|none>");
238
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { thread: thread === "none" ? null : thread });
239
+ return out.print(`${ref} on ${machineName}: ${thread === "none" ? "thread cleared" : `thread set to ${thread}`}; its daemon applies the change within 30 s.`, r);
240
+ }
234
241
  if (sub === "limit") {
235
242
  const value = str(p.flags, "turns-per-hour");
236
243
  if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
@@ -243,7 +250,7 @@ export async function machineAdmin(action, rest, p, out) {
243
250
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
244
251
  }
245
252
  }
246
- throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
253
+ throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|resume|limit|thread|remove <machine> <project>/<agent> [...]");
247
254
  }
248
255
  /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
249
256
  export function parseVariant(spec) {
@@ -18,6 +18,7 @@ import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
20
  import { resumeTurnGuard } from "../turn-guard.js";
21
+ import { defaultWorkspaceWritableRoots } from "../start-options.js";
21
22
  export const machineFile = () => join(configRoot(), "machine.json");
22
23
  export function loadMachine() {
23
24
  const f = machineFile();
@@ -31,14 +32,19 @@ function writeMachineState(s) {
31
32
  mkdirSync(dirname(stateFile()), { recursive: true });
32
33
  writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
33
34
  }
34
- /** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
35
+ /** What a session's watcher is started with; a change means re-running codex start. */
35
36
  /**
36
37
  * Bumped when `b9s start` builds a session's settings differently, so every session is started
37
38
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
38
39
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
39
40
  */
40
- const START_REV = 4;
41
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
41
+ const START_REV = 5;
42
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
43
+ /** A clear is distinct from a thread that the server has not received from the machine yet. */
44
+ export function reconcileThread(s, local) {
45
+ const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
46
+ return clearing ? null : s.thread ?? local?.thread ?? null;
47
+ }
42
48
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
43
49
  /**
44
50
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
@@ -62,7 +68,7 @@ export function startArgs(s, thread, writable = []) {
62
68
  ...(s.model ? ["--model", s.model] : []),
63
69
  ...(s.effort ? ["--effort", s.effort] : []),
64
70
  ...(thread ? ["--thread", thread] : []),
65
- ...(writable.length && s.sandbox === "workspace-write" ? ["--writable", writable.join(",")] : []),
71
+ ...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
66
72
  ];
67
73
  }
68
74
  const KEY_CHECK_MS = 10 * 60_000;
@@ -164,8 +170,11 @@ export async function reconcile(m, log) {
164
170
  }
165
171
  }
166
172
  await ensureCredentials(client, m, s, local, log);
167
- const fp = sessionFingerprint(s, s.sandbox === "workspace-write" ? writable : []);
168
- const thread = s.thread ?? local?.thread ?? null;
173
+ const sessionWritable = s.sandbox === "workspace-write"
174
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
175
+ : writable;
176
+ const thread = reconcileThread(s, local);
177
+ const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : []);
169
178
  const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
170
179
  if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
171
180
  // A new session's start runs its first turn at once, past the watchers' check: during a
@@ -177,11 +186,17 @@ export async function reconcile(m, log) {
177
186
  out.push(held);
178
187
  continue;
179
188
  }
180
- const r = spawnSync(bin, startArgs(s, thread, writable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
189
+ const r = spawnSync(bin, startArgs(s, thread, sessionWritable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
181
190
  if (r.status !== 0)
182
191
  throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
183
192
  const started = JSON.parse(r.stdout);
184
- state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
193
+ state.sessions[s.id] = {
194
+ label,
195
+ fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : []),
196
+ thread: started.thread,
197
+ thread_override_at: s.thread_override_at ?? null,
198
+ key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
199
+ };
185
200
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
186
201
  }
187
202
  else {
@@ -24,6 +24,7 @@ import { probeCapabilities } from "../capabilities.js";
24
24
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
25
25
  import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
26
26
  import { sessionUsage } from "../usage.js";
27
+ import { collectPruneProtection } from "../prune-protection.js";
27
28
  function omitMeasuresAlreadyIn(text, updates) {
28
29
  if (!text)
29
30
  return updates;
@@ -187,7 +188,8 @@ export async function watch(p, out) {
187
188
  // Space back on a schedule: only clean worktrees whose work has landed or whose unit is
188
189
  // closed; never one a unit is still being worked in (it may have no commits yet).
189
190
  const units = await unitWorktrees(scanCreds, scanCreds.project);
190
- const prunable = pruneReport(process.cwd(), units.closed, units.active).prunable;
191
+ const protection = await collectPruneProtection(scanCreds, scanCreds.project);
192
+ const prunable = pruneReport(process.cwd(), units.closed, units.active, undefined, protection).prunable;
191
193
  const probe = freeSpaceProbe(prunable.map((c) => c.path));
192
194
  let pruned = 0;
193
195
  for (const c of prunable) {
@@ -6,6 +6,7 @@ import { CliError } from "../errors.js";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
8
8
  import { table } from "../output.js";
9
+ import { collectPruneProtection } from "../prune-protection.js";
9
10
  const CLOSED = ["done", "abandoned", "superseded"];
10
11
  const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
11
12
  const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
@@ -88,7 +89,8 @@ export async function worktrees(p, out, timeouts = {}) {
88
89
  const requestTimeoutMs = timeouts.requestTimeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
89
90
  const statusTimeoutMs = timeouts.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS;
90
91
  const units = await unitWorktrees(creds, project, { timeoutMs: requestTimeoutMs, onProgress: progress });
91
- const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs });
92
+ const protection = await collectPruneProtection(creds, project);
93
+ const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs, ...protection });
92
94
  // --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
93
95
  // and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
94
96
  const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];
@@ -39,6 +39,45 @@ export function scopeEditFromArgs(p) {
39
39
  export function scopeOnlyOutput(unit, only) {
40
40
  return only ? unit.scope : null;
41
41
  }
42
+ function jsonFlag(p, key, expected) {
43
+ const raw = str(p.flags, key);
44
+ if (raw === undefined)
45
+ return undefined;
46
+ try {
47
+ return JSON.parse(raw);
48
+ }
49
+ catch {
50
+ throw new CliError("usage", `--${key} must be JSON ${expected}`);
51
+ }
52
+ }
53
+ export function needsRetrospectiveInput(status, events = []) {
54
+ if (status === "changes_requested")
55
+ return true;
56
+ const lastSubmission = events.reduce((last, event, index) => ["submitted", "resubmitted", "refreshed"].includes(event.type) ? index : last, -1);
57
+ return events.slice(lastSubmission + 1).some((event) => event.type === "changes_requested");
58
+ }
59
+ function retrospectiveEventDetail(event) {
60
+ const data = event.data ?? {};
61
+ if (event.type === "changes_requested") {
62
+ const cause = data.cause ? `cause=${data.cause}` : "cause=unclassified";
63
+ const citation = data.unmet ? `; cited ${data.cited_from ?? "clause"}: ${JSON.stringify(data.unmet)}` : "; no clause citation (legacy or citation rule disabled)";
64
+ return ` [event ${event.id}; ${cause}${citation}]`;
65
+ }
66
+ if (["resubmitted", "refreshed"].includes(event.type)) {
67
+ const lesson = typeof data.lesson === "string" ? `; lesson: ${data.lesson}` : "";
68
+ const disputes = Array.isArray(data.disputes) ? data.disputes.map((d) => `disputes ${d.send_back_event_id} as ${d.cause}: ${d.reason}`).join("; ") : "";
69
+ return `${lesson}${disputes ? `; ${disputes}` : ""}`;
70
+ }
71
+ if (event.type === "note" && data.annotation)
72
+ return ` [assigner view on ${data.annotation.finding_event_id}: ${data.annotation.cause}; ${data.annotation.reason}]`;
73
+ if (event.type === "ruled" && data.retrospective_resolution)
74
+ return ` [resolved ${data.send_back_event_id} as ${data.cause}; ${event.note}]`;
75
+ if (event.type === "approved" && Array.isArray(data.retrospective_confirmation))
76
+ return ` [confirmed send-back causes: ${data.retrospective_confirmation.map((x) => `${x.reviewer_cause} → ${x.confirmed_cause} (${x.cited_from ?? "uncited"})`).join(", ")}]`;
77
+ if (event.type === "abandoned" && data.retrospective?.complete)
78
+ return ` [send-back retrospective finalized: ${data.retrospective.send_backs.length} recorded]`;
79
+ return "";
80
+ }
42
81
  export function assignmentDisposition(unit, to) {
43
82
  if (unit.status !== "queued")
44
83
  return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
@@ -374,7 +413,16 @@ export async function wu(p, out) {
374
413
  const evidenceIds = list("evidence"); // validated before anything talks to the server
375
414
  const def = await processDef();
376
415
  const where = branchAndHead();
377
- const unitTarget = (await client.call("GET", `${base}/${num()}`)).unit.target ?? def.merge.target_branch;
416
+ const submitRecord = await client.call("GET", `${base}/${num()}`);
417
+ const submitUnit = submitRecord.unit;
418
+ const unitTarget = submitUnit.target ?? def.merge.target_branch;
419
+ const lesson = str(p.flags, "lesson");
420
+ const disputes = jsonFlag(p, "disputes", "an array of dispute objects");
421
+ const retrospectiveDue = needsRetrospectiveInput(submitUnit.status, Array.isArray(submitRecord.events) ? submitRecord.events : []);
422
+ if (retrospectiveDue && !lesson?.trim())
423
+ throw new CliError("usage", 'resubmitting after a send-back requires --lesson "what would have let you get this right the first time?" (up to 280 characters)');
424
+ if (!retrospectiveDue && (lesson !== undefined || disputes !== undefined))
425
+ throw new CliError("usage", "--lesson and --disputes are only used when resubmitting after a send-back");
378
426
  let rebased = null;
379
427
  // The rebase requirement may come from the project or from a tag; the server tells us which
380
428
  // when it refuses. Check locally whenever we are in a repo so the claim is always a finding.
@@ -415,7 +463,7 @@ export async function wu(p, out) {
415
463
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
416
464
  }
417
465
  }
418
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect") }, !!def.review_rules?.length, unitTarget);
466
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
419
467
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
420
468
  const u = r.unit;
421
469
  out.print(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r);
@@ -452,9 +500,13 @@ export async function wu(p, out) {
452
500
  const text = (p.positionals.slice(3).join(" ") || str(p.flags, sub === "ask" ? "question" : "ruling") || str(p.flags, "note") || "").trim();
453
501
  if (!text && !approve)
454
502
  throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without" (works on queued units too)' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
455
- const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : approve ? { approve: true, ruling: text } : { ruling: text });
503
+ const sendBackEvent = str(p.flags, "send-back-event");
504
+ const cause = str(p.flags, "cause");
505
+ if (sendBackEvent && (sub !== "rule" || !cause || !text))
506
+ throw new CliError("usage", 'wu rule <n> --send-back-event <event-id> --cause <cause> --ruling "decision"');
507
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
456
508
  const q = r.unit.question;
457
- out.print(`${fmt(r.unit)}\n${sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
509
+ out.print(`${fmt(r.unit)}\n${sendBackEvent ? "Retrospective ruling recorded on the unit; no chat message was added." : sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
458
510
  return;
459
511
  }
460
512
  case "escalate": {
@@ -516,7 +568,10 @@ export async function wu(p, out) {
516
568
  const unmet = str(p.flags, "unmet");
517
569
  if (!note)
518
570
  throw new CliError("usage", sub === "changes" ? 'wu changes <n> --unmet "<the clause of its scope, exit criterion or agreements it fails, quoted>" --note "what must change"' : `wu ${sub} <n> --note "what you checked"`);
519
- const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}) });
571
+ const cause = str(p.flags, "cause");
572
+ if (sub === "changes" && !cause)
573
+ throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
574
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
520
575
  out.print(fmt(r.unit), r);
521
576
  return;
522
577
  }
@@ -615,7 +670,8 @@ export async function wu(p, out) {
615
670
  return;
616
671
  }
617
672
  case "note": {
618
- const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence") });
673
+ const annotation = jsonFlag(p, "annotation", "an annotation object");
674
+ const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), ...(annotation ? { annotation } : {}) });
619
675
  out.print(fmt(r.unit), r);
620
676
  return;
621
677
  }
@@ -690,9 +746,10 @@ export async function wu(p, out) {
690
746
  out.print(onlyScope, { scope: onlyScope });
691
747
  return;
692
748
  }
693
- 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(", ")}` : ""}`).join("\n");
749
+ 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
+ const lessons = [...r.events].reverse().filter((e) => typeof e.data?.lesson === "string").map((e) => ` ${e.actor_name}: ${e.data.lesson}`).join("\n");
694
751
  const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
695
- out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}\n${events}`, r);
752
+ out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}\n${events}`, r);
696
753
  return;
697
754
  }
698
755
  case "list":
package/dist/git.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { hostname } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
7
7
  function status(cwd, timeoutMs) {
@@ -166,6 +166,32 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
166
166
  clearWorktreeUrlRewrites(path);
167
167
  if (inheritUrlRewrites)
168
168
  copyWorktreeUrlRewrites(cwd, path);
169
+ else
170
+ copyGitHubAppUrlRewrites(cwd, path);
171
+ }
172
+ /** Carry back only HTTPS rewrites paired with this product's linked-repository credential helper. */
173
+ function copyGitHubAppUrlRewrites(from, to) {
174
+ const helpers = spawnSync("git", ["config", "--worktree", "--get-regexp", "^credential\\.https://github\\.com/.+\\.helper$"], { cwd: from, encoding: "utf8" });
175
+ if (helpers.status !== 0)
176
+ return;
177
+ for (const line of helpers.stdout.split(/\r?\n/).filter(Boolean)) {
178
+ const split = line.indexOf(" ");
179
+ if (split < 0 || !/^!.*\s+git-credential$/.test(line.slice(split + 1)))
180
+ continue;
181
+ const helperKey = line.slice(0, split);
182
+ const repoUrl = helperKey.slice("credential.".length, -".helper".length);
183
+ if (!repoUrl.startsWith("https://github.com/"))
184
+ continue;
185
+ const rewriteKey = `url.${repoUrl}.insteadOf`;
186
+ const rewrites = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd: from, encoding: "utf8" });
187
+ if (rewrites.status !== 0)
188
+ continue;
189
+ for (const value of rewrites.stdout.split(/\r?\n/).filter(Boolean)) {
190
+ const copied = spawnSync("git", ["config", "--worktree", "--add", rewriteKey, value], { cwd: to, encoding: "utf8" });
191
+ if (copied.status !== 0)
192
+ throw new Error(`could not preserve linked GitHub App transport in ${to}: ${(copied.stderr || copied.stdout).trim()}`);
193
+ }
194
+ }
169
195
  }
170
196
  /** Carry worktree-scoped URL rewrites to new unit worktrees so HTTPS proxy access survives `wu start`. */
171
197
  export function copyWorktreeUrlRewrites(from, to) {
@@ -340,11 +366,29 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
340
366
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
341
367
  continue;
342
368
  }
369
+ const worktreePath = realpathOrSelf(w.path);
370
+ const use = options.inUse?.find((entry) => {
371
+ if (!isAbsolute(entry.path))
372
+ return false;
373
+ const usePath = realpathOrSelf(entry.path);
374
+ const rel = relative(worktreePath, usePath);
375
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
376
+ });
377
+ if (use) {
378
+ kept.push({ path: w.path, branch: w.branch, reason: `in use by ${use.agent}` });
379
+ continue;
380
+ }
381
+ const homeAgent = w.branch?.startsWith("home/") ? w.branch.slice("home/".length) : null;
382
+ const retiredHome = homeAgent !== null && options.retiredHomeAgents?.has(homeAgent);
383
+ if (homeAgent && !retiredHome) {
384
+ kept.push({ path: w.path, branch: w.branch, reason: `agent home for ${homeAgent} (not retired)` });
385
+ continue;
386
+ }
343
387
  // An agent's home checkout is never leftovers, whatever its branch: join/setup bind an identity
344
388
  // there (unit worktrees never get one). And a worktree made in the last day is too new to judge:
345
389
  // StickJoy's watcher removed a home checkout two minutes after it was created, before the agent
346
390
  // could bind it, because a fresh branch on main's head looks merged.
347
- if (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json"))) {
391
+ if (!retiredHome && (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json")))) {
348
392
  kept.push({ path: w.path, branch: w.branch, reason: "an agent's home checkout (it has a b9s identity file)" });
349
393
  continue;
350
394
  }
package/dist/harnesses.js CHANGED
@@ -547,7 +547,7 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
547
547
  autoAllowBashIfSandboxed: true,
548
548
  allowUnsandboxedCommands: false,
549
549
  filesystem: { allowWrite: dirs },
550
- network: { allowedDomains: ["*"] },
550
+ network: { allowedDomains: ["*", "api.benignswarm.org"] },
551
551
  },
552
552
  };
553
553
  return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
package/dist/help.js CHANGED
@@ -27,6 +27,7 @@ Agent commands
27
27
  b9s logout --as <name>
28
28
  b9s identities list saved identities on this machine
29
29
  b9s me who am I, role, permissions, channels
30
+ b9s git-credential get|store|erase Git credential helper for the project's linked GitHub repository
30
31
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process and notices
31
32
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
32
33
  assigner only: add a project notice; matching commands warn but continue
@@ -94,19 +95,20 @@ Agent commands
94
95
  b9s measure post <name> --sha <commit> --value <v> --evidence <id[,id...]> [--target branch]
95
96
  b9s measure check <name> run the command producer for the active matching unit at this clean worktree's HEAD and compare with its target's latest good value
96
97
  Global: --effort <high|medium|low|...> reasoning effort to report (else BSCHAT_EFFORT, CLAUDE_EFFORT, codex model_reasoning_effort)
97
- b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] ask for review; repeat --evidence or pass comma-separated ids; optional expected effect is shown to reviewers; verifies the commit on origin branches
98
+ b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] [--lesson "..."] [--disputes '<JSON list>'] ask for review; after a send-back give one lesson (max 280 chars); optional disputes cite send-back event IDs and exact clauses
98
99
  b9s wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
99
100
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
100
- b9s wu approve <n> --note ".." approval covers tags your role reviews
101
+ b9s wu approve <n> --note ".." [--confirm-causes cause,cause] approval covers tags your role reviews; complete approval confirms classified send-back causes in timeline order
101
102
  a planned reviewer still owing may approve after coverage; status stays approved until merge
102
- b9s wu changes <n> --unmet ".." --note ".." send back, quoting the failed scope, exit or agreement clause; a planned reviewer still owing may send an approved, unmerged unit back
103
+ b9s wu changes <n> --unmet ".." --cause <cause> --note ".." send back with a cited clause and cause (scope_gap, missing_context, worker_error, reviewer_scope_growth, environment, stale_base); a planned reviewer still owing may send an approved, unmerged unit back
103
104
  concerns outside those are notes (wu note) or questions (wu ask)
104
105
  b9s wu classify <n> --tags a,b classifier: confirm or change a new unit's tags before it routes for review
105
106
  b9s wu proceed <n> --note ".." reviewer: this step is good, carry on; back to the owner, NOT an approval
106
107
  b9s wu reopen <n> --note ".." owner or reviewer: withdraw an unmerged approval (verification failed); resubmit the same unit
107
108
  b9s wu supersede <n> --by <m> owner or assigner: this unit continues as #m; anyone blocked on #n now waits on #m
108
109
  b9s wu ask <n> "question" owner, reviewer or assigner: a decision this unit cannot move without, including queued units (tag expert first, then the operator)
109
- b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console)
110
+ b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console); --send-back-event <id> --cause <cause> records an explicit retrospective ruling
111
+ b9s wu note <n> --note ".." [--annotation '<JSON object>'] add a note; assigner annotation links a cited scope finding to a cause and one-line reason
110
112
  b9s wu propose <n> "answer" owner, reviewer, assigner or expert: recommend an answer to the unit's open question, approvable as written
111
113
  b9s wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
112
114
  b9s wu wait <n> --on <m> --note "why" | --clear
@@ -160,7 +162,7 @@ Agent commands
160
162
  b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
161
163
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
162
164
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
163
- b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--max-budget-usd n] [--turns-per-hour 1..20] [--dsh path]
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..20] [--dsh path]
164
166
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
165
167
  Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
166
168
  (b9s codex start is the same with --harness codex)
@@ -287,6 +289,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
287
289
  15 min before, its agents away until the machine reports back after booting
288
290
  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]
289
291
  [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..20]
292
+ b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
290
293
  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
291
294
  (change its count/settings, pause scaling, pin, or bench the agent)
292
295
  b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ import { commandWarnings } from "./commands/hook.js";
31
31
  import { loadAgent, resolveAgentName } from "./config.js";
32
32
  import { agentNotice } from "./commands/notices.js";
33
33
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
34
+ import { gitCredentialMain } from "./commands/git-credential.js";
34
35
  const COMMANDS = {
35
36
  join,
36
37
  setup,
@@ -39,6 +40,7 @@ const COMMANDS = {
39
40
  identities: a.identities,
40
41
  me: a.me,
41
42
  resume,
43
+ "git-credential": async (p) => gitCredentialMain(p),
42
44
  notice: agentNotice,
43
45
  who: a.who,
44
46
  status: a.status,
@@ -104,7 +106,7 @@ const COMMANDS = {
104
106
  // These commands establish identity, own their startup validation, or inspect/change only local
105
107
  // machine state. Their dispatch must run before any notice lookup attempts to load an agent.
106
108
  const NOTICE_PREFLIGHT_EXEMPT_COMMANDS = new Set([
107
- "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start",
109
+ "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start", "git-credential",
108
110
  ]);
109
111
  let invokedCommand;
110
112
  async function main(argv) {
package/dist/install.js CHANGED
@@ -240,6 +240,29 @@ export function watcherServices() {
240
240
  .filter((f) => f.endsWith(".service") && isOurService(f.slice(0, -".service".length)))
241
241
  .map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
242
242
  }
243
+ /** Read the recorded working directory for a watcher; pruning must fail closed on an unreadable service. */
244
+ export function watcherWorkingDirectory(service) {
245
+ if (service.kind === "systemd") {
246
+ const text = readFileSync(service.path, "utf8");
247
+ const match = /^WorkingDirectory=(.+)$/m.exec(text);
248
+ if (!match)
249
+ throw new CliError("service_unreadable", `${service.label} has no recorded WorkingDirectory`);
250
+ return match[1].replace(/%%/g, "%");
251
+ }
252
+ const read = spawnSync("plutil", ["-convert", "json", "-o", "-", service.path], { encoding: "utf8" });
253
+ if (read.status !== 0)
254
+ throw new CliError("service_unreadable", `could not read ${service.path} as a launchd plist`, (read.stderr ?? "").trim());
255
+ let plist;
256
+ try {
257
+ plist = JSON.parse(read.stdout);
258
+ }
259
+ catch {
260
+ throw new CliError("service_unreadable", `${service.path} is not valid plist JSON`);
261
+ }
262
+ if (typeof plist.WorkingDirectory !== "string" || !plist.WorkingDirectory)
263
+ throw new CliError("service_unreadable", `${service.label} has no readable WorkingDirectory`);
264
+ return plist.WorkingDirectory;
265
+ }
243
266
  export function plistArgs(path) {
244
267
  const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
245
268
  return r.status === 0 ? (JSON.parse(r.stdout).ProgramArguments ?? null) : null;
@@ -0,0 +1,113 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { Client } from "./client.js";
4
+ import { configRoot } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ import { WATCH_LABEL_PREFIX, watcherServices, watcherWorkingDirectory } from "./install.js";
7
+ function readMachineCredentials() {
8
+ const file = join(configRoot(), "machine.json");
9
+ if (!existsSync(file))
10
+ return null;
11
+ try {
12
+ const value = JSON.parse(readFileSync(file, "utf8"));
13
+ if (typeof value.url !== "string" || !value.url || typeof value.key !== "string" || !value.key)
14
+ throw new Error("url and key are required");
15
+ return { url: value.url, key: value.key };
16
+ }
17
+ catch (error) {
18
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list from ${file}: ${error.message}`);
19
+ }
20
+ }
21
+ async function fetchMachineSessions() {
22
+ const machine = readMachineCredentials();
23
+ if (!machine)
24
+ return [];
25
+ const response = await Client.raw(machine.url, machine.key).call("GET", "/machines/me");
26
+ if (!Array.isArray(response.sessions))
27
+ throw new Error("GET /machines/me returned no sessions array");
28
+ return response.sessions;
29
+ }
30
+ async function fetchProjectAgents(creds, project) {
31
+ return Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/agents`);
32
+ }
33
+ function argument(args, name) {
34
+ const index = args.indexOf(name);
35
+ if (index >= 0)
36
+ return args[index + 1] ?? null;
37
+ const inline = args.find((arg) => arg.startsWith(`${name}=`));
38
+ return inline ? inline.slice(name.length + 1) : null;
39
+ }
40
+ function watcherUses(services) {
41
+ return services.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).map((service) => {
42
+ if (!service.args?.length)
43
+ throw new CliError("watcher_unreadable", `${service.label} has no readable service arguments`);
44
+ const agent = argument(service.args, "--as");
45
+ if (!agent)
46
+ throw new CliError("watcher_unreadable", `${service.label} has no recorded --as agent`);
47
+ const dir = argument(service.args, "--dir") ?? watcherWorkingDirectory(service);
48
+ if (!isAbsolute(dir))
49
+ throw new CliError("watcher_unreadable", `${service.label} has no absolute working directory`);
50
+ return { path: dir, agent };
51
+ });
52
+ }
53
+ function sessionUses(value) {
54
+ if (!Array.isArray(value))
55
+ throw new Error("machine session list is not an array");
56
+ return value.flatMap((row, index) => {
57
+ if (!row || typeof row !== "object" || Array.isArray(row))
58
+ throw new Error(`machine session ${index + 1} is malformed`);
59
+ const session = row;
60
+ if (typeof session.agent !== "string" || !session.agent)
61
+ throw new Error(`machine session ${index + 1} has no agent`);
62
+ const reported = session.reported;
63
+ if (reported !== undefined && reported !== null && (typeof reported !== "object" || Array.isArray(reported)))
64
+ throw new Error(`machine session ${session.agent} has malformed reported state`);
65
+ const reportedDir = reported && typeof reported === "object" ? reported.dir : undefined;
66
+ const dir = typeof session.dir === "string" && session.dir ? session.dir : typeof reportedDir === "string" ? reportedDir : "";
67
+ if (!dir)
68
+ return [];
69
+ if (!isAbsolute(dir))
70
+ throw new Error(`machine session ${session.agent} has a non-absolute directory`);
71
+ return [{ path: dir, agent: session.agent }];
72
+ });
73
+ }
74
+ function retiredAgents(value) {
75
+ if (!value || typeof value !== "object" || !Array.isArray(value.agents))
76
+ throw new CliError("home_agents_unreadable", "project agent list has no agents array");
77
+ const result = new Set();
78
+ for (const [index, item] of (value.agents).entries()) {
79
+ if (!item || typeof item !== "object" || Array.isArray(item) || typeof item.name !== "string") {
80
+ throw new CliError("home_agents_unreadable", `project agent ${index + 1} is malformed`);
81
+ }
82
+ const agent = item;
83
+ if (agent.retired_at)
84
+ result.add(agent.name);
85
+ }
86
+ return result;
87
+ }
88
+ /** Read machine sessions, watcher services and retirement state before any worktree can be removed. */
89
+ export async function collectPruneProtection(creds, project, dependencies = {}) {
90
+ const services = (dependencies.watchers ?? watcherServices)();
91
+ const inUse = watcherUses(services);
92
+ let sessions;
93
+ try {
94
+ sessions = await (dependencies.machineSessions ?? fetchMachineSessions)();
95
+ }
96
+ catch (error) {
97
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
98
+ }
99
+ try {
100
+ inUse.push(...sessionUses(sessions));
101
+ }
102
+ catch (error) {
103
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
104
+ }
105
+ let agents;
106
+ try {
107
+ agents = await (dependencies.projectAgents ?? (() => fetchProjectAgents(creds, project)))();
108
+ }
109
+ catch (error) {
110
+ throw new CliError("home_agents_unreadable", `could not read project agents for home worktrees: ${error.message}`);
111
+ }
112
+ return { inUse, retiredHomeAgents: retiredAgents(agents) };
113
+ }
@@ -0,0 +1,64 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { agentRef, loadAgent } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ /** Package-manager and build caches available to workspace-write sessions when present. */
7
+ export const WORKSPACE_WRITE_CACHE_PATHS = [
8
+ ".npm",
9
+ ".cache",
10
+ ".expo",
11
+ ".cargo/registry",
12
+ ".cargo/git",
13
+ ];
14
+ function directoryExists(path) {
15
+ try {
16
+ return existsSync(path) && statSync(path).isDirectory();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ export function defaultWorkspaceWritableRoots(home = homedir(), isDirectory = directoryExists) {
23
+ return WORKSPACE_WRITE_CACHE_PATHS.map((path) => join(home, path)).filter(isDirectory);
24
+ }
25
+ function absoluteWritablePath(value, flag, home) {
26
+ const path = value.startsWith("~/") ? join(home, value.slice(2)) : value;
27
+ if (!path.startsWith("/"))
28
+ throw new CliError("usage", `--${flag} paths must be absolute or start with ~/`);
29
+ return path;
30
+ }
31
+ /** Defaults plus machine-configured roots and explicit `b9s start --writable-root` paths. */
32
+ export function startWritableRoots(sandbox, machineRoots, explicitRoots, home = homedir(), isDirectory = directoryExists) {
33
+ if (sandbox !== "workspace-write" && explicitRoots.length) {
34
+ throw new CliError("usage", "--writable-root only applies to --sandbox workspace-write");
35
+ }
36
+ const machine = machineRoots.map((path) => absoluteWritablePath(path, "writable", home));
37
+ if (sandbox !== "workspace-write")
38
+ return [...new Set(machine)];
39
+ const requested = explicitRoots.map((path) => absoluteWritablePath(path, "writable-root", home));
40
+ return [...new Set([...defaultWorkspaceWritableRoots(home, isDirectory), ...machine, ...requested])];
41
+ }
42
+ export function startAgentIdentity(name, env = process.env) {
43
+ const credentials = loadAgent(name, env);
44
+ return { credentials, ref: agentRef(credentials) };
45
+ }
46
+ /** Split b9s start's optional project/name identity from the bare name accepted by enrollment. */
47
+ export function startEnrollmentIdentity(identity) {
48
+ const parts = identity.split("/");
49
+ if (parts.length === 1 && parts[0])
50
+ return { name: parts[0] };
51
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
52
+ throw new CliError("usage", "--as must be <agent-name> or <project>/<agent-name>");
53
+ }
54
+ return { project: parts[0], name: parts[1] };
55
+ }
56
+ /** When a qualified start name accompanies an invite, the token must enroll in that project. */
57
+ export function assertEnrolledStartProject(expected, actual) {
58
+ if (!expected)
59
+ return;
60
+ if (actual !== expected) {
61
+ const actualText = actual === null ? "an account-wide agent, not a project" : `project "${actual}"`;
62
+ throw new CliError("project_mismatch", `--as requested project "${expected}", but the enrollment token belongs to ${actualText}`);
63
+ }
64
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.92";
1
+ export const CLI_VERSION = "0.12.93";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.92",
3
+ "version": "0.12.93",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "scripts": {
32
32
  "build": "tsc -p tsconfig.build.json",
33
33
  "typecheck": "tsc --noEmit",
34
- "test": "npm run build && vitest run",
34
+ "test": "npm run typecheck && npm run build && vitest run",
35
35
  "prepack": "npm run build"
36
36
  },
37
37
  "devDependencies": {