@botbuddy/cli 1.6.3 → 1.7.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botbuddy/cli",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ // BOT-1400: plan a lossless multi-version reconciliation for the CLI publish
3
+ // workflow.
4
+ //
5
+ // The publish workflow serializes all runs through one static concurrency
6
+ // group so its dist-tag backward-move guard is correct (only one run publishes
7
+ // at a time). GitHub keeps at most one running + one pending run per group, so
8
+ // if 3+ CLI version bumps land inside a single ~2-minute publish window the
9
+ // *middle* version's queued run is dropped and that version never publishes.
10
+ //
11
+ // This module closes that gap without weakening the serialization: the single
12
+ // surviving run (always the newest push, which becomes the pending run) walks
13
+ // main's recent first-parent history, collects every distinct CLI version
14
+ // between the most recently *published* version and HEAD, and orders them
15
+ // ascending. The workflow then publishes each intermediate from its own
16
+ // historical tree — in ascending order, so every stable publish moves `latest`
17
+ // forward and every prerelease moves `next` forward — before its existing
18
+ // single-version logic handles HEAD. No version is lost; no dist-tag moves
19
+ // backward under any interleaving.
20
+ //
21
+ // The git walk is bounded (recent commits touching cli/package.json) and stops
22
+ // at the first already-published version, so an ancient, deliberately
23
+ // superseded version is never resurrected. Per-version publish-vs-skip against
24
+ // the live dist-tag is still decided in the workflow (it reflects live registry
25
+ // state as the loop advances); this module only orders the candidates.
26
+
27
+ import { execFileSync } from "node:child_process";
28
+ import { readFileSync } from "node:fs";
29
+
30
+ import { compareSemver, isPrerelease } from "./publish-equal.mjs";
31
+
32
+ // How far back to walk commits that touched the `cli/` tree. The loss window is
33
+ // a handful of rapid bumps (each a few commits); 60 is comfortably generous
34
+ // while bounding the git work and guaranteeing termination. planReconciliation
35
+ // stops at the first already-published version, so this only bounds pathological
36
+ // cases — and even an over-broad tail is caught by the workflow's per-version
37
+ // already-published check before anything is republished.
38
+ const DEFAULT_LIMIT = 60;
39
+
40
+ // Reduce a newest→oldest history of { version, commit } to the ascending list
41
+ // of distinct versions that must be reconciled: everything strictly newer than
42
+ // the most recently published version in that history, excluding anything
43
+ // already on npm. Each version keeps its NEWEST commit so the published tarball
44
+ // carries every change shipped under that version.
45
+ export function planReconciliation(history, published) {
46
+ const publishedSet = new Set((published ?? []).map(String));
47
+ const tail = [];
48
+ const seen = new Set();
49
+ for (const entry of history) {
50
+ const version = String(entry.version);
51
+ if (seen.has(version)) continue; // dedupe; the newest commit was seen first
52
+ seen.add(version);
53
+ // Stop at the first already-published version: everything older than it was
54
+ // reconciled when it (or a later version) published. This is what prevents
55
+ // resurrecting an old, superseded version.
56
+ if (publishedSet.has(version)) break;
57
+ tail.push({ version, commit: entry.commit });
58
+ }
59
+ return tail
60
+ .sort((a, b) => compareSemver(a.version, b.version))
61
+ .map((e) => ({ version: e.version, commit: e.commit, prerelease: isPrerelease(e.version) }));
62
+ }
63
+
64
+ // Accepts the raw `npm view <pkg> versions --json` payload (an array, or a bare
65
+ // string when only one version exists) and returns the reconciliation plan.
66
+ export function planFromHistory(history, publishedRaw) {
67
+ const published = Array.isArray(publishedRaw) ? publishedRaw : [publishedRaw];
68
+ return planReconciliation(history, published);
69
+ }
70
+
71
+ function git(args, cwd) {
72
+ // Strip the location-override git env vars so `cwd` always selects the repo.
73
+ // Git sets GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE while running a hook; if we
74
+ // inherited them, a git command here would silently target the hook's repo
75
+ // instead of `cwd` (e.g. a reconcile invoked from a pre-push hook, or a test
76
+ // exercising a scratch repo under one). Everything else is inherited.
77
+ const env = { ...process.env };
78
+ delete env.GIT_DIR;
79
+ delete env.GIT_WORK_TREE;
80
+ delete env.GIT_INDEX_FILE;
81
+ return execFileSync("git", args, { cwd, env, encoding: "utf8" });
82
+ }
83
+
84
+ // Walk main's first-parent history from `headSha` over commits that touched the
85
+ // publishable CLI tree (`cli/`), reading the package version at each, newest →
86
+ // oldest. Walking the whole `cli/` tree — not just `cli/package.json` — is what
87
+ // lets a CLI-only fix committed AFTER a version bump (same version, no
88
+ // package.json change) be the newest commit for that version, so the archived
89
+ // tree carries that fix rather than the older bump commit's tree. First-parent
90
+ // keeps us on the mainline (side-branch commits from a merge never inject a
91
+ // version). Returns [{ version, commit }].
92
+ export function buildHistory(headSha, { limit = DEFAULT_LIMIT, cwd = process.cwd() } = {}) {
93
+ const raw = git(
94
+ ["log", "--first-parent", "-n", String(limit), "--format=%H", headSha, "--", "cli"],
95
+ cwd,
96
+ );
97
+ const commits = raw.split("\n").map((l) => l.trim()).filter(Boolean);
98
+ const history = [];
99
+ for (const commit of commits) {
100
+ let version;
101
+ try {
102
+ const pkg = JSON.parse(git(["show", `${commit}:cli/package.json`], cwd));
103
+ version = pkg?.version;
104
+ } catch {
105
+ // cli/package.json did not exist / was unparseable at this commit — we
106
+ // have walked past the package's introduction; stop.
107
+ break;
108
+ }
109
+ if (typeof version !== "string" || version.length === 0) break;
110
+ history.push({ version, commit });
111
+ }
112
+ return history;
113
+ }
114
+
115
+ if (import.meta.url === `file://${process.argv[1]}`) {
116
+ const args = process.argv.slice(2);
117
+ // `--plan <headSha>`: read the registry versions JSON on stdin, print the
118
+ // ascending reconciliation plan as `<version>\t<commit>\t<stable|prerelease>`
119
+ // (one row per version to publish, newest last). Prints nothing when there is
120
+ // nothing to reconcile.
121
+ if (args[0] === "--plan") {
122
+ const headSha = args[1];
123
+ if (!headSha) {
124
+ console.error("usage: reconcile.mjs --plan <headSha> (registry versions JSON on stdin)");
125
+ process.exit(2);
126
+ }
127
+ try {
128
+ const publishedRaw = JSON.parse(readFileSync(0, "utf8"));
129
+ const history = buildHistory(headSha, { cwd: process.cwd() });
130
+ for (const entry of planFromHistory(history, publishedRaw)) {
131
+ process.stdout.write(`${entry.version}\t${entry.commit}\t${entry.prerelease ? "prerelease" : "stable"}\n`);
132
+ }
133
+ process.exit(0);
134
+ } catch (err) {
135
+ console.error(String(err?.message ?? err));
136
+ process.exit(2);
137
+ }
138
+ }
139
+ console.error("usage: reconcile.mjs --plan <headSha>");
140
+ process.exit(2);
141
+ }
@@ -79,6 +79,10 @@ export function withPrincipalReceipt(receipt, profile, registration = {}) {
79
79
  profile: profile.name,
80
80
  tenant_id: registration.sessionTenant ?? profile.tenant,
81
81
  agent_id: registration.agentId ?? null,
82
+ // BOT-1467: the arming session's agent, when the relay attributed the wait
83
+ // to it instead of the profile agent (null for an ordinary profile wait).
84
+ session_id: registration.sessionId ?? null,
85
+ session_agent_id: registration.sessionAgentId ?? null,
82
86
  },
83
87
  };
84
88
  }
package/src/wait.mjs CHANGED
@@ -93,6 +93,7 @@ OPTIONS
93
93
  --heartbeat keep this agent session alive while waiting (so it is not reaped)
94
94
  --url <base> relay base URL (default $BOTBUDDY_RELAY_URL or https://api.bot-buddy.ai/functions/v1)
95
95
  --profile <name> tenant-bound machine profile (normally read from .botbuddy-agent.json)
96
+ --session-id <uuid> attribute this wait to the arming session (the work-graph session id from register_agent); default $BOTBUDDY_SESSION_ID
96
97
  --token <key> explicit agent key override; otherwise the profile-specific env is used
97
98
  --help show this help
98
99
 
@@ -133,6 +134,9 @@ function parseArgv(argv) {
133
134
  url: process.env.BOTBUDDY_RELAY_URL || "https://api.bot-buddy.ai/functions/v1",
134
135
  token: null,
135
136
  profile: null,
137
+ // BOT-1467: attribute this wait to the arming session's agent (the id from
138
+ // register_agent) instead of the tenant-bound profile agent. Env fallback.
139
+ sessionId: process.env.BOTBUDDY_SESSION_ID || null,
136
140
  help: false,
137
141
  };
138
142
  for (let i = 0; i < argv.length; i++) {
@@ -155,6 +159,7 @@ function parseArgv(argv) {
155
159
  else if (a === "--url") opts.url = optionValue();
156
160
  else if (a === "--token") opts.token = optionValue();
157
161
  else if (a === "--profile") opts.profile = optionValue();
162
+ else if (a === "--session-id") opts.sessionId = optionValue();
158
163
  else if (a.startsWith("--")) opts.unknown = a;
159
164
  else opts.conditions.push(a);
160
165
  }
@@ -176,6 +181,9 @@ async function registerWait(opts, conditions, deadlineIso) {
176
181
  action: "register",
177
182
  profile: opts.agentProfile.name,
178
183
  expected_tenant: opts.agentProfile.tenant,
184
+ // BOT-1467: name the arming work-graph session so the relay resolves and attributes
185
+ // the wait to its agent (validated same-owner) instead of the profile agent.
186
+ ...(opts.sessionId ? { session_id: opts.sessionId } : {}),
179
187
  client_version: VERSION,
180
188
  wait_protocol_version: WAIT_PROTOCOL_VERSION,
181
189
  conditions,
@@ -224,6 +232,11 @@ async function registerWait(opts, conditions, deadlineIso) {
224
232
  // can't bind to one workspace (ci / pr-review / bare tenant-primary event). A hard
225
233
  // stop — arming it untracked would only ever park to timeout.
226
234
  "tenant_ambiguous",
235
+ // BOT-1467: a caller-actionable session-attribution rejection — a malformed
236
+ // --session-id, or one passed without a profile. Arming it untracked would
237
+ // only ever park to timeout, so it's a hard stop, not the live-only fallback.
238
+ "invalid_session_agent",
239
+ "session_agent_requires_profile",
227
240
  ]);
228
241
  if (INVALID_CONDITION_CODES.has(body.error)) {
229
242
  const err = new Error(body.detail || body.error);
@@ -293,6 +306,10 @@ async function registerWait(opts, conditions, deadlineIso) {
293
306
  // new relay (the deploy-skew case, acceptable because waits are short-lived).
294
307
  sessionTenant: body.session_tenant ?? null,
295
308
  agentId: body.agent_id ?? null,
309
+ // BOT-1467: the session agent the relay attributed the wait to, if any (it
310
+ // echoes session_agent_id only when it overrode the profile agent).
311
+ sessionId: body.session_id ?? null,
312
+ sessionAgentId: body.session_agent_id ?? null,
296
313
  };
297
314
  }
298
315
 
@@ -565,6 +582,9 @@ export async function runWait(argv) {
565
582
  // pre-BOT-1259 behaviour for a wait the server never scoped.
566
583
  let sessionTenant;
567
584
  let registeredAgentId = null;
585
+ // BOT-1467: the session agent the relay attributed the wait to (when overridden).
586
+ let registeredSessionAgentId = null;
587
+ let registeredSessionId = null;
568
588
  if (needsRelay) {
569
589
  try {
570
590
  const reg = await registerWait(opts, conditions, new Date(deadlineMs).toISOString());
@@ -572,6 +592,8 @@ export async function runWait(argv) {
572
592
  opts.waitSessionId = waitSessionId;
573
593
  sessionTenant = reg.sessionTenant;
574
594
  registeredAgentId = reg.agentId;
595
+ registeredSessionAgentId = reg.sessionAgentId;
596
+ registeredSessionId = reg.sessionId;
575
597
  // BOT-1184: adopt the server's canonical host for each lock condition so the
576
598
  // local matcher builds the same subject_key the availability/claim-grant
577
599
  // signals carry (armed under an alias like 'jono-mac', the signal uses the
@@ -709,6 +731,8 @@ export async function runWait(argv) {
709
731
  withClientIdentity(withPrincipalReceipt(receipt, opts.agentProfile, {
710
732
  sessionTenant,
711
733
  agentId: registeredAgentId,
734
+ sessionAgentId: registeredSessionAgentId,
735
+ sessionId: registeredSessionId,
712
736
  })),
713
737
  opts.receiptMaxBytes,
714
738
  );