benignswarm 0.12.27 → 0.12.29

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
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", "on", "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"];
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", "defer", "hold", "clear", "met", "shared"];
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", "defer", "hold", "clear", "met", "shared", "archive"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -6,8 +6,8 @@ import { bool, str } from "../args.js";
6
6
  import { loadAgent, resolveAgentName } from "../config.js";
7
7
  import { Client } from "../client.js";
8
8
  import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
9
- import { scanProject } from "./worktrees.js";
10
- import { prunableWorktrees, removeWorktreeIfClean } from "../git.js";
9
+ import { scanProject, unitWorktrees } from "./worktrees.js";
10
+ import { pruneReport, removeWorktreeIfClean } from "../git.js";
11
11
  import { CliError } from "../errors.js";
12
12
  import { acquireWatchLock } from "../lock.js";
13
13
  import { gatherUpdates } from "./hook.js";
@@ -85,8 +85,10 @@ export async function watch(p, out) {
85
85
  const r = await scanProject(scanCreds, scanCreds.project);
86
86
  log(`worktree scan: ${r.recorded} in ${r.repo}${r.missing ? `, ${r.missing} gone` : ""}`);
87
87
  if (bool(p.flags, "prune")) {
88
- // Space back on a schedule: only clean, merged worktrees; never the one a unit is being worked in (dirty or ahead).
89
- for (const c of prunableWorktrees()) {
88
+ // Space back on a schedule: only clean worktrees whose work has landed or whose unit is
89
+ // closed; never one a unit is still being worked in (it may have no commits yet).
90
+ const units = await unitWorktrees(scanCreds, scanCreds.project);
91
+ for (const c of pruneReport(process.cwd(), units.closed, units.active).prunable) {
90
92
  const res = removeWorktreeIfClean(c.path);
91
93
  log(res.removed ? `pruned merged worktree ${c.path}${c.branch ? ` (${c.branch})` : ""}` : `kept ${c.path}: ${res.reason}`);
92
94
  }
@@ -1,10 +1,39 @@
1
- import { realpathSync } from "node:fs";
1
+ import { existsSync, realpathSync } from "node:fs";
2
2
  import { str, bool } from "../args.js";
3
3
  import { Client } from "../client.js";
4
4
  import { loadAgent, resolveAgentName } from "../config.js";
5
5
  import { CliError } from "../errors.js";
6
- import { defaultMachine, scanWorktrees, pruneReport, removeWorktreeIfClean } from "../git.js";
6
+ import { spawnSync } from "node:child_process";
7
+ import { archiveWorktreeChanges, defaultMachine, scanWorktrees, pruneReport, removeWorktreeIfClean } from "../git.js";
7
8
  import { table } from "../output.js";
9
+ const CLOSED = ["done", "abandoned", "superseded"];
10
+ /**
11
+ * What the project's units say about worktrees on this machine: worktrees of units not yet
12
+ * closed (by path, and by branch for a path recorded elsewhere) are never pruned; clean
13
+ * worktrees of done, abandoned or superseded units may be (a superseded unit's work lives on its
14
+ * branch, which is never deleted; a successor still on that branch keeps it as an open unit). Most recorded paths of old units are gone from
15
+ * disk and are skipped one by one; a failure to read the units is an error, never a quieter
16
+ * prune (before, one missing path threw and silently discarded every closed unit).
17
+ */
18
+ export async function unitWorktrees(creds, project) {
19
+ const all = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/work-units?all=1`);
20
+ const closed = new Map();
21
+ const active = { paths: new Map(), branches: new Map() };
22
+ for (const u of all.units) {
23
+ const label = `WU #${u.number} (${u.status})`;
24
+ if (!CLOSED.includes(u.status)) {
25
+ if (u.branch && u.branch !== "main")
26
+ active.branches.set(u.branch, label);
27
+ if (u.worktree && existsSync(u.worktree))
28
+ active.paths.set(realpathSync(u.worktree), label);
29
+ continue;
30
+ }
31
+ if (!u.worktree || !existsSync(u.worktree))
32
+ continue;
33
+ closed.set(realpathSync(u.worktree), `WU #${u.number} ${u.status}`);
34
+ }
35
+ return { closed, active };
36
+ }
8
37
  /**
9
38
  * The project's worktree registry.
10
39
  * bschat worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
@@ -21,15 +50,30 @@ export async function worktrees(p, out) {
21
50
  // Space back: delete linked worktrees that are clean and merged into the base branch. Dry run
22
51
  // unless --yes. Branches are kept (deleting a worktree never deletes its branch).
23
52
  // 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}`);
53
+ const units = await unitWorktrees(creds, project);
54
+ const rep = pruneReport(process.cwd(), units.closed, units.active);
55
+ // --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
56
+ // and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
57
+ const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];
58
+ if (archive.length) {
59
+ const text = archive.map((k) => ` ${k.path}${k.branch ? ` (${k.branch})` : ""}: ${k.archivable}`).join("\n");
60
+ if (!bool(p.flags, "yes"))
61
+ out.print(`${archive.length} closed unit worktree(s) with uncommitted files would be archived to a branch and removed (run again with --yes):\n${text}`, { archive });
62
+ else {
63
+ const done = [];
64
+ for (const k of archive) {
65
+ const n = /WU #(\d+)/.exec(k.archivable)?.[1] ?? "unit";
66
+ const branch = archiveWorktreeChanges(k.path, `wu${n}-leftovers`, `Leftover uncommitted files from WU #${n} worktree, archived ${new Date().toISOString().slice(0, 10)} before removal`);
67
+ const r = spawnSync("git", ["worktree", "remove", "--force", k.path], { encoding: "utf8" });
68
+ if (r.status !== 0)
69
+ throw new CliError("git", `archived ${k.path} to ${branch} but could not remove it: ${(r.stderr || r.stdout).trim()}`);
70
+ done.push(` ${k.path} -> ${branch}`);
71
+ }
72
+ out.print(`Archived and removed ${done.length} worktree(s):\n${done.join("\n")}`, { archived: done });
73
+ }
30
74
  }
31
- catch { /* the worktree is gone or the server is unreachable: fall back to merged-only */ }
32
- const rep = pruneReport(process.cwd(), closedUnitPaths);
75
+ const archived = new Set(bool(p.flags, "yes") ? archive.map((k) => k.path) : []);
76
+ rep.kept = rep.kept.filter((k) => !archived.has(k.path));
33
77
  const candidates = rep.prunable;
34
78
  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")}` : "";
35
79
  if (!candidates.length) {
@@ -368,7 +368,11 @@ function cleanupUnitWorktree(wt, def, keep) {
368
368
  if (wt === repoParent() || worktreeForBranch(def.merge.target_branch) === wt)
369
369
  return "";
370
370
  const res = removeWorktreeIfClean(wt);
371
- return res.removed ? `\nRemoved worktree ${wt} (branch kept).` : `\nWorktree ${wt} kept: ${res.reason}.`;
371
+ if (res.removed)
372
+ return `\nRemoved worktree ${wt} (branch kept).`;
373
+ if (res.reason === "uncommitted changes")
374
+ return `\nWorktree ${wt} kept: it has uncommitted files that are not on the branch. Commit them to the branch if they belong to the record, or run bschat worktrees prune --archive --yes to save them to an archive branch and remove the worktree.`;
375
+ return `\nWorktree ${wt} kept: ${res.reason}.`;
372
376
  }
373
377
  /**
374
378
  * One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
package/dist/git.js CHANGED
@@ -1,6 +1,7 @@
1
- import { existsSync, realpathSync, rmSync } from "node:fs";
1
+ import { copyFileSync, existsSync, realpathSync, rmSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { hostname } from "node:os";
4
+ import { join } from "node:path";
4
5
  function git(args, cwd) {
5
6
  const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
6
7
  if (r.status !== 0)
@@ -196,12 +197,30 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
196
197
  export function prunableWorktrees(cwd = process.cwd()) {
197
198
  return pruneReport(cwd).prunable;
198
199
  }
200
+ /**
201
+ * Whether everything on `head` is already in `base` by content: merging it would leave base's
202
+ * tree unchanged. True for a branch that landed by merge, rebase, cherry-pick or squash, which
203
+ * ancestry alone misses (ester: WU 68, 98, 99, 101, 102 all landed rebased or squashed, and their
204
+ * 20 GB worktrees were kept as "N commits not on origin/main"). Null when git cannot tell.
205
+ */
206
+ export function landedByContent(head, base, cwd) {
207
+ const baseTree = git(["rev-parse", `${base}^{tree}`], cwd);
208
+ if (!baseTree)
209
+ return null;
210
+ const r = spawnSync("git", ["merge-tree", "--write-tree", "--no-messages", base, head], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 120_000 });
211
+ if (r.status === 1)
212
+ return false; // conflicts: the branch still differs from base
213
+ if (r.status !== 0)
214
+ return null;
215
+ return r.stdout.split("\n")[0].trim() === baseTree;
216
+ }
199
217
  /**
200
218
  * Every linked worktree sorted into prunable or kept, with the reason. "Merged" means the
201
219
  * 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.
220
+ * machine whose local main is behind does not keep work that already landed, or that its
221
+ * changes are already there by content (rebased or squashed landings).
203
222
  */
204
- export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map()) {
223
+ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }) {
205
224
  const scan = scanWorktrees(cwd);
206
225
  if (!scan)
207
226
  return { prunable: [], kept: [], base: null };
@@ -217,8 +236,16 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map()) {
217
236
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
218
237
  continue;
219
238
  }
239
+ // A unit still being worked keeps its worktree whatever git says: one just started has no
240
+ // commits yet, so its head is on the base and it looks merged (ester WU 110 and 111).
241
+ const active = activeUnits.paths.get(realpathOrSelf(w.path)) ?? (w.branch ? activeUnits.branches.get(w.branch) : undefined);
242
+ if (active) {
243
+ kept.push({ path: w.path, branch: w.branch, reason: `${active} is not closed` });
244
+ continue;
245
+ }
246
+ const closedNote = closedUnitPaths.get(realpathOrSelf(w.path));
220
247
  if (w.dirty !== false) {
221
- kept.push({ path: w.path, branch: w.branch, reason: w.dirty === null ? "cannot read its status" : "uncommitted changes" });
248
+ kept.push({ path: w.path, branch: w.branch, reason: `${w.dirty === null ? "cannot read its status" : "uncommitted changes"}${closedNote ? ` (${closedNote}${w.dirty ? "; --archive saves them to a branch and removes it" : ""})` : ""}`, ...(closedNote && w.dirty === true ? { archivable: closedNote } : {}) });
222
249
  continue;
223
250
  }
224
251
  const onRemote = remoteBase && w.head ? spawnSync("git", ["merge-base", "--is-ancestor", w.head, remoteBase], { cwd: scan.repo, stdio: "ignore" }).status === 0 : false;
@@ -226,10 +253,14 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map()) {
226
253
  prunable.push({ path: w.path, branch: w.branch });
227
254
  continue;
228
255
  }
256
+ const landedOn = remoteBase ?? base;
257
+ if (landedOn && w.head && landedByContent(w.head, landedOn, scan.repo) === true) {
258
+ prunable.push({ path: w.path, branch: w.branch, why: `its changes are on ${landedOn} (rebased or squashed)` });
259
+ continue;
260
+ }
229
261
  // 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 });
262
+ if (closedNote) {
263
+ prunable.push({ path: w.path, branch: w.branch, why: closedNote });
233
264
  continue;
234
265
  }
235
266
  kept.push({ path: w.path, branch: w.branch, reason: `${w.ahead ?? "?"} commit${w.ahead === 1 ? "" : "s"} not on ${remoteBase ?? base ?? "the base branch"}` });
@@ -276,6 +307,35 @@ export function ensureReviewWorktree(path, sha, cwd = process.cwd()) {
276
307
  return { created: true };
277
308
  }
278
309
  /** Removes a worktree only when it is clean; returns false when it is dirty or git refuses. */
310
+ /**
311
+ * Saves every uncommitted change in a worktree (modified, staged, untracked; not ignored files)
312
+ * as one commit on top of its HEAD, on branch `archive/<name>`, through a temporary index so the
313
+ * worktree's own index and files are untouched and no commit hooks run. Returns the branch.
314
+ * Throws when any step fails: nothing may be removed on the strength of a failed archive.
315
+ */
316
+ export function archiveWorktreeChanges(path, name, message) {
317
+ const run = (args, env = process.env) => {
318
+ const r = spawnSync("git", args, { cwd: path, encoding: "utf8", env });
319
+ if (r.status !== 0)
320
+ throw new Error(`git ${args[0]} failed in ${path}: ${(r.stderr || r.stdout).trim()}`);
321
+ return r.stdout.trim();
322
+ };
323
+ const index = run(["rev-parse", "--git-path", "index"]);
324
+ const tmp = `${index}.bschat-archive-${process.pid}`;
325
+ copyFileSync(index.startsWith("/") ? index : join(path, index), tmp.startsWith("/") ? tmp : join(path, tmp));
326
+ try {
327
+ const env = { ...process.env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
328
+ run(["add", "-A"], env);
329
+ const tree = run(["write-tree"], env);
330
+ const commit = run(["commit-tree", "-p", "HEAD", "-m", message, tree]);
331
+ const branch = `archive/${name}`;
332
+ run(["branch", branch, commit]);
333
+ return branch;
334
+ }
335
+ finally {
336
+ rmSync(tmp.startsWith("/") ? tmp : join(path, tmp), { force: true });
337
+ }
338
+ }
279
339
  export function removeWorktreeIfClean(path, cwd = process.cwd()) {
280
340
  const status = git(["status", "--porcelain"], path);
281
341
  if (status === null)
package/dist/help.js CHANGED
@@ -79,7 +79,8 @@ Agent commands
79
79
  bschat wu tags <n> --add a --remove b retag (owner before review, a reviewer during it; may add a reviewer)
80
80
  bschat wu done <n> --merged <sha> [--keep-worktree] after approval; verifies the sha is on the target; removes the unit's clean worktree
81
81
  bschat wu abandon <n> [--note ..] wu list [--all] / wu show <n> for state and timeline
82
- bschat worktrees prune [--yes] remove linked worktrees that are clean and merged into the base (dry run without --yes)
82
+ bschat worktrees prune [--yes] [--archive] remove clean worktrees whose work landed or whose unit is closed (dry run without --yes);
83
+ --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it
83
84
  bschat worktrees [scan] the project's worktree registry (machine, path, branch, dirty, merged, who);
84
85
  scan reports every linked worktree of the repo you are in (watchers do this hourly)
85
86
  bschat goal [set "<text>" [--state s] | achieved | paused | stalled | abandoned | clear]
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.27";
1
+ export const CLI_VERSION = "0.12.29";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.27",
3
+ "version": "0.12.29",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {