benignswarm 0.12.96 → 0.12.97

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.
@@ -5,9 +5,9 @@ import { Client } from "../client.js";
5
5
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
6
6
  import { readState } from "../state.js";
7
7
  import { codexRollout, sessionsOf } from "../sessions.js";
8
- import { sessionUsage, watcherClaudeUsage } from "../usage.js";
8
+ import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionUsage } from "../usage.js";
9
9
  import { CliError } from "../errors.js";
10
- import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
10
+ import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
11
11
  import { join, resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
13
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -198,6 +198,14 @@ export function createCutoffBundle(cwd, branch, oversized, pushError) {
198
198
  }
199
199
  return { archive, manifest: { captured: files.map(({ path, bytes }) => ({ path, size: bytes.length })), omitted, skipped } };
200
200
  }
201
+ export function parseLandsWith(value) {
202
+ if (value === undefined || value === "" || value === "clear")
203
+ return null;
204
+ const parsed = Number(value);
205
+ if (!Number.isInteger(parsed) || parsed < 1)
206
+ throw new CliError("usage", `invalid base work-unit number ${JSON.stringify(value)} (expected a positive integer)`);
207
+ return parsed;
208
+ }
201
209
  export function assignmentDisposition(unit, to) {
202
210
  if (unit.status !== "queued")
203
211
  return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
@@ -346,11 +354,11 @@ export async function wu(p, out) {
346
354
  const tags = (u) => (u.tags.length ? u.tags.map((t) => `#${t}`).join(" ") : "(untagged)");
347
355
  const fmt = (u) => {
348
356
  const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
349
- const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
357
+ const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
350
358
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
351
359
  const approvals = u.approvals.map((a) => a.name).join(", ");
352
360
  return [
353
- `WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}\n minimum tier: ${u.min_tier ?? "routine"}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
361
+ `WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
354
362
  u.candidate_record?.tags?.length ? ` ${u.candidate_record.agent} first-round approval: ${u.candidate_record.tags.map((x) => `#${x.tag} ${x.approved_first_round}/${x.units} (${Math.round(x.rate * 100)}%)`).join(", ")}` : null,
355
363
  ` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
356
364
  Object.keys(u.tag_focus ?? {}).length ? ` review focus:\n${Object.entries(u.tag_focus).map(([tag, focus]) => ` #${tag}: ${focus}`).join("\n")}` : null,
@@ -399,20 +407,20 @@ export async function wu(p, out) {
399
407
  case "open": {
400
408
  const title = p.positionals.slice(2).join(" ").trim();
401
409
  if (!title)
402
- throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id]');
410
+ throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id]');
403
411
  const unitTags = list("tags");
404
412
  const scope = await scopeText();
405
413
  // The unit exists first (it needs its number for the branch name), then its worktree is made
406
414
  // and recorded exactly as `wu start` would; --here keeps the current checkout.
407
- const r = await client.call("POST", base, { title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), min_tier: str(p.flags, "tier"), force: bool(p.flags, "force"), ...branchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null });
415
+ const r = await client.call("POST", base, { title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) });
408
416
  const n = r.unit.number;
409
417
  if (r.unit.waiting_on != null) {
410
418
  out.print(`${fmt(r.unit)}\nWait until ${r.unit.waits_on.map((on) => `WU #${on}`).join(", ")} closes, then start with: b9s wu start ${n}`, r);
411
419
  return;
412
420
  }
413
421
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
414
- const where = branchAndHead(path);
415
- const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
422
+ const where = symbolicBranchAndHead(path);
423
+ const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name) });
416
424
  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: b9s wu submit ${n} --evidence <id>`, { ...s, worktree: path, branch, mode });
417
425
  return;
418
426
  }
@@ -432,28 +440,25 @@ export async function wu(p, out) {
432
440
  }
433
441
  const to = str(p.flags, "to");
434
442
  const reason = str(p.flags, "reason");
435
- const allowLowerTier = bool(p.flags, "allow-lower-tier");
436
- if (allowLowerTier && (!reason?.trim() || reason.trim().length > 1000))
437
- throw new CliError("usage", '--allow-lower-tier requires --reason "why this lower-tier assignment is needed" (up to 1000 characters)');
438
- if (allowLowerTier && (to === "auto" || to === "queue"))
439
- throw new CliError("usage", "--allow-lower-tier applies only when naming an agent");
440
443
  if (!to)
441
- throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
444
+ throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id] [--replay-of <n>]');
442
445
  const existingNumber = Number(p.positionals[2]);
443
446
  if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
444
447
  if (p.flags.after !== undefined)
445
448
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
446
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
447
- out.print(`${fmt(r.unit)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}`, r);
449
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
450
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r);
448
451
  return;
449
452
  }
450
453
  const title = p.positionals.slice(2).join(" ").trim();
451
454
  if (!title)
452
- throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
455
+ throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id] [--replay-of <n>]');
456
+ const explicitBranch = str(p.flags, "branch") ?? null;
457
+ assertNotShaBranch(explicitBranch);
453
458
  const scope = await scopeText();
454
459
  const replay = str(p.flags, "replay-of");
455
- const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
456
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${assignmentGuidanceOutput(r.warnings ?? [])}`, r);
460
+ const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }) });
461
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, r);
457
462
  return;
458
463
  }
459
464
  case "park": {
@@ -477,6 +482,15 @@ export async function wu(p, out) {
477
482
  out.print(`${fmt(r.unit)}\nReturned to the queue; branch and event history were kept.`, r);
478
483
  return;
479
484
  }
485
+ case "lands-with": {
486
+ const baseUnit = p.positionals[3];
487
+ if (!baseUnit)
488
+ throw new CliError("usage", 'wu lands-with <n> <base-unit-number|clear>');
489
+ const value = baseUnit === "clear" ? null : parseLandsWith(baseUnit);
490
+ const r = await client.call("POST", `${base}/${num()}/lands-with`, { lands_with: value });
491
+ out.print(`${fmt(r.unit)}\n${value === null ? "Stack relation cleared." : `Merge waits for WU #${value} to land.`}`, r);
492
+ return;
493
+ }
480
494
  case "take": {
481
495
  // Pull a queued unit: for yourself (qualified by works or trial), or for someone with --to (assigners).
482
496
  const to = str(p.flags, "to") ?? null;
@@ -506,10 +520,10 @@ export async function wu(p, out) {
506
520
  const target = unit.target ?? def.merge.target_branch;
507
521
  const prepared = prepareWorktree(n, unit, def, p, await checkoutExclude());
508
522
  const { path, branch, mode } = prepared;
509
- const where = branchAndHead(path);
523
+ const where = symbolicBranchAndHead(path);
510
524
  let r;
511
525
  try {
512
- r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
526
+ r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode, ...startTelemetry(name) });
513
527
  }
514
528
  catch (error) {
515
529
  if (prepared.created) {
@@ -519,7 +533,7 @@ export async function wu(p, out) {
519
533
  }
520
534
  throw error;
521
535
  }
522
- 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: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
536
+ out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
523
537
  return;
524
538
  }
525
539
  case "decline": {
@@ -573,7 +587,7 @@ export async function wu(p, out) {
573
587
  }
574
588
  }
575
589
  const pr = str(p.flags, "pr") ?? null;
576
- const usage = await roundUsage(client, base, num(), name);
590
+ const telemetry = await roundTelemetry(client, base, num(), name);
577
591
  let branchValueIds = [];
578
592
  if (where.head) {
579
593
  try {
@@ -585,7 +599,7 @@ export async function wu(p, out) {
585
599
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
586
600
  }
587
601
  }
588
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
602
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
589
603
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
590
604
  const u = r.unit;
591
605
  out.print(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r);
@@ -729,7 +743,8 @@ export async function wu(p, out) {
729
743
  throw new CliError("usage", "--merged and --no-source are mutually exclusive");
730
744
  if (!noSource && evidence.length)
731
745
  throw new CliError("usage", "--evidence on wu done requires --no-source");
732
- const unit = (await client.call("GET", `${base}/${num()}`)).unit;
746
+ const doneRecord = await client.call("GET", `${base}/${num()}`);
747
+ const unit = doneRecord.unit;
733
748
  const landsIn = unit.target ?? def.merge.target_branch;
734
749
  let verifiedRemoteTarget = null;
735
750
  let noCommitsBeyondTarget = false;
@@ -775,7 +790,12 @@ export async function wu(p, out) {
775
790
  else if (def.merge.require_merge_commit) {
776
791
  throw new CliError("usage", `this project's process requires the merge commit: b9s wu done ${num()} --merged <sha>`);
777
792
  }
778
- const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged, ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: noCommitsBeyondTarget } : {}) });
793
+ // An assigner/reviewer/operator may close another owner's unit. Their local harness is not
794
+ // evidence about the owner's context, so leave those fields out and let the API record unknown.
795
+ const telemetry = unit.owner_name === creds.agent
796
+ ? await telemetryFromEvents(name, Array.isArray(doneRecord.events) ? doneRecord.events : [])
797
+ : null;
798
+ const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged, ...(telemetry ? { context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason } : {}), ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: noCommitsBeyondTarget } : {}) });
779
799
  out.print(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
780
800
  return;
781
801
  }
@@ -969,12 +989,12 @@ export async function wu(p, out) {
969
989
  if (str(p.flags, k))
970
990
  qs.set(k, str(p.flags, k));
971
991
  const r = await client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`);
972
- const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", title: u.title.slice(0, 50) }));
973
- out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "title"]) : "(no open work units; b9s wu list --all for closed ones)", r);
992
+ const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
993
+ out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "base", "title"]) : "(no open work units; b9s wu list --all for closed ones)", r);
974
994
  return;
975
995
  }
976
996
  default:
977
- throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
997
+ throw new CliError("usage", "wu open|assign|lands-with|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
978
998
  }
979
999
  }
980
1000
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -1002,8 +1022,10 @@ export async function processCmd(p, out) {
1002
1022
  const lines = [
1003
1023
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
1004
1024
  `Machine capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
1025
+ `Heavy job classes: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
1026
+ `Unlisted heavy workflows use the exclusive unknown-heavy class (the whole safe budget); an unknown budget or stale telemetry waits for operator review.`,
1005
1027
  vocab.length ? `Tags (use them on b9s wu open --tags):` : `No tag vocabulary yet: units route to the default approver (${d.default_approver_role ?? "none"}).`,
1006
- ...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.min_tier && t.min_tier !== "routine" ? ` · minimum tier ${t.min_tier}` : ""}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""}${t.requires?.length ? ` · requires capabilities ${t.requires.join(", ")}` : ""}${t.focus ? ` · reviewer focus: ${t.focus}` : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
1028
+ ...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""}${t.requires?.length ? ` · requires capabilities ${t.requires.join(", ")}` : ""}${t.focus ? ` · reviewer focus: ${t.focus}` : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
1007
1029
  ...Object.entries(d.scope_templates ?? {}).flatMap(([tag, template]) => [` #${tag} scope template:`, ...template.sections.map((section) => ` ${section.name}${section.required ? " (required)" : ""}${section.hint ? ` — ${section.hint}` : ""}`)]),
1008
1030
  ...(d.review_rules?.length ? [`Path review rules:`, ...d.review_rules.map((rule) => ` ${rule.paths.join(", ")} -> ${rule.add_tags.map((t) => `#${t}`).join(" ")} (${rule.reason})`)] : []),
1009
1031
  `Untagged units are approved by ${d.default_approver_role ?? "nobody (set a default approver)"}.${d.classification === "classifier" ? ` A ${d.classifier_role} confirms tags before review.` : ""}`,
@@ -1038,40 +1060,44 @@ function cleanupUnitWorktree(wt, def, keep) {
1038
1060
  * One worktree per unit, made (or repaired) here. Exceptions are explicit and recorded: --branch
1039
1061
  * continues existing work in its own worktree; --here uses the current checkout (single-agent repos).
1040
1062
  */
1063
+ function symbolicBranchAndHead(cwd = process.cwd()) {
1064
+ return { branch: symbolicBranch(cwd), head: branchAndHead(cwd).head };
1065
+ }
1066
+ function assertNotShaBranch(branch, flag = "--branch") {
1067
+ if (branch && isShaBranchName(branch)) {
1068
+ throw new CliError("usage", `refusing ${flag} ${branch}: never name a branch after a commit SHA`, "Pass a descriptive branch name like wu/123-fix or omit --branch to create one from origin's target.");
1069
+ }
1070
+ }
1041
1071
  function prepareWorktree(n, unit, def, p, exclude = []) {
1042
1072
  // The unit's own target when it has one: a lane or release branch the work lands in.
1043
1073
  const target = unit.target ?? def.merge.target_branch;
1044
1074
  const log = (line) => process.stderr.write(`b9s: ${line}\n`);
1045
- // Where reviewers may be on other machines, origin is the truth: start from origin's target, not
1046
- // this machine's possibly stale copy, and continue a pinned branch from what origin has of it.
1047
- const remoteFirst = !!def.merge.require_pushed;
1048
- let baseRef = target;
1049
- if (!p.flags.here) {
1050
- if (remoteFirst) {
1051
- if (!fetchRef(target))
1052
- throw new CliError("no_remote", `cannot fetch ${target} from origin, and this project requires work to start from origin's ${target}`, "Check the remote is reachable and try again.");
1053
- baseRef = `origin/${target}`;
1054
- log(`starting from origin/${target} (${fullSha(baseRef)?.slice(0, 9)}); this machine's ${target} is not used`);
1055
- }
1056
- else if (fullSha(target) === null && !(fetchRef(target) && fullSha(`origin/${target}`) !== null)) {
1057
- throw new CliError("no_target", `the unit lands in ${target}, which this repository does not have`, `git fetch origin ${target}:${target} then try again`);
1058
- }
1059
- }
1075
+ const explicitBranch = str(p.flags, "branch") ?? null;
1076
+ assertNotShaBranch(explicitBranch);
1060
1077
  if (p.flags.here)
1061
- return { mode: "here", path: process.cwd(), branch: branchAndHead().branch, created: false, branchCreated: false };
1078
+ return { mode: "here", path: process.cwd(), branch: symbolicBranch(), created: false, branchCreated: false };
1062
1079
  const name = repoName();
1063
1080
  const parent = repoParent();
1064
1081
  if (!name || !parent)
1065
1082
  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");
1066
- const pinned = str(p.flags, "branch") ?? unit.branch ?? null;
1083
+ // Always fetch and branch from origin's target so a stale local target or detached HEAD never becomes the base.
1084
+ const fetchedTarget = fetchRemoteBranch(target);
1085
+ if (!fetchedTarget.ok) {
1086
+ throw new CliError("no_remote", `cannot fetch ${target} from origin: ${fetchedTarget.reason}`, `Check that origin is configured and reachable with branch ${target}, then try again.`);
1087
+ }
1088
+ let baseRef = fetchedTarget.ref;
1089
+ log(`starting from ${baseRef} (${fullSha(baseRef)?.slice(0, 9)})`);
1090
+ const recordedBranch = unit.branch && !isShaBranchName(unit.branch) ? unit.branch : null;
1091
+ if (unit.branch && !recordedBranch)
1092
+ log(`ignoring recorded SHA-like branch ${unit.branch}; creating a wu/${n}-... branch from ${baseRef}`);
1093
+ const pinned = explicitBranch ?? recordedBranch;
1067
1094
  if (pinned) {
1068
1095
  const existing = worktreeForBranch(pinned);
1069
1096
  const path = existing ?? resolve(parent, `${name}-wu${n}`);
1070
- // ensureWorktree creates local branches when they do not exist; remember that too so a
1071
- // subsequent server refusal can remove every artifact made by this start attempt.
1072
- let branchCreated = !existing && fullSha(pinned) === null;
1097
+ // Check local branch refs explicitly: fullSha(pinned) would also resolve bare SHAs or tags.
1098
+ let branchCreated = !existing && fullSha(`refs/heads/${pinned}`) === null;
1073
1099
  // Continuing someone else's branch from another machine: take origin's copy of it when we have none.
1074
- if (!existing && remoteFirst && fullSha(pinned) === null && fetchRef(pinned)) {
1100
+ if (!existing && fullSha(`refs/heads/${pinned}`) === null && fetchRemoteBranch(pinned).ok) {
1075
1101
  const r = spawnSync("git", ["branch", "--track", pinned, `origin/${pinned}`], { cwd: process.cwd(), encoding: "utf8" });
1076
1102
  if (r.status !== 0)
1077
1103
  throw new CliError("no_branch", `cannot create ${pinned} from origin: ${(r.stderr || r.stdout).trim()}`);
@@ -1091,7 +1117,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
1091
1117
  throw new CliError("no_base", `cannot find ${baseRef} as of ${unit.replay.created_at} for the replay`, `git fetch origin ${target} then try again`);
1092
1118
  baseRef = at;
1093
1119
  }
1094
- const branchCreated = fullSha(branch) === null;
1120
+ const branchCreated = fullSha(`refs/heads/${branch}`) === null;
1095
1121
  const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
1096
1122
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
1097
1123
  }
@@ -1300,14 +1326,26 @@ export async function lock(p, out) {
1300
1326
  }
1301
1327
  if (!lockName)
1302
1328
  throw new CliError("usage", `${cmd} <name> (e.g. b9s lock build --unit 60 --note "exact run")`);
1329
+ const intended = {
1330
+ acquire: "b9s lock <name>", list: "b9s locks", release: "b9s unlock <name>", show: "b9s locks", status: "b9s locks",
1331
+ };
1332
+ if (cmd !== "unlock" && Object.hasOwn(intended, lockName))
1333
+ throw new CliError("usage", `lock name ${lockName} is reserved; use ${intended[lockName]}`);
1334
+ if (cmd !== "unlock" && bool(p.flags, "remove-empty"))
1335
+ throw new CliError("usage", "--remove-empty is only valid with b9s unlock <name>");
1303
1336
  if (cmd === "unlock") {
1304
- const r = await client.call("POST", `/projects/${project}/locks/${lockName}/release`, { shared: bool(p.flags, "shared") });
1337
+ const removeEmpty = bool(p.flags, "remove-empty");
1338
+ const r = await client.call("POST", `/projects/${project}/locks/${lockName}/release`, { shared: bool(p.flags, "shared"), machine: str(p.flags, "machine"), ...(removeEmpty ? { remove_empty: true } : {}) });
1339
+ if (removeEmpty) {
1340
+ out.print(`${lockName} removed as an empty lock.`, r);
1341
+ return;
1342
+ }
1305
1343
  out.print(r.lock.holder_name ? `${lockName} released; now held by ${r.lock.holder_name}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}.` : `${lockName} released; free.`, r);
1306
1344
  return;
1307
1345
  }
1308
1346
  const unit = str(p.flags, "unit");
1309
1347
  // Scoped to this machine unless --shared: the resource is this box's CPU and disk.
1310
- const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared") });
1348
+ const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared"), machine: str(p.flags, "machine") });
1311
1349
  out.print(r.maintenance
1312
1350
  ? `${lockName} is not handed out now: ${r.maintenance}. You are #${r.position} in line and will be @mentioned when it is yours after the window; do not poll. Leave the queue: b9s unlock ${lockName}`
1313
1351
  : r.acquired
@@ -1360,41 +1398,53 @@ export async function askOperator(p, out) {
1360
1398
  const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal });
1361
1399
  out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
1362
1400
  }
1363
- /**
1364
- * Tokens the agent's harness session used since the unit started or was last submitted, for the
1365
- * model comparison (docs/MODEL-COMPARISON.md). Never fails a submission: an unreadable session is
1366
- * recorded as unavailable with the reason.
1367
- */
1368
- async function roundUsage(client, base, n, name) {
1369
- const until = new Date().toISOString();
1370
- let since = until;
1401
+ function measurableSession(name) {
1402
+ const sessionId = process.env.BSCHAT_SESSION_ID;
1403
+ if (sessionId) {
1404
+ const provider = process.env.BSCHAT_PROVIDER;
1405
+ const remembered = readState(name).harness_session;
1406
+ return claudeSessionWithHookMetadata(sessionId, "", provider === "anthropic" || provider === "deepseek" ? provider : undefined, remembered);
1407
+ }
1408
+ let session = readState(name).harness_session;
1409
+ if (!session) {
1410
+ // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1411
+ const ref = agentRef(loadAgent(name));
1412
+ const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1413
+ if (rollout)
1414
+ session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1415
+ }
1416
+ return session;
1417
+ }
1418
+ /** Opening/starting a unit establishes the explicit zero-compaction baseline. */
1419
+ function startTelemetry(name) {
1420
+ const at = new Date().toISOString();
1421
+ return { context: sessionContext(measurableSession(name), at), compactions_since_last: 0, compactions_reason: null };
1422
+ }
1423
+ async function roundTelemetry(client, base, n, name) {
1371
1424
  try {
1372
1425
  const events = (await client.call("GET", `${base}/${n}`)).events;
1373
- const marks = events.filter((e) => ["started", "submitted", "resubmitted", "refreshed"].includes(e.type)).map((e) => e.at);
1374
- since = marks.length ? marks[marks.length - 1] : (events[0]?.at ?? until);
1426
+ return telemetryFromEvents(name, events);
1375
1427
  }
1376
1428
  catch (e) {
1377
- return { harness: "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the unit's timeline: ${e.message}` };
1429
+ const until = new Date().toISOString();
1430
+ const reason = `could not read the unit's timeline: ${e.message}`;
1431
+ const usage = { harness: "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason };
1432
+ return { usage, context: { pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason }, compactions: { count: null, reason } };
1378
1433
  }
1379
- let session = readState(name).harness_session;
1434
+ }
1435
+ async function telemetryFromEvents(name, events) {
1436
+ const until = new Date().toISOString();
1437
+ const marks = events.filter((e) => ["opened", "started", "submitted", "resubmitted", "refreshed"].includes(e.type)).map((e) => e.at);
1438
+ const since = marks.length ? marks[marks.length - 1] : (events[0]?.at ?? until);
1439
+ const session = measurableSession(name);
1380
1440
  try {
1381
- // Turn-mode watchers bind the session id they were configured to resume. Prefer that exact
1382
- // transcript over any older hook binding left by another Claude Code session on this machine.
1383
- if (process.env.BSCHAT_SESSION_ID) {
1384
- const provider = process.env.BSCHAT_PROVIDER;
1385
- return watcherClaudeUsage(process.env.BSCHAT_SESSION_ID, since, until, provider === "anthropic" || provider === "deepseek" ? provider : undefined);
1386
- }
1387
- if (!session) {
1388
- // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1389
- const ref = agentRef(loadAgent(name));
1390
- const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1391
- if (rollout)
1392
- session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1393
- }
1394
- return sessionUsage(session, since, until);
1441
+ const usage = sessionUsage(session, since, until);
1442
+ return { usage, context: sessionContext(session, until), compactions: sessionCompactions(session, since, until) };
1395
1443
  }
1396
1444
  catch (e) {
1397
- return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the session: ${e.message}` };
1445
+ const reason = `could not read the session: ${e.message}`;
1446
+ const usage = { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason };
1447
+ return { usage, context: { pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason }, compactions: { count: null, reason } };
1398
1448
  }
1399
1449
  }
1400
1450
  /** b9s explain <ask-id> "...": the operator asked (the banner's Explain) for your request in plain words. */