benignswarm 0.12.12 → 0.12.17

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
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "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", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source"];
4
- export const BOOL_FLAGS = ["json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon"];
3
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "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", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by"];
4
+ export const BOOL_FLAGS = ["json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "hold"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -1,8 +1,9 @@
1
+ import { realpathSync } from "node:fs";
1
2
  import { str, bool } from "../args.js";
2
3
  import { Client } from "../client.js";
3
4
  import { loadAgent, resolveAgentName } from "../config.js";
4
5
  import { CliError } from "../errors.js";
5
- import { defaultMachine, scanWorktrees, prunableWorktrees, removeWorktreeIfClean } from "../git.js";
6
+ import { defaultMachine, scanWorktrees, pruneReport, removeWorktreeIfClean } from "../git.js";
6
7
  import { table } from "../output.js";
7
8
  /**
8
9
  * The project's worktree registry.
@@ -19,13 +20,24 @@ export async function worktrees(p, out) {
19
20
  if (sub === "prune") {
20
21
  // Space back: delete linked worktrees that are clean and merged into the base branch. Dry run
21
22
  // unless --yes. Branches are kept (deleting a worktree never deletes its branch).
22
- const candidates = prunableWorktrees();
23
+ // Worktrees recorded on units that are done or abandoned: clean ones go even if their branch never merged.
24
+ const closedUnitPaths = new Map();
25
+ try {
26
+ const all = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/work-units?all=1`);
27
+ for (const u of all.units)
28
+ if (u.worktree && (u.status === "done" || u.status === "abandoned"))
29
+ closedUnitPaths.set(realpathSync(u.worktree), `WU #${u.number} ${u.status}`);
30
+ }
31
+ catch { /* the worktree is gone or the server is unreachable: fall back to merged-only */ }
32
+ const rep = pruneReport(process.cwd(), closedUnitPaths);
33
+ const candidates = rep.prunable;
34
+ const keptText = rep.kept.length ? `\nKept ${rep.kept.length} (measured against ${rep.base ?? "the base branch"}):\n${rep.kept.map((k) => ` ${k.path}${k.branch ? ` (${k.branch})` : ""}: ${k.reason}`).join("\n")}` : "";
23
35
  if (!candidates.length) {
24
- out.print("(no clean, merged worktrees to remove)", { removed: [], candidates: [] });
36
+ out.print(`(no clean, merged worktrees to remove)${keptText}`, { removed: [], candidates: [], kept: rep.kept });
25
37
  return;
26
38
  }
27
39
  if (!bool(p.flags, "yes")) {
28
- out.print(`${candidates.length} clean, merged worktree(s) would be removed (run again with --yes):\n${candidates.map((c) => ` ${c.path}${c.branch ? ` (${c.branch})` : ""}`).join("\n")}`, { removed: [], candidates });
40
+ out.print(`${candidates.length} clean, merged worktree(s) would be removed (run again with --yes):\n${candidates.map((c) => ` ${c.path}${c.branch ? ` (${c.branch})` : ""}${c.why ? `: ${c.why}, branch kept` : ""}`).join("\n")}${keptText}`, { removed: [], candidates, kept: rep.kept });
29
41
  return;
30
42
  }
31
43
  const removed = [];
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { str } from "../args.js";
3
4
  import { Client } from "../client.js";
@@ -41,7 +42,7 @@ export async function wu(p, out) {
41
42
  };
42
43
  const tags = (u) => (u.tags.length ? u.tags.map((t) => `#${t}`).join(" ") : "(untagged)");
43
44
  const fmt = (u) => {
44
- const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
45
+ const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}` : null, u.hold ? "held" : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
45
46
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
46
47
  const approvals = u.approvals.map((a) => a.name).join(", ");
47
48
  return [
@@ -74,8 +75,8 @@ export async function wu(p, out) {
74
75
  if (!title || !to)
75
76
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--tags a,b] [--evidence id] [--replay-of <n>]');
76
77
  const replay = str(p.flags, "replay-of");
77
- const r = await client.call("POST", `${base}/assign`, { to, title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null });
78
- out.print(`${fmt(r.unit)}\n${r.unit.status === "queued" ? `Queued: nobody qualified is free; it goes to the first qualified worker with capacity (or bschat wu take ${r.unit.number} --to <agent>).` : `Assigned to ${r.unit.owner_name}; they start it with bschat wu start ${r.unit.number}.`}`, r);
78
+ const r = await client.call("POST", `${base}/assign`, { to, title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold });
79
+ out.print(`${fmt(r.unit)}\n${r.unit.status === "queued" && r.unit.preferred_name ? `Reserved for ${r.unit.preferred_name}, who is busy: theirs when free, open to any qualified worker after the takeover window (--hold keeps it assigned to them).` : r.unit.status === "queued" ? `Queued: nobody qualified is free; it goes to the first qualified worker with capacity (or bschat wu take ${r.unit.number} --to <agent>).` : `Assigned to ${r.unit.owner_name}; they start it with bschat wu start ${r.unit.number}.`}`, r);
79
80
  return;
80
81
  }
81
82
  case "take": {
@@ -140,7 +141,24 @@ export async function wu(p, out) {
140
141
  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.`}`, r);
141
142
  return;
142
143
  }
144
+ case "reopen": {
145
+ const note = str(p.flags, "note");
146
+ if (!note)
147
+ throw new CliError("usage", 'wu reopen <n> --note "why the approval is withdrawn"');
148
+ const r = await client.call("POST", `${base}/${num()}/reopen`, { note });
149
+ out.print(`${fmt(r.unit)}\nReopened: continue on the same branch and resubmit this unit.`, r);
150
+ return;
151
+ }
152
+ case "supersede": {
153
+ const by = str(p.flags, "by");
154
+ if (!by)
155
+ throw new CliError("usage", 'wu supersede <n> --by <m> [--note ".."] (this unit continues as #m)');
156
+ const r = await client.call("POST", `${base}/${num()}/supersede`, { by: Number(by), note: str(p.flags, "note") ?? "" });
157
+ out.print(fmt(r.unit), r);
158
+ return;
159
+ }
143
160
  case "approve":
161
+ case "proceed":
144
162
  case "changes": {
145
163
  const note = str(p.flags, "note");
146
164
  if (!note)
@@ -182,25 +200,13 @@ export async function wu(p, out) {
182
200
  throw new CliError("usage", `this project's process requires the merge commit: bschat wu done ${num()} --merged <sha>`);
183
201
  }
184
202
  const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged });
185
- // The unit's worktree goes with it when it is clean and we are not standing in it.
186
- let cleanup = "";
187
- const wt = r.unit.worktree;
188
- if (wt && !p.flags["keep-worktree"]) {
189
- if (resolve(process.cwd()).startsWith(resolve(wt)))
190
- cleanup = `\nWorktree ${wt} left in place (you are in it); remove it from elsewhere: git worktree remove ${wt}`;
191
- else if (wt === repoParent() || worktreeForBranch(def.merge.target_branch) === wt)
192
- cleanup = "";
193
- else {
194
- const res = removeWorktreeIfClean(wt);
195
- cleanup = res.removed ? `\nRemoved worktree ${wt}.` : `\nWorktree ${wt} kept: ${res.reason}.`;
196
- }
197
- }
198
- out.print(fmt(r.unit) + cleanup, r);
203
+ out.print(fmt(r.unit) + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
199
204
  return;
200
205
  }
201
206
  case "abandon": {
202
207
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
203
- out.print(fmt(r.unit), r);
208
+ // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
209
+ out.print(fmt(r.unit) + cleanupUnitWorktree(r.unit.worktree, await processDef(), !!p.flags["keep-worktree"]), r);
204
210
  return;
205
211
  }
206
212
  case "note": {
@@ -302,6 +308,17 @@ export async function processCmd(p, out) {
302
308
  await client.call("POST", `/projects/${project}/process/ack`, { version: r.process.version });
303
309
  }
304
310
  /** Per agent per tag, what real units have shown. */
311
+ /** A closed unit's worktree goes when it is clean and we are not standing in it; the branch and its commits stay. */
312
+ function cleanupUnitWorktree(wt, def, keep) {
313
+ if (!wt || keep)
314
+ return "";
315
+ if (resolve(process.cwd()).startsWith(resolve(wt)))
316
+ return `\nWorktree ${wt} left in place (you are in it); remove it from elsewhere: git worktree remove ${wt}`;
317
+ if (wt === repoParent() || worktreeForBranch(def.merge.target_branch) === wt)
318
+ return "";
319
+ const res = removeWorktreeIfClean(wt);
320
+ return res.removed ? `\nRemoved worktree ${wt} (branch kept).` : `\nWorktree ${wt} kept: ${res.reason}.`;
321
+ }
305
322
  /**
306
323
  * One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
307
324
  * continues existing work in its own worktree; --here uses the current checkout (single-agent repos).
@@ -309,9 +326,22 @@ export async function processCmd(p, out) {
309
326
  function prepareWorktree(n, unit, def, p) {
310
327
  // The unit's own target when it has one: a lane or release branch the work lands in.
311
328
  const target = unit.target ?? def.merge.target_branch;
312
- if (!p.flags.here && fullSha(target) === null && !(fetchRef(target) && fullSha(`origin/${target}`) !== null))
313
- throw new CliError("no_target", `the unit lands in ${target}, which this repository does not have`, `git fetch origin ${target}:${target} then try again`);
314
329
  const log = (line) => process.stderr.write(`bschat: ${line}\n`);
330
+ // Where reviewers may be on other machines, origin is the truth: start from origin's target, not
331
+ // this machine's possibly stale copy, and continue a pinned branch from what origin has of it.
332
+ const remoteFirst = !!def.merge.require_pushed;
333
+ let baseRef = target;
334
+ if (!p.flags.here) {
335
+ if (remoteFirst) {
336
+ if (!fetchRef(target))
337
+ throw new CliError("no_remote", `cannot fetch ${target} from origin, and this project requires work to start from origin's ${target}`, "Check the remote is reachable and try again.");
338
+ baseRef = `origin/${target}`;
339
+ log(`starting from origin/${target} (${fullSha(baseRef)?.slice(0, 9)}); this machine's ${target} is not used`);
340
+ }
341
+ else if (fullSha(target) === null && !(fetchRef(target) && fullSha(`origin/${target}`) !== null)) {
342
+ throw new CliError("no_target", `the unit lands in ${target}, which this repository does not have`, `git fetch origin ${target}:${target} then try again`);
343
+ }
344
+ }
315
345
  if (p.flags.here)
316
346
  return { mode: "here", path: process.cwd(), branch: branchAndHead().branch };
317
347
  const name = repoName();
@@ -322,15 +352,21 @@ function prepareWorktree(n, unit, def, p) {
322
352
  if (pinned) {
323
353
  const existing = worktreeForBranch(pinned);
324
354
  const path = existing ?? resolve(parent, `${name}-wu${n}`);
355
+ // Continuing someone else's branch from another machine: take origin's copy of it when we have none.
356
+ if (!existing && remoteFirst && fullSha(pinned) === null && fetchRef(pinned)) {
357
+ const r = spawnSync("git", ["branch", "--track", pinned, `origin/${pinned}`], { cwd: process.cwd(), encoding: "utf8" });
358
+ if (r.status !== 0)
359
+ throw new CliError("no_branch", `cannot create ${pinned} from origin: ${(r.stderr || r.stdout).trim()}`);
360
+ log(`created ${pinned} from origin/${pinned}`);
361
+ }
325
362
  if (!existing)
326
- ensureWorktree(path, pinned, target, process.cwd(), log);
363
+ ensureWorktree(path, pinned, baseRef, process.cwd(), log);
327
364
  return { mode: "branch", path, branch: pinned };
328
365
  }
329
366
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
330
367
  const branch = `wu/${n}-${slug}`;
331
368
  const path = resolve(parent, `${name}-wu${n}`);
332
369
  // A replay starts from the target branch as it was when the original was opened: the same ground, none of the original's work.
333
- let baseRef = target;
334
370
  if (unit.replay?.created_at) {
335
371
  const at = commitAtTime(target, unit.replay.created_at);
336
372
  if (!at)
package/dist/git.js CHANGED
@@ -194,14 +194,47 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
194
194
  * worktrees are never candidates, whatever their age.
195
195
  */
196
196
  export function prunableWorktrees(cwd = process.cwd()) {
197
+ return pruneReport(cwd).prunable;
198
+ }
199
+ /**
200
+ * Every linked worktree sorted into prunable or kept, with the reason. "Merged" means the
201
+ * worktree's head is on the base branch here or on origin's copy of it (fetched first), so a
202
+ * machine whose local main is behind does not keep work that already landed.
203
+ */
204
+ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map()) {
197
205
  const scan = scanWorktrees(cwd);
198
206
  if (!scan)
199
- return [];
207
+ return { prunable: [], kept: [], base: null };
200
208
  const here = realpathOrSelf(cwd);
201
- return scan.worktrees
202
- .filter((w) => realpathOrSelf(w.path) !== realpathOrSelf(scan.repo) && !here.startsWith(realpathOrSelf(w.path)))
203
- .filter((w) => w.dirty === false && w.merged === true)
204
- .map((w) => ({ path: w.path, branch: w.branch }));
209
+ const base = scan.worktrees.find((w) => w.base)?.base ?? null;
210
+ const remoteBase = base && fetchRef(base, "origin", scan.repo) && fullSha(`origin/${base}`, scan.repo) ? `origin/${base}` : null;
211
+ const prunable = [];
212
+ const kept = [];
213
+ for (const w of scan.worktrees) {
214
+ if (realpathOrSelf(w.path) === realpathOrSelf(scan.repo))
215
+ continue;
216
+ if (here.startsWith(realpathOrSelf(w.path))) {
217
+ kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
218
+ continue;
219
+ }
220
+ if (w.dirty !== false) {
221
+ kept.push({ path: w.path, branch: w.branch, reason: w.dirty === null ? "cannot read its status" : "uncommitted changes" });
222
+ continue;
223
+ }
224
+ const onRemote = remoteBase && w.head ? spawnSync("git", ["merge-base", "--is-ancestor", w.head, remoteBase], { cwd: scan.repo, stdio: "ignore" }).status === 0 : false;
225
+ if (w.merged === true || onRemote) {
226
+ prunable.push({ path: w.path, branch: w.branch });
227
+ continue;
228
+ }
229
+ // A clean worktree of a closed unit holds nothing the branch does not: nobody is working there.
230
+ const closed = closedUnitPaths.get(realpathOrSelf(w.path));
231
+ if (closed) {
232
+ prunable.push({ path: w.path, branch: w.branch, why: closed });
233
+ continue;
234
+ }
235
+ kept.push({ path: w.path, branch: w.branch, reason: `${w.ahead ?? "?"} commit${w.ahead === 1 ? "" : "s"} not on ${remoteBase ?? base ?? "the base branch"}` });
236
+ }
237
+ return { prunable, kept, base: remoteBase ?? base };
205
238
  }
206
239
  /** The remote's current head for a branch, asked of the remote itself; null when there is no remote or it cannot be reached. */
207
240
  export function remoteHead(branch, remote = "origin", cwd = process.cwd()) {
package/dist/help.js CHANGED
@@ -33,7 +33,9 @@ Agent commands
33
33
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
34
34
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
35
35
  bschat wu assign "<title>" --to <agent|auto|queue> --scope ".." [--tags a,b] [--replay-of n] hand out a unit (assigner roles);
36
- auto queues it when nobody qualified is free; queue waits deliberately
36
+ auto queues it when nobody qualified is free; queue waits deliberately; naming a
37
+ busy worker reserves it for them (theirs when free, anyone's after the takeover
38
+ window); --hold keeps it assigned to them however long it takes
37
39
  bschat wu take <n> [--to <agent>] pull a queued unit for yourself (qualified by works or trial), or hand it to someone
38
40
  bschat wu next take the oldest queued unit you qualify for
39
41
  --to auto picks the active worker qualified for the tags with the lightest load;
@@ -58,6 +60,9 @@ Agent commands
58
60
  bschat wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
59
61
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
60
62
  bschat wu approve|changes <n> --note ".." your approval covers the tags your role reviews; classify <n> --tags a,b
63
+ bschat wu proceed <n> --note ".." reviewer: this step is good, carry on; back to the owner, NOT an approval
64
+ bschat wu reopen <n> --note ".." owner or reviewer: withdraw an unmerged approval (verification failed); resubmit the same unit
65
+ bschat wu supersede <n> --by <m> owner or assigner: this unit continues as #m; anyone blocked on #n now waits on #m
61
66
  bschat wu tags <n> --add a --remove b retag (owner before review, a reviewer during it; may add a reviewer)
62
67
  bschat wu done <n> --merged <sha> [--keep-worktree] after approval; verifies the sha is on the target; removes the unit's clean worktree
63
68
  bschat wu abandon <n> [--note ..] wu list [--all] / wu show <n> for state and timeline
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.12";
1
+ export const CLI_VERSION = "0.12.17";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.12",
3
+ "version": "0.12.17",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {