@botiverse/stamp-cli 0.3.2 → 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.
package/README.md CHANGED
@@ -19,6 +19,7 @@ stamp pr list
19
19
  stamp pr view 123 --repo org/repo
20
20
  stamp pr diff 123 --repo org/repo
21
21
  stamp pr checks 123 --repo org/repo
22
+ stamp pr comment 123 --repo org/repo --body-file ./comment.md
22
23
  ```
23
24
 
24
25
  - Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
@@ -64,6 +65,31 @@ reading through Stamp rather than a local GitHub credential:
64
65
  - `--json` returns the service's validated machine envelope. Human-formatted
65
66
  output strips terminal control characters from provider-authored text.
66
67
 
68
+ ### Ordinary PR comments
69
+
70
+ `stamp pr comment 123 -R org/repo --body-file ./comment.md` uses a **human Stamp
71
+ session with a bound GitHub account**, and posts as that GitHub user. Agent
72
+ sessions are rejected; there is no fallback to an App or another person's token.
73
+ The existing human session authentication applies; this command does not create
74
+ a new login flow. The web inbox does not yet provide a comment composer.
75
+
76
+ Use `--body TEXT` (`-b`) or `--body-file FILE` (`-F`); `--body-file -` reads stdin
77
+ and preserves paragraphs. A PR URL can replace the number/repository pair.
78
+ Comments must be nonempty and at most 64 KiB of UTF-8 text. Closed or merged PRs
79
+ can still receive comments. This is an ordinary conversation comment, not a
80
+ review, inline code comment, approval or merge.
81
+
82
+ GitHub must permit the bound user's token to create comments; its
83
+ [issue-comment API](https://docs.github.com/en/rest/issues/comments#create-an-issue-comment)
84
+ accepts GitHub App user tokens with Issues or Pull requests write permission.
85
+ Stamp's existing repository visibility checks also apply.
86
+
87
+ Success prints the confirmed comment URL and GitHub actor; `--json` includes
88
+ `repository`, `number`, `commentId`, `url` and `actorLogin`. Each explicit command
89
+ is a new send, with no persistent deduplication. Neither CLI nor provider adapter
90
+ automatically resends a comment. If a response is lost or cannot be validated,
91
+ the command exits nonzero and asks you to inspect the PR before sending again.
92
+
67
93
  The Raft manifest exposes only `agent-login`. Key enrollment, identity binding,
68
94
  receipt reads, PR creation and subscriptions all use this CLI; the HTTP APIs
69
95
  remain available to service clients. `stamp migration-help` maps retired action
@@ -8,6 +8,7 @@ import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
8
8
  const URL_BASE = process.env.STAMP_URL || STAMP_DEFAULT_URL;
9
9
 
10
10
  await main(process.argv.slice(2), {
11
+ argv1: process.argv[1],
11
12
  urlBase: URL_BASE,
12
13
  urlExplicit: Boolean(process.env.STAMP_URL),
13
14
  serviceDefault: "raft-git-gateway-staging",
package/bin/stamp.mjs CHANGED
@@ -1,9 +1,65 @@
1
1
  #!/usr/bin/env node
2
- // stamp — CLI for the Agent Git gateway.
3
- // Default instance is the current staging HTTPS origin.
2
+ // stamp — CLI for the Agent Git gateway, targeting the PRODUCTION instance.
3
+ //
4
+ // Task #439: the production service slug and the default origin used to be
5
+ // resolved INDEPENDENTLY (lib/agent-login.mjs: STAMP_SERVICE="stamp" while the
6
+ // default URL was the staging origin). Once the production `stamp` service was
7
+ // registered, an unconfigured `stamp login` became a prod-slug + staging-origin
8
+ // pair — a wrong-environment target.
9
+ //
10
+ // The instance is pinned as a COHERENT PAIR (prod slug + prod origin) and the
11
+ // pair is defended. The defense compares the PARSED ORIGIN, not the raw string:
12
+ // `https://staging.stamp.build/` (trailing slash), `HTTPS://STAGING.STAMP.BUILD`
13
+ // and an explicit `:443` are the same origin and must be refused just the same.
4
14
  import { main } from "../lib/main.mjs";
5
- import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
6
15
 
7
- const URL_BASE = process.env.STAMP_URL || STAMP_DEFAULT_URL;
16
+ const PROD_URL = "https://stamp.build";
17
+ const PROD_SERVICE = "stamp";
18
+ const STAGING_URL = "https://staging.stamp.build";
19
+ const STAGING_SERVICE = "raft-git-gateway-staging";
8
20
 
9
- await main(process.argv.slice(2), { urlBase: URL_BASE, urlExplicit: Boolean(process.env.STAMP_URL) });
21
+ // Canonical origin of a URL, or null when it is not an absolute http(s) URL.
22
+ function originOf(value) {
23
+ try {
24
+ const parsed = new URL(value);
25
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
26
+ return parsed.origin; // lowercases host, drops default port + path/query
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ // Canonical origin -> the service slug that owns it.
33
+ //
34
+ // SUPPORT BOUNDARY: this map lists the instances the CLI KNOWS. The pairing
35
+ // invariant can only be enforced where the origin<->service mapping is known;
36
+ // a self-hosted instance is not covered (the CLI has no general way to learn
37
+ // its mapping). Do not describe the guarantee as universal.
38
+ const KNOWN_INSTANCES = new Map([
39
+ [originOf(PROD_URL), PROD_SERVICE],
40
+ [originOf(STAGING_URL), STAGING_SERVICE],
41
+ ]);
42
+ const originService = KNOWN_INSTANCES;
43
+
44
+ const url = process.env.STAMP_URL || PROD_URL;
45
+ const urlOrigin = originOf(url);
46
+ const owner = urlOrigin === null ? undefined : originService.get(urlOrigin);
47
+
48
+ // The instance this invocation targets. An explicit STAMP_SERVICE must match the
49
+ // origin's owner; otherwise derive it (a non-default origin needs its slug).
50
+ const requested = process.env.STAMP_SERVICE;
51
+ if (owner !== undefined && requested !== undefined && requested !== owner) {
52
+ process.stderr.write(
53
+ `stamp: STAMP_URL=${url} belongs to service ${owner}, not ${requested} — refusing to pair them (task #439).\n` +
54
+ "Set both explicitly for a non-default instance, or use `stamp-staging` for staging.\n",
55
+ );
56
+ process.exit(2);
57
+ }
58
+ const service = requested ?? owner ?? PROD_SERVICE;
59
+
60
+ await main(process.argv.slice(2), {
61
+ argv1: process.argv[1],
62
+ urlBase: url,
63
+ urlExplicit: Boolean(process.env.STAMP_URL),
64
+ serviceDefault: service,
65
+ });
@@ -7,6 +7,7 @@ import { randomBytes } from "node:crypto";
7
7
  import { agentAuthPath, writeAgentSession } from "@botiverse/agent-session-store";
8
8
  import { parseAgentSession, readBoundedText, STAMP_SERVICE } from "./agent-login.mjs";
9
9
  import { AgentError, agentFail } from "./errors.mjs";
10
+ import { storeMatchesOrigin } from "./auth.mjs";
10
11
 
11
12
  export const REFRESH_SKEW_MS = 60_000;
12
13
  const REFRESH_DEADLINE_MS = 20_000;
@@ -78,7 +79,9 @@ export async function getFreshAgentAccessToken(a, opts = {}) {
78
79
  const now = opts.now ?? Date.now();
79
80
  const store = readStore(a, service);
80
81
  if (!store) return null;
81
- if (!accessExpiresWithinSkew(store, now)) return store.access_token;
82
+ // Task #439: never use a store issued for a different origin than the target.
83
+ if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
84
+ if (storeMatchesOrigin(store, opts.apiBase ?? store.api_base) && !accessExpiresWithinSkew(store, now)) return store.access_token;
82
85
  return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, false, opts.deadlineMs ?? REFRESH_DEADLINE_MS, undefined, opts.apiBase);
83
86
  }
84
87
 
@@ -87,7 +90,8 @@ export async function forceRefreshAgentToken(a, opts = {}) {
87
90
  const now = opts.now ?? Date.now();
88
91
  const store = readStore(a, service);
89
92
  if (!store) return null;
90
- const reused = successorIfRejected(store, opts.rejectedAccess);
93
+ if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
94
+ const reused = storeMatchesOrigin(store, opts.apiBase ?? store.api_base) ? successorIfRejected(store, opts.rejectedAccess) : null;
91
95
  if (reused) return reused;
92
96
  return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, true, opts.deadlineMs ?? REFRESH_DEADLINE_MS, opts.rejectedAccess, opts.apiBase);
93
97
  }
@@ -103,11 +107,14 @@ async function singleFlightRefresh(a, service, baseline, now, fetchImpl, sleepIm
103
107
  } catch (e) {
104
108
  if (e?.code !== "EEXIST") throw e;
105
109
  acquired = acquireIfDeadOwner(lock, ownerId);
106
- if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess);
110
+ if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase);
107
111
  }
108
112
  try {
109
113
  const fresh = readStore(a, service);
110
114
  if (!fresh) return null;
115
+ if (!storeMatchesOrigin(fresh, apiBase ?? fresh.api_base)) return null;
116
+ // A cached token may only be returned when the stored session belongs to the
117
+ // TARGET origin; anything else is refused upstream (no replay, no migration).
111
118
  const reused = successorIfRejected(fresh, rejectedAccess);
112
119
  if (reused) return reused;
113
120
  if (!force && !accessExpiresWithinSkew(fresh, now)) return fresh.access_token;
@@ -162,16 +169,22 @@ function ownerAlive(pid) {
162
169
  try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
163
170
  }
164
171
 
165
- async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess) {
172
+ async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase) {
173
+ // The waiter must accept a session that the winner rewrote to the TARGET
174
+ // origin — comparing against the (possibly legacy) baseline base would make it
175
+ // poll until timeout even though the store is already correct (@skyzh).
176
+ const targetBase = apiBase ?? baseline.api_base;
166
177
  const maxPolls = Math.ceil(LOCK_WAIT_MS / LOCK_POLL_MS);
167
178
  for (let i = 0; i < maxPolls; i += 1) {
168
179
  await sleepImpl(LOCK_POLL_MS);
169
180
  const cur = readStore(a, service);
181
+ if (cur && !storeMatchesOrigin(cur, targetBase)) continue;
170
182
  const reused = successorIfRejected(cur, rejectedAccess);
171
183
  if (reused) return reused;
172
184
  if (cur && cur.refresh_token !== baseline.refresh_token) return cur.access_token;
173
185
  }
174
186
  const cur = readStore(a, service);
187
+ if (cur && !storeMatchesOrigin(cur, targetBase)) agentFail("notLoggedIn");
175
188
  const reused = successorIfRejected(cur, rejectedAccess);
176
189
  if (reused) return reused;
177
190
  if (!force && cur && !accessExpired(cur, now)) return cur.access_token;
package/lib/auth.mjs CHANGED
@@ -4,7 +4,69 @@ import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } fro
4
4
  import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
5
5
  import { AgentError, agentFail } from "./errors.mjs";
6
6
 
7
- export function resolveAuth({ urlBase, urlExplicit, env = process.env, service = env.STAMP_SERVICE || STAMP_SERVICE, locale = "en" }) {
7
+ // Canonical origin of a URL, or null when it is not an absolute http(s) URL.
8
+ // Task #439: comparisons on the stored/api base MUST normalize the origin —
9
+ // a trailing slash, upper-case host or explicit :443 are the SAME origin and
10
+ // must not slip past the "this is a legacy default" check.
11
+ function originOf(value) {
12
+ try {
13
+ const parsed = new URL(value);
14
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
15
+ return parsed.origin;
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ // Known instance map: canonical origin -> the service slug that owns it.
22
+ // SUPPORT BOUNDARY: only the instances the CLI knows can be checked statically.
23
+ // A self-hosted instance's origin<->service mapping is not knowable locally.
24
+ const KNOWN_INSTANCES = new Map([
25
+ ["https://stamp.build", "stamp"],
26
+ ["https://staging.stamp.build", "raft-git-gateway-staging"],
27
+ ]);
28
+ // storeMatchesOrigin reports whether a stored session belongs to the SAME
29
+ // instance as the target base. It is ONE branch-free property — the parsed
30
+ // origins must be strictly equal — and it must hold at EVERY actual use
31
+ // (token read, refresh, 401 retry), not once at resolveAuth (@Tenny: "use site"
32
+ // is plural; the refresh path re-reads the store file).
33
+ //
34
+ // There is deliberately NO migration of a renamed host: a session issued for a
35
+ // superseded origin is treated as belonging to a DIFFERENT instance and is
36
+ // refused (the caller re-logs in). Such a session would otherwise have to be
37
+ // replayed or refreshed, and that branch produced every defect in this task
38
+ // (@Mason, 2026-09-13: "删" — the one saved re-login is already documented as
39
+ // expected, so the branch is not worth its concurrency+cache complexity).
40
+ export function storeMatchesOrigin(store, apiBase) {
41
+ if (!store) return false;
42
+ const target = originOf(apiBase);
43
+ const stored = originOf(store.api_base);
44
+ return stored !== null && stored === target;
45
+ }
46
+
47
+ export function assertCoherentPair(apiBase, service) {
48
+ const origin = originOf(apiBase);
49
+ if (origin === null) return; // non-http(s) base: out of this check's scope
50
+ const owner = KNOWN_INSTANCES.get(origin);
51
+ if (owner === undefined) {
52
+ // Unknown origin (e.g. a self-hosted instance): its origin<->service
53
+ // mapping is not knowable locally, so it is outside this check. See the
54
+ // support boundary above — do not read this as a universal guarantee.
55
+ return;
56
+ }
57
+ if (service !== owner) {
58
+ agentFail("pair_mismatch", { origin, service, owner });
59
+ }
60
+ }
61
+
62
+ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service, locale = "en", cliName = "stamp" }) {
63
+ // The instance slug may be left unset (e.g. `stamp-staging` passes only its
64
+ // base). Derive it: an explicit STAMP_SERVICE wins, else the base's owner,
65
+ // else the production default. Task #439: entry default, env and a stored
66
+ // session must all resolve to ONE coherent pair.
67
+ if (service === undefined || service === "") {
68
+ service = env.STAMP_SERVICE || KNOWN_INSTANCES.get(originOf(urlBase)) || STAMP_SERVICE;
69
+ }
8
70
  const admission = admitAgent(env);
9
71
  if (admission.kind === "fail_closed") {
10
72
  agentFail("admission_partial", { reason: admission.reason });
@@ -13,20 +75,56 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service =
13
75
  const a = admission.env;
14
76
  const store = readStore(a, service);
15
77
  const storedBase = store?.api_base;
16
- const apiBase = urlExplicit
78
+ // Task #439: compare the stored base on its PARSED ORIGIN, not the raw
79
+ // string. A legacy default stored with a trailing slash, different case or
80
+ // an explicit :443 is still that legacy default and must be superseded by
81
+ // the caller's coherent base — otherwise a stale stored spelling silently
82
+ // retargets the request. A genuinely non-legacy custom instance is still
83
+ // preserved (that is the existing custom-base feature).
84
+ const storedOrigin = originOf(storedBase);
85
+ const legacyOrigins = new Set([STAMP_LEGACY_STAGING_URL, STAMP_LEGACY_DEFAULT_URL].map(originOf));
86
+ const apiBase = urlExplicit || (storedOrigin !== null && legacyOrigins.has(storedOrigin))
17
87
  ? urlBase
18
- : ([STAMP_LEGACY_STAGING_URL, STAMP_LEGACY_DEFAULT_URL].includes(storedBase) ? urlBase : (storedBase ?? urlBase));
88
+ : (storedBase ?? urlBase);
89
+ // The final resolved pair must belong to one instance. Checked here so every
90
+ // source (entry default / env / stored session) is covered, before any
91
+ // network work. Task #439.
92
+ assertCoherentPair(apiBase, service);
93
+
94
+ // Task #439 (@skyzh): a stored session is bound to the ORIGIN it was issued
95
+ // against. If the resolved origin differs from the origin the session was
96
+ // stored for (e.g. we just superseded a legacy staging base with prod), the
97
+ // cached access/refresh tokens must NOT be replayed against the new origin —
98
+ // that would send a foreign instance's credential to this one. Treat such a
99
+ // store as absent so the caller must log in afresh.
100
+ // No migration: a store issued for a DIFFERENT origin is not usable here.
101
+ // The refusal names the origin so the reader knows why and what to do.
102
+ const usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
103
+ const storedOriginElsewhere = !usableStore && storedOrigin !== null ? storedOrigin : null;
19
104
  return {
20
105
  mode: "agent",
21
106
  apiBase,
22
107
  agentEnv: a,
23
108
  service,
24
109
  async token() {
110
+ if (!usableStore) {
111
+ if (storedOriginElsewhere !== null) {
112
+ throw new AgentError("sessionOriginMismatch", {
113
+ stored: storedOriginElsewhere,
114
+ target: originOf(apiBase) ?? apiBase,
115
+ cli: cliName,
116
+ });
117
+ }
118
+ throw new AgentError("notLoggedIn");
119
+ }
25
120
  const tok = await getFreshAgentAccessToken(a, { service, apiBase });
26
121
  if (!tok) throw new AgentError("notLoggedIn");
27
122
  return tok;
28
123
  },
29
- async retryToken(rejectedAccess) { return forceRefreshAgentToken(a, { service, apiBase, rejectedAccess }); },
124
+ async retryToken(rejectedAccess) {
125
+ if (!usableStore) return null;
126
+ return forceRefreshAgentToken(a, { service, apiBase, rejectedAccess });
127
+ },
30
128
  logout() {
31
129
  const p = agentAuthPath(a, service);
32
130
  if (existsSync(p)) unlinkSync(p);
@@ -35,6 +133,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service =
35
133
  };
36
134
  }
37
135
  const token = env.STAMP_TOKEN || "";
136
+ assertCoherentPair(urlBase, service);
38
137
  return {
39
138
  mode: "human",
40
139
  apiBase: urlBase,
package/lib/errors.mjs CHANGED
@@ -11,6 +11,11 @@ const apiRecoveryKeys = new Map([
11
11
  ["PR_DETAIL_FAILED", "prReadUnavailable"],
12
12
  ["PR_DIFF_FAILED", "prReadUnavailable"],
13
13
  ["PR_INBOX_FAILED", "prReadUnavailable"],
14
+ // Cursor scope/format rejections (task #397 slice 1): the cursor is bound to
15
+ // (tenant, server, viewer scope, filter); a mismatched or malformed cursor is
16
+ // a recoverable user error, never a generic contract mismatch.
17
+ ["PR_INBOX_CURSOR_SCOPE", "prCursorScope"],
18
+ ["PR_INBOX_CURSOR_INVALID", "prCursorInvalid"],
14
19
  ]);
15
20
 
16
21
  /** Stable machine code on `.code`; English catalog text on `.message` for tests. */
package/lib/locale.mjs CHANGED
@@ -1,12 +1,17 @@
1
1
  /** User-visible copy. Machine protocol fields and stable error codes stay English. */
2
2
  export const messages = {
3
3
  en: {
4
- usagePrCreate: "usage: stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
5
- usagePrRead: "usage: stamp pr <list|view|diff|checks> [arguments]",
6
- usagePrList: "usage: stamp pr list",
7
- usagePrView: "usage: stamp pr view <number|URL> [--repo OWNER/REPO]",
8
- usagePrDiff: "usage: stamp pr diff <number|URL> [--repo OWNER/REPO] [--name-only]",
9
- usagePrChecks: "usage: stamp pr checks <number|URL> [--repo OWNER/REPO]",
4
+ usagePrCreate: "usage: {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
5
+ usagePrRead: "usage: {cli} pr <list|view|diff|checks|comment> [arguments]",
6
+ usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) (human GitHub identity required)",
7
+ prCommentBodyInvalid: "Comment must be nonempty and at most 64 KiB of UTF-8 text.",
8
+ prCommentCreated: "Comment posted as {actor}: {url}",
9
+ prCommentRejected: "Comment request was rejected. Check your human session, GitHub binding, repository access and input.",
10
+ prCommentOutcomeUnknown: "Comment outcome is unknown. Check the PR comments before sending again; do not automatically resend.",
11
+ usagePrList: "usage: {cli} pr list",
12
+ usagePrView: "usage: {cli} pr view <number|URL> [--repo OWNER/REPO]",
13
+ usagePrDiff: "usage: {cli} pr diff <number|URL> [--repo OWNER/REPO] [--name-only]",
14
+ usagePrChecks: "usage: {cli} pr checks <number|URL> [--repo OWNER/REPO]",
10
15
  prReadInvalidResponse: "Stamp returned an invalid PR read response; retry after checking the service version.",
11
16
  prReadCoordinateMismatch: "Stamp returned PR coordinates different from the requested repository or number; refusing to display them.",
12
17
  prListEmpty: "No Stamp-created pull requests found.",
@@ -23,55 +28,66 @@ export const messages = {
23
28
  prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
24
29
  prReadDiffIncomplete: "GitHub did not return the complete PR diff; retry later instead of relying on partial files.",
25
30
  prReadUnavailable: "The PR read is temporarily unavailable; retry after checking Stamp service status.",
26
- prRequired: "Missing {flag}; use stamp receipt get <id> to obtain the published coordinates.",
31
+ prListMore: "More results available; rerun with --limit and --cursor {cursor}.",
32
+ prSection_drafts: "Drafts",
33
+ prSection_changes: "Changes requested",
34
+ prSection_approved: "Approved",
35
+ prSection_approvals: "Has approvals",
36
+ prSection_waiting: "Waiting for review",
37
+ prSection_history: "History",
38
+ prSection_unavailable: "Status unavailable",
39
+ prCursorScope: "This cursor does not belong to the current identity or scope; rerun {cli} pr list from the start.",
40
+ prCursorInvalid: "The cursor is invalid or expired; rerun {cli} pr list from the start.",
41
+ prRequired: "Missing {flag}; use {cli} receipt get <id> to obtain the published coordinates.",
27
42
  prRepository: "--repo must be OWNER/REPO.",
28
43
  prSHA: "--sha must be the exact 40-character lowercase published commit SHA.",
29
44
  prBodyRequired: "Provide a non-empty PR description with --body or --body-file (use - for stdin).",
30
- prCheckArguments: "Check the PR arguments with stamp pr create --help; correct invalid or empty values before retrying.",
45
+ prCheckArguments: "Check the PR arguments with {cli} pr create --help; correct invalid or empty values before retrying.",
31
46
  prCheckConfiguration: "Ask the service administrator to repair the GitHub App configuration before retrying.",
32
47
  prBodyConflict: "Use either --body or --body-file, not both.",
33
48
  prBodyRead: "Cannot read --body-file; check the file path or pass - for stdin.",
34
49
  prIdempotency: "--idempotency-key must contain 16–128 letters, digits, dots, underscores, colons, or hyphens.",
35
50
  prCreated: "Created PR #{number}: {url}",
36
51
  prExisting: "Existing PR #{number}: {url}",
37
- prWaitPublished: "Check stamp receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
52
+ prWaitPublished: "Check {cli} receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
38
53
  prCheckReceipt: "Read the receipt again and check --repo, --head and --sha against the exact published commit.",
39
54
  prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
40
55
  prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
41
56
  prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
42
- apiBindIdentity: "Bind this agent first with `stamp identity bind --email <agent-email>`, then retry the command.",
57
+ apiBindIdentity: "Bind this agent first with `{cli} identity bind --email <agent-email>`, then retry the command.",
43
58
  apiRepositoryNotInstalled: "Check OWNER/REPO spelling, or ask a server owner to install the Stamp GitHub App on that repository, then retry.",
44
59
  apiContributionDenied: "Ask a server owner to grant this agent an active Write-or-higher repository role, then retry.",
45
60
  apiRepositoryNotAuthorized: "Ask a server owner to verify the Stamp GitHub App installation and this agent's identity binding, then retry.",
46
61
 
47
- usage: `stamp {version} — Agent Git gateway CLI (future origin stamp.build)
62
+ usage: `{cli} {version} — Agent Git gateway CLI
48
63
 
49
- stamp login agent: PKCE login via raft (no browser); human: how to set STAMP_TOKEN
50
- stamp logout agent: forget the stored session
51
- stamp whoami who the gateway thinks you are
52
- stamp migration-help old manifest actions → CLI mapping
53
- stamp key enroll [--public-key FILE|-] bind this agent's SSH public key (default ~/.ssh/id_ed25519.pub)
54
- stamp identity bind --email ADDR bind commit-author email (DCO)
55
- stamp receipt get <id> gateway acceptance + GitHub publication status
56
- stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
57
- stamp pr list
58
- stamp pr view <number|URL> --repo OWNER/REPO
59
- stamp pr diff <number|URL> --repo OWNER/REPO [--name-only]
60
- stamp pr checks <number|URL> --repo OWNER/REPO
61
- stamp repo clone <repository> [<directory>] [-- <gitflags>...]
64
+ {cli} login agent: PKCE login via raft (no browser); human: how to set STAMP_TOKEN
65
+ {cli} logout agent: forget the stored session
66
+ {cli} whoami who the gateway thinks you are
67
+ {cli} migration-help old manifest actions → CLI mapping
68
+ {cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (default ~/.ssh/id_ed25519.pub)
69
+ {cli} identity bind --email ADDR bind commit-author email (DCO)
70
+ {cli} receipt get <id> gateway acceptance + GitHub publication status
71
+ {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
72
+ {cli} pr list
73
+ {cli} pr view <number|URL> --repo OWNER/REPO
74
+ {cli} pr diff <number|URL> --repo OWNER/REPO [--name-only]
75
+ {cli} pr checks <number|URL> --repo OWNER/REPO
76
+ {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human)
77
+ {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
62
78
 
63
- stamp follow <owner/repo> --kind issue|pull --number N
64
- stamp unfollow <owner/repo> --kind issue|pull --number N
65
- stamp subscription pause|resume <owner/repo> --kind issue|pull --number N
66
- stamp subscriptions
67
- stamp watch <owner/repo> --event TYPE
68
- stamp unwatch <owner/repo> --event TYPE
79
+ {cli} follow <owner/repo> --kind issue|pull --number N
80
+ {cli} unfollow <owner/repo> --kind issue|pull --number N
81
+ {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N
82
+ {cli} subscriptions
83
+ {cli} watch <owner/repo> --event TYPE
84
+ {cli} unwatch <owner/repo> --event TYPE
69
85
 
70
86
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
71
87
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
72
88
 
73
89
  flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
74
- usageRepoClone: "usage: stamp repo clone <repository> [<directory>] [-- <gitflags>...]",
90
+ usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [-- <gitflags>...]",
75
91
  cloned: "Cloned {repository} from {url}",
76
92
  cloneFailed: "clone of {repository} via the Stamp gateway failed",
77
93
  loginHumanIntro: "Not a managed Raft agent. Humans and CI use STAMP_TOKEN:",
@@ -82,18 +98,20 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
82
98
  logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
83
99
  enrolled: "enrolled {fingerprint} ({keyId})",
84
100
  bound: "bound {email}",
85
- usageKeyEnroll: "usage: stamp key enroll [--public-key FILE|-]",
86
- usageIdentityBind: "usage: stamp identity bind --email ADDR",
87
- usageReceiptGet: "usage: stamp receipt get <receipt-id>",
88
- usageFollow: "usage: stamp <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
89
- usageSubscription: "usage: stamp subscription pause|resume <owner/repo> --kind issue|pull --number N",
90
- usageWatch: "usage: stamp {cmd} <owner/repo> --event TYPE",
101
+ usageKeyEnroll: "usage: {cli} key enroll [--public-key FILE|-]",
102
+ usageIdentityBind: "usage: {cli} identity bind --email ADDR",
103
+ usageReceiptGet: "usage: {cli} receipt get <receipt-id>",
104
+ usageFollow: "usage: {cli} <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
105
+ usageSubscription: "usage: {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N",
106
+ usageWatch: "usage: {cli} {cmd} <owner/repo> --event TYPE",
91
107
  helpInstall: "install: {cmds}",
92
108
  helpAgentLogin: "agent login: {text}",
93
- sessionRejected: "stamp: session rejected — run `stamp login`",
94
- checkToken: "stamp: check STAMP_TOKEN",
95
- notLoggedIn: "not logged in: run `stamp login` (managed agent)",
96
- stampTokenMissing: "STAMP_TOKEN is not set (session or deploy token); inside a managed agent run `stamp login`",
109
+ sessionRejected: "{cli}: session rejected — run `{cli} login`",
110
+ checkToken: "{cli}: check STAMP_TOKEN",
111
+ notLoggedIn: "not logged in: run `{cli} login` (managed agent)",
112
+ sessionOriginMismatch: "the stored session was issued for {stored}, not {target} — run `{cli} login` again",
113
+ pair_mismatch: "refusing a mismatched instance pair: {origin} belongs to service {owner}, not {service} (task #439)",
114
+ stampTokenMissing: "STAMP_TOKEN is not set (session or deploy token); inside a managed agent run `{cli} login`",
97
115
  admission_partial: "refusing to run: partial managed-agent environment ({reason}); not falling back to STAMP_TOKEN",
98
116
  invoke_not_json: "agent-login: `raft integration invoke` did not return JSON",
99
117
  invoke_not_object: "agent-login: invoke output is not an object",
@@ -135,12 +153,17 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
135
153
  refresh_wait_timeout: "agent-login: timed out waiting for a concurrent token refresh",
136
154
  },
137
155
  "zh-CN": {
138
- usagePrCreate: "用法:stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
139
- usagePrRead: "用法:stamp pr <list|view|diff|checks> [参数]",
140
- usagePrList: "用法:stamp pr list",
141
- usagePrView: "用法:stamp pr view <编号|URL> [--repo OWNER/REPO]",
142
- usagePrDiff: "用法:stamp pr diff <编号|URL> [--repo OWNER/REPO] [--name-only]",
143
- usagePrChecks: "用法:stamp pr checks <编号|URL> [--repo OWNER/REPO]",
156
+ usagePrCreate: "用法:{cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
157
+ usagePrRead: "用法:{cli} pr <list|view|diff|checks|comment> [参数]",
158
+ usagePrComment: "用法:{cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-)(需要本人 GitHub 身份)",
159
+ prCommentBodyInvalid: "评论不能为空,UTF-8 文本最多 64 KiB。",
160
+ prCommentCreated: "已以 {actor} 身份发表评论:{url}",
161
+ prCommentRejected: "评论请求被拒绝,请检查人类会话、GitHub 绑定、仓库权限和输入。",
162
+ prCommentOutcomeUnknown: "评论结果不明。请先查看 PR 评论,不要自动重发。",
163
+ usagePrList: "用法:{cli} pr list",
164
+ usagePrView: "用法:{cli} pr view <编号|URL> [--repo OWNER/REPO]",
165
+ usagePrDiff: "用法:{cli} pr diff <编号|URL> [--repo OWNER/REPO] [--name-only]",
166
+ usagePrChecks: "用法:{cli} pr checks <编号|URL> [--repo OWNER/REPO]",
144
167
  prReadInvalidResponse: "Stamp 返回了无效的 PR 读取响应;请检查服务版本后重试。",
145
168
  prReadCoordinateMismatch: "Stamp 返回的 PR 坐标与请求的仓库或编号不一致;已拒绝显示。",
146
169
  prListEmpty: "没有找到通过 Stamp 创建的 Pull Request。",
@@ -157,55 +180,66 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
157
180
  prReadHeadMoved: "Stamp 读取 diff 时 PR head 已变化;请重新运行命令并审阅新的 head。",
158
181
  prReadDiffIncomplete: "GitHub 未返回完整的 PR diff;请稍后重试,不要依赖部分文件。",
159
182
  prReadUnavailable: "PR 读取暂时不可用;请检查 Stamp 服务状态后重试。",
160
- prRequired: "缺少 {flag};用 stamp receipt get <id> 获取已发表提交的信息。",
183
+ prListMore: "还有更多结果;用 --limit 与 --cursor {cursor} 继续翻页。",
184
+ prSection_drafts: "草稿",
185
+ prSection_changes: "需修改",
186
+ prSection_approved: "已批准",
187
+ prSection_approvals: "有批准",
188
+ prSection_waiting: "等待评审",
189
+ prSection_history: "历史",
190
+ prSection_unavailable: "状态暂不可用",
191
+ prCursorScope: "该 cursor 不属于当前身份或范围;请从头重新运行 {cli} pr list。",
192
+ prCursorInvalid: "cursor 无效或已过期;请从头重新运行 {cli} pr list。",
193
+ prRequired: "缺少 {flag};用 {cli} receipt get <id> 获取已发表提交的信息。",
161
194
  prRepository: "--repo 必须为 OWNER/REPO。",
162
195
  prSHA: "--sha 必须是已发表提交的精确 40 位小写 SHA。",
163
196
  prBodyRequired: "请用 --body 或 --body-file 提供非空 PR 正文(用 - 从标准输入读取)。",
164
- prCheckArguments: "请用 stamp pr create --help 检查参数,修正无效或空值后再重试。",
197
+ prCheckArguments: "请用 {cli} pr create --help 检查参数,修正无效或空值后再重试。",
165
198
  prCheckConfiguration: "请先联系服务管理员修复 GitHub App 配置,再重试。",
166
199
  prBodyConflict: "--body 与 --body-file 只能选一个。",
167
200
  prBodyRead: "无法读取 --body-file;请检查路径,或用 - 从标准输入读取。",
168
201
  prIdempotency: "--idempotency-key 必须为 16–128 位字母、数字、点、下划线、冒号或连字符。",
169
202
  prCreated: "已创建 PR #{number}:{url}",
170
203
  prExisting: "已有 PR #{number}:{url}",
171
- prWaitPublished: "请用 stamp receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
204
+ prWaitPublished: "请用 {cli} receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
172
205
  prCheckReceipt: "请重新读取 receipt,并核对 --repo、--head 和 --sha 是否与已发表提交一致。",
173
206
  prCheckAccess: "请与仓库管理员核对仓库权限和允许的目标分支。",
174
207
  prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
175
208
  prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
176
- apiBindIdentity: "请先运行 `stamp identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
209
+ apiBindIdentity: "请先运行 `{cli} identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
177
210
  apiRepositoryNotInstalled: "请检查 OWNER/REPO 拼写,或请 Server Owner 为该仓库安装 Stamp GitHub App,再重试。",
178
211
  apiContributionDenied: "请让 Server Owner 为此 Agent 授予有效的 Write 或更高仓库角色,再重试。",
179
212
  apiRepositoryNotAuthorized: "请让 Server Owner 核对 Stamp GitHub App 安装与此 Agent 的身份绑定,再重试。",
180
213
 
181
- usage: `stamp {version} — Agent Git 网关 CLI(未来域名 stamp.build)
214
+ usage: `{cli} {version} — Agent Git 网关 CLI
182
215
 
183
- stamp login Agent:经 raft 做 PKCE 登录(无浏览器);人类:如何设置 STAMP_TOKEN
184
- stamp logout Agent:忘掉已存会话
185
- stamp whoami 网关认为你是谁
186
- stamp migration-help 旧 manifest action → CLI 对照
187
- stamp key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
188
- stamp identity bind --email ADDR 绑定提交作者邮箱(DCO)
189
- stamp receipt get <id> 网关接受与 GitHub 发表状态
190
- stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
191
- stamp pr list
192
- stamp pr view <编号|URL> --repo OWNER/REPO
193
- stamp pr diff <编号|URL> --repo OWNER/REPO [--name-only]
194
- stamp pr checks <编号|URL> --repo OWNER/REPO
195
- stamp repo clone <repository> [<directory>] [-- <gitflags>...]
216
+ {cli} login Agent:经 raft 做 PKCE 登录(无浏览器);人类:如何设置 STAMP_TOKEN
217
+ {cli} logout Agent:忘掉已存会话
218
+ {cli} whoami 网关认为你是谁
219
+ {cli} migration-help 旧 manifest action → CLI 对照
220
+ {cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
221
+ {cli} identity bind --email ADDR 绑定提交作者邮箱(DCO)
222
+ {cli} receipt get <id> 网关接受与 GitHub 发表状态
223
+ {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
224
+ {cli} pr list
225
+ {cli} pr view <编号|URL> --repo OWNER/REPO
226
+ {cli} pr diff <编号|URL> --repo OWNER/REPO [--name-only]
227
+ {cli} pr checks <编号|URL> --repo OWNER/REPO
228
+ {cli} pr comment <编号|URL> --repo OWNER/REPO --body-file FILE|- (本人 GitHub 身份)
229
+ {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
196
230
 
197
- stamp follow <owner/repo> --kind issue|pull --number N
198
- stamp unfollow <owner/repo> --kind issue|pull --number N
199
- stamp subscription pause|resume <owner/repo> --kind issue|pull --number N
200
- stamp subscriptions
201
- stamp watch <owner/repo> --event TYPE
202
- stamp unwatch <owner/repo> --event TYPE
231
+ {cli} follow <owner/repo> --kind issue|pull --number N
232
+ {cli} unfollow <owner/repo> --kind issue|pull --number N
233
+ {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N
234
+ {cli} subscriptions
235
+ {cli} watch <owner/repo> --event TYPE
236
+ {cli} unwatch <owner/repo> --event TYPE
203
237
 
204
238
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
205
239
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
206
240
 
207
241
  flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
208
- usageRepoClone: "用法:stamp repo clone <repository> [<directory>] [-- <gitflags>...]",
242
+ usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [-- <gitflags>...]",
209
243
  cloned: "已从 {url} 克隆 {repository}",
210
244
  cloneFailed: "经 Stamp 网关克隆 {repository} 失败",
211
245
  loginHumanIntro: "当前不是受管 Raft Agent。人类和 CI 使用 STAMP_TOKEN:",
@@ -216,18 +250,20 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
216
250
  logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
217
251
  enrolled: "已登记 {fingerprint}({keyId})",
218
252
  bound: "已绑定 {email}",
219
- usageKeyEnroll: "用法:stamp key enroll [--public-key FILE|-]",
220
- usageIdentityBind: "用法:stamp identity bind --email ADDR",
221
- usageReceiptGet: "用法:stamp receipt get <receipt-id>",
222
- usageFollow: "用法:stamp <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
223
- usageSubscription: "用法:stamp subscription pause|resume <owner/repo> --kind issue|pull --number N",
224
- usageWatch: "用法:stamp {cmd} <owner/repo> --event TYPE",
253
+ usageKeyEnroll: "用法:{cli} key enroll [--public-key FILE|-]",
254
+ usageIdentityBind: "用法:{cli} identity bind --email ADDR",
255
+ usageReceiptGet: "用法:{cli} receipt get <receipt-id>",
256
+ usageFollow: "用法:{cli} <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
257
+ usageSubscription: "用法:{cli} subscription pause|resume <owner/repo> --kind issue|pull --number N",
258
+ usageWatch: "用法:{cli} {cmd} <owner/repo> --event TYPE",
225
259
  helpInstall: "安装:{cmds}",
226
260
  helpAgentLogin: "Agent 登录:{text}",
227
- sessionRejected: "stamp: 会话被拒绝 — 请运行 `stamp login`",
228
- checkToken: "stamp: 请检查 STAMP_TOKEN",
229
- notLoggedIn: "尚未登录:请运行 `stamp login`(受管 Agent)",
230
- stampTokenMissing: "未设置 STAMP_TOKEN(会话或部署令牌);在受管 Agent 内请运行 `stamp login`",
261
+ sessionRejected: "{cli}: 会话被拒绝 — 请运行 `{cli} login`",
262
+ checkToken: "{cli}: 请检查 STAMP_TOKEN",
263
+ notLoggedIn: "尚未登录:请运行 `{cli} login`(受管 Agent)",
264
+ sessionOriginMismatch: "已存会话是给 {stored} 签发的,不是 {target}——请重新运行 `{cli} login`",
265
+ pair_mismatch: "拒绝不匹配的实例配对:{origin} 属于服务 {owner},而非 {service}(task #439)",
266
+ stampTokenMissing: "未设置 STAMP_TOKEN(会话或部署令牌);在受管 Agent 内请运行 `{cli} login`",
231
267
  admission_partial: "拒绝运行:受管 Agent 环境不完整({reason});不会回退到 STAMP_TOKEN",
232
268
  invoke_not_json: "agent-login: `raft integration invoke` 没有返回 JSON",
233
269
  invoke_not_object: "agent-login: invoke 输出不是对象",
@@ -276,9 +312,28 @@ export function selectLocale(env = process.env, explicit) {
276
312
  return "en";
277
313
  }
278
314
 
315
+ // The binary that targets THIS instance. Set once by the entry point (main());
316
+ // every command reference in the tables uses `{cli}` so user-visible copy names
317
+ // the binary the reader actually invoked — a staging user must never be told to
318
+ // run `stamp` (@phage: the error surface reaches users before the docs).
319
+ // Product names ("Stamp"), the package id and historical facts are NOT `{cli}`.
320
+ let cliName = "stamp";
321
+
322
+ export function setCliName(name) {
323
+ if (typeof name === "string" && name.length > 0) cliName = name;
324
+ }
325
+
326
+ /** The `<binary>:` banner that prefixes user-facing diagnostics. It names the
327
+ * binary the user actually ran, so a staging user sees `stamp-staging:` and not
328
+ * the production name (task #444 / #439). */
329
+ export function prefix() {
330
+ return `${cliName}: `;
331
+ }
332
+
279
333
  export function t(locale, key, vars = {}) {
280
334
  const table = messages[locale] || messages.en;
281
335
  let s = table[key] || messages.en[key] || key;
282
- for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, String(v));
336
+ const all = { cli: cliName, ...vars };
337
+ for (const [k, v] of Object.entries(all)) s = s.replaceAll(`{${k}}`, String(v));
283
338
  return s;
284
339
  }
package/lib/main.mjs CHANGED
@@ -5,19 +5,25 @@ import { createRequire } from "node:module";
5
5
  import { resolveAuth } from "./auth.mjs";
6
6
  import { makeClient, ApiError } from "./client.mjs";
7
7
  import { runAgentLogin } from "./agent-login.mjs";
8
- import { selectLocale, t } from "./locale.mjs";
8
+ import { basename } from "node:path";
9
+ import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
9
10
  import { pullRequestInput, pullRequestRecovery } from "./pull-request.mjs";
11
+ import { parsePRCommentArgs, validatePRCommentResult } from "./pr-comment.mjs";
10
12
  import {
11
13
  formatPRChecks,
12
14
  formatPRDetail,
13
15
  formatPRDiff,
14
16
  formatPRList,
17
+ formatPRListSections,
15
18
  parsePRDiffArgs,
16
19
  parsePRListArgs,
17
20
  parsePRTargetArgs,
18
21
  prChecksExitCode,
19
22
  prDetailPath,
23
+ PR_SECTIONS,
20
24
  prDiffPath,
25
+ prSection,
26
+ safeInline,
21
27
  validatePRDetail,
22
28
  validatePRDiff,
23
29
  validatePRListResponse,
@@ -25,6 +31,12 @@ import {
25
31
  import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone } from "./repo-clone.mjs";
26
32
  import { apiErrorGuidance, presentError } from "./errors.mjs";
27
33
 
34
+ function sectionLabels(locale) {
35
+ const labels = {};
36
+ for (const name of Object.values(PR_SECTIONS)) labels[`prSection_${name}`] = t(locale, `prSection_${name}`);
37
+ return labels;
38
+ }
39
+
28
40
  const require = createRequire(import.meta.url);
29
41
  const pkg = require("../package.json");
30
42
 
@@ -57,8 +69,8 @@ function objectArgs(args, locale) {
57
69
 
58
70
  function emitApiGuidance(error, locale, write) {
59
71
  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}`);
72
+ if (guidance.code && guidance.code !== error.body?.error) write(`${prefix()}${guidance.code}`);
73
+ if (guidance.action) write(`${prefix()}${guidance.action}`);
62
74
  // A typed code without a known/bounded action is not enough to suppress a
63
75
  // command-specific fallback (for example PR head-drift guidance).
64
76
  return Boolean(guidance.action);
@@ -71,7 +83,7 @@ export async function main(argv, opts) {
71
83
  const env = opts.env ?? process.env;
72
84
  const exit = opts.exit ?? ((code) => process.exit(code));
73
85
  // 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"]);
86
+ const localValues = new Set(["--public-key", "--email", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "-b", "-F", "-R"]);
75
87
  let json = false, langFlag, help = false, version = false;
76
88
  const commandArgs = [];
77
89
  for (let i = 0; i < args.length; i++) {
@@ -87,6 +99,12 @@ export async function main(argv, opts) {
87
99
  }
88
100
  args.splice(0, args.length, ...commandArgs);
89
101
  const locale = selectLocale(env, langFlag);
102
+ // The binary that targets THIS instance; every user-visible command reference
103
+ // follows it (usage, guidance, recovery). Derived from the invoked file so
104
+ // `stamp-staging` names itself — the error surface reaches users before docs.
105
+ const cliName = opts.cliName
106
+ ?? (opts.argv1 ? basename(opts.argv1).replace(/\.mjs$/, "") : "stamp");
107
+ setCliName(cliName);
90
108
  if (version) { out(pkg.version); return exit(0); }
91
109
  const cmd = args.shift();
92
110
  if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
@@ -94,9 +112,9 @@ export async function main(argv, opts) {
94
112
 
95
113
  let auth;
96
114
  try {
97
- auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale, service: env.STAMP_SERVICE || opts.serviceDefault || undefined });
115
+ auth = resolveAuth({ urlBase: opts.urlBase, urlExplicit: opts.urlExplicit, env, locale, service: env.STAMP_SERVICE || opts.serviceDefault || undefined, cliName });
98
116
  } catch (e) {
99
- err(`stamp: ${presentError(locale, e)}`);
117
+ err(`${prefix()}${presentError(locale, e)}`);
100
118
  return exit(1);
101
119
  }
102
120
  const api = makeClient(auth, opts.fetchImpl);
@@ -197,6 +215,20 @@ export async function main(argv, opts) {
197
215
  }
198
216
  case "pr": {
199
217
  const sub = args.shift();
218
+ if (sub === "comment") {
219
+ const input = parsePRCommentArgs(args);
220
+ try {
221
+ const result = validatePRCommentResult(await api("POST", input.path, input.body), input.target);
222
+ emit(result, () => out(t(locale, "prCommentCreated", { url: result.url, actor: result.actorLogin })));
223
+ } catch (e) {
224
+ // A lost/malformed success response may conceal a completed write.
225
+ // Never retry this command automatically or print submitted body.
226
+ err(`${prefix()}${t(locale, e instanceof ApiError && e.status >= 400 && e.status < 500 ? "prCommentRejected" : "prCommentOutcomeUnknown")}`);
227
+ if (e instanceof ApiError) emitApiGuidance(e, locale, err);
228
+ return exit(1);
229
+ }
230
+ return exit(0);
231
+ }
200
232
  if (sub === "create") {
201
233
  const input = pullRequestInput(args);
202
234
  try {
@@ -204,7 +236,7 @@ export async function main(argv, opts) {
204
236
  emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
205
237
  } catch (e) {
206
238
  if (e instanceof ApiError && e.status !== 401) {
207
- err(`stamp: ${e.message}`);
239
+ err(`${prefix()}${e.message}`);
208
240
  if (!emitApiGuidance(e, locale, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
209
241
  return exit(1);
210
242
  }
@@ -213,17 +245,33 @@ export async function main(argv, opts) {
213
245
  return exit(0);
214
246
  }
215
247
  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
- });
248
+ const { path, sections } = parsePRListArgs(args);
249
+ const paged = path.includes("limit=");
250
+ const d = validatePRListResponse(await api("GET", path), paged);
251
+ const labels = {
252
+ statusUnavailable: t(locale, "prStatusUnavailable"),
253
+ ci: t(locale, "prCIShort"),
254
+ agent: t(locale, "prAgentShort"),
255
+ ...sectionLabels(locale),
256
+ };
257
+ emit(
258
+ // The derived section is OPT-IN: a bare `--json` stays byte/structure
259
+ // back-compatible with the pre-section envelope, so a strict consumer
260
+ // never meets an unknown key. Only an explicit `--sections` adds it.
261
+ sections
262
+ ? { ...d, items: d.items.map((item) => ({ ...item, section: prSection(item) })) }
263
+ : d,
264
+ () => {
265
+ const lines = sections ? formatPRListSections(d, labels) : formatPRList(d, labels);
266
+ if (lines.length === 0) out(t(locale, "prListEmpty"));
267
+ else for (const line of lines) out(line);
268
+ // Surface the pagination continuation (a present cursor is never
269
+ // an error — it means "there is more"). The cursor is an untrusted
270
+ // wire string: strip terminal control sequences before writing it
271
+ // (the JSON path keeps the verified raw value).
272
+ if (d.nextCursor) out(t(locale, "prListMore", { cursor: safeInline(d.nextCursor) }));
273
+ },
274
+ );
227
275
  return exit(0);
228
276
  }
229
277
  if (sub === "view") {
@@ -297,12 +345,12 @@ export async function main(argv, opts) {
297
345
  }
298
346
  } catch (e) {
299
347
  if (e instanceof ApiError) {
300
- err(`stamp: ${e.message}`);
348
+ err(`${prefix()}${e.message}`);
301
349
  emitApiGuidance(e, locale, err);
302
350
  if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
303
351
  return exit(1);
304
352
  }
305
- err(`stamp: ${presentError(locale, e)}`);
353
+ err(`${prefix()}${presentError(locale, e)}`);
306
354
  return exit(1);
307
355
  }
308
356
  }
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { AgentError } from "./errors.mjs";
3
+ import { parsePRTargetArgs, prDetailPath } from "./pr-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
+ }
package/lib/pr-read.mjs CHANGED
@@ -73,9 +73,43 @@ 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/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
+
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
+ const path = query === "" ? "/v1/pr-inbox" : `/v1/pr-inbox?${query}`;
112
+ return { path, sections };
79
113
  }
80
114
 
81
115
  export function parsePRTargetArgs(input, usageCode = "usagePrRead") {
@@ -131,7 +165,7 @@ function requireSHA(value) {
131
165
  return sha;
132
166
  }
133
167
 
134
- function safeInline(value) {
168
+ export function safeInline(value) {
135
169
  return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]+/g, " ").replace(/\s+/g, " ").trim();
136
170
  }
137
171
 
@@ -141,7 +175,7 @@ function safeMultiline(value) {
141
175
  .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
142
176
  }
143
177
 
144
- export function validatePRListResponse(value) {
178
+ export function validatePRListResponse(value, paged = false) {
145
179
  const response = requireObject(value);
146
180
  if (!Array.isArray(response.items)) throw new AgentError("prReadInvalidResponse");
147
181
  for (const raw of response.items) {
@@ -164,7 +198,27 @@ export function validatePRListResponse(value) {
164
198
  }
165
199
  requireString(item.updatedAt);
166
200
  }
167
- if (response.nextCursor !== null || response.truncated !== false) throw new AgentError("prReadInvalidResponse");
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
+ }
168
222
  return response;
169
223
  }
170
224
 
@@ -234,6 +288,47 @@ export function validatePRDiff(value, expected) {
234
288
  return response;
235
289
  }
236
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
+
237
332
  export function formatPRList(response, labels = {}) {
238
333
  return response.items.map((item) => [
239
334
  safeInline(item.repository),
@@ -246,6 +341,39 @@ export function formatPRList(response, labels = {}) {
246
341
  ].join("\t"));
247
342
  }
248
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
+
249
377
  export function formatPRDetail(detail, labels) {
250
378
  const lines = [
251
379
  `${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.2",
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",