@botiverse/stamp-cli 0.3.1 → 0.3.3

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.
@@ -0,0 +1,429 @@
1
+ import { AgentError } from "./errors.mjs";
2
+
3
+ const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
4
+ const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
5
+ const reviewStates = new Set([
6
+ "HAS_ACTIVE_REVIEW",
7
+ "HAS_UNADDRESSED_CHANGES_REQUESTED",
8
+ "IS_FULLY_APPROVED",
9
+ "ONE_OR_MORE_APPROVALS",
10
+ ]);
11
+ const terminalPassConclusions = new Set(["success", "neutral", "skipped"]);
12
+ const pendingCheckStates = new Set(["", "expected", "in_progress", "pending", "queued", "requested", "waiting"]);
13
+
14
+ function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
15
+ const matches = [];
16
+ for (let i = 0; i < args.length; i++) {
17
+ if (args[i] === `--${long}` || (short && args[i] === `-${short}`)) {
18
+ matches.push({ index: i, inline: false });
19
+ } else if (args[i].startsWith(`--${long}=`)) {
20
+ matches.push({ index: i, inline: true });
21
+ }
22
+ }
23
+ if (matches.length === 0) return undefined;
24
+ if (matches.length > 1) throw new AgentError(usageCode);
25
+ const { index, inline } = matches[0];
26
+ if (inline) {
27
+ const value = args[index].slice(long.length + 3);
28
+ if (value === "") throw new AgentError(usageCode);
29
+ args.splice(index, 1);
30
+ return value;
31
+ }
32
+ const value = args[index + 1];
33
+ if (value === undefined || value.startsWith("-")) throw new AgentError(usageCode);
34
+ args.splice(index, 2);
35
+ return value;
36
+ }
37
+
38
+ function takeBooleanFlag(args, long) {
39
+ const i = args.indexOf(`--${long}`);
40
+ if (i === -1) return false;
41
+ args.splice(i, 1);
42
+ return true;
43
+ }
44
+
45
+ function strictPositiveInt(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
46
+ if (value === undefined) return fallback;
47
+ if (!/^[1-9][0-9]*$/.test(value)) return null;
48
+ const parsed = Number(value);
49
+ return Number.isSafeInteger(parsed) && parsed <= maximum ? parsed : null;
50
+ }
51
+
52
+ function repositoryParts(value) {
53
+ const match = String(value ?? "").trim().match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
54
+ if (!match || match[1] === "." || match[1] === ".." || match[2] === "." || match[2] === "..") return null;
55
+ return { owner: match[1], repo: match[2] };
56
+ }
57
+
58
+ function sameRepository(left, right) {
59
+ return String(left).toLowerCase() === String(right).toLowerCase();
60
+ }
61
+
62
+ function targetFromURL(value) {
63
+ let parsed;
64
+ try { parsed = new URL(value); } catch { return null; }
65
+ if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== "github.com" || parsed.port || parsed.username || parsed.password) {
66
+ return null;
67
+ }
68
+ const parts = parsed.pathname.split("/").filter(Boolean);
69
+ const marker = parts[2];
70
+ if (parts.length < 4 || (marker !== "pull" && marker !== "pulls")) return null;
71
+ const repository = repositoryParts(`${parts[0]}/${parts[1]}`);
72
+ const number = strictPositiveInt(parts[3]);
73
+ return repository && number ? { ...repository, number } : null;
74
+ }
75
+
76
+ /**
77
+ * Parse `stamp pr list` args (task #397 slice 1 + #345 CLI lane).
78
+ *
79
+ * Optional, opt-in pagination — the wire adds `?limit=` and an OPAQUE cursor to
80
+ * the SAME `/v1/pr-inbox` path (never a new path):
81
+ * --limit <n> 1..200 page size
82
+ * --cursor <s> an opaque server token, passed through VERBATIM (never parsed,
83
+ * never cached, never reused across identities: it is bound to
84
+ * (tenant, server, viewer scope, filter) server-side)
85
+ *
86
+ * With NEITHER flag the path is byte-identical to before (full set, truncated
87
+ * false, nextCursor null) — the server guarantees that back-compat.
88
+ */
89
+ export const PR_LIST_MAX_LIMIT = 200;
90
+
91
+ export function parsePRListArgs(input) {
92
+ const args = [...input];
93
+ const limitRaw = takeNamedFlag(args, "limit", undefined, "usagePrList");
94
+ const cursor = takeNamedFlag(args, "cursor", undefined, "usagePrList");
95
+ const sections = takeBooleanFlag(args, "sections");
96
+ if (args.length !== 0) throw new AgentError("usagePrList");
97
+
98
+ const params = new URLSearchParams();
99
+ if (limitRaw !== undefined) {
100
+ const limit = strictPositiveInt(limitRaw, null, PR_LIST_MAX_LIMIT);
101
+ if (limit === null) throw new AgentError("usagePrList");
102
+ params.set("limit", String(limit));
103
+ }
104
+ if (cursor !== undefined) {
105
+ // A cursor is only meaningful with a page size; the server 400s a cursor
106
+ // without a limit, so refuse it locally with the usage error instead.
107
+ if (!params.has("limit")) throw new AgentError("usagePrList");
108
+ params.set("cursor", cursor);
109
+ }
110
+ const query = params.toString();
111
+ const path = query === "" ? "/v1/pr-inbox" : `/v1/pr-inbox?${query}`;
112
+ return { path, sections };
113
+ }
114
+
115
+ export function parsePRTargetArgs(input, usageCode = "usagePrRead") {
116
+ const args = [...input];
117
+ const repoFlag = takeNamedFlag(args, "repo", "R", usageCode);
118
+ const target = args.shift();
119
+ if (!target || args.length !== 0) throw new AgentError(usageCode);
120
+ const fromURL = targetFromURL(target);
121
+ if (fromURL) {
122
+ if (repoFlag && (!repositoryParts(repoFlag) || !sameRepository(`${fromURL.owner}/${fromURL.repo}`, repoFlag))) {
123
+ throw new AgentError(usageCode);
124
+ }
125
+ return fromURL;
126
+ }
127
+ const repository = repositoryParts(repoFlag);
128
+ const number = strictPositiveInt(target);
129
+ if (!repository || !number) throw new AgentError(usageCode);
130
+ return { ...repository, number };
131
+ }
132
+
133
+ export function parsePRDiffArgs(input) {
134
+ const args = [...input];
135
+ const nameOnly = takeBooleanFlag(args, "name-only");
136
+ return { ...parsePRTargetArgs(args, "usagePrDiff"), nameOnly };
137
+ }
138
+
139
+ export function prDetailPath(target) {
140
+ return `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}`;
141
+ }
142
+
143
+ export function prDiffPath(target) {
144
+ return `${prDetailPath(target)}/diff`;
145
+ }
146
+
147
+ function requireObject(value) {
148
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new AgentError("prReadInvalidResponse");
149
+ return value;
150
+ }
151
+
152
+ function requireString(value) {
153
+ if (typeof value !== "string") throw new AgentError("prReadInvalidResponse");
154
+ return value;
155
+ }
156
+
157
+ function requireNumber(value) {
158
+ if (!Number.isInteger(value) || value <= 0) throw new AgentError("prReadInvalidResponse");
159
+ return value;
160
+ }
161
+
162
+ function requireSHA(value) {
163
+ const sha = requireString(value);
164
+ if (!/^[0-9a-f]{40}$/.test(sha)) throw new AgentError("prReadInvalidResponse");
165
+ return sha;
166
+ }
167
+
168
+ export function safeInline(value) {
169
+ return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]+/g, " ").replace(/\s+/g, " ").trim();
170
+ }
171
+
172
+ function safeMultiline(value) {
173
+ return String(value)
174
+ .replace(/\r\n?/g, "\n")
175
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
176
+ }
177
+
178
+ export function validatePRListResponse(value, paged = false) {
179
+ const response = requireObject(value);
180
+ if (!Array.isArray(response.items)) throw new AgentError("prReadInvalidResponse");
181
+ for (const raw of response.items) {
182
+ const item = requireObject(raw);
183
+ if (!repositoryParts(requireString(item.repository))) throw new AgentError("prReadInvalidResponse");
184
+ requireNumber(item.number);
185
+ requireString(item.title);
186
+ requireString(item.url);
187
+ requireString(item.raftAgentId);
188
+ requireSHA(item.headSha);
189
+ if (!Array.isArray(item.reviewStates) || item.reviewStates.some((state) => !reviewStates.has(state))) {
190
+ throw new AgentError("prReadInvalidResponse");
191
+ }
192
+ const status = requireString(item.status);
193
+ const ciStatus = requireString(item.ciStatus);
194
+ if (status === "UNKNOWN") {
195
+ if (ciStatus !== "none" || item.reviewStates.length !== 0) throw new AgentError("prReadInvalidResponse");
196
+ } else {
197
+ if (!consolidatedStatuses.has(status) || !ciStatuses.has(ciStatus)) throw new AgentError("prReadInvalidResponse");
198
+ }
199
+ requireString(item.updatedAt);
200
+ }
201
+ // Pagination (task #397 slice 1): nextCursor is a string|null, truncated a
202
+ // boolean. Both are surfaced to the caller; a present cursor means "there is
203
+ // more", never an error. When the caller did not request a page (no
204
+ // limit/cursor), the server still returns nextCursor=null / truncated=false
205
+ // — assert that back-compat contract.
206
+ const nextCursor = response.nextCursor;
207
+ if (nextCursor !== null && typeof nextCursor !== "string") throw new AgentError("prReadInvalidResponse");
208
+ if (typeof response.truncated !== "boolean") throw new AgentError("prReadInvalidResponse");
209
+ // `truncated` and `nextCursor` must AGREE: a cursor is exactly the "there is
210
+ // more" signal, so a page is truncated iff it carries a cursor. Accepting
211
+ // (truncated=false, nextCursor="x") would print "continue" while the protocol
212
+ // says the page is complete; (truncated=true, nextCursor=null) would report
213
+ // success on a page the CLI cannot continue.
214
+ if (paged) {
215
+ if (response.truncated !== (nextCursor !== null)) throw new AgentError("prReadInvalidResponse");
216
+ return response;
217
+ }
218
+ // Unpaged (back-compat): strictly the pre-pagination contract.
219
+ if (nextCursor !== null || response.truncated !== false) {
220
+ throw new AgentError("prReadInvalidResponse");
221
+ }
222
+ return response;
223
+ }
224
+
225
+ export function validatePRDetail(value, expected) {
226
+ const detail = requireObject(value);
227
+ requireString(detail.repository);
228
+ requireNumber(detail.number);
229
+ requireString(detail.title);
230
+ requireString(detail.url);
231
+ requireString(detail.author);
232
+ requireSHA(detail.headSha);
233
+ requireSHA(detail.baseSha);
234
+ requireSHA(detail.mergeBaseSha);
235
+ requireString(detail.headRef);
236
+ requireString(detail.baseRef);
237
+ if (!ciStatuses.has(requireString(detail.ciStatus))) throw new AgentError("prReadInvalidResponse");
238
+ requireString(detail.reviewStatus);
239
+ requireString(detail.reviewFreshness);
240
+ if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
241
+ requireString(detail.updatedAt);
242
+ requireString(detail.body);
243
+ if (!Array.isArray(detail.checks)) throw new AgentError("prReadInvalidResponse");
244
+ for (const raw of detail.checks) {
245
+ const check = requireObject(raw);
246
+ requireString(check.name);
247
+ requireString(check.status);
248
+ requireString(check.conclusion);
249
+ requireString(check.url);
250
+ }
251
+ for (const links of [detail.dependencies, detail.dependents]) {
252
+ if (!Array.isArray(links)) throw new AgentError("prReadInvalidResponse");
253
+ for (const raw of links) {
254
+ const link = requireObject(raw);
255
+ requireNumber(link.number);
256
+ requireString(link.title);
257
+ requireString(link.url);
258
+ requireString(link.reason);
259
+ }
260
+ }
261
+ if (expected && (!sameRepository(detail.repository, `${expected.owner}/${expected.repo}`) || detail.number !== expected.number)) {
262
+ throw new AgentError("prReadCoordinateMismatch");
263
+ }
264
+ return detail;
265
+ }
266
+
267
+ export function validatePRDiff(value, expected) {
268
+ const response = requireObject(value);
269
+ requireString(response.repository);
270
+ requireNumber(response.number);
271
+ requireSHA(response.baseSha);
272
+ requireSHA(response.headSha);
273
+ if (expected && (!sameRepository(response.repository, `${expected.owner}/${expected.repo}`) || response.number !== expected.number)) {
274
+ throw new AgentError("prReadCoordinateMismatch");
275
+ }
276
+ if (!Array.isArray(response.files)) throw new AgentError("prReadInvalidResponse");
277
+ for (const raw of response.files) {
278
+ const file = requireObject(raw);
279
+ requireString(file.path);
280
+ requireString(file.status);
281
+ if (!Number.isInteger(file.additions) || file.additions < 0 || !Number.isInteger(file.deletions) || file.deletions < 0) {
282
+ throw new AgentError("prReadInvalidResponse");
283
+ }
284
+ if (file.patch !== null && file.patch !== undefined && typeof file.patch !== "string") {
285
+ throw new AgentError("prReadInvalidResponse");
286
+ }
287
+ }
288
+ return response;
289
+ }
290
+
291
+ /**
292
+ * Author-oriented Graphite-style section for an agent-view PR row (task #397
293
+ * slice 2), derived purely from the wire fields the server already returns
294
+ * (`status` + `reviewStates`). First-match order matches the server's
295
+ * `DefaultInboxSections` intent:
296
+ *
297
+ * drafts <- status=DRAFT
298
+ * changes <- HAS_UNADDRESSED_CHANGES_REQUESTED (before approved)
299
+ * approved <- IS_FULLY_APPROVED (authoritative reviewDecision)
300
+ * approved(more) <- ONE_OR_MORE_APPROVALS and NOT IS_FULLY_APPROVED
301
+ * waiting <- status=OPEN with none of the above
302
+ * history <- MERGING / MERGED / CLOSED
303
+ * unavailable <- status=UNKNOWN (its own bucket, never folded into waiting)
304
+ *
305
+ * Kept pure and exported so the mapping is unit-testable.
306
+ */
307
+ export const PR_SECTIONS = Object.freeze({
308
+ drafts: "drafts",
309
+ changes: "changes",
310
+ approved: "approved",
311
+ approvals: "approvals",
312
+ waiting: "waiting",
313
+ history: "history",
314
+ unavailable: "unavailable",
315
+ });
316
+
317
+ export function prSection(item) {
318
+ const status = item.status;
319
+ const states = Array.isArray(item.reviewStates) ? item.reviewStates : [];
320
+ const has = (s) => states.includes(s);
321
+
322
+ if (status === "UNKNOWN") return PR_SECTIONS.unavailable;
323
+ if (status === "DRAFT") return PR_SECTIONS.drafts;
324
+ if (status === "MERGING" || status === "MERGED" || status === "CLOSED") return PR_SECTIONS.history;
325
+ // From here status === "OPEN".
326
+ if (has("HAS_UNADDRESSED_CHANGES_REQUESTED")) return PR_SECTIONS.changes;
327
+ if (has("IS_FULLY_APPROVED")) return PR_SECTIONS.approved;
328
+ if (has("ONE_OR_MORE_APPROVALS")) return PR_SECTIONS.approvals;
329
+ return PR_SECTIONS.waiting;
330
+ }
331
+
332
+ export function formatPRList(response, labels = {}) {
333
+ return response.items.map((item) => [
334
+ safeInline(item.repository),
335
+ `#${item.number}`,
336
+ safeInline(item.status === "UNKNOWN" ? (labels.statusUnavailable ?? item.status) : item.status),
337
+ `${labels.ci ?? "CI"}:${safeInline(item.ciStatus)}`,
338
+ `${labels.agent ?? "Agent"}:${safeInline(item.raftAgentId)}`,
339
+ safeInline(item.title),
340
+ safeInline(item.updatedAt),
341
+ ].join("\t"));
342
+ }
343
+
344
+ const SECTION_ORDER = [
345
+ PR_SECTIONS.drafts,
346
+ PR_SECTIONS.changes,
347
+ PR_SECTIONS.approved,
348
+ PR_SECTIONS.approvals,
349
+ PR_SECTIONS.waiting,
350
+ PR_SECTIONS.history,
351
+ PR_SECTIONS.unavailable,
352
+ ];
353
+
354
+ /**
355
+ * Group the list rows by derived section (task #397 slice 2), keeping the flat
356
+ * per-row format intact and emitting each section as a labelled block in the
357
+ * fixed first-match order. Empty sections are omitted.
358
+ */
359
+ export function formatPRListSections(response, labels = {}) {
360
+ const buckets = new Map(SECTION_ORDER.map((s) => [s, []]));
361
+ for (const item of response.items) buckets.get(prSection(item)).push(item);
362
+ const lines = [];
363
+ for (const section of SECTION_ORDER) {
364
+ const items = buckets.get(section);
365
+ if (items.length === 0) continue;
366
+ lines.push(`${labels.section ?? ""}${sectionLabel(section, labels)}`.trim());
367
+ for (const line of formatPRList({ items }, labels)) lines.push(` ${line}`);
368
+ }
369
+ return lines;
370
+ }
371
+
372
+ function sectionLabel(section, labels) {
373
+ const key = `prSection_${section}`;
374
+ return labels[key] ?? section;
375
+ }
376
+
377
+ export function formatPRDetail(detail, labels) {
378
+ const lines = [
379
+ `${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
380
+ `${labels.head}: ${safeInline(detail.headSha)}`,
381
+ `${labels.checks}: ${safeInline(detail.ciStatus)}`,
382
+ `${labels.review}: ${safeInline(detail.reviewStatus)}`,
383
+ safeInline(detail.url),
384
+ ];
385
+ if (typeof detail.body === "string" && detail.body !== "") lines.push("", safeMultiline(detail.body));
386
+ return lines;
387
+ }
388
+
389
+ export function formatPRDiff(response, nameOnly, unavailableLabel) {
390
+ if (nameOnly) return response.files.map((file) => safeInline(file.path));
391
+ return response.files.map((file) => {
392
+ const summary = `${safeInline(file.path)}\t${safeInline(file.status)}\t+${file.additions}\t-${file.deletions}`;
393
+ if (typeof file.patch === "string" && file.patch !== "") return `${summary}\n${safeMultiline(file.patch)}`;
394
+ return `${summary}\t${unavailableLabel}`;
395
+ });
396
+ }
397
+
398
+ export function formatPRChecks(detail) {
399
+ return detail.checks.map((check) => [check.name, check.status, check.conclusion || "-", check.url].map(safeInline).join("\t"));
400
+ }
401
+
402
+ export function prChecksExitCode(detail) {
403
+ // Match `gh pr checks`: an empty check set is not evidence that CI passed.
404
+ // Keep it non-zero so automation cannot treat an unconfigured or unavailable
405
+ // check suite as a green pull request.
406
+ if (detail.checks.length === 0) return 1;
407
+ let pending = false;
408
+ for (const check of detail.checks) {
409
+ const status = check.status.toLowerCase();
410
+ const conclusion = check.conclusion.toLowerCase();
411
+ if (pendingCheckStates.has(status)) {
412
+ pending = true;
413
+ } else if (status === "completed") {
414
+ if (conclusion === "") pending = true;
415
+ else if (!terminalPassConclusions.has(conclusion)) return 1;
416
+ } else if (status === "success") {
417
+ // The server projects legacy commit statuses as the same state in both
418
+ // fields. An inconsistent payload must not let `status=success` mask a
419
+ // failing conclusion.
420
+ if (conclusion !== "success") return 1;
421
+ } else {
422
+ // Legacy commit statuses use status=success|failure|error instead of a
423
+ // check-run's completed + conclusion pair. Unknown terminal values fail
424
+ // closed rather than silently reporting a green PR.
425
+ return 1;
426
+ }
427
+ }
428
+ return pending ? 8 : 0;
429
+ }
@@ -0,0 +1,60 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ export function parseRepoCloneArgs(args) {
4
+ const dash = args.indexOf("--");
5
+ const gitFlags = dash === -1 ? [] : args.slice(dash + 1);
6
+ const rest = dash === -1 ? args : args.slice(0, dash);
7
+ const repository = rest[0];
8
+ const directory = rest[1];
9
+ if (!repository || rest.length > 2) {
10
+ return null;
11
+ }
12
+ return { repository, directory, gitFlags };
13
+ }
14
+
15
+ export function parseRepository(input, defaultOwner) {
16
+ const raw = String(input ?? "").trim();
17
+ if (!raw) return null;
18
+ let value = raw.replace(/\.git$/i, "");
19
+ const github = value.match(
20
+ /^(?:https?:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+)\/?$/i,
21
+ );
22
+ if (github) {
23
+ return { owner: github[1], name: github[2] };
24
+ }
25
+ if (!value.includes("://") && !value.includes("@") && value.includes("/")) {
26
+ const parts = value.split("/").filter(Boolean);
27
+ if (parts.length === 2) {
28
+ return { owner: parts[0], name: parts[1] };
29
+ }
30
+ }
31
+ if (!value.includes("/") && !value.includes(":") && defaultOwner) {
32
+ return { owner: defaultOwner, name: value };
33
+ }
34
+ return null;
35
+ }
36
+
37
+ export function gatewayCloneURL(host, port, owner, name) {
38
+ const hostname = String(host ?? "").trim();
39
+ const parsedPort = Number(port);
40
+ const sshPort = Number.isInteger(parsedPort) && parsedPort > 0 ? parsedPort : 22;
41
+ const authority = hostname.includes(":") ? `[${hostname}]:${sshPort}` : `${hostname}:${sshPort}`;
42
+ return `ssh://git@${authority}/${owner}/${name}.git`;
43
+ }
44
+
45
+ export function runGitClone({ url, directory, gitFlags, env, spawnImpl = spawn }) {
46
+ const args = ["clone", ...(gitFlags ?? []), url];
47
+ if (directory) args.push(directory);
48
+ return new Promise((resolve, reject) => {
49
+ const child = spawnImpl("git", args, {
50
+ env: env ?? process.env,
51
+ stdio: ["ignore", "pipe", "pipe"],
52
+ });
53
+ let stdout = "";
54
+ let stderr = "";
55
+ child.stdout?.on("data", (b) => { stdout += b; });
56
+ child.stderr?.on("data", (b) => { stderr += b; });
57
+ child.on("error", reject);
58
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
59
+ });
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "CLI for Stamp — Agent Git gateway in the Raft loop (bin stamp; future origin stamp.build)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "repository": {
25
25
  "type": "git",
26
- "url": "git+https://github.com/botiverse/raft-github-integration.git"
26
+ "url": "git+https://github.com/botiverse/stamp.git"
27
27
  },
28
28
  "publishConfig": {
29
29
  "access": "public"