@botiverse/stamp-cli 0.3.2 → 0.3.4

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/lib/main.mjs CHANGED
@@ -1,68 +1,37 @@
1
- import { readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
1
  import { createRequire } from "node:module";
2
+ import { basename } from "node:path";
5
3
  import { resolveAuth } from "./auth.mjs";
6
4
  import { makeClient, ApiError } from "./client.mjs";
7
- import { runAgentLogin } from "./agent-login.mjs";
8
- import { selectLocale, t } from "./locale.mjs";
9
- import { pullRequestInput, pullRequestRecovery } from "./pull-request.mjs";
10
- import {
11
- formatPRChecks,
12
- formatPRDetail,
13
- formatPRDiff,
14
- formatPRList,
15
- parsePRDiffArgs,
16
- parsePRListArgs,
17
- parsePRTargetArgs,
18
- prChecksExitCode,
19
- prDetailPath,
20
- prDiffPath,
21
- validatePRDetail,
22
- validatePRDiff,
23
- validatePRListResponse,
24
- } from "./pr-read.mjs";
25
- import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone } from "./repo-clone.mjs";
26
- import { apiErrorGuidance, presentError } from "./errors.mjs";
5
+ import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
6
+ import { presentError, printGatewayError } from "./errors.mjs";
7
+ import * as session from "./commands/session.mjs";
8
+ import * as key from "./commands/key.mjs";
9
+ import * as identity from "./commands/identity.mjs";
10
+ import * as receipt from "./commands/receipt.mjs";
11
+ import * as repo from "./commands/repo.mjs";
12
+ import * as pr from "./commands/pr.mjs";
13
+ import * as subscribe from "./commands/subscribe.mjs";
27
14
 
28
15
  const require = createRequire(import.meta.url);
29
16
  const pkg = require("../package.json");
30
17
 
31
- function takeFlag(args, name, dflt) {
32
- const i = args.indexOf(`--${name}`);
33
- if (i === -1) return dflt;
34
- const v = args[i + 1];
35
- args.splice(i, 2);
36
- return v;
37
- }
38
-
39
- function readPublicKey(path) {
40
- if (path === "-") return readFileSync(0, "utf8").trim();
41
- return readFileSync(path, "utf8").trim();
42
- }
43
-
44
- function objectArgs(args, locale) {
45
- const repository = args.shift();
46
- const rawKind = takeFlag(args, "kind");
47
- // Keep the concise user-facing `pull` spelling while sending the gateway's
48
- // canonical GitHubObjectKind on the wire. Also accept the canonical spelling
49
- // for scripts that already learned it from a response/event payload.
50
- const kind = rawKind === "pull" ? "pull_request" : rawKind;
51
- const number = Number(takeFlag(args, "number"));
52
- if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
53
- throw new Error(t(locale, "usageFollow"));
54
- }
55
- return { repository, kind, number };
56
- }
57
-
58
- function emitApiGuidance(error, locale, write) {
59
- const guidance = apiErrorGuidance(locale, error.body);
60
- if (guidance.code && guidance.code !== error.body?.error) write(`stamp: ${guidance.code}`);
61
- if (guidance.action) write(`stamp: ${guidance.action}`);
62
- // A typed code without a known/bounded action is not enough to suppress a
63
- // command-specific fallback (for example PR head-drift guidance).
64
- return Boolean(guidance.action);
65
- }
18
+ const commands = {
19
+ login: session.login,
20
+ logout: session.logout,
21
+ whoami: session.whoami,
22
+ "migration-help": session.migrationHelp,
23
+ key: key.run,
24
+ identity: identity.run,
25
+ receipt: receipt.run,
26
+ repo: repo.run,
27
+ pr: pr.run,
28
+ follow: subscribe.follow,
29
+ unfollow: subscribe.follow,
30
+ subscription: subscribe.subscription,
31
+ subscriptions: subscribe.subscriptions,
32
+ watch: subscribe.watch,
33
+ unwatch: subscribe.watch,
34
+ };
66
35
 
67
36
  export async function main(argv, opts) {
68
37
  const args = [...argv];
@@ -70,8 +39,7 @@ export async function main(argv, opts) {
70
39
  const err = opts.stderr ?? ((s) => console.error(s));
71
40
  const env = opts.env ?? process.env;
72
41
  const exit = opts.exit ?? ((code) => process.exit(code));
73
- // Global flags are options, never values of --title/--body/etc.
74
- const localValues = new Set(["--public-key", "--email", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key"]);
42
+ const localValues = new Set(["--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
75
43
  let json = false, langFlag, help = false, version = false;
76
44
  const commandArgs = [];
77
45
  for (let i = 0; i < args.length; i++) {
@@ -87,6 +55,8 @@ export async function main(argv, opts) {
87
55
  }
88
56
  args.splice(0, args.length, ...commandArgs);
89
57
  const locale = selectLocale(env, langFlag);
58
+ const cliName = opts.cliName ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : undefined);
59
+ if (cliName !== undefined) setCliName(cliName);
90
60
  if (version) { out(pkg.version); return exit(0); }
91
61
  const cmd = args.shift();
92
62
  if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
@@ -94,215 +64,30 @@ export async function main(argv, opts) {
94
64
 
95
65
  let auth;
96
66
  try {
97
- auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale, service: env.STAMP_SERVICE || opts.serviceDefault || undefined });
67
+ auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale, service: env.STAMP_SERVICE || opts.serviceDefault || undefined, cliName });
98
68
  } catch (e) {
99
- err(`stamp: ${presentError(locale, e)}`);
69
+ err(`${prefix()}${presentError(locale, e)}`);
70
+ return exit(1);
71
+ }
72
+ const api = makeClient(auth, opts.fetchImpl, {
73
+ readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
74
+ });
75
+ const handler = commands[cmd];
76
+ if (!handler) {
77
+ out(t(locale, "usage", { version: pkg.version }));
100
78
  return exit(1);
101
79
  }
102
- const api = makeClient(auth, opts.fetchImpl);
103
80
 
104
81
  try {
105
- switch (cmd) {
106
- case "login": {
107
- if (auth.mode !== "agent") {
108
- out(t(locale, "loginHumanIntro"));
109
- out(t(locale, "loginHumanBrowser", { url: auth.apiBase }));
110
- out(t(locale, "loginHumanCI"));
111
- return exit(0);
112
- }
113
- const login = opts.loginImpl ?? runAgentLogin;
114
- const session = await login(auth.agentEnv, auth.apiBase, { service: auth.service, fetchImpl: opts.fetchImpl });
115
- emit({ ok: true, service: auth.service, api_base: auth.apiBase, access_expires_at: session.access_expires_at },
116
- () => out(t(locale, "loginAgentReady", { service: auth.service, url: auth.apiBase, expires: session.access_expires_at })));
117
- return exit(0);
118
- }
119
- case "logout": {
120
- const p = auth.logout();
121
- out(p ? t(locale, "logoutForgot", { path: p }) : t(locale, "logoutNothing"));
122
- return exit(0);
123
- }
124
- case "whoami": {
125
- const me = await api("GET", "/v1/me");
126
- emit(me, () => out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${auth.apiBase}`));
127
- return exit(0);
128
- }
129
- case "migration-help": {
130
- const fetchImpl = opts.fetchImpl ?? fetch;
131
- const res = await fetchImpl(`${auth.apiBase}/v1/migration-help`, {
132
- headers: { "accept-language": locale === "zh-CN" ? "zh-CN" : "en" },
133
- });
134
- const d = await res.json();
135
- emit(d, () => {
136
- out(t(locale, "helpInstall", { cmds: (d.install ?? []).join(" ; ") }));
137
- out(t(locale, "helpAgentLogin", { text: d.login?.agent ?? "" }));
138
- for (const [from, to] of Object.entries(d.actions_to_cli ?? {})) {
139
- const note = d.notes?.[from];
140
- out(note ? ` ${from} → ${to} (${note})` : ` ${from} → ${to}`);
141
- }
142
- });
143
- return exit(0);
144
- }
145
- case "key": {
146
- const sub = args.shift();
147
- if (sub !== "enroll") throw new Error(t(locale, "usageKeyEnroll"));
148
- const keyPath = takeFlag(args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
149
- const publicKey = readPublicKey(keyPath);
150
- const d = await api("POST", "/v1/keys", { publicKey });
151
- emit(d, () => out(t(locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
152
- return exit(0);
153
- }
154
- case "identity": {
155
- const sub = args.shift();
156
- if (sub !== "bind") throw new Error(t(locale, "usageIdentityBind"));
157
- const agentEmail = takeFlag(args, "email");
158
- if (!agentEmail) throw new Error(t(locale, "usageIdentityBind"));
159
- const d = await api("POST", "/v1/identities", { agentEmail });
160
- emit(d, () => out(t(locale, "bound", { email: d.agentEmail })));
161
- return exit(0);
162
- }
163
- case "receipt": {
164
- const sub = args.shift();
165
- const id = args.shift();
166
- if (sub !== "get" || !id) throw new Error(t(locale, "usageReceiptGet"));
167
- const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
168
- emit(d, () => out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
169
- return exit(0);
170
- }
171
- case "repo": {
172
- if (args.shift() !== "clone") throw new Error(t(locale, "usageRepoClone"));
173
- const parsed = parseRepoCloneArgs(args);
174
- if (!parsed) throw new Error(t(locale, "usageRepoClone"));
175
- const me = await api("GET", "/v1/me");
176
- const defaultOwner = me?.github?.login;
177
- const repo = parseRepository(parsed.repository, defaultOwner);
178
- if (!repo) throw new Error(t(locale, "usageRepoClone"));
179
- const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
180
- const git = opts.gitCloneImpl ?? runGitClone;
181
- const result = await git({
182
- url,
183
- directory: parsed.directory,
184
- gitFlags: parsed.gitFlags,
185
- env: opts.gitEnv ?? env,
186
- });
187
- if (result.code !== 0) {
188
- if (result.stderr) err(result.stderr.trimEnd());
189
- throw new Error(t(locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
190
- }
191
- if (result.stderr) err(result.stderr.trimEnd());
192
- emit(
193
- { ok: true, repository: `${repo.owner}/${repo.name}`, url, directory: parsed.directory ?? repo.name },
194
- () => out(t(locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url })),
195
- );
196
- return exit(0);
197
- }
198
- case "pr": {
199
- const sub = args.shift();
200
- if (sub === "create") {
201
- const input = pullRequestInput(args);
202
- try {
203
- const d = await api("POST", "/v1/pull-requests", input);
204
- emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
205
- } catch (e) {
206
- if (e instanceof ApiError && e.status !== 401) {
207
- err(`stamp: ${e.message}`);
208
- if (!emitApiGuidance(e, locale, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
209
- return exit(1);
210
- }
211
- throw e;
212
- }
213
- return exit(0);
214
- }
215
- if (sub === "list" || sub === "ls") {
216
- const path = parsePRListArgs(args);
217
- const d = validatePRListResponse(await api("GET", path));
218
- emit(d, () => {
219
- const lines = formatPRList(d, {
220
- statusUnavailable: t(locale, "prStatusUnavailable"),
221
- ci: t(locale, "prCIShort"),
222
- agent: t(locale, "prAgentShort"),
223
- });
224
- if (lines.length === 0) out(t(locale, "prListEmpty"));
225
- else for (const line of lines) out(line);
226
- });
227
- return exit(0);
228
- }
229
- if (sub === "view") {
230
- const target = parsePRTargetArgs(args, "usagePrView");
231
- const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
232
- emit(d, () => {
233
- for (const line of formatPRDetail(d, {
234
- head: t(locale, "prHeadLabel"),
235
- checks: t(locale, "prChecksLabel"),
236
- review: t(locale, "prReviewLabel"),
237
- })) out(line);
238
- });
239
- return exit(0);
240
- }
241
- if (sub === "diff") {
242
- const target = parsePRDiffArgs(args);
243
- const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
244
- emit(d, () => {
245
- const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
246
- if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
247
- else out(chunks.join("\n"));
248
- });
249
- return exit(0);
250
- }
251
- if (sub === "checks") {
252
- const target = parsePRTargetArgs(args, "usagePrChecks");
253
- const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
254
- emit(d.checks, () => {
255
- const lines = formatPRChecks(d);
256
- if (lines.length === 0) out(t(locale, "prChecksEmpty"));
257
- else for (const line of lines) out(line);
258
- });
259
- return exit(prChecksExitCode(d));
260
- }
261
- throw new Error(t(locale, "usagePrRead"));
262
- }
263
- case "follow":
264
- case "unfollow": {
265
- const body = objectArgs(args, locale);
266
- const path = cmd === "follow" ? "/v1/subscriptions/objects/follow" : "/v1/subscriptions/objects/unfollow";
267
- const d = await api("POST", path, body);
268
- emit(d, () => out(JSON.stringify(d)));
269
- return exit(0);
270
- }
271
- case "subscription": {
272
- const sub = args.shift();
273
- if (sub !== "pause" && sub !== "resume") throw new Error(t(locale, "usageSubscription"));
274
- const body = objectArgs(args, locale);
275
- const d = await api("POST", `/v1/subscriptions/objects/${sub}`, body);
276
- emit(d, () => out(JSON.stringify(d)));
277
- return exit(0);
278
- }
279
- case "subscriptions": {
280
- const d = await api("GET", "/v1/subscriptions");
281
- emit(d, () => out(JSON.stringify(d, null, 2)));
282
- return exit(0);
283
- }
284
- case "watch":
285
- case "unwatch": {
286
- const repository = args.shift();
287
- const eventType = takeFlag(args, "event");
288
- if (!repository || !eventType) throw new Error(t(locale, "usageWatch", { cmd }));
289
- const path = cmd === "watch" ? "/v1/subscriptions/repositories/subscribe" : "/v1/subscriptions/repositories/unsubscribe";
290
- const d = await api("POST", path, { repository, eventType });
291
- emit(d, () => out(JSON.stringify(d)));
292
- return exit(0);
293
- }
294
- default:
295
- out(t(locale, "usage", { version: pkg.version }));
296
- return exit(cmd ? 1 : 0);
297
- }
82
+ return await handler({ cmd, args, api, auth, locale, emit, out, err, exit, env, opts });
298
83
  } catch (e) {
299
84
  if (e instanceof ApiError) {
300
- err(`stamp: ${e.message}`);
301
- emitApiGuidance(e, locale, err);
85
+ err(`${prefix()}${e.message}`);
86
+ printGatewayError(e, err);
302
87
  if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
303
88
  return exit(1);
304
89
  }
305
- err(`stamp: ${presentError(locale, e)}`);
90
+ err(`${prefix()}${presentError(locale, e)}`);
306
91
  return exit(1);
307
92
  }
308
93
  }
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { AgentError } from "../errors.mjs";
3
+ import { parsePRTargetArgs, prDetailPath } from "./read.mjs";
4
+
5
+ export function parsePRCommentArgs(input) {
6
+ const targetArgs = [], flags = new Map();
7
+ for (let i = 0; i < input.length; i++) {
8
+ const arg = input[i];
9
+ const match = arg.match(/^(--body|--body-file)(?:=(.*))?$/s);
10
+ const name = match?.[1] ?? ({ "-b": "--body", "-F": "--body-file" })[arg];
11
+ if (!name) { targetArgs.push(arg); continue; }
12
+ if (flags.has(name)) throw new AgentError("usagePrComment");
13
+ const value = match?.[2] ?? input[++i];
14
+ if (value === undefined) throw new AgentError("usagePrComment");
15
+ flags.set(name, value);
16
+ }
17
+ const target = parsePRTargetArgs(targetArgs, "usagePrComment");
18
+ if (flags.size !== 1) throw new AgentError("usagePrComment");
19
+ let body = flags.get("--body");
20
+ if (flags.has("--body-file")) {
21
+ const file = flags.get("--body-file");
22
+ try { body = readFileSync(file === "-" ? 0 : file, "utf8"); }
23
+ catch { throw new AgentError("prBodyRead"); }
24
+ }
25
+ if (!body?.trim() || Buffer.byteLength(body, "utf8") > 65536) throw new AgentError("prCommentBodyInvalid");
26
+ return { target, path: `${prDetailPath(target)}/comments`, body: { body } };
27
+ }
28
+
29
+ export function validatePRCommentResult(result, target) {
30
+ const expectedRepo = `${target.owner}/${target.repo}`;
31
+ const valid = result && typeof result === "object" && !Array.isArray(result)
32
+ && typeof result.repository === "string" && result.repository.toLowerCase() === expectedRepo.toLowerCase()
33
+ && result.number === target.number && Number.isSafeInteger(result.commentId) && result.commentId > 0
34
+ && typeof result.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(result.actorLogin)
35
+ && typeof result.url === "string"
36
+ && result.url.toLowerCase() === `https://github.com/${expectedRepo}/pull/${target.number}#issuecomment-${result.commentId}`.toLowerCase();
37
+ if (!valid) throw new AgentError("prCommentOutcomeUnknown");
38
+ return result;
39
+ }
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { AgentError } from "./errors.mjs";
3
+ import { AgentError } from "../errors.mjs";
4
4
 
5
5
  const names = new Set(["receipt", "repo", "head", "sha", "base", "title", "body", "body-file", "idempotency-key"]);
6
6
 
@@ -1,4 +1,4 @@
1
- import { AgentError } from "./errors.mjs";
1
+ import { AgentError } from "../errors.mjs";
2
2
 
3
3
  const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
4
4
  const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
@@ -11,7 +11,7 @@ const reviewStates = new Set([
11
11
  const terminalPassConclusions = new Set(["success", "neutral", "skipped"]);
12
12
  const pendingCheckStates = new Set(["", "expected", "in_progress", "pending", "queued", "requested", "waiting"]);
13
13
 
14
- function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
14
+ export function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
15
15
  const matches = [];
16
16
  for (let i = 0; i < args.length; i++) {
17
17
  if (args[i] === `--${long}` || (short && args[i] === `-${short}`)) {
@@ -73,9 +73,47 @@ function targetFromURL(value) {
73
73
  return repository && number ? { ...repository, number } : null;
74
74
  }
75
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/inbox/pull-requests` 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
+
76
91
  export function parsePRListArgs(input) {
77
- if (input.length !== 0) throw new AgentError("usagePrList");
78
- return "/v1/pr-inbox";
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
+ // task #413: the SSOT is /v1/inbox/pull-requests; the server keeps
112
+ // /v1/pr-inbox as a Deprecation alias for one version cycle. The CLI targets
113
+ // the SSOT (one build point).
114
+ const base = "/v1/inbox/pull-requests";
115
+ const path = query === "" ? base : `${base}?${query}`;
116
+ return { path, sections };
79
117
  }
80
118
 
81
119
  export function parsePRTargetArgs(input, usageCode = "usagePrRead") {
@@ -131,7 +169,7 @@ function requireSHA(value) {
131
169
  return sha;
132
170
  }
133
171
 
134
- function safeInline(value) {
172
+ export function safeInline(value) {
135
173
  return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]+/g, " ").replace(/\s+/g, " ").trim();
136
174
  }
137
175
 
@@ -141,7 +179,7 @@ function safeMultiline(value) {
141
179
  .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
142
180
  }
143
181
 
144
- export function validatePRListResponse(value) {
182
+ export function validatePRListResponse(value, paged = false) {
145
183
  const response = requireObject(value);
146
184
  if (!Array.isArray(response.items)) throw new AgentError("prReadInvalidResponse");
147
185
  for (const raw of response.items) {
@@ -164,7 +202,27 @@ export function validatePRListResponse(value) {
164
202
  }
165
203
  requireString(item.updatedAt);
166
204
  }
167
- if (response.nextCursor !== null || response.truncated !== false) throw new AgentError("prReadInvalidResponse");
205
+ // Pagination (task #397 slice 1): nextCursor is a string|null, truncated a
206
+ // boolean. Both are surfaced to the caller; a present cursor means "there is
207
+ // more", never an error. When the caller did not request a page (no
208
+ // limit/cursor), the server still returns nextCursor=null / truncated=false
209
+ // — assert that back-compat contract.
210
+ const nextCursor = response.nextCursor;
211
+ if (nextCursor !== null && typeof nextCursor !== "string") throw new AgentError("prReadInvalidResponse");
212
+ if (typeof response.truncated !== "boolean") throw new AgentError("prReadInvalidResponse");
213
+ // `truncated` and `nextCursor` must AGREE: a cursor is exactly the "there is
214
+ // more" signal, so a page is truncated iff it carries a cursor. Accepting
215
+ // (truncated=false, nextCursor="x") would print "continue" while the protocol
216
+ // says the page is complete; (truncated=true, nextCursor=null) would report
217
+ // success on a page the CLI cannot continue.
218
+ if (paged) {
219
+ if (response.truncated !== (nextCursor !== null)) throw new AgentError("prReadInvalidResponse");
220
+ return response;
221
+ }
222
+ // Unpaged (back-compat): strictly the pre-pagination contract.
223
+ if (nextCursor !== null || response.truncated !== false) {
224
+ throw new AgentError("prReadInvalidResponse");
225
+ }
168
226
  return response;
169
227
  }
170
228
 
@@ -234,6 +292,47 @@ export function validatePRDiff(value, expected) {
234
292
  return response;
235
293
  }
236
294
 
295
+ /**
296
+ * Author-oriented Graphite-style section for an agent-view PR row (task #397
297
+ * slice 2), derived purely from the wire fields the server already returns
298
+ * (`status` + `reviewStates`). First-match order matches the server's
299
+ * `DefaultInboxSections` intent:
300
+ *
301
+ * drafts <- status=DRAFT
302
+ * changes <- HAS_UNADDRESSED_CHANGES_REQUESTED (before approved)
303
+ * approved <- IS_FULLY_APPROVED (authoritative reviewDecision)
304
+ * approved(more) <- ONE_OR_MORE_APPROVALS and NOT IS_FULLY_APPROVED
305
+ * waiting <- status=OPEN with none of the above
306
+ * history <- MERGING / MERGED / CLOSED
307
+ * unavailable <- status=UNKNOWN (its own bucket, never folded into waiting)
308
+ *
309
+ * Kept pure and exported so the mapping is unit-testable.
310
+ */
311
+ export const PR_SECTIONS = Object.freeze({
312
+ drafts: "drafts",
313
+ changes: "changes",
314
+ approved: "approved",
315
+ approvals: "approvals",
316
+ waiting: "waiting",
317
+ history: "history",
318
+ unavailable: "unavailable",
319
+ });
320
+
321
+ export function prSection(item) {
322
+ const status = item.status;
323
+ const states = Array.isArray(item.reviewStates) ? item.reviewStates : [];
324
+ const has = (s) => states.includes(s);
325
+
326
+ if (status === "UNKNOWN") return PR_SECTIONS.unavailable;
327
+ if (status === "DRAFT") return PR_SECTIONS.drafts;
328
+ if (status === "MERGING" || status === "MERGED" || status === "CLOSED") return PR_SECTIONS.history;
329
+ // From here status === "OPEN".
330
+ if (has("HAS_UNADDRESSED_CHANGES_REQUESTED")) return PR_SECTIONS.changes;
331
+ if (has("IS_FULLY_APPROVED")) return PR_SECTIONS.approved;
332
+ if (has("ONE_OR_MORE_APPROVALS")) return PR_SECTIONS.approvals;
333
+ return PR_SECTIONS.waiting;
334
+ }
335
+
237
336
  export function formatPRList(response, labels = {}) {
238
337
  return response.items.map((item) => [
239
338
  safeInline(item.repository),
@@ -246,6 +345,39 @@ export function formatPRList(response, labels = {}) {
246
345
  ].join("\t"));
247
346
  }
248
347
 
348
+ const SECTION_ORDER = [
349
+ PR_SECTIONS.drafts,
350
+ PR_SECTIONS.changes,
351
+ PR_SECTIONS.approved,
352
+ PR_SECTIONS.approvals,
353
+ PR_SECTIONS.waiting,
354
+ PR_SECTIONS.history,
355
+ PR_SECTIONS.unavailable,
356
+ ];
357
+
358
+ /**
359
+ * Group the list rows by derived section (task #397 slice 2), keeping the flat
360
+ * per-row format intact and emitting each section as a labelled block in the
361
+ * fixed first-match order. Empty sections are omitted.
362
+ */
363
+ export function formatPRListSections(response, labels = {}) {
364
+ const buckets = new Map(SECTION_ORDER.map((s) => [s, []]));
365
+ for (const item of response.items) buckets.get(prSection(item)).push(item);
366
+ const lines = [];
367
+ for (const section of SECTION_ORDER) {
368
+ const items = buckets.get(section);
369
+ if (items.length === 0) continue;
370
+ lines.push(`${labels.section ?? ""}${sectionLabel(section, labels)}`.trim());
371
+ for (const line of formatPRList({ items }, labels)) lines.push(` ${line}`);
372
+ }
373
+ return lines;
374
+ }
375
+
376
+ function sectionLabel(section, labels) {
377
+ const key = `prSection_${section}`;
378
+ return labels[key] ?? section;
379
+ }
380
+
249
381
  export function formatPRDetail(detail, labels) {
250
382
  const lines = [
251
383
  `${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
@@ -0,0 +1,82 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
3
+
4
+ const shaRE = /^[0-9a-f]{40}$/;
5
+ const methods = new Set(["", "merge", "squash", "rebase"]);
6
+
7
+ function requireSHA(value, usageCode) {
8
+ if (typeof value !== "string" || !shaRE.test(value)) throw new AgentError(usageCode);
9
+ return value;
10
+ }
11
+
12
+ function parseWriteTarget(input, usageCode) {
13
+ const args = [...input];
14
+ const head = takeNamedFlag(args, "head", undefined, usageCode);
15
+ const base = takeNamedFlag(args, "base", undefined, usageCode);
16
+ const body = takeNamedFlag(args, "body", "b", usageCode);
17
+ const methodRaw = takeNamedFlag(args, "method", undefined, usageCode);
18
+ const target = parsePRTargetArgs(args, usageCode);
19
+ const expectedHead = requireSHA(head, usageCode);
20
+ const expectedBase = requireSHA(base, usageCode);
21
+ const mergeMethod = methodRaw === undefined ? "" : String(methodRaw).toLowerCase();
22
+ if (!methods.has(mergeMethod)) throw new AgentError(usageCode);
23
+ if (body !== undefined && !body.trim()) throw new AgentError(usageCode);
24
+ return { target, expectedHead, expectedBase, body, mergeMethod };
25
+ }
26
+
27
+ export function parsePRApproveArgs(input) {
28
+ const parsed = parseWriteTarget(input, "usagePrApprove");
29
+ if (parsed.mergeMethod) throw new AgentError("usagePrApprove");
30
+ return {
31
+ target: parsed.target,
32
+ path: `${prDetailPath(parsed.target)}/approve`,
33
+ method: "POST",
34
+ body: {
35
+ expectedHead: parsed.expectedHead,
36
+ expectedBase: parsed.expectedBase,
37
+ ...(parsed.body !== undefined ? { body: parsed.body } : {}),
38
+ },
39
+ };
40
+ }
41
+
42
+ export function parsePRMergeArgs(input) {
43
+ const parsed = parseWriteTarget(input, "usagePrMerge");
44
+ if (parsed.body !== undefined) throw new AgentError("usagePrMerge");
45
+ return {
46
+ target: parsed.target,
47
+ path: `${prDetailPath(parsed.target)}/merge`,
48
+ method: "PUT",
49
+ body: {
50
+ expectedHead: parsed.expectedHead,
51
+ expectedBase: parsed.expectedBase,
52
+ ...(parsed.mergeMethod ? { mergeMethod: parsed.mergeMethod } : {}),
53
+ },
54
+ };
55
+ }
56
+
57
+ function requireObject(value, code) {
58
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new AgentError(code);
59
+ return value;
60
+ }
61
+
62
+ export function validatePRApproveResult(result, target) {
63
+ const expectedRepo = `${target.owner}/${target.repo}`;
64
+ const d = requireObject(result, "prApproveOutcomeUnknown");
65
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
66
+ && d.number === target.number
67
+ && shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
68
+ && typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin);
69
+ if (!valid) throw new AgentError("prApproveOutcomeUnknown");
70
+ return d;
71
+ }
72
+
73
+ export function validatePRMergeResult(result, target) {
74
+ const expectedRepo = `${target.owner}/${target.repo}`;
75
+ const d = requireObject(result, "prMergeOutcomeUnknown");
76
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
77
+ && d.number === target.number && d.merged === true
78
+ && shaRE.test(d.mergeSha) && shaRE.test(d.mergedHead) && shaRE.test(d.mergedBase)
79
+ && typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin);
80
+ if (!valid) throw new AgentError("prMergeOutcomeUnknown");
81
+ return d;
82
+ }