benignswarm 0.12.88 → 0.12.90

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 { readState } from "../state.js";
7
7
  import { codexRollout, sessionsOf } from "../sessions.js";
8
8
  import { 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, worktreeForBranch } from "../git.js";
10
+ import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
11
11
  import { resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
13
  export function scopeEditFromArgs(p) {
@@ -102,7 +102,17 @@ export function changedPathsAgainstTarget(target, cwd = process.cwd()) {
102
102
  return diff.stdout.split("\0").filter((path) => path.length > 0);
103
103
  }
104
104
  export function submitPayload(fields, hasReviewRules, target, cwd = process.cwd()) {
105
- return { ...fields, changed_paths: hasReviewRules ? changedPathsAgainstTarget(target, cwd) : [] };
105
+ const paths = changedPathsAgainstTarget(target, cwd);
106
+ const directories = {}, fileKinds = {};
107
+ for (const path of paths) {
108
+ const slash = path.lastIndexOf("/");
109
+ const directory = slash < 0 ? "(root)" : path.slice(0, path.indexOf("/"));
110
+ const basename = path.slice(slash + 1), dot = basename.lastIndexOf(".");
111
+ const kind = dot <= 0 ? "(no extension)" : basename.slice(dot).toLowerCase();
112
+ directories[directory] = (directories[directory] ?? 0) + 1;
113
+ fileKinds[kind] = (fileKinds[kind] ?? 0) + 1;
114
+ }
115
+ return { ...fields, changed_paths: hasReviewRules ? paths : [], changed_path_summary: { total: paths.length, by_directory: directories, by_file_kind: fileKinds, paths: paths.slice(0, 200), truncated: paths.length > 200 } };
106
116
  }
107
117
  export function branchValueIdsAtHead(values, head) {
108
118
  if (!head)
@@ -157,6 +167,11 @@ export async function wu(p, out) {
157
167
  }
158
168
  return items;
159
169
  };
170
+ const afterUnits = () => list("after").map((item) => {
171
+ if (!/^\d+$/.test(item) || Number(item) < 1)
172
+ throw new CliError("usage", `--after expects comma-separated work unit numbers, got ${JSON.stringify(item)}`);
173
+ return Number(item);
174
+ });
160
175
  const num = () => {
161
176
  const n = Number(p.positionals[2]);
162
177
  if (!Number.isInteger(n) || n < 1)
@@ -165,7 +180,8 @@ export async function wu(p, out) {
165
180
  };
166
181
  const tags = (u) => (u.tags.length ? u.tags.map((t) => `#${t}`).join(" ") : "(untagged)");
167
182
  const fmt = (u) => {
168
- const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}` : null, u.hold && u.status === "assigned" ? "held" : null, u.waiting_on ? `waits on #${u.waiting_on}` : 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(" · ");
183
+ const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
184
+ 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(" · ");
169
185
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
170
186
  const approvals = u.approvals.map((a) => a.name).join(", ");
171
187
  return [
@@ -177,7 +193,8 @@ export async function wu(p, out) {
177
193
  u.question ? ` QUESTION for ${u.question.level === "expert" ? `a ${u.question.roles.join(" or ")}` : "the operator"} (asked by ${u.question.asked_by}${u.question.passed_by ? `, passed up by ${u.question.passed_by}` : ""}): ${u.question.text}` : null,
178
194
  u.evidence_claims?.total ? ` evidence claims: ${u.evidence_claims.confirmed} confirmed / ${u.evidence_claims.refuted} refuted / ${u.evidence_claims.unchecked} unchecked\n${u.evidence_claims.items.map((claim) => ` [${claim.state}] ${claim.filename}: ${claim.claim}${claim.verifier_name ? ` — ${claim.verifier_name}${claim.note ? `: ${claim.note}` : ""}` : ""}`).join("\n")}` : null,
179
195
  ` ${u.branch ? `${u.branch}${u.head ? ` @ ${u.head}` : ""}` : "no branch recorded"}${u.worktree ? ` in ${u.worktree.replace(/^\/(Users|home)\/[^/]+\//, "~/")}` : ""}${u.pr_url ? ` · ${u.pr_url}` : ""}${u.merged_sha ? ` · merged ${u.merged_sha}` : ""}${u.evidence.length ? ` · evidence ${u.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}`,
180
- u.scope ? ` scope: ${u.scope}` : null,
196
+ (u.base_scope ?? u.scope) ? ` scope: ${u.base_scope ?? u.scope}` : null,
197
+ u.scope_amendments?.length ? ` scope amendments:\n${u.scope_amendments.map((amendment) => ` ${amendment.at} ${amendment.author}: ${amendment.text}`).join("\n")}` : null,
181
198
  ].filter(Boolean).join("\n");
182
199
  };
183
200
  const processDef = async () => (await client.call("GET", `/projects/${project}/process`)).process.definition;
@@ -217,13 +234,17 @@ export async function wu(p, out) {
217
234
  case "open": {
218
235
  const title = p.positionals.slice(2).join(" ").trim();
219
236
  if (!title)
220
- throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--tier routine|careful|expert] [--evidence id]');
237
+ 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]');
221
238
  const unitTags = list("tags");
222
239
  const scope = await scopeText();
223
240
  // The unit exists first (it needs its number for the branch name), then its worktree is made
224
241
  // and recorded exactly as `wu start` would; --here keeps the current checkout.
225
- const r = await client.call("POST", base, { title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), 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 });
242
+ 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 });
226
243
  const n = r.unit.number;
244
+ if (r.unit.waiting_on != null) {
245
+ 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);
246
+ return;
247
+ }
227
248
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
228
249
  const where = branchAndHead(path);
229
250
  const s = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
@@ -245,27 +266,33 @@ export async function wu(p, out) {
245
266
  return;
246
267
  }
247
268
  const to = str(p.flags, "to");
269
+ const reason = str(p.flags, "reason");
248
270
  if (!to)
249
- 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] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
271
+ 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>]');
250
272
  const existingNumber = Number(p.positionals[2]);
251
273
  if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
252
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to });
274
+ if (p.flags.after !== undefined)
275
+ throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
276
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
253
277
  out.print(fmt(r.unit), r);
254
278
  return;
255
279
  }
256
280
  const title = p.positionals.slice(2).join(" ").trim();
257
281
  if (!title)
258
- 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] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
282
+ 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>]');
259
283
  const scope = await scopeText();
260
284
  const replay = str(p.flags, "replay-of");
261
- const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, 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") });
285
+ 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 }) });
262
286
  out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
263
287
  return;
264
288
  }
265
289
  case "take": {
266
290
  // Pull a queued unit: for yourself (qualified by works or trial), or for someone with --to (assigners).
267
291
  const to = str(p.flags, "to") ?? null;
268
- const r = await client.call("POST", `${base}/${num()}/take`, { to });
292
+ const reason = str(p.flags, "reason");
293
+ if (reason !== undefined && !to)
294
+ throw new CliError("usage", 'wu take <n> --to <agent> --reason "why" is only for an assigner handing work to a named agent');
295
+ const r = await client.call("POST", `${base}/${num()}/take`, { to, ...(reason === undefined ? {} : { reason }) });
269
296
  out.print(`${fmt(r.unit)}\n${to ? `Handed to ${r.unit.owner_name}.` : `Yours. Start it: b9s wu start ${r.unit.number}`}`, r);
270
297
  return;
271
298
  }
@@ -310,7 +337,7 @@ export async function wu(p, out) {
310
337
  throw new CliError("usage", 'wu decline <n> --note "why" [--waits-on <milestone,...> | --defer] (a planning unit needs one of them)');
311
338
  const waits = str(p.flags, "waits-on");
312
339
  const r = await client.call("POST", `${base}/${num()}/decline`, { note, ...(waits ? { waits_on: waits.split(",").map((k) => k.trim()).filter(Boolean) } : {}), ...(bool(p.flags, "defer") ? { defer: true } : {}) });
313
- out.print(fmt(r.unit), r);
340
+ out.print(`Declined; now ${r.unit.status}.\n${fmt(r.unit)}`, r);
314
341
  return;
315
342
  }
316
343
  case "submit": {
@@ -477,16 +504,44 @@ export async function wu(p, out) {
477
504
  out.print(fmt(r.unit), r);
478
505
  return;
479
506
  }
507
+ case "kind": {
508
+ const kind = str(p.flags, "kind");
509
+ const reason = str(p.flags, "reason");
510
+ if (!kind || !reason)
511
+ throw new CliError("usage", 'wu kind <n> --kind <product_change|enabling_tooling|diagnosis_audit|documentation|rework|needs_classification> --reason "why"');
512
+ const r = await client.call("POST", `${base}/${num()}/kind`, { kind, reason });
513
+ out.print(fmt(r.unit), r);
514
+ return;
515
+ }
480
516
  case "done": {
481
517
  const def = await processDef();
482
518
  const merged = str(p.flags, "merged") ?? null;
519
+ const noSource = bool(p.flags, "no-source");
520
+ const evidence = list("evidence");
521
+ if (noSource && merged)
522
+ throw new CliError("usage", "--merged and --no-source are mutually exclusive");
523
+ if (!noSource && evidence.length)
524
+ throw new CliError("usage", "--evidence on wu done requires --no-source");
483
525
  const unit = (await client.call("GET", `${base}/${num()}`)).unit;
484
526
  const landsIn = unit.target ?? def.merge.target_branch;
485
527
  let verifiedRemoteTarget = null;
528
+ let noCommitsBeyondTarget = false;
486
529
  if (unit.replay_of) {
487
530
  // A replay is an evaluation: it closes without merging (the server records it as evaluated).
488
- if (merged)
489
- throw new CliError("usage", `WU #${num()} is a replay, compared and never merged: close it without --merged`);
531
+ if (merged || noSource)
532
+ throw new CliError("usage", `WU #${num()} is a replay, compared and never merged: close it without --merged or --no-source`);
533
+ }
534
+ else if (noSource) {
535
+ if (!evidence.length)
536
+ throw new CliError("usage", "--no-source requires at least one --evidence id");
537
+ if (unit.branch) {
538
+ const check = verifyNoCommitsBeyondTarget(unit.branch, landsIn, process.cwd(), def.merge.require_pushed);
539
+ if (check.on === null)
540
+ throw new CliError("unknown_commit", `cannot verify ${unit.branch} against ${check.ref}`, `Fetch the branch and ${landsIn} in the project repository, then retry`);
541
+ if (!check.on)
542
+ throw new CliError("has_commits", `${unit.branch} has commits not contained by ${check.ref}; --no-source is only for work with no commits beyond its target`);
543
+ noCommitsBeyondTarget = true;
544
+ }
490
545
  }
491
546
  else if (merged) {
492
547
  // Where pushes are required the remote target is the truth, not this machine's copy of it.
@@ -513,7 +568,7 @@ export async function wu(p, out) {
513
568
  else if (def.merge.require_merge_commit) {
514
569
  throw new CliError("usage", `this project's process requires the merge commit: b9s wu done ${num()} --merged <sha>`);
515
570
  }
516
- const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged });
571
+ 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 } : {}) });
517
572
  out.print(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
518
573
  return;
519
574
  }
@@ -629,6 +684,10 @@ export async function wu(p, out) {
629
684
  }
630
685
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
631
686
  export async function preflightQueuedStart(client, base, n, unit) {
687
+ if (unit.waiting_on != null) {
688
+ const waits = unit.waits_on?.length ? unit.waits_on : [unit.waiting_on];
689
+ throw new CliError("unit_waiting", `work unit #${n} waits on ${waits.map((on) => `#${on}`).join(", ")}; start it after those units close`);
690
+ }
632
691
  if (unit.status === "queued")
633
692
  await client.call("POST", `${base}/${n}/start`, {});
634
693
  }
@@ -761,7 +820,7 @@ export async function milestones(p, out) {
761
820
  */
762
821
  export async function milestonesWith(client, project, sub, p, out) {
763
822
  if (sub === "export") {
764
- const list = (await client.call("GET", `/projects/${project}/milestones`)).milestones.map((m) => ({ key: m.key, title: m.title, exit: m.exit, ...(m.source ? { source: m.source } : {}), depends_on: m.dependencies ?? m.depends_on, default_tags: m.default_tags ?? [], ...(m.priority !== null && m.priority !== undefined ? { priority: m.priority } : {}) }));
823
+ const list = (await client.call("GET", `/projects/${project}/milestones`)).milestones.map((m) => ({ key: m.key, title: m.title, exit: m.exit, expectations: m.expectations ?? [], ...(m.source ? { source: m.source } : {}), depends_on: m.dependencies ?? m.depends_on, default_tags: m.default_tags ?? [], ...(m.priority !== null && m.priority !== undefined ? { priority: m.priority } : {}) }));
765
824
  const text = JSON.stringify(list, null, 2) + "\n";
766
825
  const file = str(p.flags, "out");
767
826
  if (file) {
@@ -834,17 +893,28 @@ export async function milestoneWith(client, project, sub, key, p, out, decisionP
834
893
  const dependencies = [...deps.map((key) => ({ key, kind: "blocks" })), ...informs.map((key) => ({ key, kind: "informs" }))];
835
894
  const exit = str(p.flags, "exit") ?? existing?.exit ?? "";
836
895
  const source = str(p.flags, "source") ?? existing?.source ?? "";
896
+ let expectations = existing?.expectations ?? [];
897
+ if (str(p.flags, "expectations") !== undefined) {
898
+ try {
899
+ expectations = JSON.parse(str(p.flags, "expectations"));
900
+ }
901
+ catch {
902
+ throw new CliError("usage", "--expectations must be a JSON list of {measure, direction?, value?, checkpoint?: closure}");
903
+ }
904
+ if (!Array.isArray(expectations))
905
+ throw new CliError("usage", "--expectations must be a JSON list of expectation objects");
906
+ }
837
907
  const default_tags = str(p.flags, "default-tags") !== undefined ? (str(p.flags, "default-tags") ?? "").split(",").map((s) => s.trim().replace(/^#/, "")).filter(Boolean) : existing?.default_tags ?? [];
838
908
  // --priority <n> (higher first) or none; the steward asks for units only on the highest-priority ready slices.
839
909
  const pr = str(p.flags, "priority");
840
910
  if (pr !== undefined && pr !== "none" && !/^-?\d+$/.test(pr))
841
911
  throw new CliError("usage", "--priority takes a whole number (higher first) or none");
842
912
  const priority = pr === undefined ? existing?.priority ?? null : pr === "none" ? null : Number(pr);
843
- const next = cur.map((m) => ({ key: m.key, title: m.title, exit: m.exit, source: m.source ?? "", depends_on: m.dependencies ?? m.depends_on, default_tags: m.default_tags ?? [], priority: m.priority ?? null }));
913
+ const next = cur.map((m) => ({ key: m.key, title: m.title, exit: m.exit, expectations: m.expectations ?? [], source: m.source ?? "", depends_on: m.dependencies ?? m.depends_on, default_tags: m.default_tags ?? [], priority: m.priority ?? null }));
844
914
  if (existing)
845
- Object.assign(next.find((m) => m.key === key), { title, exit, source, depends_on: dependencies, default_tags, priority });
915
+ Object.assign(next.find((m) => m.key === key), { title, exit, expectations, source, depends_on: dependencies, default_tags, priority });
846
916
  else
847
- next.push({ key, title, exit, source, depends_on: dependencies, default_tags, priority });
917
+ next.push({ key, title, exit, expectations, source, depends_on: dependencies, default_tags, priority });
848
918
  const r = await client.call("PUT", `/projects/${project}/milestones`, { milestones: next });
849
919
  const m = r.milestones.find((x) => x.key === key);
850
920
  out.print(`${sub === "add" ? "Added" : "Updated"} milestone ${m.key}: ${m.title} [${m.ready ? "ready" : `waits on ${m.waiting_on.join(", ")}`}]${!m.exit && !m.depends_on.length ? " (container: never chased)" : ""}`, r);
@@ -960,6 +1030,15 @@ export async function askOperator(p, out) {
960
1030
  const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
961
1031
  if (!project)
962
1032
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1033
+ if (p.positionals[1] === "withdraw") {
1034
+ const id = p.positionals[2];
1035
+ const note = str(p.flags, "note")?.trim();
1036
+ if (!id || !note)
1037
+ throw new CliError("usage", 'ask-operator withdraw <key> --note "why this no longer needs an operator answer"');
1038
+ const result = await client.call("POST", `/projects/${project}/asks/${id}/withdraw`, { note });
1039
+ out.print(`Withdrew ask ${id}; it is no longer waiting on the operator.`, result);
1040
+ return;
1041
+ }
963
1042
  const amend = str(p.flags, "amend");
964
1043
  if (amend) {
965
1044
  const text = (p.positionals.slice(1).join(" ") || str(p.flags, "question") || "").trim();
package/dist/git.js CHANGED
@@ -2,6 +2,18 @@ import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync,
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { hostname } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
+ import { CliError } from "./errors.js";
6
+ export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
7
+ function status(cwd, timeoutMs) {
8
+ const r = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
9
+ const errorCode = r.error?.code;
10
+ if (errorCode === "ETIMEDOUT" || (r.error && /timed out/i.test(r.error.message))) {
11
+ throw new CliError("timeout", `git status timed out after ${timeoutMs} ms in worktree ${cwd}`);
12
+ }
13
+ if (r.status !== 0)
14
+ return null;
15
+ return r.stdout.trim();
16
+ }
5
17
  function git(args, cwd) {
6
18
  // Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
7
19
  // the 1 MB default made such a worktree unreadable rather than dirty.
@@ -42,7 +54,7 @@ export function mergeFacts(cwd, worktree) {
42
54
  return { repo, base, merged, ahead: count === null ? null : Number(count) };
43
55
  }
44
56
  /** Every linked worktree of the repository at cwd, with the same facts an agent call reports. */
45
- export function scanWorktrees(cwd = process.cwd()) {
57
+ export function scanWorktrees(cwd = process.cwd(), options = {}) {
46
58
  const list = git(["worktree", "list", "--porcelain"], cwd);
47
59
  if (list === null)
48
60
  return null;
@@ -50,13 +62,15 @@ export function scanWorktrees(cwd = process.cwd()) {
50
62
  if (!paths.length)
51
63
  return null;
52
64
  const repo = paths[0];
65
+ options.onProgress?.(`Scanning repository ${repo}`);
53
66
  const worktrees = paths.map((p) => {
67
+ options.onProgress?.(`Scanning worktree ${p}`);
54
68
  const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
55
69
  const head = git(["rev-parse", "--short", "HEAD"], p);
56
- const status = git(["status", "--porcelain"], p);
70
+ const worktreeStatus = status(p, options.statusTimeoutMs);
57
71
  const f = head ? mergeFacts(p, p) : { base: null, merged: null, ahead: null };
58
72
  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 };
73
+ return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty };
60
74
  });
61
75
  return { repo, worktrees };
62
76
  }
@@ -71,6 +85,25 @@ export function isAncestor(ancestor, ref, cwd = process.cwd()) {
71
85
  const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, stdio: "ignore" });
72
86
  return r.status === 0;
73
87
  }
88
+ /** Confirm an evidence-only unit branch contains no commits missing from its configured target. */
89
+ export function verifyNoCommitsBeyondTarget(branch, target, cwd = process.cwd(), requirePushed = false) {
90
+ if (requirePushed) {
91
+ const ref = `origin/${target}`;
92
+ const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
93
+ if (!fetched)
94
+ return { on: null, ref };
95
+ return { on: isAncestor(branch, ref, cwd), ref };
96
+ }
97
+ const local = isAncestor(branch, target, cwd);
98
+ if (local === true)
99
+ return { on: true, ref: target };
100
+ const ref = `origin/${target}`;
101
+ const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
102
+ if (!fetched)
103
+ return { on: local, ref: target };
104
+ const remote = isAncestor(branch, ref, cwd);
105
+ return remote === true ? { on: true, ref } : { on: remote, ref };
106
+ }
74
107
  /** Branch and short head of the worktree at cwd, or nulls outside a repo. */
75
108
  export function branchAndHead(cwd = process.cwd()) {
76
109
  const a = collectAuto({ model: undefined, machine: "", cwd });
@@ -118,12 +151,16 @@ export function commitAtTime(ref, iso, cwd = process.cwd()) {
118
151
  export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = []) {
119
152
  const exists = git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], cwd) !== null;
120
153
  const sparse = exclude.length > 0;
121
- const args = ["worktree", "add", ...(sparse ? ["--no-checkout"] : []), ...(exists ? [path, branch] : ["-b", branch, path, base])];
154
+ // Always defer checkout until we have explicitly applied this project's policy. Otherwise Git
155
+ // may inherit the source worktree's shared sparse-checkout settings.
156
+ const args = ["worktree", "add", "--no-checkout", ...(exists ? [path, branch] : ["-b", branch, path, base])];
122
157
  const r = spawnSync("git", args, { cwd, encoding: "utf8" });
123
158
  if (r.status !== 0)
124
159
  throw new Error(`git ${args.join(" ")}: ${(r.stderr || r.stdout).trim()}`);
125
160
  if (sparse)
126
161
  applySparse(path, exclude);
162
+ else
163
+ applyFullCheckout(path);
127
164
  }
128
165
  /**
129
166
  * Non-cone sparse checkout patterns that keep everything except `exclude` (repository paths such as
@@ -138,6 +175,14 @@ export function applySparse(path, exclude) {
138
175
  throw new Error(`git ${args.join(" ")} in ${path}: ${(r.stderr || r.stdout).trim()}`);
139
176
  }
140
177
  }
178
+ /** Disables any inherited sparse-checkout configuration and checks out every tracked path. */
179
+ export function applyFullCheckout(path) {
180
+ for (const args of [["sparse-checkout", "disable"], ["reset", "-q", "--hard", "HEAD"]]) {
181
+ const r = spawnSync("git", args, { cwd: path, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
182
+ if (r.status !== 0)
183
+ throw new Error(`git ${args.join(" ")} in ${path}: ${(r.stderr || r.stdout).trim()}`);
184
+ }
185
+ }
141
186
  /** What git says about the worktree at `path`, from `git worktree list` plus a status probe. */
142
187
  export function worktreeState(path, cwd = process.cwd()) {
143
188
  const list = git(["worktree", "list", "--porcelain"], cwd) ?? "";
@@ -203,8 +248,9 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
203
248
  repaired = true;
204
249
  }
205
250
  const files = (git(["ls-files"], cwd) ?? "").split("\n").length;
206
- if (files > 20_000)
207
- log(`creating ${path} (${files.toLocaleString()} tracked files${exclude.length ? `, leaving out ${exclude.join(", ")}` : "; this can take a minute or more"})`);
251
+ log(exclude.length
252
+ ? `creating ${path} with project checkout exclusions: ${exclude.join(", ")}${files > 20_000 ? ` (${files.toLocaleString()} tracked files)` : ""}`
253
+ : `creating ${path} with a full checkout (no project exclusions)${files > 20_000 ? `; ${files.toLocaleString()} tracked files, this can take a minute or more` : ""}`);
208
254
  createWorktree(path, branch, base, cwd, exclude);
209
255
  return { created: true, repaired };
210
256
  }
@@ -239,8 +285,8 @@ export function landedByContent(head, base, cwd) {
239
285
  * machine whose local main is behind does not keep work that already landed, or that its
240
286
  * changes are already there by content (rebased or squashed landings).
241
287
  */
242
- export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }, minAgeMs = 24 * 3600_000) {
243
- const scan = scanWorktrees(cwd);
288
+ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }, minAgeMs = 24 * 3600_000, options = {}) {
289
+ const scan = scanWorktrees(cwd, { ...options, statusTimeoutMs: options.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS });
244
290
  if (!scan)
245
291
  return { prunable: [], kept: [], base: null };
246
292
  const here = realpathOrSelf(cwd);
@@ -439,19 +485,19 @@ export function formatBytes(n) {
439
485
  return n < 0 ? `-${s}` : s;
440
486
  }
441
487
  /** Removes a prune candidate: an empty checkout (re-checked here) by force, anything else only when clean. */
442
- export function removePrunable(c, cwd = process.cwd()) {
488
+ export function removePrunable(c, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
443
489
  if (!c.empty)
444
- return removeWorktreeIfClean(c.path, cwd);
490
+ return removeWorktreeIfClean(c.path, cwd, statusTimeoutMs);
445
491
  if (!existsSync(c.path) || !readdirSync(c.path).every((e) => e === ".git"))
446
492
  return { removed: false, reason: "no longer an empty checkout" };
447
493
  const r = spawnSync("git", ["worktree", "remove", "--force", c.path], { cwd, encoding: "utf8" });
448
494
  return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
449
495
  }
450
- export function removeWorktreeIfClean(path, cwd = process.cwd()) {
451
- const status = git(["status", "--porcelain"], path);
452
- if (status === null)
496
+ export function removeWorktreeIfClean(path, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
497
+ const worktreeStatus = status(path, statusTimeoutMs);
498
+ if (worktreeStatus === null)
453
499
  return { removed: false, reason: "not a worktree" };
454
- if (status.length > 0)
500
+ if (worktreeStatus.length > 0)
455
501
  return { removed: false, reason: "uncommitted changes" };
456
502
  const r = spawnSync("git", ["worktree", "remove", path], { cwd, encoding: "utf8" });
457
503
  return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
package/dist/harnesses.js CHANGED
@@ -226,6 +226,11 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
226
226
  },
227
227
  startedSince() { return dshEvents(readInvocation(invocationOffset)).some((e) => e.type === "status" && e.phase === "turn_start"); },
228
228
  turnError: () => dshResultError(readInvocation(invocationOffset)),
229
+ turnOutput: () => readInvocation(invocationOffset).slice(-800),
230
+ turnTokens: () => {
231
+ const events = dshEvents(readInvocation(invocationOffset));
232
+ return events.reduce((sum, event) => sum + (event.usage?.inputTokens ?? 0) + (event.usage?.cacheReadTokens ?? 0) + (event.usage?.cacheWriteTokens ?? 0) + (event.usage?.outputTokens ?? 0), 0);
233
+ },
229
234
  limitUntil: () => null,
230
235
  isLimit: () => false,
231
236
  };
@@ -247,6 +252,24 @@ function codexProbe(thread) {
247
252
  },
248
253
  startedSince(ms) { const ph = read(); return !!ph?.startedAt && Date.parse(ph.startedAt) >= ms - 5_000; },
249
254
  turnError() { return read()?.lastError ?? null; },
255
+ turnOutput() {
256
+ const path = codexRollout(thread);
257
+ if (!path)
258
+ return "";
259
+ const messages = readFileSync(path, "utf8").split("\n").flatMap((line) => {
260
+ try {
261
+ const event = JSON.parse(line);
262
+ if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
263
+ return [];
264
+ const content = event.payload.message.content;
265
+ return typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
266
+ }
267
+ catch {
268
+ return [];
269
+ }
270
+ });
271
+ return messages.join("\n").slice(-800);
272
+ },
250
273
  limitUntil: usageLimitUntil,
251
274
  isLimit: (e) => !!e && /usage limit/i.test(e),
252
275
  };
@@ -378,6 +401,29 @@ function claudeProbe(session, ref) {
378
401
  return !!p && Date.parse(p) >= ms - 5_000;
379
402
  },
380
403
  turnError: () => lastResult()?.error ?? null,
404
+ turnOutput: () => {
405
+ if (!existsSync(resultFile))
406
+ return "";
407
+ try {
408
+ const result = JSON.parse(readFileSync(resultFile, "utf8").trim().split("\n").filter((line) => line.startsWith("{")).pop() ?? "");
409
+ return typeof result.result === "string" ? result.result.slice(-800) : "";
410
+ }
411
+ catch {
412
+ return readFileSync(resultFile, "utf8").slice(-800);
413
+ }
414
+ },
415
+ turnTokens: () => {
416
+ if (!existsSync(resultFile))
417
+ return null;
418
+ try {
419
+ const result = JSON.parse(readFileSync(resultFile, "utf8").trim().split("\n").filter((line) => line.startsWith("{")).pop() ?? "");
420
+ const u = result.usage;
421
+ return u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : null;
422
+ }
423
+ catch {
424
+ return null;
425
+ }
426
+ },
381
427
  limitUntil: (e) => claudeLimitUntil(e),
382
428
  isLimit: claudeIsLimit,
383
429
  };