benignswarm 0.12.28 → 0.12.30

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)
@@ -7,7 +7,7 @@ import { loadAgent, resolveAgentName } from "../config.js";
7
7
  import { Client } from "../client.js";
8
8
  import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
9
9
  import { scanProject, unitWorktrees } from "./worktrees.js";
10
- import { pruneReport, removeWorktreeIfClean } from "../git.js";
10
+ import { pruneReport, removePrunable } from "../git.js";
11
11
  import { CliError } from "../errors.js";
12
12
  import { acquireWatchLock } from "../lock.js";
13
13
  import { gatherUpdates } from "./hook.js";
@@ -89,7 +89,7 @@ export async function watch(p, out) {
89
89
  // closed; never one a unit is still being worked in (it may have no commits yet).
90
90
  const units = await unitWorktrees(scanCreds, scanCreds.project);
91
91
  for (const c of pruneReport(process.cwd(), units.closed, units.active).prunable) {
92
- const res = removeWorktreeIfClean(c.path);
92
+ const res = removePrunable(c);
93
93
  log(res.removed ? `pruned merged worktree ${c.path}${c.branch ? ` (${c.branch})` : ""}` : `kept ${c.path}: ${res.reason}`);
94
94
  }
95
95
  }
@@ -3,13 +3,15 @@ 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, removePrunable } from "../git.js";
7
8
  import { table } from "../output.js";
8
9
  const CLOSED = ["done", "abandoned", "superseded"];
9
10
  /**
10
11
  * What the project's units say about worktrees on this machine: worktrees of units not yet
11
12
  * closed (by path, and by branch for a path recorded elsewhere) are never pruned; clean
12
- * worktrees of done or abandoned units may be. Most recorded paths of old units are gone from
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
13
15
  * disk and are skipped one by one; a failure to read the units is an error, never a quieter
14
16
  * prune (before, one missing path threw and silently discarded every closed unit).
15
17
  */
@@ -26,7 +28,7 @@ export async function unitWorktrees(creds, project) {
26
28
  active.paths.set(realpathSync(u.worktree), label);
27
29
  continue;
28
30
  }
29
- if (u.status === "superseded" || !u.worktree || !existsSync(u.worktree))
31
+ if (!u.worktree || !existsSync(u.worktree))
30
32
  continue;
31
33
  closed.set(realpathSync(u.worktree), `WU #${u.number} ${u.status}`);
32
34
  }
@@ -50,6 +52,28 @@ export async function worktrees(p, out) {
50
52
  // Worktrees recorded on units that are done or abandoned: clean ones go even if their branch never merged.
51
53
  const units = await unitWorktrees(creds, project);
52
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
+ }
74
+ }
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));
53
77
  const candidates = rep.prunable;
54
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")}` : "";
55
79
  if (!candidates.length) {
@@ -63,7 +87,7 @@ export async function worktrees(p, out) {
63
87
  const removed = [];
64
88
  const kept = [];
65
89
  for (const c of candidates) {
66
- const r = removeWorktreeIfClean(c.path);
90
+ const r = removePrunable(c);
67
91
  if (r.removed)
68
92
  removed.push(c.path);
69
93
  else
@@ -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,8 +1,11 @@
1
- import { existsSync, realpathSync, rmSync } from "node:fs";
1
+ import { copyFileSync, existsSync, readdirSync, 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
- const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
6
+ // Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
7
+ // the 1 MB default made such a worktree unreadable rather than dirty.
8
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024 });
6
9
  if (r.status !== 0)
7
10
  return null;
8
11
  return r.stdout.trim();
@@ -52,7 +55,8 @@ export function scanWorktrees(cwd = process.cwd()) {
52
55
  const head = git(["rev-parse", "--short", "HEAD"], p);
53
56
  const status = git(["status", "--porcelain"], p);
54
57
  const f = head ? mergeFacts(p, p) : { base: null, merged: null, ahead: null };
55
- return { path: p, branch, head, dirty: status === null ? null : status.length > 0, base: f.base, merged: f.merged, ahead: f.ahead };
58
+ const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
59
+ return { path: p, branch, head, dirty: status === null ? null : status.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty };
56
60
  });
57
61
  return { repo, worktrees };
58
62
  }
@@ -243,8 +247,14 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
243
247
  continue;
244
248
  }
245
249
  const closedNote = closedUnitPaths.get(realpathOrSelf(w.path));
250
+ // Nothing but .git: a checkout that never happened. There are no files to lose, and archiving
251
+ // it would record "every file deleted". The branch is untouched.
252
+ if (w.empty) {
253
+ prunable.push({ path: w.path, branch: w.branch, empty: true, why: `empty checkout (an interrupted git worktree add)${closedNote ? `, ${closedNote}` : ""}` });
254
+ continue;
255
+ }
246
256
  if (w.dirty !== false) {
247
- kept.push({ path: w.path, branch: w.branch, reason: `${w.dirty === null ? "cannot read its status" : "uncommitted changes"}${closedNote ? ` (${closedNote}: look before discarding)` : ""}` });
257
+ 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 } : {}) });
248
258
  continue;
249
259
  }
250
260
  const onRemote = remoteBase && w.head ? spawnSync("git", ["merge-base", "--is-ancestor", w.head, remoteBase], { cwd: scan.repo, stdio: "ignore" }).status === 0 : false;
@@ -306,6 +316,44 @@ export function ensureReviewWorktree(path, sha, cwd = process.cwd()) {
306
316
  return { created: true };
307
317
  }
308
318
  /** Removes a worktree only when it is clean; returns false when it is dirty or git refuses. */
319
+ /**
320
+ * Saves every uncommitted change in a worktree (modified, staged, untracked; not ignored files)
321
+ * as one commit on top of its HEAD, on branch `archive/<name>`, through a temporary index so the
322
+ * worktree's own index and files are untouched and no commit hooks run. Returns the branch.
323
+ * Throws when any step fails: nothing may be removed on the strength of a failed archive.
324
+ */
325
+ export function archiveWorktreeChanges(path, name, message) {
326
+ const run = (args, env = process.env) => {
327
+ const r = spawnSync("git", args, { cwd: path, encoding: "utf8", env });
328
+ if (r.status !== 0)
329
+ throw new Error(`git ${args[0]} failed in ${path}: ${(r.stderr || r.stdout).trim()}`);
330
+ return r.stdout.trim();
331
+ };
332
+ const index = run(["rev-parse", "--git-path", "index"]);
333
+ const tmp = `${index}.bschat-archive-${process.pid}`;
334
+ copyFileSync(index.startsWith("/") ? index : join(path, index), tmp.startsWith("/") ? tmp : join(path, tmp));
335
+ try {
336
+ const env = { ...process.env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
337
+ run(["add", "-A"], env);
338
+ const tree = run(["write-tree"], env);
339
+ const commit = run(["commit-tree", "-p", "HEAD", "-m", message, tree]);
340
+ const branch = `archive/${name}`;
341
+ run(["branch", branch, commit]);
342
+ return branch;
343
+ }
344
+ finally {
345
+ rmSync(tmp.startsWith("/") ? tmp : join(path, tmp), { force: true });
346
+ }
347
+ }
348
+ /** Removes a prune candidate: an empty checkout (re-checked here) by force, anything else only when clean. */
349
+ export function removePrunable(c, cwd = process.cwd()) {
350
+ if (!c.empty)
351
+ return removeWorktreeIfClean(c.path, cwd);
352
+ if (!existsSync(c.path) || !readdirSync(c.path).every((e) => e === ".git"))
353
+ return { removed: false, reason: "no longer an empty checkout" };
354
+ const r = spawnSync("git", ["worktree", "remove", "--force", c.path], { cwd, encoding: "utf8" });
355
+ return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
356
+ }
309
357
  export function removeWorktreeIfClean(path, cwd = process.cwd()) {
310
358
  const status = git(["status", "--porcelain"], path);
311
359
  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.28";
1
+ export const CLI_VERSION = "0.12.30";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.28",
3
+ "version": "0.12.30",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {