benignswarm 0.12.40 → 0.12.42

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.
@@ -7,7 +7,7 @@ import { join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { ensureInstall } from "../install.js";
10
- import { HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
10
+ import { claudeCheckoutOwner, claudeCheckoutTaken, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
11
  import { detectVendor } from "../vendor.js";
12
12
  function repoRoot() {
13
13
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
@@ -40,6 +40,11 @@ export async function setup(p, out) {
40
40
  const vendor = normalizeVendor(str(p.flags, "vendor") ?? creds.vendor);
41
41
  const root = str(p.flags, "dir") ?? repoRoot();
42
42
  const model = resolveModel(str(p.flags, "model"), process.env, process.cwd(), ref);
43
+ if (harnessList(p, vendor).includes("claude-code") && !bool(p.flags, "replace")) {
44
+ const owner = claudeCheckoutOwner(root);
45
+ if (owner && owner !== ref && owner !== creds.agent)
46
+ throw claudeCheckoutTaken(root, owner, creds.agent);
47
+ }
43
48
  const inst = machineInstall();
44
49
  const idPath = writeIdentity(root, vendor, creds.agent, model, bool(p.flags, "replace"), creds.project);
45
50
  const files = await fetchSkill(creds.url);
@@ -70,6 +75,13 @@ export async function join(p, out) {
70
75
  // A second agent of the same vendor in one worktree must not steal the repo mapping. With
71
76
  // --no-bind the credentials are saved and the agent is addressed per call instead.
72
77
  const noBind = bool(p.flags, "no-bind");
78
+ // --no-bind keeps the repo's mapping, but for Claude Code the hook still runs as the bound agent
79
+ // in every session here: a second Claude Code agent needs its own worktree, not --no-bind.
80
+ if (vendor === "claude-code" && !bool(p.flags, "replace")) {
81
+ const owner = claudeCheckoutOwner(root);
82
+ if (owner && owner.split("/").pop() !== name)
83
+ throw claudeCheckoutTaken(root, owner, name);
84
+ }
73
85
  if (!noBind)
74
86
  writeIdentityDryRun(root, vendor, name, bool(p.flags, "replace"));
75
87
  // The machine's one bschat install comes first: if it cannot be made, the token is not spent.
package/dist/git.js CHANGED
@@ -223,7 +223,7 @@ export function landedByContent(head, base, cwd) {
223
223
  * machine whose local main is behind does not keep work that already landed, or that its
224
224
  * changes are already there by content (rebased or squashed landings).
225
225
  */
226
- export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }) {
226
+ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }, minAgeMs = 24 * 3600_000) {
227
227
  const scan = scanWorktrees(cwd);
228
228
  if (!scan)
229
229
  return { prunable: [], kept: [], base: null };
@@ -239,6 +239,19 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
239
239
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
240
240
  continue;
241
241
  }
242
+ // An agent's home checkout is never leftovers, whatever its branch: join/setup bind an identity
243
+ // there (unit worktrees never get one). And a worktree made in the last day is too new to judge:
244
+ // StickJoy's watcher removed a home checkout two minutes after it was created, before the agent
245
+ // could bind it, because a fresh branch on main's head looks merged.
246
+ if (existsSync(join(w.path, ".bschat", "identity.json"))) {
247
+ kept.push({ path: w.path, branch: w.branch, reason: "an agent's home checkout (it has .bschat/identity.json)" });
248
+ continue;
249
+ }
250
+ const made = worktreeCreatedMs(w.path);
251
+ if (made !== null && Date.now() - made < minAgeMs) {
252
+ kept.push({ path: w.path, branch: w.branch, reason: "created less than a day ago" });
253
+ continue;
254
+ }
242
255
  // A unit still being worked keeps its worktree whatever git says: one just started has no
243
256
  // commits yet, so its head is on the base and it looks merged (ester WU 110 and 111).
244
257
  const active = activeUnits.paths.get(realpathOrSelf(w.path)) ?? (w.branch ? activeUnits.branches.get(w.branch) : undefined);
@@ -388,3 +401,13 @@ export function removeWorktreeIfClean(path, cwd = process.cwd()) {
388
401
  const r = spawnSync("git", ["worktree", "remove", path], { cwd, encoding: "utf8" });
389
402
  return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
390
403
  }
404
+ /** When a linked worktree was created: its `.git` file is written once by `git worktree add`. */
405
+ export function worktreeCreatedMs(path) {
406
+ try {
407
+ const st = statSync(join(path, ".git"));
408
+ return st.birthtimeMs > 0 ? st.birthtimeMs : st.mtimeMs;
409
+ }
410
+ catch {
411
+ return null;
412
+ }
413
+ }
package/dist/harness.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { shellPath } from "./install.js";
3
- import { dirname, join } from "node:path";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import { CliError } from "./errors.js";
5
5
  /** Canonical vendor ids and the aliases people type. */
6
6
  const VENDOR_ALIASES = {
@@ -45,6 +45,8 @@ export function writeIdentity(root, vendor, name, model, replace, project) {
45
45
  file = readIdentityFile(p);
46
46
  const existing = file.agents[vendor];
47
47
  if (existing && existing.name !== name && !replace) {
48
+ if (vendor === "claude-code")
49
+ throw claudeCheckoutTaken(root, existing.project ? `${existing.project}/${existing.name}` : existing.name, name);
48
50
  throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Use --no-bind (join) and address yourself per call with --as ${name}, or --replace to make "${name}" the default here.`);
49
51
  }
50
52
  file.agents[vendor] = { name, project, ...(model ? { model } : {}) };
@@ -182,3 +184,33 @@ export function withBschatHooks(hooks, bin) {
182
184
  }
183
185
  return out;
184
186
  }
187
+ /**
188
+ * The Claude Code agent this checkout's hook runs as (its settings' BSCHAT_AGENT, else the identity
189
+ * file's claude-code entry), or null when none is bound here.
190
+ */
191
+ export function claudeCheckoutOwner(root) {
192
+ const sp = join(root, ".claude", "settings.local.json");
193
+ if (existsSync(sp)) {
194
+ try {
195
+ const env = JSON.parse(readFileSync(sp, "utf8")).env;
196
+ if (env?.BSCHAT_AGENT)
197
+ return env.BSCHAT_AGENT;
198
+ }
199
+ catch {
200
+ throw new CliError("bad_settings", `${sp} is not valid JSON; fix it or remove it`);
201
+ }
202
+ }
203
+ const idp = findIdentityFile(root);
204
+ const e = idp && idp.startsWith(root) ? readIdentityFile(idp).agents["claude-code"] : undefined;
205
+ return e ? (e.project ? `${e.project}/${e.name}` : e.name) : null;
206
+ }
207
+ /**
208
+ * Two Claude Code agents cannot share a checkout: its hook runs as one agent for every Claude Code
209
+ * session opened there, so the second session would be handed the first agent's messages, and
210
+ * they would count as delivered. Learned from StickJoy: a second agent joined with --no-bind, and
211
+ * once the hook worked it would have taken the triage lead's notifications. The way out is a worktree.
212
+ */
213
+ export function claudeCheckoutTaken(root, owner, name) {
214
+ const sibling = join(dirname(root), `${basename(root)}-${name}`);
215
+ return new CliError("checkout_taken", `this checkout's Claude Code hook runs as ${owner} for every Claude Code session opened here, so ${name} would be handed ${owner}'s messages (and they would count as delivered)`, `Give ${name} its own worktree: git -C ${root} worktree add ${sibling} then start Claude Code in ${sibling} and run this command there. (--replace makes ${name} this checkout's Claude Code agent instead of ${owner}.)`);
216
+ }
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { feedback } from "./commands/feedback.js";
11
11
  import { goal } from "./commands/goal.js";
12
12
  import { wake } from "./commands/wake.js";
13
13
  import { doctor, install } from "./commands/install.js";
14
+ import { warnIfForeignCopy } from "./install.js";
14
15
  import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
15
16
  import { worktrees } from "./commands/worktrees.js";
16
17
  import { CliError } from "./errors.js";
@@ -82,6 +83,7 @@ async function main(argv) {
82
83
  const fn = COMMANDS[cmd];
83
84
  if (!fn)
84
85
  throw new CliError("usage", `unknown command ${cmd}`, "Run: bschat --help");
86
+ warnIfForeignCopy(cmd, CLI_VERSION);
85
87
  await fn(p, out);
86
88
  return 0;
87
89
  }
package/dist/install.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { configRoot } from "./config.js";
@@ -106,3 +106,61 @@ export function reloadLaunchAgent(label, path) {
106
106
  export function restartLaunchAgent(label) {
107
107
  return spawnSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/${label}`], { stdio: "ignore" }).status === 0;
108
108
  }
109
+ /** Commands that legitimately run from a copy other than the recorded install (npx join, old npx hooks). */
110
+ const GUARD_EXEMPT = new Set(["join", "setup", "install", "doctor", "hook", "watch"]);
111
+ /**
112
+ * The line to print when this process is not the machine's recorded install, or null. Pure, so
113
+ * it is tested without a machine: `self` and `recorded` are real paths, `lastAt` when this copy
114
+ * was last warned about (epoch ms).
115
+ */
116
+ export function foreignCopyNotice(cmd, self, selfVersion, rec, recorded, lastAt, now) {
117
+ if (!rec || !recorded || GUARD_EXEMPT.has(cmd) || self === recorded)
118
+ return null;
119
+ if (lastAt !== null && now - lastAt < 24 * 3600_000)
120
+ return null;
121
+ return `[bschat] this is ${self} (${selfVersion}), not this machine's install ${rec.bin} (${rec.version}). Run that one (put ${dirname(rec.bin)} first on PATH, or remove this copy), or see: bschat doctor`;
122
+ }
123
+ /**
124
+ * Warns once a day per copy when a bschat other than the recorded install runs: another
125
+ * `npm i -g` with a different Node quietly puts a second copy ahead on PATH (a publish routine
126
+ * did exactly that and an operator's shell ran 0.12.37, which had no install command).
127
+ * Never fails a command: a machine state it cannot read only skips the notice.
128
+ */
129
+ export function warnIfForeignCopy(cmd, selfVersion) {
130
+ let rec;
131
+ try {
132
+ rec = readInstall();
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ if (!rec || !process.argv[1])
138
+ return;
139
+ let self;
140
+ let recorded;
141
+ try {
142
+ self = realpathSync(process.argv[1]);
143
+ recorded = realpathSync(rec.bin);
144
+ }
145
+ catch {
146
+ return;
147
+ }
148
+ const stateFile = join(configRoot(), "state", "foreign-copy.json");
149
+ let seen = {};
150
+ try {
151
+ if (existsSync(stateFile))
152
+ seen = JSON.parse(readFileSync(stateFile, "utf8"));
153
+ }
154
+ catch {
155
+ seen = {};
156
+ }
157
+ const line = foreignCopyNotice(cmd, self, selfVersion, rec, recorded, seen[self] ?? null, Date.now());
158
+ if (!line)
159
+ return;
160
+ process.stderr.write(line + "\n");
161
+ try {
162
+ mkdirSync(dirname(stateFile), { recursive: true });
163
+ writeFileSync(stateFile, JSON.stringify({ ...seen, [self]: Date.now() }));
164
+ }
165
+ catch { /* the notice simply repeats next time */ }
166
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.40";
1
+ export const CLI_VERSION = "0.12.42";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.40",
3
+ "version": "0.12.42",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {