benignswarm 0.12.133 → 0.12.134

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.
@@ -19,6 +19,14 @@ export function commandLabel(command) {
19
19
  const line = command.join(" ").replace(/\s+/g, " ").trim();
20
20
  return line.length <= 200 ? line : `${line.slice(0, 197)}...`;
21
21
  }
22
+ function shellQuote(value) {
23
+ return `'${value.replace(/'/g, `'\\''`)}'`;
24
+ }
25
+ function unlockCommand(o) {
26
+ const project = o.projectSelection ? ` --project ${shellQuote(o.projectSelection)}` : "";
27
+ const scope = o.shared ? " --shared" : ` --machine ${shellQuote(o.machine)}`;
28
+ return `b9s --as ${shellQuote(o.identity)} unlock ${shellQuote(o.lock)} --job ${shellQuote(o.jobId)}${scope}${project}`;
29
+ }
22
30
  export async function runUnderLock(o, deps) {
23
31
  const now = deps.now ?? Date.now;
24
32
  const label = commandLabel(o.command);
@@ -26,12 +34,13 @@ export async function runUnderLock(o, deps) {
26
34
  const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
27
35
  const release = async (completion) => {
28
36
  try {
29
- await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
37
+ const result = await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
38
+ forgetLockJob(o.jobsFile, o.jobsKey, o.token);
39
+ return result;
30
40
  }
31
41
  catch (error) {
32
- throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: b9s unlock ${o.lock}${o.shared ? " --shared" : ""} --job ${o.jobId}`);
42
+ throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`);
33
43
  }
34
- forgetLockJob(o.jobsFile, o.jobsKey, o.token);
35
44
  };
36
45
  let r = await deps.call("POST", `${base}/acquire`, acquireBody);
37
46
  if (r.job_token !== o.token)
@@ -59,7 +68,11 @@ export async function runUnderLock(o, deps) {
59
68
  deps.log(`job ${o.jobId} holds ${o.lock}; running: ${label}`);
60
69
  const result = await deps.run(o.command);
61
70
  code = typeof result === "number" ? result : result.exit_code;
62
- await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
71
+ const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
72
+ if (released.gate_receipt?.recorded === false) {
73
+ const configured = released.gate_receipt.configured_command;
74
+ deps.log(`Gate receipt not recorded: ${released.gate_receipt.reason ?? "the reported gate result was refused"}.${configured ? ` Use the configured command: ${configured}` : " No complete gate command is configured."}`);
75
+ }
63
76
  }
64
77
  catch (error) {
65
78
  if (!error || !(error instanceof CliError) || error.code !== "lock_release_failed")
@@ -89,20 +102,47 @@ export function processDeps(call, log) {
89
102
  }),
90
103
  run: (command) => new Promise((resolve, reject) => {
91
104
  const child = spawn(command[0], command.slice(1), { stdio: ["inherit", "pipe", "inherit"] });
92
- let output = "";
105
+ let tail = "";
106
+ let gateOutput = false;
107
+ let baseline;
108
+ let testedTree;
109
+ const consumeLines = (text, final = false) => {
110
+ const lines = (tail + text).split(/\r?\n/);
111
+ const incomplete = lines.pop() ?? "";
112
+ if (final) {
113
+ tail = "";
114
+ if (incomplete)
115
+ lines.push(incomplete);
116
+ }
117
+ else {
118
+ tail = incomplete.slice(-2048);
119
+ }
120
+ for (const line of lines) {
121
+ if (/^gate:/i.test(line))
122
+ gateOutput = true;
123
+ const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
124
+ // The gate's header is authoritative. Tests run later in the same process
125
+ // may print fixture marker lines; they must not replace the real SHAs.
126
+ if (baselineMatch && !baseline)
127
+ baseline = baselineMatch[1].toLowerCase();
128
+ const treeMatch = line.match(/^gate: tested tree ([0-9a-f]{40})\s*$/i);
129
+ if (treeMatch && !testedTree)
130
+ testedTree = treeMatch[1].toLowerCase();
131
+ }
132
+ };
93
133
  child.stdout?.on("data", (chunk) => {
94
134
  process.stdout.write(chunk);
95
- if (output.length < 8192)
96
- output += chunk.toString("utf8").slice(0, 8192 - output.length);
135
+ consumeLines(chunk.toString("utf8"));
97
136
  });
98
137
  forward = (signal) => { child.kill(signal); };
99
138
  child.once("error", (error) => { forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
100
- child.once("exit", (code, signal) => {
139
+ // `close` follows stdout's `end`, so the final marker lines have been
140
+ // consumed before we construct the receipt sent with the lock release.
141
+ child.once("close", (code, signal) => {
101
142
  forward = undefined;
143
+ consumeLines("", true);
102
144
  const exit_code = code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0);
103
- const baseline = output.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
104
- const testedTree = output.match(/^gate: tested tree ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
105
- resolve({ exit_code, ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
145
+ resolve({ exit_code, ...(gateOutput ? { gate_output: true } : {}), ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
106
146
  });
107
147
  }),
108
148
  dispose: () => { for (const signal of signals)
@@ -10,7 +10,7 @@ import { createHash } from "node:crypto";
10
10
  import { homedir, totalmem, userInfo } from "node:os";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { bool, str } from "../args.js";
13
- import { configRoot, loadAgent, resolveAgentName } from "../config.js";
13
+ import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
14
14
  import { Client } from "../client.js";
15
15
  import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
16
16
  import { scanProject, unitWorktrees } from "./worktrees.js";
@@ -443,6 +443,27 @@ export async function resolveWatcherWorkUnitBinding(name) {
443
443
  return { binding: null, reason: "current work-unit assignment event is unavailable" };
444
444
  }
445
445
  }
446
+ /**
447
+ * Runs `work` with BSCHAT_AGENT naming this watcher's agent, then puts the environment back.
448
+ * The watcher is started with --as, so its own environment carries no identity; the git it runs
449
+ * to prepare a unit worktree calls the b9s credential helper as a child process, which can only
450
+ * learn who it is from the environment. Without this every fetch for a linked repository failed
451
+ * with no_identity and the watcher exited before any turn (0.12.133).
452
+ */
453
+ export function withAgentEnv(ref, work) {
454
+ const had = Object.prototype.hasOwnProperty.call(process.env, "BSCHAT_AGENT");
455
+ const before = process.env.BSCHAT_AGENT;
456
+ process.env.BSCHAT_AGENT = ref;
457
+ try {
458
+ return work();
459
+ }
460
+ finally {
461
+ if (had)
462
+ process.env.BSCHAT_AGENT = before;
463
+ else
464
+ delete process.env.BSCHAT_AGENT;
465
+ }
466
+ }
446
467
  /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
447
468
  async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
448
469
  const creds = loadAgent(name);
@@ -473,7 +494,7 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
473
494
  }
474
495
  const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
475
496
  const { prepareWorktreeForWatcher } = await import("./wu.js");
476
- const prepared = prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []);
497
+ const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []));
477
498
  return { number: binding.work_unit_number, path: prepared.path, status: unit.status };
478
499
  }
479
500
  catch (error) {
@@ -1702,7 +1702,8 @@ export async function lock(p, out) {
1702
1702
  const deps = processDeps((method, path, body) => client.call(method, path, body, { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1703
1703
  try {
1704
1704
  process.exitCode = await runUnderLock({
1705
- project, lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1705
+ project, identity: agentRef(creds), projectSelection: creds.project ? undefined : project,
1706
+ lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1706
1707
  jobId: createHash("sha256").update(runToken).digest("hex").slice(0, 12),
1707
1708
  jobsFile: lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`), jobsKey: lockJobKey(project, runName, shared ? null : machine),
1708
1709
  }, deps);
package/dist/help.js CHANGED
@@ -131,7 +131,7 @@ Agent commands
131
131
  acquisition queues through a machine maintenance drain/window and resumes after it
132
132
  machine identity is this host's hostname plus its registered label, shared by all agents here
133
133
  save the returned job token; reuse --token to check/retry the same job
134
- b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run the command, then release; exits with its code and records configured gate completion
134
+ b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run and release; gate receipt outcome is separate and does not change the command exit code
135
135
  polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
136
136
  b9s locks shows waiter poll age; reported-command holders do not expire
137
137
  b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.133";
1
+ export const CLI_VERSION = "0.12.134";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.133",
3
+ "version": "0.12.134",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {