benignswarm 0.12.7 → 0.12.8

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.
@@ -2,7 +2,7 @@ import { str } from "../args.js";
2
2
  import { Client } from "../client.js";
3
3
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
4
4
  import { CliError } from "../errors.js";
5
- import { branchAndHead, commitAtTime, createWorktree, isAncestor, removeWorktreeIfClean, repoName, repoParent, worktreeForBranch } from "../git.js";
5
+ import { branchAndHead, commitAtTime, ensureWorktree, isAncestor, removeWorktreeIfClean, repoName, repoParent, worktreeForBranch } from "../git.js";
6
6
  import { resolve } from "node:path";
7
7
  import { table } from "../output.js";
8
8
  /**
@@ -56,8 +56,14 @@ export async function wu(p, out) {
56
56
  const title = p.positionals.slice(2).join(" ").trim();
57
57
  if (!title)
58
58
  throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--tags a,b] [--evidence id]');
59
+ // The unit exists first (it needs its number for the branch name), then its worktree is made
60
+ // and recorded exactly as `wu start` would; --here keeps the current checkout.
59
61
  const r = await client.call("POST", base, { title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), evidence: list("evidence"), ...branchAndHead(), worktree: process.cwd() });
60
- out.print(`${fmt(r.unit)}\nSubmit for review when ready: bschat wu submit ${r.unit.number} --evidence <id>`, r);
62
+ const n = r.unit.number;
63
+ const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p);
64
+ const where = branchAndHead(path);
65
+ const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
66
+ out.print(`${fmt(s.unit)}\n${mode === "here" ? "Working in this checkout." : `Your worktree: ${path} (branch ${branch})\n cd ${path}\nWork there.`}\nSubmit for review when ready: bschat wu submit ${n} --evidence <id>`, { ...s, worktree: path, branch, mode });
61
67
  return;
62
68
  }
63
69
  case "assign": {
@@ -88,50 +94,11 @@ export async function wu(p, out) {
88
94
  return;
89
95
  }
90
96
  case "start": {
91
- // One worktree per unit, made here. Exceptions are explicit and recorded: --branch continues
92
- // existing work in its own worktree; --here uses the current checkout (single-agent repos).
93
97
  const n = num();
94
98
  const unit = (await client.call("GET", `${base}/${n}`)).unit;
95
99
  const def = await processDef();
96
100
  const target = def.merge.target_branch;
97
- let mode;
98
- let path;
99
- let branch;
100
- if (p.flags.here) {
101
- mode = "here";
102
- path = process.cwd();
103
- branch = branchAndHead().branch;
104
- }
105
- else {
106
- const name = repoName();
107
- const parent = repoParent();
108
- if (!name || !parent)
109
- throw new CliError("not_a_repo", "run wu start from a checkout of the project's repository (it creates your worktree next to it), or pass --here");
110
- const pinned = str(p.flags, "branch") ?? unit.branch ?? null;
111
- if (pinned) {
112
- mode = "branch";
113
- branch = pinned;
114
- const existing = worktreeForBranch(pinned);
115
- path = existing ?? resolve(parent, `${name}-wu${n}`);
116
- if (!existing)
117
- createWorktree(path, pinned, target);
118
- }
119
- else {
120
- mode = "fresh";
121
- const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
122
- branch = `wu/${n}-${slug}`;
123
- path = resolve(parent, `${name}-wu${n}`);
124
- // A replay starts from the target branch as it was when the original was opened: the same ground, none of the original's work.
125
- let baseRef = target;
126
- if (unit.replay?.created_at) {
127
- const at = commitAtTime(target, unit.replay.created_at);
128
- if (!at)
129
- throw new CliError("no_base", `cannot find ${target} as of ${unit.replay.created_at} for the replay`, `git fetch origin ${target}:${target} then try again`);
130
- baseRef = at;
131
- }
132
- createWorktree(path, branch, baseRef);
133
- }
134
- }
101
+ const { path, branch, mode } = prepareWorktree(n, unit, def, p);
135
102
  const where = branchAndHead(path);
136
103
  const r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
137
104
  out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from ${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: bschat wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
@@ -276,6 +243,41 @@ export async function processCmd(p, out) {
276
243
  await client.call("POST", `/projects/${project}/process/ack`, { version: r.process.version });
277
244
  }
278
245
  /** Per agent per tag, what real units have shown. */
246
+ /**
247
+ * One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
248
+ * continues existing work in its own worktree; --here uses the current checkout (single-agent repos).
249
+ */
250
+ function prepareWorktree(n, unit, def, p) {
251
+ const target = def.merge.target_branch;
252
+ const log = (line) => process.stderr.write(`bschat: ${line}\n`);
253
+ if (p.flags.here)
254
+ return { mode: "here", path: process.cwd(), branch: branchAndHead().branch };
255
+ const name = repoName();
256
+ const parent = repoParent();
257
+ if (!name || !parent)
258
+ throw new CliError("not_a_repo", "run this from a checkout of the project's repository (it creates your worktree next to it), or pass --here");
259
+ const pinned = str(p.flags, "branch") ?? unit.branch ?? null;
260
+ if (pinned) {
261
+ const existing = worktreeForBranch(pinned);
262
+ const path = existing ?? resolve(parent, `${name}-wu${n}`);
263
+ if (!existing)
264
+ ensureWorktree(path, pinned, target, process.cwd(), log);
265
+ return { mode: "branch", path, branch: pinned };
266
+ }
267
+ const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
268
+ const branch = `wu/${n}-${slug}`;
269
+ const path = resolve(parent, `${name}-wu${n}`);
270
+ // A replay starts from the target branch as it was when the original was opened: the same ground, none of the original's work.
271
+ let baseRef = target;
272
+ if (unit.replay?.created_at) {
273
+ const at = commitAtTime(target, unit.replay.created_at);
274
+ if (!at)
275
+ throw new CliError("no_base", `cannot find ${target} as of ${unit.replay.created_at} for the replay`, `git fetch origin ${target}:${target} then try again`);
276
+ baseRef = at;
277
+ }
278
+ ensureWorktree(path, branch, baseRef, process.cwd(), log);
279
+ return { mode: "fresh", path, branch };
280
+ }
279
281
  export async function record(p, out) {
280
282
  const name = resolveAgentName(str(p.flags, "as"));
281
283
  const creds = loadAgent(name);
package/dist/git.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { existsSync, realpathSync, rmSync } from "node:fs";
1
2
  import { spawnSync } from "node:child_process";
2
3
  import { hostname } from "node:os";
3
4
  function git(args, cwd) {
@@ -117,6 +118,76 @@ export function createWorktree(path, branch, base, cwd = process.cwd()) {
117
118
  if (r.status !== 0)
118
119
  throw new Error(`git ${args.join(" ")}: ${(r.stderr || r.stdout).trim()}`);
119
120
  }
121
+ /** What git says about the worktree at `path`, from `git worktree list` plus a status probe. */
122
+ export function worktreeState(path, cwd = process.cwd()) {
123
+ const list = git(["worktree", "list", "--porcelain"], cwd) ?? "";
124
+ let cur = null;
125
+ let found = null;
126
+ const target = realpathOrSelf(path);
127
+ for (const line of `${list}\n`.split("\n")) {
128
+ if (line.startsWith("worktree "))
129
+ cur = { path: line.slice(9), branch: null, locked: null, prunable: false };
130
+ else if (cur && line.startsWith("branch "))
131
+ cur.branch = line.slice(7).replace(/^refs\/heads\//, "");
132
+ else if (cur && line.startsWith("locked"))
133
+ cur.locked = line.slice(6).trim() || "locked";
134
+ else if (cur && line.startsWith("prunable"))
135
+ cur.prunable = true;
136
+ else if (line === "" && cur) {
137
+ if (realpathOrSelf(cur.path) === target)
138
+ found = cur;
139
+ cur = null;
140
+ }
141
+ }
142
+ if (!found)
143
+ return existsSync(path) ? { state: "foreign" } : { state: "absent" };
144
+ if (found.locked && /^initializing/.test(found.locked))
145
+ return { state: "partial", reason: "git worktree add was interrupted (locked: initializing)" };
146
+ if (found.prunable)
147
+ return { state: "partial", reason: "git lists it as prunable" };
148
+ if (git(["status", "--porcelain"], path) === null)
149
+ return { state: "partial", reason: "the checkout cannot report its status" };
150
+ return { state: "ready", branch: found.branch };
151
+ }
152
+ function realpathOrSelf(p) {
153
+ try {
154
+ return realpathSync(p);
155
+ }
156
+ catch {
157
+ return p;
158
+ }
159
+ }
160
+ /**
161
+ * The unit's worktree, made or repaired as needed. A worktree left half-written by an interrupted
162
+ * `git worktree add` (a harness timeout on a large repo) is removed and created again rather than
163
+ * failing on "already exists"; an existing complete worktree on the right branch is reused.
164
+ */
165
+ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = () => { }) {
166
+ const st = worktreeState(path, cwd);
167
+ if (st.state === "foreign")
168
+ throw new Error(`${path} exists but is not a worktree of this repository; move it aside or pass --here`);
169
+ if (st.state === "ready") {
170
+ if (st.branch !== branch)
171
+ throw new Error(`${path} is checked out on ${st.branch ?? "a detached HEAD"}, not ${branch}; remove it or pass --branch ${st.branch ?? ""}`.trim());
172
+ return { created: false, repaired: false };
173
+ }
174
+ let repaired = false;
175
+ if (st.state === "partial") {
176
+ log(`${path}: ${st.reason}; removing it and checking out again`);
177
+ const rm = spawnSync("git", ["worktree", "remove", "--force", "--force", path], { cwd, encoding: "utf8" });
178
+ if (rm.status !== 0) {
179
+ spawnSync("git", ["worktree", "prune"], { cwd, encoding: "utf8" });
180
+ rmSync(path, { recursive: true, force: true });
181
+ spawnSync("git", ["worktree", "prune"], { cwd, encoding: "utf8" });
182
+ }
183
+ repaired = true;
184
+ }
185
+ const files = (git(["ls-files"], cwd) ?? "").split("\n").length;
186
+ if (files > 20_000)
187
+ log(`creating ${path} (${files.toLocaleString()} tracked files; this can take a minute or more)`);
188
+ createWorktree(path, branch, base, cwd);
189
+ return { created: true, repaired };
190
+ }
120
191
  /** Removes a worktree only when it is clean; returns false when it is dirty or git refuses. */
121
192
  export function removeWorktreeIfClean(path, cwd = process.cwd()) {
122
193
  const status = git(["status", "--porcelain"], path);
package/dist/help.js CHANGED
@@ -29,7 +29,7 @@ Agent commands
29
29
  bschat follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
30
30
  other channels appear as a one-line unread digest
31
31
  bschat process the project's process: tag vocabulary, who reviews what, requirements, agreements
32
- bschat wu open "<title>" --scope "..." [--tags a,b] [--evidence id] open a work unit; tags come from the vocabulary
32
+ bschat wu open "<title>" --scope "..." [--tags a,b] [--evidence id] [--here] open a work unit in its own worktree; tags come from the vocabulary
33
33
  bschat wu assign "<title>" --to <agent|auto|queue> --scope ".." [--tags a,b] [--replay-of n] hand out a unit (assigner roles);
34
34
  auto queues it when nobody qualified is free; queue waits deliberately
35
35
  bschat wu take <n> [--to <agent>] pull a queued unit for yourself (qualified by works or trial), or hand it to someone
@@ -37,6 +37,8 @@ Agent commands
37
37
  --to auto picks the active worker qualified for the tags with the lightest load;
38
38
  it exists on the board as assigned and the sweep chases it; wu decline <n> --note
39
39
  bschat wu start <n> [--branch b | --here] take it up: makes ../<repo>-wu<n> on branch wu/<n>-<slug> (replays: from the
40
+ target as of the original); a worktree left half-written by an interrupted
41
+ checkout is removed and made again; wu open does the same for your own units
40
42
  target branch as of the original); --branch continues existing work; --here uses this checkout
41
43
  bschat record per agent per tag: first-round approvals, changes, replays, reviews overturned
42
44
  bschat record --by model the same, keyed by model and effort setting (stamped on start and on each verdict)
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.7";
1
+ export const CLI_VERSION = "0.12.8";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.7",
3
+ "version": "0.12.8",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {