@botiverse/stamp-cli 0.3.7 → 0.3.9

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
@@ -2,7 +2,11 @@
2
2
 
3
3
  CLI for the Agent Git gateway. Bin `stamp`. Package `@botiverse/stamp-cli`.
4
4
  Session storage is `@botiverse/agent-session-store` (fail-closed Raft agent
5
- admission, atomic 0600 `auth.json`). Future public origin: `stamp.build`.
5
+ admission, atomic 0600 `auth.json`). Production origin: `https://stamp.build`.
6
+ The canonical Agent workflow is the instance-rendered
7
+ [`https://stamp.build/llms.txt`](https://stamp.build/llms.txt) (or
8
+ `https://staging.stamp.build/llms.txt` for staging); this package README explains
9
+ the command contracts but is not a second workflow source.
6
10
 
7
11
  ```sh
8
12
  npm i -g @botiverse/stamp-cli
@@ -14,22 +18,29 @@ stamp identity bind --email agent@example.com
14
18
  stamp repo clone org/repo
15
19
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/my-change
16
20
  stamp receipt get <id>
21
+ stamp receipt list
17
22
  stamp pr create --receipt <published-id> --repo org/repo --head agent/my-change --sha <exact-sha> --base main --title "My change" --body-file ./pr-body.md
18
23
  stamp pr list
19
24
  stamp pr view 123 --repo org/repo
25
+ stamp pr review 123 --repo org/repo
20
26
  stamp pr diff 123 --repo org/repo
21
27
  stamp pr checks 123 --repo org/repo
22
28
  stamp pr comment 123 --repo org/repo --body-file ./comment.md
29
+ stamp pr edit 123 --repo org/repo --title "Clearer title" --body-file ./pr-body.md
30
+ stamp pr approve 123 --repo org/repo --head <exact-head-sha> --base <exact-base-sha>
31
+ stamp pr unapprove 123 --repo org/repo --head <exact-head-sha> --base <exact-base-sha>
32
+ stamp pr merge 123 --repo org/repo --auto --head <exact-head-sha> --base <exact-base-sha>
23
33
  ```
24
34
 
25
35
  - Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
26
36
  - Human / CI: `STAMP_TOKEN`
27
- - Instance: `STAMP_URL` (default `https://staging.stamp.build`)
37
+ - Instance: `stamp` defaults to `https://stamp.build`; `stamp-staging` defaults
38
+ to `https://staging.stamp.build`; `STAMP_URL` overrides either explicitly
28
39
  - Raft app slug: `STAMP_SERVICE` (must match the gateway: `STAMP_SERVICE` or `RAFT_OAUTH_CLIENT_ID`; staging today is `raft-git-gateway-staging`, future `stamp`)
29
40
 
30
41
  Two installed bins, sharing one implementation:
31
42
 
32
- - `stamp` — default service slug `stamp` (the future production registration)
43
+ - `stamp` — production origin and service slug `stamp`
33
44
  - `stamp-staging` — pinned to today's staging registration: origin `https://staging.stamp.build`, service `raft-git-gateway-staging`, push remote `ssh://git@ssh.staging.stamp.build:443/...`; works with zero environment configuration
34
45
 
35
46
  Configuration layering is `environment > executable defaults`: `STAMP_URL` and
@@ -65,6 +76,14 @@ expanded to `refs/heads/...`; full refs also work. Use `--body-file -` for stdin
65
76
  `--body` for inline text. A non-empty description is required. `--json` prints the
66
77
  service receipt; a denial exits nonzero with recovery guidance.
67
78
 
79
+ Beginning with CLI 0.3.9, `--repo`, `--head`, and `--sha` may all be omitted.
80
+ The command waits up to 120 seconds for the push receipt to become `PUBLISHED`,
81
+ then derives those three coordinates from the receipt. If explicit coordinates
82
+ race asynchronous publication, it waits and retries exactly once with the same
83
+ idempotency key. A failed/rejected receipt stops immediately; a timeout says the
84
+ receipt is still accepted and the identical command is safe to rerun. CLI 0.3.8
85
+ and older require an explicit `PUBLISHED` receipt's repository, ref, and SHA.
86
+
68
87
  The read-only PR commands follow the familiar `gh pr` command group while
69
88
  reading through Stamp rather than a local GitHub credential:
70
89
 
@@ -79,6 +98,57 @@ reading through Stamp rather than a local GitHub credential:
79
98
  - `--json` returns the service's validated machine envelope. Human-formatted
80
99
  output strips terminal control characters from provider-authored text.
81
100
 
101
+ `stamp pr edit` changes the title, description, or both on a PR the current
102
+ Agent created through Stamp. Ownership comes from Stamp's durable creation
103
+ receipt, not the shared GitHub App author: another Agent, another Raft Server,
104
+ or a PR opened outside Stamp is refused before any provider write. Updating the
105
+ description regenerates the protected Stamp attribution/footer; callers supply
106
+ only their description text. If the provider outcome cannot be confirmed, the
107
+ command exits nonzero and requires a PR re-read before any retry.
108
+
109
+ ### Approving as an Agent
110
+
111
+ With an Agent session, `stamp pr approve` records the approval **in Stamp** (a
112
+ durable receipt), not as a GitHub review: PRs opened through Stamp are authored
113
+ on GitHub by the shared App, so an App review would read as self-approval.
114
+ `--head` and `--base` must be the exact current SHAs (a move is refused with
115
+ `PR_HEAD_MOVED` / `PR_BASE_MOVED`), the approval counts only for that head, the
116
+ PR's own author is refused (`SELF_APPROVAL_NOT_ALLOWED`), and there is no
117
+ `--body`. `stamp pr unapprove` withdraws it. With a human session, `stamp pr
118
+ approve` submits a GitHub review as the bound user, as before.
119
+
120
+ ### Merging as an Agent
121
+
122
+ With an Agent session, `stamp pr merge` works once there is an independent
123
+ approval of the PR's exact current head from someone other than its author
124
+ (another Agent's Stamp approval, or a GitHub approval from a human with write
125
+ access) and no outstanding request for changes; otherwise it is refused with
126
+ `PR_NOT_APPROVED` and the reasons. The author may merge too, once someone else
127
+ approved. `--head` and `--base` must be the exact current SHAs (`PR_HEAD_MOVED` /
128
+ `PR_BASE_MOVED`). The merge happens as the **Stamp App**, pinned to that head, so
129
+ GitHub refuses it if the head moved; GitHub's branch protection still applies.
130
+ The result names `mergedBy: "stamp-app"` and the merging Agent.
131
+
132
+ The PR's author normally registers auto-merge immediately after creation:
133
+
134
+ ```sh
135
+ stamp pr merge 123 -R org/repo --auto --head <exact-head-sha> --base <exact-base-sha>
136
+ ```
137
+
138
+ This records intent; it is not approval. Stamp merges only when another
139
+ principal approves that exact head and the pinned verdict is `READY`. A new push
140
+ makes the registration `VOID`; re-read, get a new independent review, and have
141
+ the author register the new coordinates. Read the current state with `--auto
142
+ --status` and withdraw an unchanged registration with `--auto --cancel --head
143
+ ... --base ...`.
144
+
145
+ `stamp pr close` withdraws a PR the current Agent created through Stamp, under
146
+ the same receipt-ownership gate as `pr edit` — another Agent, another Raft
147
+ Server, or a PR opened outside Stamp is refused before any provider write, and
148
+ an already-closed or merged PR is reported as not open rather than as a silent
149
+ success. If the provider outcome cannot be confirmed, the command exits nonzero
150
+ and requires a PR re-read before any retry.
151
+
82
152
  ### Ordinary PR comments
83
153
 
84
154
  `stamp pr comment 123 -R org/repo --body-file ./comment.md` uses a **human Stamp
@@ -110,3 +180,21 @@ remain available to service clients. `stamp migration-help` maps retired action
110
180
  names to commands. The retirement follows the Stamp owner's explicit cutover
111
181
  decision; the general Raft migration guide's optional compatibility period is
112
182
  over for this service.
183
+
184
+ ### Agent merge queue
185
+
186
+ Use `stamp pr queue enqueue <NUMBER -R OWNER/REPO|PR_URL> --request-id ID --head SHA --base SHA`
187
+ for an enabled native queue. Choose and save a 16–128 character request ID before
188
+ sending (letters/digits/underscore/hyphen, first character alphanumeric).
189
+ Independent approval of the current head is required; this accepts a request,
190
+ not a promise to merge. Use `stamp pr queue status ... --request-id ID --json`
191
+ to reconcile an uncertain reply, and `stamp pr queue withdraw ... --request-id ID`
192
+ to withdraw it. Reuse the same ID and coordinates; never create a new ID to retry
193
+ a lost response. Receipt reads/withdrawal are limited to the original agent and
194
+ server. Only requests still waiting can be withdrawn. Once a request enters a running
195
+ batch, withdrawal returns `QUEUE_BATCH_IN_FLIGHT` without canceling any member;
196
+ wait for completion and read the same request ID. Terminal receipts
197
+ retain verified landing SHA; `notificationQueued` is not delivery confirmation.
198
+ New admission requires the existing notification worker configured. This is a
199
+ source capability, not a claim that the deployment enables queues or delivery.
200
+ See [the queue contract](../docs/batch-merge-queue.md#agent-queue-requests).
@@ -10,6 +10,7 @@ import {
10
10
  sshCommandFor,
11
11
  writePinnedKnownHosts,
12
12
  } from "../repo/ssh.mjs";
13
+ import { readRecordedIdentity } from "../repo/identities.mjs";
13
14
 
14
15
  // The SSH fingerprint of a known_hosts line: base64(sha256(raw key)), which is
15
16
  // what `ssh-keygen -lf` prints and what an announcement quotes. Printing it is
@@ -101,7 +102,12 @@ export async function run(ctx) {
101
102
  written: knownHostsPath,
102
103
  effective: probe.effective.raw,
103
104
  sshCommand: sshCommandFor({
104
- identityPath: resolveIdentityPath(ctx.env, ""),
105
+ // The key this instance enrolled (task #645, cross dogfooding #643):
106
+ // suggesting ~/.ssh/id_ed25519 to an agent that enrolled another key
107
+ // turns a host-key fix into a publickey denial. Same order as
108
+ // `repo clone`: STAMP_SSH_IDENTITY, then the recorded key, then the
109
+ // default path.
110
+ identityPath: resolveIdentityPath(ctx.env, "", readRecordedIdentity(ctx.env, ctx.auth?.apiBase)),
105
111
  knownHostsPath,
106
112
  }),
107
113
  }));
@@ -1,10 +1,15 @@
1
+ import { formatAutoMerge, isAutoMergeArgs, parsePRAutoMergeArgs, validatePRAutoMergeResult } from "../pr/write.mjs";
2
+ import { formatVerdictLine } from "../pr/verdict.mjs";
3
+ import { parsePRQueueArgs, validatePRQueueResult } from "../pr/queue.mjs";
1
4
  import { t, prefix } from "../locale.mjs";
2
5
  import { ApiError, NetworkError } from "../client.mjs";
3
6
  import { AgentError, printGatewayError } from "../errors.mjs";
4
- import { pullRequestInput, pullRequestRecovery } from "../pr/create.mjs";
7
+ import { publishWaitMs, pullRequestDraft, pullRequestNextLines, pullRequestInput, pullRequestNeedsReceipt, pullRequestRecovery, waitForPublishedReceipt } from "../pr/create.mjs";
5
8
  import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
9
+ import { parsePREditArgs, validatePREditResult } from "../pr/edit.mjs";
10
+ import { parsePRCloseArgs, validatePRCloseResult } from "../pr/close.mjs";
6
11
  import { formatPRReview, reviewBrief } from "../pr/review.mjs";
7
- import { parsePRApproveArgs, parsePRMergeArgs, validatePRApproveResult, validatePRMergeResult } from "../pr/write.mjs";
12
+ import { parsePRApproveArgs, parsePRMergeArgs, parsePRUnapproveArgs, validatePRApproveResult, validatePRMergeResult, validatePRUnapproveResult } from "../pr/write.mjs";
8
13
  import {
9
14
  formatPRChecks,
10
15
  formatPRDetail,
@@ -58,6 +63,14 @@ async function writeCommand(ctx, run) {
58
63
  export async function run(ctx) {
59
64
  const { args, api, emit, out, err, locale, exit } = ctx;
60
65
  const sub = args.shift();
66
+ if (sub === "queue") {
67
+ ctx.unknownKey = "prQueueOutcomeUnknown";
68
+ return writeCommand(ctx, async () => {
69
+ const input = parsePRQueueArgs(args);
70
+ const result = validatePRQueueResult(await api(input.method, input.path, input.body), input);
71
+ emit(result, () => out(t(locale, "prQueueReceipt", { repository: result.repository, number: result.number, id: result.requestId, state: result.receipt.state, reason: result.receipt.reason || "—", landing: result.receipt.landingSha || "—", queued: String(result.receipt.notificationQueued) })));
72
+ });
73
+ }
61
74
  if (sub === "comment") {
62
75
  ctx.rejectKey = "prCommentRejected";
63
76
  ctx.unknownKey = "prCommentOutcomeUnknown";
@@ -73,7 +86,27 @@ export async function run(ctx) {
73
86
  return writeCommand(ctx, async () => {
74
87
  const input = parsePRApproveArgs(args);
75
88
  const result = validatePRApproveResult(await api(input.method, input.path, input.body), input.target);
76
- emit(result, () => out(t(locale, "prApproved", { actor: result.reviewerLogin, repository: result.repository, number: result.number })));
89
+ emit(result, () => out(result.recordedBy === "stamp"
90
+ ? t(locale, "prApprovedByStamp", { actor: result.reviewer, repository: result.repository, number: result.number, head: result.approvedHead })
91
+ : t(locale, "prApproved", { actor: result.reviewerLogin, repository: result.repository, number: result.number })));
92
+ });
93
+ }
94
+ if (sub === "unapprove") {
95
+ ctx.rejectKey = "prUnapproveRejected";
96
+ ctx.unknownKey = "prUnapproveOutcomeUnknown";
97
+ return writeCommand(ctx, async () => {
98
+ const input = parsePRUnapproveArgs(args);
99
+ const result = validatePRUnapproveResult(await api(input.method, input.path, input.body), input.target);
100
+ emit(result, () => out(t(locale, "prUnapproved", { actor: result.reviewer, repository: result.repository, number: result.number, head: result.approvedHead })));
101
+ });
102
+ }
103
+ if (sub === "merge" && isAutoMergeArgs(args)) {
104
+ ctx.rejectKey = "prMergeRejected";
105
+ ctx.unknownKey = "prMergeOutcomeUnknown";
106
+ return writeCommand(ctx, async () => {
107
+ const input = parsePRAutoMergeArgs(args);
108
+ const result = validatePRAutoMergeResult(await api(input.method, input.path, input.body), input.target);
109
+ emit(result, () => out(formatAutoMerge(result, (key, vars) => t(locale, key, vars))));
77
110
  });
78
111
  }
79
112
  if (sub === "merge") {
@@ -82,14 +115,55 @@ export async function run(ctx) {
82
115
  return writeCommand(ctx, async () => {
83
116
  const input = parsePRMergeArgs(args);
84
117
  const result = validatePRMergeResult(await api(input.method, input.path, input.body), input.target);
85
- emit(result, () => out(t(locale, "prMerged", { actor: result.actorLogin, sha: result.mergeSha, repository: result.repository, number: result.number })));
118
+ emit(result, () => out(result.mergedBy === "stamp-app"
119
+ ? t(locale, "prMergedByApp", { actor: result.agent, sha: result.mergeSha, repository: result.repository, number: result.number, head: result.mergedHead })
120
+ : t(locale, "prMerged", { actor: result.actorLogin, sha: result.mergeSha, repository: result.repository, number: result.number })));
121
+ });
122
+ }
123
+ if (sub === "close") {
124
+ ctx.rejectKey = "prCloseRejected";
125
+ ctx.unknownKey = "prCloseOutcomeUnknown";
126
+ return writeCommand(ctx, async () => {
127
+ const input = parsePRCloseArgs(args);
128
+ const result = validatePRCloseResult(await api(input.method, input.path), input.target);
129
+ emit(result, () => out(t(locale, "prClosed", { repository: result.repository, number: result.number, url: result.url })));
130
+ });
131
+ }
132
+ if (sub === "edit") {
133
+ ctx.rejectKey = "prEditRejected";
134
+ ctx.unknownKey = "prEditOutcomeUnknown";
135
+ return writeCommand(ctx, async () => {
136
+ const input = parsePREditArgs(args);
137
+ const result = validatePREditResult(await api("PATCH", input.path, input.body), input.target);
138
+ emit(result, () => out(t(locale, "prEdited", { repository: result.repository, number: result.number, url: result.url })));
86
139
  });
87
140
  }
88
141
  if (sub === "create") {
89
- const input = pullRequestInput(args);
142
+ const waitOpts = process.env.STAMP_PUBLISH_WAIT_MS ? { timeoutMs: publishWaitMs(process.env.STAMP_PUBLISH_WAIT_MS), intervalMs: 50 } : {};
143
+ // Validate everything that needs no network first, as before. One draft
144
+ // serves both builds, so the body is read once (see pullRequestDraft).
145
+ const draft = pullRequestDraft(args);
146
+ let input = pullRequestInput(args, pullRequestNeedsReceipt(args) ? { repository: "o/r", targetRef: "refs/heads/x", publishedSha: "0".repeat(40) } : null, draft);
147
+ let waited = false;
148
+ if (pullRequestNeedsReceipt(args)) {
149
+ input = pullRequestInput(args, await waitForPublishedReceipt(api, input.receiptId, waitOpts), draft);
150
+ waited = true;
151
+ }
90
152
  try {
91
- const d = await api("POST", "/v1/pull-requests", input);
92
- emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
153
+ let d;
154
+ try {
155
+ d = await api("POST", "/v1/pull-requests", input);
156
+ } catch (e) {
157
+ // Created too soon after the push: wait for publication, then retry
158
+ // once with the same idempotency key.
159
+ if (waited || !(e instanceof ApiError) || e.body?.error !== "PUBLISHED_RECEIPT_NOT_FOUND") throw e;
160
+ await waitForPublishedReceipt(api, input.receiptId, waitOpts);
161
+ d = await api("POST", "/v1/pull-requests", input);
162
+ }
163
+ emit(d, () => {
164
+ out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url }));
165
+ for (const line of pullRequestNextLines(d, ctx.auth?.apiBase, (key, vars) => t(locale, key, vars))) out(line);
166
+ });
93
167
  } catch (e) {
94
168
  if (e instanceof ApiError && e.status !== 401) {
95
169
  err(`${prefix()}${e.message}`);
@@ -128,6 +202,7 @@ export async function run(ctx) {
128
202
  const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
129
203
  emit(d, () => {
130
204
  for (const line of formatPRDetail(d, {
205
+ verdictLine: d.verdict ? formatVerdictLine(d.verdict, (key) => t(locale, key)) : "",
131
206
  head: t(locale, "prHeadLabel"),
132
207
  checks: t(locale, "prChecksLabel"),
133
208
  ciUnreadable: t(locale, "prCIUnreadable"),
@@ -1,7 +1,24 @@
1
1
  import { t } from "../locale.mjs";
2
+ import { formatReceiptLine, parseReceiptListArgs, validateReceiptList } from "../receipt/list.mjs";
2
3
 
3
4
  export async function run(ctx) {
4
5
  const sub = ctx.args.shift();
6
+ if (sub === "list") {
7
+ const { path } = parseReceiptListArgs(ctx.args);
8
+ const d = validateReceiptList(await ctx.api("GET", path));
9
+ ctx.emit(d, () => {
10
+ if (d.items.length === 0) {
11
+ ctx.out(t(ctx.locale, "receiptListEmpty"));
12
+ } else {
13
+ for (const item of d.items) {
14
+ ctx.out(formatReceiptLine(item));
15
+ if (item.lastError) ctx.out(` last error: ${item.lastError}`);
16
+ }
17
+ }
18
+ if (d.nextCursor) ctx.out(t(ctx.locale, "receiptListMore", { cursor: d.nextCursor }));
19
+ });
20
+ return ctx.exit(0);
21
+ }
5
22
  const id = ctx.args.shift();
6
23
  if (sub !== "get" || !id) throw new Error(t(ctx.locale, "usageReceiptGet"));
7
24
  const d = await ctx.api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
package/lib/locale.mjs CHANGED
@@ -1,8 +1,11 @@
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: {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|review|diff|checks|comment|approve|merge> [arguments]",
4
+ usagePrQueue: "usage: {cli} pr queue <enqueue|status|withdraw> <NUMBER -R OWNER/REPO|PR_URL> --request-id ID [--head SHA --base SHA (enqueue only)]; ID: 16–128 letters/digits/underscore/hyphen, first alphanumeric; choose it before sending and retain it",
5
+ prQueueOutcomeUnknown: "Queue outcome is unknown. Read pr queue status with the same PR and --request-id before another write; do not generate a new ID or automatically resend.",
6
+ prQueueReceipt: "Queue {repository}#{number}, request {id}: {state}; reason: {reason}; landing: {landing}; terminal notification queued: {queued} (not delivery confirmation)",
7
+ 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]; without --repo/--head/--sha they come from the published receipt",
8
+ usagePrRead: "usage: {cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [arguments]",
6
9
  usagePrReview: "usage: {cli} pr review <number|URL> [--repo OWNER/REPO] — the exact head to pin, base, merge-base, checks, and the diff/patch-id commands against the merge-base",
7
10
  prReviewExactHead: "Exact head",
8
11
  prReviewBase: "Base",
@@ -10,15 +13,28 @@ export const messages = {
10
13
  prReviewMergeBaseRule: "log, stat, diff and patch-id against the merge-base, never against the current base: the base branch may have advanced since this branch forked, and those commits would show up as the PR's",
11
14
  prReviewCommands: "Local review (after cloning through Stamp)",
12
15
  prReviewVerdict: "Verdict to post",
13
- usagePrApprove: "usage: {cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT] (human GitHub identity required)",
14
- usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (human GitHub identity required)",
16
+ usagePrApprove: "usage: {cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT] (human: GitHub review; agent: recorded by Stamp, no --body)",
17
+ usagePrUnapprove: "usage: {cli} pr unapprove <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA (agent: withdraws your Stamp-recorded approval of that head)",
18
+ usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (human: as your GitHub identity; agent: as the Stamp App, once someone other than the author approved that exact head)\n {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --auto --head SHA --base SHA [--method ...] | --auto --cancel --head SHA --base SHA | --auto --status (author agent: let Stamp merge once someone else approves that head and the verdict is READY)",
15
19
  prApproved: "Approved {repository}#{number} as {actor}",
20
+ prApprovedByStamp: "Approved {repository}#{number} at {head} as {actor} (recorded by Stamp)",
21
+ prUnapproved: "Withdrew approval of {repository}#{number} at {head} as {actor} (recorded by Stamp)",
16
22
  prMerged: "Merged {repository}#{number} as {actor} ({sha})",
17
- prApproveRejected: "Approve was rejected. Check your human session, GitHub binding, repository access, and --head/--base.",
18
- prMergeRejected: "Merge was rejected. Check your human session, GitHub binding, repository access, --head/--base, and mergeability.",
23
+ prMergedByApp: "Merged {repository}#{number} at {head} as the Stamp App for {actor} ({sha})",
24
+ prAutoMerge_ARMED: "{repository}#{number} will be merged by Stamp ({method}) at head {head} once someone other than the author approves it and the verdict is READY",
25
+ prAutoMerge_VOID: "{repository}#{number}: the auto-merge registration was for head {head}, which the PR no longer has; register again for the current head",
26
+ prAutoMerge_CANCELLED: "{repository}#{number}: auto-merge withdrawn",
27
+ prAutoMerge_NONE: "{repository}#{number}: not registered for auto-merge",
28
+ prAutoMerge_CLOSED: "{repository}#{number} is closed or merged; the auto-merge registration has nothing left to do",
29
+ prAutoMerge_EXPIRED: "{repository}#{number}: the auto-merge registration expired (registered more than 14 days ago); register again",
30
+ prAutoMergeUnchanged: "(nothing changed)",
31
+ prApproveRejected: "Approve was rejected. Check your session, repository access, and --head/--base (a human also needs a GitHub binding; an agent cannot approve a PR it opened).",
32
+ prMergeRejected: "Merge was rejected. Check your session, repository access, --head/--base, the approval (an agent merge needs an approval of that exact head from someone other than the author), and mergeability (a human also needs a GitHub binding).",
19
33
  prApproveOutcomeUnknown: "Approve outcome is unknown. Re-read the PR reviews before sending again; do not automatically resend.",
34
+ prUnapproveRejected: "Unapprove was rejected. Check your agent session, repository access, and --head/--base.",
35
+ prUnapproveOutcomeUnknown: "Unapprove outcome is unknown. Retry the same command; it is idempotent.",
20
36
  prMergeOutcomeUnknown: "Merge outcome is unknown. Re-read the PR before sending again; do not automatically resend.",
21
- apiHumanPrincipal: "Agents cannot approve or merge. Use a human STAMP_TOKEN session.",
37
+ apiHumanPrincipal: "This action needs a human STAMP_TOKEN session.",
22
38
  apiWriteCoords: "Re-read the PR and retry with both --head and --base.",
23
39
  apiGitHubBinding: "Bind your GitHub account in Stamp settings, then retry.",
24
40
  usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) [--expected-head SHA] (a human posts as their bound GitHub identity; an agent posts as the Stamp App with an attribution line naming the agent; with --expected-head the comment is refused if the pull request has moved)",
@@ -27,6 +43,16 @@ export const messages = {
27
43
  prCommentCreated: "Comment posted as {actor}: {url}",
28
44
  prCommentRejected: "Comment request was rejected. Check your session, GitHub binding (humans), repository access and input.",
29
45
  prCommentOutcomeUnknown: "Comment outcome is unknown. Check the PR comments before sending again; do not automatically resend.",
46
+ usagePrEdit: "usage: {cli} pr edit <NUMBER -R OWNER/REPO|PR_URL> [--title TITLE] [--body TEXT|--body-file FILE|-] (only the agent recorded on Stamp's creation receipt may edit; provide title, body, or both)",
47
+ usagePrClose: "usage: {cli} pr close <NUMBER -R OWNER/REPO|PR_URL> (only the agent recorded on Stamp's creation receipt may close)",
48
+ prClosed: "Closed {repository}#{number}: {url}",
49
+ prCloseRejected: "PR close was rejected. Confirm this agent created the PR through Stamp and still has repository access.",
50
+ prCloseOutcomeUnknown: "PR close outcome is unknown. Re-read the PR before deciding whether to send the close again; do not automatically resend.",
51
+ prEditTitleInvalid: "PR title must be nonempty and at most 256 bytes of UTF-8 text.",
52
+ prEditBodyInvalid: "PR description must be nonempty and at most 64 KiB of UTF-8 text.",
53
+ prEdited: "Updated {repository}#{number}: {url}",
54
+ prEditRejected: "PR edit was rejected. Confirm this agent created the PR through Stamp and still has repository access.",
55
+ prEditOutcomeUnknown: "PR edit outcome is unknown. Re-read the PR before deciding whether to send the edit again; do not automatically resend.",
30
56
  usagePrList: "usage: {cli} pr list",
31
57
  usagePrView: "usage: {cli} pr view <number|URL> [--repo OWNER/REPO]",
32
58
  usagePrDiff: "usage: {cli} pr diff <number|URL> [--repo OWNER/REPO] [--name-only]",
@@ -46,6 +72,23 @@ export const messages = {
46
72
  prChecksUnreadable: "Checks could not be read for this pull request, so this is not \"no checks\" — the gateway was refused by GitHub (most often a missing Checks permission on the app). Treat CI as unknown.",
47
73
  prCIUnreadable: "unreadable",
48
74
  prVerdictCIUnreadable: "CI unreadable — not evidence of green",
75
+ prVerdictLabel: "Stamp verdict",
76
+ verdict_READY: "can land now",
77
+ verdict_MERGED: "already merged",
78
+ verdict_CLOSED: "closed",
79
+ verdict_DRAFT: "draft",
80
+ verdict_CONFLICT: "conflicts with the base",
81
+ verdict_CI_UNREADABLE: "CI cannot be read — not evidence of green",
82
+ verdict_CI_FAILING: "a required check failed",
83
+ verdict_CI_NOT_EXECUTED: "a required check did not run",
84
+ verdict_CI_PENDING: "required checks still running",
85
+ verdict_REVIEW_UNREADABLE: "the approval state cannot be read",
86
+ verdict_CHANGES_REQUESTED: "changes requested",
87
+ verdict_STALE_REVIEW: "approvals are for another head or base",
88
+ verdict_NEEDS_REVIEW: "needs a non-author approval at this head",
89
+ verdict_BEHIND: "behind the base",
90
+ verdict_BLOCKED: "GitHub blocks the merge for a reason Stamp cannot see",
91
+ verdict_UNCONFIRMED: "GitHub does not confirm a clean merge (a check is not passing, or it is still computing)",
49
92
  prReadNotFound: "Check the repository and PR number, and confirm this Agent created the PR through Stamp.",
50
93
  prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
51
94
  prReadDiffIncomplete: "GitHub did not return the complete PR diff; retry later instead of relying on partial files.",
@@ -71,9 +114,15 @@ export const messages = {
71
114
  prIdempotency: "--idempotency-key must contain 16–128 letters, digits, dots, underscores, colons, or hyphens.",
72
115
  prCreated: "Created PR #{number}: {url}",
73
116
  prExisting: "Existing PR #{number}: {url}",
117
+ prStampPage: " Stamp: {page}",
118
+ prNextAutoMerge: " Next: {cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (Stamp merges it once someone other than you approves this head and the verdict is READY)",
74
119
  prWaitPublished: "Check {cli} receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
120
+ prReceiptNotPublished: "Receipt {id} is {status}; it will not be published, so no pull request can be opened from it. See {cli} receipt get {id}.",
121
+ prPublishTimeout: "Receipt {id} is still {status} after waiting for GitHub publication; run the same command again later, or check {cli} receipt get {id}.",
122
+ prReceiptIncomplete: "Receipt {id} is published but lacks its repository, ref or commit; pass --repo, --head and --sha explicitly.",
75
123
  prCheckReceipt: "Read the receipt again and check --repo, --head and --sha against the exact published commit.",
76
124
  prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
125
+ prCheckBase: "The base branch does not exist on GitHub. Pass --base as an existing branch of the repository.",
77
126
  prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
78
127
  prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
79
128
  apiBindIdentity: "Bind this agent first with `{cli} identity bind --email <agent-email>`, then retry the command.",
@@ -93,15 +142,21 @@ export const messages = {
93
142
  {cli} known-hosts refresh re-pin this instance's SSH host key from /.well-known
94
143
  {cli} identity bind --email ADDR bind commit-author email (DCO)
95
144
  {cli} receipt get <id> gateway acceptance + GitHub publication status
145
+ {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]
146
+ list your own push receipts (newest first)
96
147
  {cli} changelog [--limit N] [--all] release history: CLI/API changes per version (--all: everything)
97
- {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
148
+ {cli} pr create --receipt ID [--repo OWNER/REPO --head BRANCH --sha SHA] --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
98
149
  {cli} pr list
99
150
  {cli} pr view <number|URL> --repo OWNER/REPO
100
151
  {cli} pr diff <number|URL> --repo OWNER/REPO [--name-only]
101
152
  {cli} pr checks <number|URL> --repo OWNER/REPO
102
- {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human)
103
- {cli} pr approve <number|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (human)
104
- {cli} pr merge <number|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (human)
153
+ {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human; agent posts as the Stamp App)
154
+ {cli} pr edit <number|URL> --repo OWNER/REPO [--title TITLE] [--body-file FILE|-] (creating agent only)
155
+ {cli} pr approve <number|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (human; agent without --body)
156
+ {cli} pr unapprove <number|URL> --repo OWNER/REPO --head SHA --base SHA (agent)
157
+ {cli} pr merge <number|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (human; agent once approved by another)
158
+ {cli} pr merge <number|URL> --repo OWNER/REPO --auto --head SHA --base SHA (author agent: merge once someone else approves)
159
+ {cli} pr queue enqueue|status|withdraw <number|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent; coordinates required for enqueue)
105
160
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
106
161
 
107
162
  {cli} follow <owner/repo> --kind issue|pull --number N
@@ -114,7 +169,8 @@ export const messages = {
114
169
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
115
170
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
116
171
 
117
- flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
172
+ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG
173
+ docs: {docs} (the agent workflow, step by step)`,
118
174
  usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
119
175
  cloned: "Cloned {repository} from {url}",
120
176
  cloneCommitTrailers: "Every commit you push here must end with these trailers, as one block at the very end with no blank line between them (GitHub only reads the last contiguous block):",
@@ -155,6 +211,10 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
155
211
  keyRevoked: "revoked {keyId}",
156
212
  usageIdentityBind: "usage: {cli} identity bind --email ADDR",
157
213
  usageReceiptGet: "usage: {cli} receipt get <receipt-id>",
214
+ usageReceiptList: "usage: {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]",
215
+ receiptListEmpty: "no receipts",
216
+ receiptListMore: "More receipts; rerun with --limit and --cursor {cursor}.",
217
+ receiptListBadResponse: "Unexpected receipt list response; check {cli} and gateway versions, then retry.",
158
218
  usageChangelog: "usage: {cli} changelog [--limit N] [--all]",
159
219
  changelogScopeAgent: "Showing CLI and API changes; --all shows everything.",
160
220
  changelogScopeAll: "Showing every change, including the web app and internal work.",
@@ -221,8 +281,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
221
281
  refresh_wait_timeout: "agent-login: timed out waiting for a concurrent token refresh",
222
282
  },
223
283
  "zh-CN": {
224
- 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]",
225
- usagePrRead: "用法:{cli} pr <list|view|review|diff|checks|comment|approve|merge> [参数]",
284
+ usagePrQueue: "用法:{cli} pr queue <enqueue|status|withdraw> <NUMBER -R OWNER/REPO|PR_URL> --request-id ID [--head SHA --base SHA(仅 enqueue)];ID 为 16–128 位字母、数字、下划线或连字符,首位为字母或数字;发送前选定并保留",
285
+ prQueueOutcomeUnknown: "队列操作结果未知。再次写入前,用同一 PR 和 --request-id 执行 pr queue status;不要生成新 ID 或自动重发。",
286
+ prQueueReceipt: "队列 {repository}#{number},请求 {id}:{state};原因:{reason};落地:{landing};终态通知已入队:{queued}(不代表送达)",
287
+ 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];省略 --repo/--head/--sha 时从已发布的 receipt 读取",
288
+ usagePrRead: "用法:{cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [参数]",
226
289
  usagePrReview: "用法:{cli} pr review <编号|URL> [--repo OWNER/REPO] —— 要钉的 exact head、base、merge-base、检查,以及对 merge-base 做 diff/patch-id 的命令",
227
290
  prReviewExactHead: "Exact head",
228
291
  prReviewBase: "Base",
@@ -230,15 +293,28 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
230
293
  prReviewMergeBaseRule: "log/stat/diff/patch-id 一律对 merge-base,不要对当前 base:base 分支可能在分叉后已前进,那些提交会被当成这张 PR 的",
231
294
  prReviewCommands: "本地复核(经 Stamp clone 之后)",
232
295
  prReviewVerdict: "要贴的判词",
233
- usagePrApprove: "用法:{cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT](需要本人 GitHub 身份)",
234
- usagePrMerge: "用法:{cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase](需要本人 GitHub 身份)",
296
+ usagePrApprove: "用法:{cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT](人类:GitHub review;Agent:由 Stamp 记录,不带 --body)",
297
+ usagePrUnapprove: "用法:{cli} pr unapprove <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA(Agent:撤回你在该 head 上由 Stamp 记录的批准)",
298
+ usagePrMerge: "用法:{cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase](人类:以本人 GitHub 身份;agent:以 Stamp App 身份,前提是作者以外的人已批准该 exact head)\n {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --auto --head SHA --base SHA [--method ...] | --auto --cancel --head SHA --base SHA | --auto --status (作者 agent:别人批准该 head 且判定为 READY 后由 Stamp 自动合入)",
235
299
  prApproved: "已以 {actor} 身份批准 {repository}#{number}",
300
+ prApprovedByStamp: "已以 {actor} 身份批准 {repository}#{number} 的 {head}(由 Stamp 记录)",
301
+ prUnapproved: "已以 {actor} 身份撤回对 {repository}#{number} 的 {head} 的批准(由 Stamp 记录)",
236
302
  prMerged: "已以 {actor} 身份合并 {repository}#{number}({sha})",
237
- prApproveRejected: "批准被拒绝。请检查人类会话、GitHub 绑定、仓库权限,以及 --head/--base。",
238
- prMergeRejected: "合并被拒绝。请检查人类会话、GitHub 绑定、仓库权限、--head/--base 和可合并性。",
303
+ prMergedByApp: "已代 {actor} 以 Stamp App 身份合并 {repository}#{number},head {head}({sha})",
304
+ prAutoMerge_ARMED: "{repository}#{number} 已登记:一旦作者以外的人批准 head {head} 且判定为 READY,Stamp 就以 {method} 方式合入",
305
+ prAutoMerge_VOID: "{repository}#{number}:自动合入登记针对的是 head {head},PR 已经不在这个 head 上了;请对当前 head 重新登记",
306
+ prAutoMerge_CANCELLED: "{repository}#{number}:自动合入已撤销",
307
+ prAutoMerge_NONE: "{repository}#{number}:没有登记自动合入",
308
+ prAutoMerge_CLOSED: "{repository}#{number} 已关闭或已合入,自动合入登记无事可做",
309
+ prAutoMerge_EXPIRED: "{repository}#{number}:自动合入登记已过期(超过 14 天),请重新登记",
310
+ prAutoMergeUnchanged: "(没有变化)",
311
+ prApproveRejected: "批准被拒绝。请检查会话、仓库权限,以及 --head/--base(人类还需要绑定 GitHub;Agent 不能批准自己开的 PR)。",
312
+ prMergeRejected: "合并被拒绝。请检查会话、仓库权限、--head/--base、批准(agent 合并需要作者以外的人批准该 exact head)和可合并性(人类还需要 GitHub 绑定)。",
239
313
  prApproveOutcomeUnknown: "批准结果不明。请先重读 PR 的 reviews,不要自动重发。",
314
+ prUnapproveRejected: "撤回批准被拒绝。请检查 Agent 会话、仓库权限,以及 --head/--base。",
315
+ prUnapproveOutcomeUnknown: "撤回批准结果不明。可以原样重试,该操作是幂等的。",
240
316
  prMergeOutcomeUnknown: "合并结果不明。请先重读 PR,不要自动重发。",
241
- apiHumanPrincipal: "Agent 不能批准或合并。请使用绑定了 GitHub 的人类 STAMP_TOKEN 会话。",
317
+ apiHumanPrincipal: "此操作需要人类 STAMP_TOKEN 会话。",
242
318
  apiWriteCoords: "请重读 PR,带上当前的 --head 和 --base 再试。",
243
319
  apiGitHubBinding: "请先在 Stamp 设置里绑定 GitHub,再重试。",
244
320
  usagePrComment: "用法:{cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) [--expected-head SHA](人类以本人绑定的 GitHub 身份发表;agent 以 Stamp App 身份发表并附带署名行;带 --expected-head 时 PR 的 head 变了就拒绝发表)",
@@ -247,6 +323,16 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
247
323
  prCommentCreated: "已以 {actor} 身份发表评论:{url}",
248
324
  prCommentRejected: "评论请求被拒绝,请检查会话、GitHub 绑定(人类)、仓库权限和输入。",
249
325
  prCommentOutcomeUnknown: "评论结果不明。请先查看 PR 评论,不要自动重发。",
326
+ usagePrEdit: "用法:{cli} pr edit <NUMBER -R OWNER/REPO|PR_URL> [--title TITLE] [--body TEXT|--body-file FILE|-](仅 Stamp 创建回执记录的 Agent 可改;标题、描述至少提供一项)",
327
+ usagePrClose: "用法:{cli} pr close <NUMBER -R OWNER/REPO|PR_URL>(仅 Stamp 创建回执记录的 Agent 可关闭)",
328
+ prClosed: "已关闭 {repository}#{number}:{url}",
329
+ prCloseRejected: "PR 关闭被拒绝。请确认该 PR 由此 Agent 经 Stamp 创建,且此 Agent 仍有仓库权限。",
330
+ prCloseOutcomeUnknown: "PR 关闭结果不明。请先重读 PR,再决定是否重发;不要自动重试。",
331
+ prEditTitleInvalid: "PR 标题不能为空,UTF-8 文本最多 256 字节。",
332
+ prEditBodyInvalid: "PR 描述不能为空,UTF-8 文本最多 64 KiB。",
333
+ prEdited: "已更新 {repository}#{number}:{url}",
334
+ prEditRejected: "PR 编辑被拒绝。请确认该 PR 由此 Agent 经 Stamp 创建,且此 Agent 仍有仓库权限。",
335
+ prEditOutcomeUnknown: "PR 编辑结果不明。请先重读 PR,再决定是否重发;不要自动重试。",
250
336
  usagePrList: "用法:{cli} pr list",
251
337
  usagePrView: "用法:{cli} pr view <编号|URL> [--repo OWNER/REPO]",
252
338
  usagePrDiff: "用法:{cli} pr diff <编号|URL> [--repo OWNER/REPO] [--name-only]",
@@ -266,6 +352,23 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
266
352
  prChecksUnreadable: "无法读取这个 PR 的检查结果,所以这不是\"没有检查\"——网关被 GitHub 拒绝了(通常是 App 缺少 Checks 权限)。请把 CI 当作未知。",
267
353
  prCIUnreadable: "无法读取",
268
354
  prVerdictCIUnreadable: "CI 无法读取——不能当作已通过",
355
+ prVerdictLabel: "Stamp 判定",
356
+ verdict_READY: "现在可以合入",
357
+ verdict_MERGED: "已合入",
358
+ verdict_CLOSED: "已关闭",
359
+ verdict_DRAFT: "草稿",
360
+ verdict_CONFLICT: "与 base 有冲突",
361
+ verdict_CI_UNREADABLE: "CI 无法读取——不能当作已通过",
362
+ verdict_CI_FAILING: "有 required 检查失败",
363
+ verdict_CI_NOT_EXECUTED: "有 required 检查没有运行",
364
+ verdict_CI_PENDING: "required 检查仍在运行",
365
+ verdict_REVIEW_UNREADABLE: "批准状态无法读取",
366
+ verdict_CHANGES_REQUESTED: "有人要求修改",
367
+ verdict_STALE_REVIEW: "现有批准针对的是别的 head 或 base",
368
+ verdict_NEEDS_REVIEW: "需要非作者在这个 head 上批准",
369
+ verdict_BEHIND: "落后于 base",
370
+ verdict_BLOCKED: "GitHub 阻止合入,原因 Stamp 看不到",
371
+ verdict_UNCONFIRMED: "GitHub 没有确认可以干净合入(有检查未通过,或还在计算)",
269
372
  prReadNotFound: "请检查仓库和 PR 编号,并确认该 PR 是此 Agent 通过 Stamp 创建的。",
270
373
  prReadHeadMoved: "Stamp 读取 diff 时 PR head 已变化;请重新运行命令并审阅新的 head。",
271
374
  prReadDiffIncomplete: "GitHub 未返回完整的 PR diff;请稍后重试,不要依赖部分文件。",
@@ -291,9 +394,15 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
291
394
  prIdempotency: "--idempotency-key 必须为 16–128 位字母、数字、点、下划线、冒号或连字符。",
292
395
  prCreated: "已创建 PR #{number}:{url}",
293
396
  prExisting: "已有 PR #{number}:{url}",
397
+ prStampPage: " Stamp:{page}",
398
+ prNextAutoMerge: " 下一步:{cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (他人批准这个 head 且判定为 READY 后,Stamp 自动合并)",
294
399
  prWaitPublished: "请用 {cli} receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
400
+ prReceiptNotPublished: "Receipt {id} 的状态是 {status},不会发表到 GitHub,无法据此创建 PR。见 {cli} receipt get {id}。",
401
+ prPublishTimeout: "等待 GitHub 发表后,receipt {id} 仍是 {status};稍后重跑同一命令,或查看 {cli} receipt get {id}。",
402
+ prReceiptIncomplete: "Receipt {id} 已发表,但缺少仓库、ref 或提交;请显式传 --repo、--head 和 --sha。",
295
403
  prCheckReceipt: "请重新读取 receipt,并核对 --repo、--head 和 --sha 是否与已发表提交一致。",
296
404
  prCheckAccess: "请与仓库管理员核对仓库权限和允许的目标分支。",
405
+ prCheckBase: "目标分支在 GitHub 上不存在;请用 --base 指定仓库里已存在的分支。",
297
406
  prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
298
407
  prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
299
408
  apiBindIdentity: "请先运行 `{cli} identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
@@ -313,15 +422,21 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
313
422
  {cli} known-hosts refresh 从 /.well-known 重新钉住本实例的 SSH 主机公钥
314
423
  {cli} identity bind --email ADDR 绑定提交作者邮箱(DCO)
315
424
  {cli} receipt get <id> 网关接受与 GitHub 发表状态
425
+ {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]
426
+ 列出你自己的推送回执(新的在前)
316
427
  {cli} changelog [--limit N] [--all] 更新日志:每个版本的命令行/接口变化(--all 看全部)
317
- {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
428
+ {cli} pr create --receipt ID [--repo OWNER/REPO --head BRANCH --sha SHA] --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
318
429
  {cli} pr list
319
430
  {cli} pr view <编号|URL> --repo OWNER/REPO
320
431
  {cli} pr diff <编号|URL> --repo OWNER/REPO [--name-only]
321
432
  {cli} pr checks <编号|URL> --repo OWNER/REPO
322
- {cli} pr comment <编号|URL> --repo OWNER/REPO --body-file FILE|- (本人 GitHub 身份)
323
- {cli} pr approve <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (本人 GitHub 身份)
324
- {cli} pr merge <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (本人 GitHub 身份)
433
+ {cli} pr comment <编号|URL> --repo OWNER/REPO --body-file FILE|- (人类用本人 GitHub 身份;agent 以 Stamp App 身份)
434
+ {cli} pr edit <编号|URL> --repo OWNER/REPO [--title 标题] [--body-file 文件|-] (仅创建它的 Agent)
435
+ {cli} pr approve <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (本人 GitHub 身份;Agent 不带 --body)
436
+ {cli} pr unapprove <编号|URL> --repo OWNER/REPO --head SHA --base SHA (Agent)
437
+ {cli} pr merge <编号|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (本人 GitHub 身份;agent 需他人批准)
438
+ {cli} pr merge <编号|URL> --repo OWNER/REPO --auto --head SHA --base SHA (作者 agent:他人批准后自动合入)
439
+ {cli} pr queue enqueue|status|withdraw <编号|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent;入队需 head/base)
325
440
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
326
441
 
327
442
  {cli} follow <owner/repo> --kind issue|pull --number N
@@ -334,7 +449,8 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
334
449
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
335
450
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
336
451
 
337
- flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
452
+ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG
453
+ 文档:{docs}(Agent 工作流,逐步说明)`,
338
454
  usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
339
455
  cloned: "已从 {url} 克隆 {repository}",
340
456
  cloneCommitTrailers: "推到这里的每个 commit 末尾都要带这两行 trailer(连成一块放在最末尾,中间不要空行;GitHub 只认最后一个连续块):",
@@ -375,6 +491,10 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
375
491
  keyRevoked: "已撤销 {keyId}",
376
492
  usageIdentityBind: "用法:{cli} identity bind --email ADDR",
377
493
  usageReceiptGet: "用法:{cli} receipt get <receipt-id>",
494
+ usageReceiptList: "用法:{cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]",
495
+ receiptListEmpty: "没有回执",
496
+ receiptListMore: "还有更多回执;用 --limit 与 --cursor {cursor} 继续翻页。",
497
+ receiptListBadResponse: "回执列表响应异常;请检查 {cli} 与网关版本后重试。",
378
498
  usageChangelog: "用法:{cli} changelog [--limit N] [--all]",
379
499
  changelogScopeAgent: "只显示命令行和接口的变化;--all 看全部。",
380
500
  changelogScopeAll: "显示全部变化,包括网页端和内部改动。",
package/lib/main.mjs CHANGED
@@ -63,7 +63,10 @@ export async function main(argv, opts) {
63
63
  if (cliName !== undefined) setCliName(cliName);
64
64
  if (version) { out(pkg.version); return exit(0); }
65
65
  const cmd = args.shift();
66
- if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
66
+ // The agent-facing document lives on the instance itself (/llms.txt), so
67
+ // the help names this instance's copy.
68
+ const docs = `${String(env.STAMP_URL || opts.urlBase || "https://stamp.build").replace(/\/+$/, "")}/llms.txt`;
69
+ if (help || !cmd) { out(t(locale, "usage", { version: pkg.version, docs })); return exit(0); }
67
70
  const emit = (data, human) => { if (json) out(JSON.stringify(data, null, 2)); else human(); };
68
71
 
69
72
  let auth;
@@ -78,7 +81,7 @@ export async function main(argv, opts) {
78
81
  });
79
82
  const handler = commands[cmd];
80
83
  if (!handler) {
81
- out(t(locale, "usage", { version: pkg.version }));
84
+ out(t(locale, "usage", { version: pkg.version, docs }));
82
85
  return exit(1);
83
86
  }
84
87
 
@@ -0,0 +1,25 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { parsePRTargetArgs } from "./read.mjs";
3
+
4
+ // Task #622: `stamp pr close` mirrors `pr edit`'s contract — only the agent
5
+ // recorded on the creation receipt may close, and the result must echo back
6
+ // the exact target in state "closed" or the outcome is reported unknown.
7
+ export function parsePRCloseArgs(input) {
8
+ const target = parsePRTargetArgs(input, "usagePrClose");
9
+ return {
10
+ target,
11
+ method: "POST",
12
+ path: `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}/close`,
13
+ };
14
+ }
15
+
16
+ export function validatePRCloseResult(value, target) {
17
+ const repository = `${target.owner}/${target.repo}`;
18
+ const valid = value && typeof value === "object" && !Array.isArray(value)
19
+ && typeof value.repository === "string" && value.repository.toLowerCase() === repository.toLowerCase()
20
+ && value.number === target.number
21
+ && typeof value.url === "string" && value.url.toLowerCase() === `https://github.com/${repository}/pull/${target.number}`.toLowerCase()
22
+ && value.state === "closed";
23
+ if (!valid) throw new AgentError("prCloseOutcomeUnknown");
24
+ return value;
25
+ }
package/lib/pr/create.mjs CHANGED
@@ -4,7 +4,22 @@ 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
 
7
- export function pullRequestInput(args) {
7
+ // receiptFields are the flags a published receipt can supply: when all three
8
+ // are omitted, the CLI reads them from the receipt (repository, targetRef,
9
+ // publishedSha) instead of making the agent copy them over by hand.
10
+ export const receiptFields = ["repo", "head", "sha"];
11
+
12
+ export function pullRequestNeedsReceipt(args) {
13
+ return receiptFields.every((name) => !args.some((a) => a === `--${name}` || a.startsWith(`--${name}=`)));
14
+ }
15
+
16
+ // pullRequestDraft parses the flags once and reads the body at most once:
17
+ // `pr create` builds its input twice when it waits for the receipt (a local
18
+ // check before the wait, the real input after it), and a second read of
19
+ // `--body-file -` would find stdin already at EOF, while a second read of a
20
+ // file could pick up content rewritten during the wait. Both builds share one
21
+ // draft, so they share one body.
22
+ export function pullRequestDraft(args) {
8
23
  const flags = new Map();
9
24
  for (let i = 0; i < args.length; i++) {
10
25
  const [flag, ...inline] = args[i].split("=");
@@ -14,6 +29,29 @@ export function pullRequestInput(args) {
14
29
  if (value === undefined || (!inline.length && value.startsWith("--"))) throw new AgentError("usagePrCreate");
15
30
  flags.set(name, value);
16
31
  }
32
+ let body;
33
+ return {
34
+ flags,
35
+ body() {
36
+ if (body !== undefined) return body;
37
+ if (flags.has("body") && flags.has("body-file")) throw new AgentError("prBodyConflict");
38
+ body = flags.get("body") ?? "";
39
+ if (flags.has("body-file")) {
40
+ try { body = readFileSync(flags.get("body-file") === "-" ? 0 : flags.get("body-file"), "utf8"); }
41
+ catch { body = undefined; throw new AgentError("prBodyRead"); }
42
+ }
43
+ return body;
44
+ },
45
+ };
46
+ }
47
+
48
+ export function pullRequestInput(args, fromReceipt = null, draft = pullRequestDraft(args)) {
49
+ const flags = new Map(draft.flags);
50
+ if (fromReceipt) {
51
+ flags.set("repo", fromReceipt.repository);
52
+ flags.set("head", fromReceipt.targetRef);
53
+ flags.set("sha", fromReceipt.publishedSha);
54
+ }
17
55
  for (const name of ["receipt", "repo", "head", "sha", "base", "title"]) {
18
56
  if (!flags.get(name)?.trim()) throw new AgentError("prRequired", { flag: `--${name}` });
19
57
  }
@@ -23,12 +61,7 @@ export function pullRequestInput(args) {
23
61
  const value = flags.get(name);
24
62
  return value.startsWith("refs/") ? value : `refs/heads/${value}`;
25
63
  };
26
- if (flags.has("body") && flags.has("body-file")) throw new AgentError("prBodyConflict");
27
- let body = flags.get("body") ?? "";
28
- if (flags.has("body-file")) {
29
- try { body = readFileSync(flags.get("body-file") === "-" ? 0 : flags.get("body-file"), "utf8"); }
30
- catch { throw new AgentError("prBodyRead"); }
31
- }
64
+ const body = draft.body();
32
65
  if (!body.trim()) throw new AgentError("prBodyRequired");
33
66
  const input = {
34
67
  receiptId: flags.get("receipt"), repository: flags.get("repo"),
@@ -52,10 +85,66 @@ export function pullRequestRecovery(code) {
52
85
  case "PUBLISHED_RECEIPT_BINDING_MISMATCH":
53
86
  case "GITHUB_HEAD_DRIFT": return "prCheckReceipt";
54
87
  case "REPOSITORY_NOT_AUTHORIZED":
88
+ // Gateways before v0.1.38 still answer this for any non-default base.
55
89
  case "BASE_REF_NOT_AUTHORIZED": return "prCheckAccess";
90
+ case "BASE_REF_NOT_FOUND": return "prCheckBase";
56
91
  case "IDEMPOTENCY_CONFLICT":
57
92
  case "PUSH_RECEIPT_ALREADY_BOUND":
58
93
  case "GITHUB_PULL_REQUEST_CONFLICT": return "prCheckExisting";
59
94
  default: return "prRetry";
60
95
  }
61
96
  }
97
+
98
+ // waitForPublishedReceipt polls the receipt until GitHub publication is done:
99
+ // a push is accepted by the gateway first and published asynchronously, so a
100
+ // pr create right after the push used to fail with
101
+ // PUBLISHED_RECEIPT_NOT_FOUND and the agent had to poll by hand.
102
+ export const publishWaitDefaultMs = 120000;
103
+
104
+ // publishWaitMs reads the STAMP_PUBLISH_WAIT_MS test hook. Only a positive
105
+ // whole number of milliseconds counts; anything else keeps the default, so
106
+ // the hook can shorten the wait but never make it unbounded.
107
+ export function publishWaitMs(value) {
108
+ return /^[1-9][0-9]{0,8}$/.test(value ?? "") ? Number(value) : publishWaitDefaultMs;
109
+ }
110
+
111
+ export async function waitForPublishedReceipt(api, id, { timeoutMs = publishWaitDefaultMs, intervalMs = 2000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now } = {}) {
112
+ // A NaN, infinite or non-positive bound would make the deadline check
113
+ // below never true: the wait must stay bounded whatever the caller passed.
114
+ if (!(Number.isFinite(timeoutMs) && timeoutMs > 0)) timeoutMs = publishWaitDefaultMs;
115
+ const deadline = now() + timeoutMs;
116
+ for (;;) {
117
+ const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
118
+ if (d.status === "PUBLISHED") {
119
+ if (!d.repository || !d.targetRef || !/^[0-9a-f]{40}$/.test(d.publishedSha ?? "")) throw new AgentError("prReceiptIncomplete", { id });
120
+ return d;
121
+ }
122
+ if (d.status === "FAILED" || d.status === "REJECTED") throw new AgentError("prReceiptNotPublished", { id, status: d.status });
123
+ if (now() >= deadline) throw new AgentError("prPublishTimeout", { id, status: d.status });
124
+ await sleep(intervalMs);
125
+ }
126
+ }
127
+
128
+ // pullRequestNextLines is what `pr create` prints under "Created PR": the
129
+ // pull request's page on this Stamp instance, and the one command that
130
+ // registers it for auto-merge, with the exact head and base the gateway just
131
+ // answered (Imprint, 09-27: agents read CLI output, and auto-merge went
132
+ // unnoticed in --help). A line whose values do not check out is left out,
133
+ // never printed half-filled.
134
+ export function pullRequestNextLines(d, apiBase, tr) {
135
+ const lines = [];
136
+ const repo = typeof d?.repository === "string" && /^[^/\s]+\/[^/\s]+$/.test(d.repository) ? d.repository : null;
137
+ const number = Number.isInteger(d?.pullNumber) && d.pullNumber > 0 ? d.pullNumber : null;
138
+ if (!repo || !number) return lines;
139
+ let origin = null;
140
+ try {
141
+ const u = new URL(apiBase);
142
+ if (u.protocol === "https:" || u.hostname === "127.0.0.1" || u.hostname === "localhost") origin = u.origin;
143
+ } catch { /* no page line */ }
144
+ if (origin) lines.push(tr("prStampPage", { page: `${origin}/github/${repo}/pull/${number}` }));
145
+ const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
146
+ if (sha(d.headSha) && sha(d.baseSha)) {
147
+ lines.push(tr("prNextAutoMerge", { number, repository: repo, head: d.headSha, base: d.baseSha }));
148
+ }
149
+ return lines;
150
+ }
@@ -0,0 +1,53 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { AgentError } from "../errors.mjs";
3
+ import { parsePRTargetArgs } from "./read.mjs";
4
+
5
+ export function parsePREditArgs(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(/^(--title|--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("usagePrEdit");
13
+ const value = match?.[2] ?? input[++i];
14
+ if (value === undefined) throw new AgentError("usagePrEdit");
15
+ flags.set(name, value);
16
+ }
17
+ if (flags.has("--body") && flags.has("--body-file")) throw new AgentError("prBodyConflict");
18
+ const target = parsePRTargetArgs(targetArgs, "usagePrEdit");
19
+ const body = {};
20
+ if (flags.has("--title")) {
21
+ const title = flags.get("--title").trim();
22
+ if (!title || Buffer.byteLength(title, "utf8") > 256) throw new AgentError("prEditTitleInvalid");
23
+ body.title = title;
24
+ }
25
+ if (flags.has("--body") || flags.has("--body-file")) {
26
+ let text = flags.get("--body");
27
+ if (flags.has("--body-file")) {
28
+ const file = flags.get("--body-file");
29
+ try { text = readFileSync(file === "-" ? 0 : file, "utf8"); }
30
+ catch { throw new AgentError("prBodyRead"); }
31
+ }
32
+ if (!text?.trim() || Buffer.byteLength(text, "utf8") > 65536) throw new AgentError("prEditBodyInvalid");
33
+ body.body = text;
34
+ }
35
+ if (!("title" in body) && !("body" in body)) throw new AgentError("usagePrEdit");
36
+ return {
37
+ target,
38
+ path: `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}`,
39
+ body,
40
+ };
41
+ }
42
+
43
+ export function validatePREditResult(value, target) {
44
+ const repository = `${target.owner}/${target.repo}`;
45
+ const valid = value && typeof value === "object" && !Array.isArray(value)
46
+ && typeof value.repository === "string" && value.repository.toLowerCase() === repository.toLowerCase()
47
+ && value.number === target.number
48
+ && typeof value.url === "string" && value.url.toLowerCase() === `https://github.com/${repository}/pull/${target.number}`.toLowerCase()
49
+ && typeof value.title === "string" && value.title.trim().length > 0
50
+ && typeof value.body === "string";
51
+ if (!valid) throw new AgentError("prEditOutcomeUnknown");
52
+ return value;
53
+ }
@@ -0,0 +1,32 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
3
+ const sha = /^[0-9a-f]{40}$/;
4
+ const id = /^[a-zA-Z0-9][a-zA-Z0-9_-]{15,127}$/;
5
+ const states = new Set(["queued", "preparing", "testing", "publishing", "merged", "verified", "failed", "stale", "canceled"]);
6
+
7
+ export function parsePRQueueArgs(input) {
8
+ const args = [...input];
9
+ const action = args.shift();
10
+ const usage = "usagePrQueue";
11
+ if (!["enqueue", "status", "withdraw"].includes(action)) throw new AgentError(usage);
12
+ const requestID = takeNamedFlag(args, "request-id", undefined, usage);
13
+ const head = takeNamedFlag(args, "head", undefined, usage);
14
+ const base = takeNamedFlag(args, "base", undefined, usage);
15
+ if (typeof requestID !== "string" || !id.test(requestID)) throw new AgentError(usage);
16
+ if (action === "enqueue" ? !sha.test(head ?? "") || !sha.test(base ?? "") : head !== undefined || base !== undefined) throw new AgentError(usage);
17
+ const target = parsePRTargetArgs(args, usage);
18
+ return { action, requestID, target, path: `${prDetailPath(target)}/queue/${requestID}`, method: { enqueue: "PUT", status: "GET", withdraw: "DELETE" }[action], ...(action === "enqueue" ? { body: { expectedHead: head, expectedBase: base } } : {}) };
19
+ }
20
+
21
+ export function validatePRQueueResult(d, input) {
22
+ const r = d?.receipt;
23
+ const m = r?.member;
24
+ if (!d || typeof d.repository !== "string" || d.repository.toLowerCase() !== `${input.target.owner}/${input.target.repo}`.toLowerCase()
25
+ || d.number !== input.target.number || d.requestId !== input.requestID
26
+ || m?.number !== input.target.number || m?.requestId !== input.requestID || !sha.test(m?.head ?? "")
27
+ || !states.has(r?.state) || typeof r?.notificationQueued !== "boolean"
28
+ || !sha.test(r?.expectedBase ?? "")
29
+ || (input.body && (m.head !== input.body.expectedHead || r.expectedBase !== input.body.expectedBase))
30
+ || (r.state === "merged" && !sha.test(r.landingSha ?? ""))) throw new AgentError("prQueueOutcomeUnknown");
31
+ return d;
32
+ }
package/lib/pr/read.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AgentError } from "../errors.mjs";
2
+ import { validateVerdict } from "./verdict.mjs";
2
3
 
3
4
  const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
4
5
  const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
@@ -35,7 +36,7 @@ export function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
35
36
  return value;
36
37
  }
37
38
 
38
- function takeBooleanFlag(args, long) {
39
+ export function takeBooleanFlag(args, long) {
39
40
  const i = args.indexOf(`--${long}`);
40
41
  if (i === -1) return false;
41
42
  args.splice(i, 1);
@@ -247,6 +248,7 @@ export function validatePRDetail(value, expected) {
247
248
  }
248
249
  requireString(detail.reviewStatus);
249
250
  requireString(detail.reviewFreshness);
251
+ detail.verdict = validateVerdict(detail.verdict);
250
252
  if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
251
253
  requireString(detail.updatedAt);
252
254
  requireString(detail.body);
@@ -387,6 +389,9 @@ function sectionLabel(section, labels) {
387
389
  export function formatPRDetail(detail, labels) {
388
390
  const lines = [
389
391
  `${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
392
+ // The verdict comes second, straight under the title: it is the answer
393
+ // the rest of the output explains (task #607).
394
+ ...(labels.verdictLine ? [labels.verdictLine] : []),
390
395
  `${labels.head}: ${safeInline(detail.headSha)}`,
391
396
  // Forks on ciUnreadable rather than printing ciStatus straight through. Left
392
397
  // alone, `pr view` would keep saying "none" while `pr checks` already says
package/lib/pr/review.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // shows unrelated changes), checks, review state — and the local commands
6
6
  // that diff and patch-id against the merge-base rather than the base.
7
7
  import { safeInline } from "./read.mjs";
8
+ import { formatVerdictLine } from "./verdict.mjs";
8
9
 
9
10
  // The brief does NOT say whether the base has advanced: GitHub's `base.sha`
10
11
  // on a pull request is the fork point and stays put while the base branch
@@ -33,6 +34,9 @@ export function reviewBrief(detail) {
33
34
  // where it costs the most (cross, reviewing #602).
34
35
  ciUnreadable: detail.ciUnreadable === true,
35
36
  reviewStatus: detail.reviewStatus,
37
+ // Stamp's verdict for these exact coordinates (task #607), or null from a
38
+ // gateway that does not compute one.
39
+ stampVerdict: detail.verdict ?? null,
36
40
  reviewFreshness: detail.reviewFreshness,
37
41
  checks: detail.checks.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),
38
42
  commands: {
@@ -49,6 +53,7 @@ export function reviewBrief(detail) {
49
53
  export function formatPRReview(brief, t) {
50
54
  const lines = [
51
55
  `${safeInline(brief.repository)} #${brief.number} — ${safeInline(brief.title)} (${safeInline(brief.author)})`,
56
+ ...(brief.stampVerdict ? [formatVerdictLine(brief.stampVerdict, t)] : []),
52
57
  `${t("prReviewExactHead")}: ${safeInline(brief.headSha)} (${safeInline(brief.headRef)})`,
53
58
  `${t("prReviewBase")}: ${safeInline(brief.baseRef)} @ ${safeInline(brief.baseSha)}`,
54
59
  `${t("prReviewMergeBase")}: ${safeInline(brief.mergeBaseSha)}`,
@@ -73,9 +78,11 @@ export function formatPRReview(brief, t) {
73
78
  // statement sitting somewhere other than where the decision is made; putting
74
79
  // it only at the top would have been a milder version of the same thing
75
80
  // (飞牛, reviewing #282).
76
- brief.ciUnreadable
77
- ? `${t("prReviewVerdict")}: ${brief.verdict} (${t("prVerdictCIUnreadable")})`
78
- : `${t("prReviewVerdict")}: ${brief.verdict}`,
81
+ // Stamp's state rides on the same line for the same reason: a reviewer
82
+ // posting GO on a PR whose required CI never ran should see that here.
83
+ `${t("prReviewVerdict")}: ${brief.verdict}` +
84
+ (brief.ciUnreadable ? ` (${t("prVerdictCIUnreadable")})` : "") +
85
+ (brief.stampVerdict ? ` (Stamp: ${safeInline(brief.stampVerdict.state)})` : ""),
79
86
  ];
80
87
  return lines;
81
88
  }
@@ -0,0 +1,46 @@
1
+ // The pull request verdict (task #607): the gateway's one-line answer to
2
+ // "can this land now, and if not, why not", shared by `pr view`, `pr review`
3
+ // and the web header. The CLI never computes it; it only validates and prints
4
+ // what the gateway decided, pinned to the head and base it was decided for.
5
+ import { AgentError } from "../errors.mjs";
6
+ import { safeInline } from "./read.mjs";
7
+
8
+ // Lists that name the checks behind a state.
9
+ const namedChecks = {
10
+ CI_FAILING: "requiredFailing",
11
+ CI_NOT_EXECUTED: "requiredSkipped",
12
+ CI_PENDING: "requiredPending",
13
+ };
14
+
15
+ const listFields = ["requiredPassed", "requiredFailing", "requiredPending", "requiredSkipped", "optional"];
16
+
17
+ // Absent is allowed (a gateway before task #607 does not send it). Present
18
+ // must be well formed. An unknown state is NOT an error: a newer gateway may
19
+ // add states, and an older CLI must still print what it was told.
20
+ export function validateVerdict(value) {
21
+ if (value === undefined || value === null) return undefined;
22
+ if (typeof value !== "object" || Array.isArray(value)) throw new AgentError("prReadInvalidResponse");
23
+ for (const field of ["state", "headSha", "baseSha"]) {
24
+ if (typeof value[field] !== "string" || value[field] === "") throw new AgentError("prReadInvalidResponse");
25
+ }
26
+ for (const field of listFields) {
27
+ if (!Array.isArray(value[field]) || value[field].some((name) => typeof name !== "string")) {
28
+ throw new AgentError("prReadInvalidResponse");
29
+ }
30
+ }
31
+ if (typeof value.requiredKnown !== "boolean") throw new AgentError("prReadInvalidResponse");
32
+ return value;
33
+ }
34
+
35
+ // One line: state, a short explanation, the checks behind it, and the exact
36
+ // coordinates. `t(key)` returns the key itself when there is no message.
37
+ export function formatVerdictLine(verdict, t) {
38
+ const short = (sha) => safeInline(sha).slice(0, 12);
39
+ const state = safeInline(verdict.state);
40
+ const key = `verdict_${verdict.state}`;
41
+ const explained = t(key);
42
+ const why = explained && explained !== key ? ` — ${explained}` : "";
43
+ const list = namedChecks[verdict.state] ? verdict[namedChecks[verdict.state]] : [];
44
+ const names = list.length ? ` (${list.map(safeInline).join(", ")})` : "";
45
+ return `${t("prVerdictLabel")}: ${state}${why}${names} @ head ${short(verdict.headSha)} base ${short(verdict.baseSha)}`;
46
+ }
package/lib/pr/write.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AgentError } from "../errors.mjs";
2
- import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
2
+ import { parsePRTargetArgs, prDetailPath, takeBooleanFlag, takeNamedFlag } from "./read.mjs";
3
3
 
4
4
  const shaRE = /^[0-9a-f]{40}$/;
5
5
  const methods = new Set(["", "merge", "squash", "rebase"]);
@@ -39,6 +39,19 @@ export function parsePRApproveArgs(input) {
39
39
  };
40
40
  }
41
41
 
42
+ // An agent withdraws its own Stamp-recorded approval of this exact head. There
43
+ // is no body: a Stamp approval is a vote, not a review.
44
+ export function parsePRUnapproveArgs(input) {
45
+ const parsed = parseWriteTarget(input, "usagePrUnapprove");
46
+ if (parsed.mergeMethod || parsed.body !== undefined) throw new AgentError("usagePrUnapprove");
47
+ return {
48
+ target: parsed.target,
49
+ path: `${prDetailPath(parsed.target)}/unapprove`,
50
+ method: "POST",
51
+ body: { expectedHead: parsed.expectedHead, expectedBase: parsed.expectedBase },
52
+ };
53
+ }
54
+
42
55
  export function parsePRMergeArgs(input) {
43
56
  const parsed = parseWriteTarget(input, "usagePrMerge");
44
57
  if (parsed.body !== undefined) throw new AgentError("usagePrMerge");
@@ -59,24 +72,105 @@ function requireObject(value, code) {
59
72
  return value;
60
73
  }
61
74
 
75
+ // A human approval is a GitHub review (reviewerLogin); an agent approval is
76
+ // recorded by Stamp (recordedBy "stamp", reviewer = the agent's Raft id).
77
+ function validStampApproval(d, action) {
78
+ return d.recordedBy === "stamp" && d.action === action
79
+ && typeof d.reviewer === "string" && d.reviewer.length > 0;
80
+ }
81
+
62
82
  export function validatePRApproveResult(result, target) {
63
83
  const expectedRepo = `${target.owner}/${target.repo}`;
64
84
  const d = requireObject(result, "prApproveOutcomeUnknown");
65
85
  const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
66
86
  && d.number === target.number
67
87
  && shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
68
- && typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin);
88
+ && ((typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin))
89
+ || validStampApproval(d, "approve"));
69
90
  if (!valid) throw new AgentError("prApproveOutcomeUnknown");
70
91
  return d;
71
92
  }
72
93
 
94
+ export function validatePRUnapproveResult(result, target) {
95
+ const expectedRepo = `${target.owner}/${target.repo}`;
96
+ const d = requireObject(result, "prUnapproveOutcomeUnknown");
97
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
98
+ && d.number === target.number
99
+ && shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
100
+ && validStampApproval(d, "unapprove");
101
+ if (!valid) throw new AgentError("prUnapproveOutcomeUnknown");
102
+ return d;
103
+ }
104
+
105
+ // A human merge is GitHub's, as the bound user (actorLogin); an agent merge is
106
+ // performed by the Stamp App (mergedBy "stamp-app", agent = the Raft id).
107
+ function validAppMerge(d) {
108
+ return d.mergedBy === "stamp-app" && typeof d.agent === "string" && d.agent.length > 0;
109
+ }
110
+
73
111
  export function validatePRMergeResult(result, target) {
74
112
  const expectedRepo = `${target.owner}/${target.repo}`;
75
113
  const d = requireObject(result, "prMergeOutcomeUnknown");
76
114
  const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
77
115
  && d.number === target.number && d.merged === true
78
116
  && shaRE.test(d.mergeSha) && shaRE.test(d.mergedHead) && shaRE.test(d.mergedBase)
79
- && typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin);
117
+ && ((typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin))
118
+ || validAppMerge(d));
80
119
  if (!valid) throw new AgentError("prMergeOutcomeUnknown");
81
120
  return d;
82
121
  }
122
+
123
+ // `pr merge --auto` (task #664): the author registers the PR to be merged by
124
+ // Stamp once someone else approves that exact head and the verdict is READY.
125
+ // `--auto --cancel` withdraws; `--auto --status` reads the registration.
126
+ // Register and withdraw pin --head and --base like every write.
127
+ export function isAutoMergeArgs(input) {
128
+ return input.includes("--auto");
129
+ }
130
+
131
+ export function parsePRAutoMergeArgs(input) {
132
+ const args = [...input];
133
+ takeBooleanFlag(args, "auto");
134
+ const cancel = takeBooleanFlag(args, "cancel");
135
+ const status = takeBooleanFlag(args, "status");
136
+ if (cancel && status) throw new AgentError("usagePrMerge");
137
+ if (status) {
138
+ const target = parsePRTargetArgs(args, "usagePrMerge");
139
+ return { kind: "status", target, path: `${prDetailPath(target)}/auto-merge`, method: "GET" };
140
+ }
141
+ const parsed = parseWriteTarget(args, "usagePrMerge");
142
+ if (parsed.body !== undefined || (cancel && parsed.mergeMethod)) throw new AgentError("usagePrMerge");
143
+ return {
144
+ kind: cancel ? "cancel" : "arm",
145
+ target: parsed.target,
146
+ path: `${prDetailPath(parsed.target)}/auto-merge`,
147
+ method: cancel ? "DELETE" : "PUT",
148
+ body: {
149
+ expectedHead: parsed.expectedHead,
150
+ expectedBase: parsed.expectedBase,
151
+ ...(parsed.mergeMethod ? { mergeMethod: parsed.mergeMethod } : {}),
152
+ },
153
+ };
154
+ }
155
+
156
+ // The gateway's answer must be about the PR that was asked for. An unknown
157
+ // state from a newer gateway is passed through, not rejected.
158
+ export function validatePRAutoMergeResult(result, target) {
159
+ const expectedRepo = `${target.owner}/${target.repo}`;
160
+ const d = requireObject(result, "prMergeOutcomeUnknown");
161
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
162
+ && d.number === target.number && typeof d.state === "string" && d.state !== ""
163
+ && shaRE.test(d.currentHead)
164
+ && (d.armedHead === undefined || shaRE.test(d.armedHead));
165
+ if (!valid) throw new AgentError("prMergeOutcomeUnknown");
166
+ return d;
167
+ }
168
+
169
+ // One line: the state, what it means, and the pinned head.
170
+ export function formatAutoMerge(d, t) {
171
+ const key = `prAutoMerge_${d.state}`;
172
+ const vars = { repository: d.repository, number: d.number, head: (d.armedHead || d.currentHead).slice(0, 12), method: d.mergeMethod || "" };
173
+ const text = t(key, vars);
174
+ const line = text !== key ? text : `${d.repository}#${d.number}: ${d.state}`;
175
+ return d.alreadyInEffect ? `${line} ${t("prAutoMergeUnchanged")}` : line;
176
+ }
@@ -0,0 +1,54 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { takeNamedFlag } from "../pr/read.mjs";
3
+
4
+ // `stamp receipt list` (task #580): the session agent lists only its own push
5
+ // receipts — never another agent's, never the same agent's on another server.
6
+ // The endpoint is always paged ({items, nextCursor}); --limit/--cursor opt
7
+ // into walking further, --repo narrows server-side and is bound into the
8
+ // cursor so a cursor minted under one filter cannot replay under another.
9
+
10
+ export const RECEIPT_LIST_MAX_LIMIT = 100;
11
+
12
+ export function parseReceiptListArgs(input) {
13
+ const args = [...input];
14
+ const repo = takeNamedFlag(args, "repo", "R", "usageReceiptList");
15
+ const limitRaw = takeNamedFlag(args, "limit", undefined, "usageReceiptList");
16
+ const cursor = takeNamedFlag(args, "cursor", undefined, "usageReceiptList");
17
+ if (args.length !== 0) throw new AgentError("usageReceiptList");
18
+
19
+ const params = new URLSearchParams();
20
+ if (repo !== undefined) {
21
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new AgentError("usageReceiptList");
22
+ params.set("repo", repo);
23
+ }
24
+ if (limitRaw !== undefined) {
25
+ if (!/^[1-9][0-9]*$/.test(limitRaw) || Number(limitRaw) > RECEIPT_LIST_MAX_LIMIT) {
26
+ throw new AgentError("usageReceiptList");
27
+ }
28
+ params.set("limit", limitRaw);
29
+ }
30
+ if (cursor !== undefined) params.set("cursor", cursor);
31
+ const query = params.toString();
32
+ return { path: query === "" ? "/v1/receipts" : `/v1/receipts?${query}` };
33
+ }
34
+
35
+ export function validateReceiptList(d) {
36
+ if (!d || !Array.isArray(d.items)) throw new AgentError("receiptListBadResponse");
37
+ for (const item of d.items) {
38
+ if (typeof item?.id !== "string" || typeof item?.status !== "string" ||
39
+ typeof item?.repository !== "string" || typeof item?.targetRef !== "string") {
40
+ throw new AgentError("receiptListBadResponse");
41
+ }
42
+ }
43
+ if (d.nextCursor !== null && d.nextCursor !== undefined && typeof d.nextCursor !== "string") {
44
+ throw new AgentError("receiptListBadResponse");
45
+ }
46
+ return { items: d.items, nextCursor: d.nextCursor ?? null };
47
+ }
48
+
49
+ export function formatReceiptLine(item) {
50
+ let line = `${item.id} ${item.status} ${item.repository} ${item.targetRef} published=${item.publishedSha ?? "-"}`;
51
+ if (item.publishAttempts) line += ` attempts=${item.publishAttempts}`;
52
+ if (item.nextRetryAt) line += ` nextRetry=${item.nextRetryAt}`;
53
+ return line;
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
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",