@botiverse/stamp-cli 0.3.8 → 0.3.10

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
@@ -18,22 +22,25 @@ stamp receipt list
18
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
19
23
  stamp pr list
20
24
  stamp pr view 123 --repo org/repo
25
+ stamp pr review 123 --repo org/repo
21
26
  stamp pr diff 123 --repo org/repo
22
27
  stamp pr checks 123 --repo org/repo
23
28
  stamp pr comment 123 --repo org/repo --body-file ./comment.md
24
29
  stamp pr edit 123 --repo org/repo --title "Clearer title" --body-file ./pr-body.md
25
30
  stamp pr approve 123 --repo org/repo --head <exact-head-sha> --base <exact-base-sha>
26
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>
27
33
  ```
28
34
 
29
35
  - Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
30
36
  - Human / CI: `STAMP_TOKEN`
31
- - 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
32
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`)
33
40
 
34
41
  Two installed bins, sharing one implementation:
35
42
 
36
- - `stamp` — default service slug `stamp` (the future production registration)
43
+ - `stamp` — production origin and service slug `stamp`
37
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
38
45
 
39
46
  Configuration layering is `environment > executable defaults`: `STAMP_URL` and
@@ -69,6 +76,14 @@ expanded to `refs/heads/...`; full refs also work. Use `--body-file -` for stdin
69
76
  `--body` for inline text. A non-empty description is required. `--json` prints the
70
77
  service receipt; a denial exits nonzero with recovery guidance.
71
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
+
72
87
  The read-only PR commands follow the familiar `gh pr` command group while
73
88
  reading through Stamp rather than a local GitHub credential:
74
89
 
@@ -114,6 +129,19 @@ approved. `--head` and `--base` must be the exact current SHAs (`PR_HEAD_MOVED`
114
129
  GitHub refuses it if the head moved; GitHub's branch protection still applies.
115
130
  The result names `mergedBy: "stamp-app"` and the merging Agent.
116
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
+
117
145
  `stamp pr close` withdraws a PR the current Agent created through Stamp, under
118
146
  the same receipt-ownership gate as `pr edit` — another Agent, another Raft
119
147
  Server, or a PR opened outside Stamp is refused before any provider write, and
package/lib/auth.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { unlinkSync, existsSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { dirname, join } from "node:path";
3
3
  import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
4
4
  import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } from "./agent-login.mjs";
5
5
  import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
@@ -147,6 +147,10 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
147
147
  apiBase,
148
148
  agentEnv: a,
149
149
  service,
150
+ // The agent's own directory for Stamp state, beside its session (artin
151
+ // 09-27): its SSH key, the enrollment record and the pinned host key.
152
+ // Never ~/.ssh or ~/.stamp, which every agent on a machine user shares.
153
+ stateDir: dirname(agentAuthPath(a, service)),
150
154
  async token() {
151
155
  if (!usableStore) {
152
156
  if (storedOriginElsewhere !== null) {
package/lib/client.mjs CHANGED
@@ -57,7 +57,10 @@ export function makeClient(auth, fetchImpl = fetch, options = {}) {
57
57
  try {
58
58
  res = await fetchImpl(`${auth.apiBase}${path}`, {
59
59
  method,
60
- headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
60
+ headers: {
61
+ authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json",
62
+ ...(options.cliVersion ? { "stamp-cli-version": options.cliVersion } : {}),
63
+ },
61
64
  body: body ? JSON.stringify(body) : undefined,
62
65
  });
63
66
  } catch (error) {
@@ -69,6 +72,7 @@ export function makeClient(auth, fetchImpl = fetch, options = {}) {
69
72
  }
70
73
  throw new NetworkError(networkErrorKey(failure), { base: auth.apiBase, cause: failure.code });
71
74
  }
75
+ options.onVersions?.(res.headers?.get?.("stamp-cli-latest") ?? "", res.headers?.get?.("stamp-cli-minimum") ?? "");
72
76
  const text = await res.text();
73
77
  let json = null;
74
78
  try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
@@ -1,10 +1,22 @@
1
1
  import { existsSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
2
  import { t } from "../locale.mjs";
5
3
  import { resolve } from "node:path";
6
4
  import { takeFlag, readPublicKey } from "../flags.mjs";
7
5
  import { recordIdentity } from "../repo/identities.mjs";
6
+ import { defaultIdentityPath } from "../repo/ssh.mjs";
7
+ import { mkdirSync } from "node:fs";
8
+ import { dirname } from "node:path";
9
+ import { spawnSync } from "node:child_process";
10
+
11
+ // generateAgentKey creates an ed25519 key with no passphrase at path (0600,
12
+ // in a 0700 directory), labelled with the agent it belongs to.
13
+ function generateAgentKey(path, agentId) {
14
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
15
+ const res = spawnSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", `stamp-agent-${agentId ?? "unknown"}`, "-f", path], { encoding: "utf8" });
16
+ if (res.error || res.status !== 0) {
17
+ throw new Error(`ssh-keygen failed: ${(res.stderr || res.error?.message || "").trim()}`);
18
+ }
19
+ }
8
20
 
9
21
  export async function run(ctx) {
10
22
  const sub = ctx.args.shift();
@@ -26,7 +38,16 @@ export async function run(ctx) {
26
38
  return ctx.exit(0);
27
39
  }
28
40
  if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
29
- const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
41
+ const agentDefault = `${defaultIdentityPath(ctx.env)}.pub`;
42
+ const keyPath = takeFlag(ctx.args, "public-key", agentDefault);
43
+ // An agent enrolling with no --public-key gets a key of its own, created in
44
+ // its own directory (artin 09-27: a shared ~/.ssh/id_ed25519 made another
45
+ // agent's key push for BoBo). Nothing to configure by hand.
46
+ let generated = false;
47
+ if (keyPath === agentDefault && ctx.env.STAMP_AGENT_STATE_DIR && !existsSync(keyPath)) {
48
+ await (ctx.opts.sshKeygenImpl ?? generateAgentKey)(keyPath.replace(/\.pub$/, ""), ctx.auth?.agentEnv?.agentId);
49
+ generated = true;
50
+ }
30
51
  if (keyPath !== "-" && !existsSync(keyPath)) {
31
52
  // The default path is the interesting case: `key enroll` on a machine with
32
53
  // no key reads a path the operator never typed, so name it and name the two
@@ -48,7 +69,8 @@ export async function run(ctx) {
48
69
  recordIdentity(ctx.env, ctx.auth.apiBase, identity);
49
70
  }
50
71
  }
51
- ctx.emit({ ...d, identity }, () => {
72
+ ctx.emit({ ...d, identity, generated }, () => {
73
+ if (generated) ctx.out(t(ctx.locale, "keyGenerated", { path: keyPath.replace(/\.pub$/, "") }));
52
74
  ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId }));
53
75
  ctx.out(identity
54
76
  ? t(ctx.locale, "enrolledIdentityRecorded", { path: identity.identityPath })
@@ -4,7 +4,7 @@ import { parsePRQueueArgs, validatePRQueueResult } from "../pr/queue.mjs";
4
4
  import { t, prefix } from "../locale.mjs";
5
5
  import { ApiError, NetworkError } from "../client.mjs";
6
6
  import { AgentError, printGatewayError } from "../errors.mjs";
7
- import { pullRequestInput, pullRequestRecovery } from "../pr/create.mjs";
7
+ import { publishWaitMs, pullRequestDraft, pullRequestNextLines, stampPullRequestPage, pullRequestInput, pullRequestNeedsReceipt, pullRequestRecovery, waitForPublishedReceipt } from "../pr/create.mjs";
8
8
  import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
9
9
  import { parsePREditArgs, validatePREditResult } from "../pr/edit.mjs";
10
10
  import { parsePRCloseArgs, validatePRCloseResult } from "../pr/close.mjs";
@@ -139,10 +139,31 @@ export async function run(ctx) {
139
139
  });
140
140
  }
141
141
  if (sub === "create") {
142
- 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
+ }
143
152
  try {
144
- const d = await api("POST", "/v1/pull-requests", input);
145
- 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
+ });
146
167
  } catch (e) {
147
168
  if (e instanceof ApiError && e.status !== 401) {
148
169
  err(`${prefix()}${e.message}`);
@@ -179,9 +200,13 @@ export async function run(ctx) {
179
200
  if (sub === "view") {
180
201
  const target = parsePRTargetArgs(args, "usagePrView");
181
202
  const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
182
- emit(d, () => {
203
+ // The Stamp page is added to --json too (stampUrl), for agents that
204
+ // build their report from it.
205
+ const stampUrl = stampPullRequestPage(ctx.auth?.apiBase, d.repository, d.number);
206
+ emit(stampUrl ? { ...d, stampUrl } : d, () => {
183
207
  for (const line of formatPRDetail(d, {
184
208
  verdictLine: d.verdict ? formatVerdictLine(d.verdict, (key) => t(locale, key)) : "",
209
+ stampPage: stampUrl ? t(locale, "prViewStampPage", { page: stampUrl }) : "",
185
210
  head: t(locale, "prHeadLabel"),
186
211
  checks: t(locale, "prChecksLabel"),
187
212
  ciUnreadable: t(locale, "prCIUnreadable"),
@@ -6,7 +6,9 @@ import { fetchPublishedKnownHosts, resolveIdentity, resolveKnownHostsPath, sshCo
6
6
  import { readRecordedIdentity } from "../repo/identities.mjs";
7
7
 
8
8
  export async function run(ctx) {
9
- if (ctx.args.shift() !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
9
+ const sub = ctx.args.shift();
10
+ if (sub === "use") return use(ctx);
11
+ if (sub !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
10
12
  const identityFlag = takeFlag(ctx.args, "identity");
11
13
  const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
12
14
  const parsed = parseRepoCloneArgs(ctx.args);
@@ -76,3 +78,39 @@ export async function run(ctx) {
76
78
  );
77
79
  return ctx.exit(0);
78
80
  }
81
+
82
+ // `stamp repo use [DIR]` gives a checkout that was not cloned through Stamp
83
+ // the same per-repository ssh settings `repo clone` writes: this agent's own
84
+ // key and the gateway's pinned host key, in the repository's local config
85
+ // only (artin 09-27: never ~/.ssh/config or a global setting, which other
86
+ // agents on the machine share).
87
+ async function use(ctx) {
88
+ const identityFlag = takeFlag(ctx.args, "identity");
89
+ const knownHostsFlag = takeFlag(ctx.args, "known-hosts");
90
+ const directory = ctx.args.shift() ?? ".";
91
+ if (ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageRepoUse"));
92
+ const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
93
+ const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
94
+ if (!existsSync(identityPath)) {
95
+ throw new Error(t(ctx.locale, source === "enrolled" ? "cloneEnrolledIdentityMissing" : "cloneIdentityMissing", { path: identityPath, origin: ctx.auth.apiBase }));
96
+ }
97
+ const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
98
+ const fetchImpl = ctx.opts.fetchImpl ?? fetch;
99
+ const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
100
+ if (!published.ok) {
101
+ throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
102
+ url: `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`,
103
+ status: published.status ?? "?",
104
+ }));
105
+ }
106
+ writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
107
+ const sshCommand = sshCommandFor({ identityPath, knownHostsPath });
108
+ const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
109
+ if (!pinned.ok) {
110
+ throw new Error(t(ctx.locale, "repoUseFailed", { directory, detail: (pinned.stderr ?? "").trim() }));
111
+ }
112
+ ctx.emit({ directory, identityPath, knownHostsPath, sshCommand }, () => {
113
+ ctx.out(t(ctx.locale, "repoUseDone", { directory, path: identityPath }));
114
+ });
115
+ return ctx.exit(0);
116
+ }
@@ -30,7 +30,15 @@ export async function logout(ctx) {
30
30
 
31
31
  export async function whoami(ctx) {
32
32
  const me = await ctx.api("GET", "/v1/me");
33
- ctx.emit(me, () => ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`));
33
+ ctx.emit(me, () => {
34
+ ctx.out(`${me.principalType} ${me.name} (${me.agentId}@${me.serverId}) ssh=${me.sshHost} @ ${ctx.auth.apiBase}`);
35
+ // An agent always has a commit email (artin 09-27): its own, or Stamp's
36
+ // default, which receives no mail. Say which, and how to use it.
37
+ const email = me.commitEmail;
38
+ if (email && typeof email.address === "string" && email.address !== "") {
39
+ ctx.out(t(ctx.locale, email.default ? "whoamiCommitEmailDefault" : "whoamiCommitEmail", { email: email.address }));
40
+ }
41
+ });
34
42
  return ctx.exit(0);
35
43
  }
36
44
 
package/lib/errors.mjs CHANGED
@@ -25,12 +25,16 @@ function stableErrorCode(value) {
25
25
  return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
26
26
  }
27
27
 
28
- // The gateway owns the repair: JSON { error, errorCode, suggestedNextAction }.
29
- // The CLI prints those fields verbatim. It does not keep a second code→copy map.
28
+ // The gateway owns the repair: JSON { error, errorCode, cause,
29
+ // suggestedNextAction }. The CLI prints those fields verbatim (artin 09-27:
30
+ // every refusal reaches the client with its cause). It does not keep a
31
+ // second code→copy map.
30
32
  export function printGatewayError(error, write) {
31
33
  const body = error.body;
32
34
  const code = stableErrorCode(body?.errorCode ?? body?.error);
33
35
  if (code && code !== body?.error) write(`${prefix()}${code}`);
36
+ const cause = typeof body?.cause === "string" ? body.cause.trim() : "";
37
+ if (cause) write(`${prefix()}${cause}`);
34
38
  const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
35
39
  if (action) write(`${prefix()}${action}`);
36
40
  return Boolean(action);
package/lib/locale.mjs CHANGED
@@ -4,7 +4,7 @@ export const messages = {
4
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
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
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]",
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
8
  usagePrRead: "usage: {cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [arguments]",
9
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",
10
10
  prReviewExactHead: "Exact head",
@@ -74,6 +74,7 @@ export const messages = {
74
74
  prVerdictCIUnreadable: "CI unreadable — not evidence of green",
75
75
  prVerdictLabel: "Stamp verdict",
76
76
  verdict_READY: "can land now",
77
+ verdict_QUEUE_READY: "approved; it lands through Stamp's merge queue: `{cli} pr queue`",
77
78
  verdict_MERGED: "already merged",
78
79
  verdict_CLOSED: "closed",
79
80
  verdict_DRAFT: "draft",
@@ -114,13 +115,21 @@ export const messages = {
114
115
  prIdempotency: "--idempotency-key must contain 16–128 letters, digits, dots, underscores, colons, or hyphens.",
115
116
  prCreated: "Created PR #{number}: {url}",
116
117
  prExisting: "Existing PR #{number}: {url}",
118
+ prStampPage: " Stamp: {page}",
119
+ prViewStampPage: "Stamp: {page}",
120
+ whoamiCommitEmail: "commit email: {email} (git config user.email {email})",
121
+ whoamiCommitEmailDefault: "commit email: {email} (Stamp's default for agents; it receives no mail. Use it: git config user.email {email}. Have your own address? {cli} identity bind --email ADDR)",
122
+ 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)",
117
123
  prWaitPublished: "Check {cli} receipt get <id>; use your own receipt after its status becomes PUBLISHED.",
124
+ prReceiptNotPublished: "Receipt {id} is {status}; it will not be published, so no pull request can be opened from it. See {cli} receipt get {id}.",
125
+ prPublishTimeout: "Receipt {id} is still {status} after waiting for GitHub publication; run the same command again later, or check {cli} receipt get {id}.",
126
+ prReceiptIncomplete: "Receipt {id} is published but lacks its repository, ref or commit; pass --repo, --head and --sha explicitly.",
118
127
  prCheckReceipt: "Read the receipt again and check --repo, --head and --sha against the exact published commit.",
119
128
  prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
120
129
  prCheckBase: "The base branch does not exist on GitHub. Pass --base as an existing branch of the repository.",
121
130
  prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
122
131
  prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
123
- apiBindIdentity: "Bind this agent first with `{cli} identity bind --email <agent-email>`, then retry the command.",
132
+ apiBindIdentity: "Run `{cli} whoami` (it gives this agent its default commit email), then retry the command.",
124
133
  apiRepositoryNotInstalled: "Check OWNER/REPO spelling, or ask a server owner to install the Stamp GitHub App on that repository, then retry.",
125
134
  apiContributionDenied: "Ask a server owner to grant this agent an active Write-or-higher repository role, then retry.",
126
135
  apiRepositoryNotAuthorized: "Ask a server owner to verify the Stamp GitHub App installation and this agent's identity binding, then retry.",
@@ -131,7 +140,7 @@ export const messages = {
131
140
  {cli} logout agent: forget the stored session
132
141
  {cli} whoami who the gateway thinks you are
133
142
  {cli} migration-help old manifest actions → CLI mapping
134
- {cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (default ~/.ssh/id_ed25519.pub)
143
+ {cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (agent default: its own key, created if missing)
135
144
  {cli} key list list this agent's enrolled SSH keys
136
145
  {cli} key revoke KEY_ID revoke one of this agent's enrolled keys
137
146
  {cli} known-hosts refresh re-pin this instance's SSH host key from /.well-known
@@ -140,7 +149,7 @@ export const messages = {
140
149
  {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]
141
150
  list your own push receipts (newest first)
142
151
  {cli} changelog [--limit N] [--all] release history: CLI/API changes per version (--all: everything)
143
- {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
152
+ {cli} pr create --receipt ID [--repo OWNER/REPO --head BRANCH --sha SHA] --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
144
153
  {cli} pr list
145
154
  {cli} pr view <number|URL> --repo OWNER/REPO
146
155
  {cli} pr diff <number|URL> --repo OWNER/REPO [--name-only]
@@ -153,6 +162,7 @@ export const messages = {
153
162
  {cli} pr merge <number|URL> --repo OWNER/REPO --auto --head SHA --base SHA (author agent: merge once someone else approves)
154
163
  {cli} pr queue enqueue|status|withdraw <number|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent; coordinates required for enqueue)
155
164
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
165
+ {cli} repo use [DIR] point an existing checkout at this agent's key (repository-local)
156
166
 
157
167
  {cli} follow <owner/repo> --kind issue|pull --number N
158
168
  {cli} unfollow <owner/repo> --kind issue|pull --number N
@@ -164,7 +174,8 @@ export const messages = {
164
174
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
165
175
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
166
176
 
167
- flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
177
+ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG
178
+ docs: {docs} (the agent workflow, step by step)`,
168
179
  usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
169
180
  cloned: "Cloned {repository} from {url}",
170
181
  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):",
@@ -194,6 +205,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
194
205
  loginTokenExpired: "Agent logged in ({service} @ {url}), but the access token expired at {expires} ({remaining}); the next command refreshes it",
195
206
  logoutForgot: "forgot agent session {path}",
196
207
  logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
208
+ cliUpdateAvailable: "stamp {current} is out of date; {latest} is available: npm install -g @botiverse/stamp-cli@latest",
209
+ usageRepoUse: "usage: {cli} repo use [DIR] [--identity KEY] [--known-hosts FILE]",
210
+ repoUseDone: "{directory}: git now reaches Stamp with this agent's key {path} (set in this repository only)",
211
+ repoUseFailed: "could not set core.sshCommand in {directory}: {detail}",
212
+ keyGenerated: "created this agent's own SSH key: {path} (kept in the agent's directory, not ~/.ssh)",
197
213
  enrolled: "enrolled {fingerprint} ({keyId})",
198
214
  enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
199
215
  enrolledIdentityNotRecorded: "the private key {path} is not on this machine, so `{cli} repo clone` here will need --identity FILE",
@@ -278,7 +294,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
278
294
  usagePrQueue: "用法:{cli} pr queue <enqueue|status|withdraw> <NUMBER -R OWNER/REPO|PR_URL> --request-id ID [--head SHA --base SHA(仅 enqueue)];ID 为 16–128 位字母、数字、下划线或连字符,首位为字母或数字;发送前选定并保留",
279
295
  prQueueOutcomeUnknown: "队列操作结果未知。再次写入前,用同一 PR 和 --request-id 执行 pr queue status;不要生成新 ID 或自动重发。",
280
296
  prQueueReceipt: "队列 {repository}#{number},请求 {id}:{state};原因:{reason};落地:{landing};终态通知已入队:{queued}(不代表送达)",
281
- 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]",
297
+ 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 读取",
282
298
  usagePrRead: "用法:{cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [参数]",
283
299
  usagePrReview: "用法:{cli} pr review <编号|URL> [--repo OWNER/REPO] —— 要钉的 exact head、base、merge-base、检查,以及对 merge-base 做 diff/patch-id 的命令",
284
300
  prReviewExactHead: "Exact head",
@@ -348,6 +364,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
348
364
  prVerdictCIUnreadable: "CI 无法读取——不能当作已通过",
349
365
  prVerdictLabel: "Stamp 判定",
350
366
  verdict_READY: "现在可以合入",
367
+ verdict_QUEUE_READY: "已批准;通过 Stamp 的合并队列合入:`{cli} pr queue`",
351
368
  verdict_MERGED: "已合入",
352
369
  verdict_CLOSED: "已关闭",
353
370
  verdict_DRAFT: "草稿",
@@ -388,13 +405,21 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
388
405
  prIdempotency: "--idempotency-key 必须为 16–128 位字母、数字、点、下划线、冒号或连字符。",
389
406
  prCreated: "已创建 PR #{number}:{url}",
390
407
  prExisting: "已有 PR #{number}:{url}",
408
+ prStampPage: " Stamp:{page}",
409
+ prViewStampPage: "Stamp:{page}",
410
+ whoamiCommitEmail: "提交邮箱:{email}(git config user.email {email})",
411
+ whoamiCommitEmailDefault: "提交邮箱:{email}(Stamp 给 agent 的默认地址,不能收信。直接用:git config user.email {email}。有自己的邮箱?{cli} identity bind --email ADDR)",
412
+ prNextAutoMerge: " 下一步:{cli} pr merge {number} --repo {repository} --auto --head {head} --base {base}\n (他人批准这个 head 且判定为 READY 后,Stamp 自动合并)",
391
413
  prWaitPublished: "请用 {cli} receipt get <id> 检查;只使用自己状态为 PUBLISHED 的 receipt。",
414
+ prReceiptNotPublished: "Receipt {id} 的状态是 {status},不会发表到 GitHub,无法据此创建 PR。见 {cli} receipt get {id}。",
415
+ prPublishTimeout: "等待 GitHub 发表后,receipt {id} 仍是 {status};稍后重跑同一命令,或查看 {cli} receipt get {id}。",
416
+ prReceiptIncomplete: "Receipt {id} 已发表,但缺少仓库、ref 或提交;请显式传 --repo、--head 和 --sha。",
392
417
  prCheckReceipt: "请重新读取 receipt,并核对 --repo、--head 和 --sha 是否与已发表提交一致。",
393
418
  prCheckAccess: "请与仓库管理员核对仓库权限和允许的目标分支。",
394
419
  prCheckBase: "目标分支在 GitHub 上不存在;请用 --base 指定仓库里已存在的分支。",
395
420
  prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
396
421
  prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
397
- apiBindIdentity: "请先运行 `{cli} identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
422
+ apiBindIdentity: "请先运行 `{cli} whoami`(它会给这个 Agent 分配默认提交邮箱),再重试命令。",
398
423
  apiRepositoryNotInstalled: "请检查 OWNER/REPO 拼写,或请 Server Owner 为该仓库安装 Stamp GitHub App,再重试。",
399
424
  apiContributionDenied: "请让 Server Owner 为此 Agent 授予有效的 Write 或更高仓库角色,再重试。",
400
425
  apiRepositoryNotAuthorized: "请让 Server Owner 核对 Stamp GitHub App 安装与此 Agent 的身份绑定,再重试。",
@@ -405,7 +430,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
405
430
  {cli} logout Agent:忘掉已存会话
406
431
  {cli} whoami 网关认为你是谁
407
432
  {cli} migration-help 旧 manifest action → CLI 对照
408
- {cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
433
+ {cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(agent 默认用它自己的 key,没有就生成)
409
434
  {cli} key list 列出此 Agent 已登记的 SSH 公钥
410
435
  {cli} key revoke KEY_ID 撤销此 Agent 的一把已登记公钥
411
436
  {cli} known-hosts refresh 从 /.well-known 重新钉住本实例的 SSH 主机公钥
@@ -414,7 +439,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
414
439
  {cli} receipt list [--repo OWNER/REPO] [--limit N] [--cursor CURSOR]
415
440
  列出你自己的推送回执(新的在前)
416
441
  {cli} changelog [--limit N] [--all] 更新日志:每个版本的命令行/接口变化(--all 看全部)
417
- {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
442
+ {cli} pr create --receipt ID [--repo OWNER/REPO --head BRANCH --sha SHA] --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
418
443
  {cli} pr list
419
444
  {cli} pr view <编号|URL> --repo OWNER/REPO
420
445
  {cli} pr diff <编号|URL> --repo OWNER/REPO [--name-only]
@@ -427,6 +452,7 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
427
452
  {cli} pr merge <编号|URL> --repo OWNER/REPO --auto --head SHA --base SHA (作者 agent:他人批准后自动合入)
428
453
  {cli} pr queue enqueue|status|withdraw <编号|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent;入队需 head/base)
429
454
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
455
+ {cli} repo use [目录] 让已有的 checkout 用这个 agent 自己的 key(只设在该仓库)
430
456
 
431
457
  {cli} follow <owner/repo> --kind issue|pull --number N
432
458
  {cli} unfollow <owner/repo> --kind issue|pull --number N
@@ -438,7 +464,8 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
438
464
  git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
439
465
  git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
440
466
 
441
- flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
467
+ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG
468
+ 文档:{docs}(Agent 工作流,逐步说明)`,
442
469
  usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
443
470
  cloned: "已从 {url} 克隆 {repository}",
444
471
  cloneCommitTrailers: "推到这里的每个 commit 末尾都要带这两行 trailer(连成一块放在最末尾,中间不要空行;GitHub 只认最后一个连续块):",
@@ -468,6 +495,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
468
495
  loginTokenExpired: "Agent 已登录({service} @ {url}),但访问令牌已于 {expires} 过期({remaining});下一条命令会自动刷新",
469
496
  logoutForgot: "已忘记 Agent 会话 {path}",
470
497
  logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
498
+ cliUpdateAvailable: "stamp {current} 已过时,新版 {latest} 可用:npm install -g @botiverse/stamp-cli@latest",
499
+ usageRepoUse: "用法:{cli} repo use [目录] [--identity KEY] [--known-hosts FILE]",
500
+ repoUseDone: "{directory}:git 现在用这个 agent 自己的 key {path} 连 Stamp(只设在这个仓库里)",
501
+ repoUseFailed: "无法在 {directory} 设置 core.sshCommand:{detail}",
502
+ keyGenerated: "已为这个 agent 生成自己的 SSH key:{path}(放在 agent 自己的目录里,不在 ~/.ssh)",
471
503
  enrolled: "已登记 {fingerprint}({keyId})",
472
504
  enrolledIdentityRecorded: "这台机器上的 `{cli} repo clone` 会使用 {path}",
473
505
  enrolledIdentityNotRecorded: "私钥 {path} 不在这台机器上,这里的 `{cli} repo clone` 需要 --identity FILE",
package/lib/main.mjs CHANGED
@@ -4,6 +4,7 @@ import { resolveAuth } from "./auth.mjs";
4
4
  import { makeClient, ApiError } from "./client.mjs";
5
5
  import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
6
6
  import { presentError, printGatewayError } from "./errors.mjs";
7
+ import { makeUpdateNotice } from "./update-check.mjs";
7
8
  import * as session from "./commands/session.mjs";
8
9
  import * as key from "./commands/key.mjs";
9
10
  import * as knownhosts from "./commands/knownhosts.mjs";
@@ -41,7 +42,7 @@ export async function main(argv, opts) {
41
42
  const args = [...argv];
42
43
  const out = opts.stdout ?? ((s) => console.log(s));
43
44
  const err = opts.stderr ?? ((s) => console.error(s));
44
- const env = opts.env ?? process.env;
45
+ let env = opts.env ?? process.env;
45
46
  const exit = opts.exit ?? ((code) => process.exit(code));
46
47
  const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
47
48
  let json = false, langFlag, help = false, version = false;
@@ -63,7 +64,10 @@ export async function main(argv, opts) {
63
64
  if (cliName !== undefined) setCliName(cliName);
64
65
  if (version) { out(pkg.version); return exit(0); }
65
66
  const cmd = args.shift();
66
- if (help || !cmd) { out(t(locale, "usage", { version: pkg.version })); return exit(0); }
67
+ // The agent-facing document lives on the instance itself (/llms.txt), so
68
+ // the help names this instance's copy.
69
+ const docs = `${String(env.STAMP_URL || opts.urlBase || "https://stamp.build").replace(/\/+$/, "")}/llms.txt`;
70
+ if (help || !cmd) { out(t(locale, "usage", { version: pkg.version, docs })); return exit(0); }
67
71
  const emit = (data, human) => { if (json) out(JSON.stringify(data, null, 2)); else human(); };
68
72
 
69
73
  let auth;
@@ -73,12 +77,21 @@ export async function main(argv, opts) {
73
77
  err(`${prefix()}${presentError(locale, e)}`);
74
78
  return exit(1);
75
79
  }
80
+ // An agent's key, enrollment record and pinned host key live in its own
81
+ // directory (auth.stateDir); the repo helpers read it from the env they
82
+ // already take. An explicit STAMP_AGENT_STATE_DIR (tests) wins.
83
+ if (auth.stateDir && !env.STAMP_AGENT_STATE_DIR) env = { ...env, STAMP_AGENT_STATE_DIR: auth.stateDir };
84
+ const onVersions = makeUpdateNotice({
85
+ current: pkg.version, env, now: opts.now,
86
+ warn: (latest) => err(`${prefix()}${t(locale, "cliUpdateAvailable", { current: pkg.version, latest })}`),
87
+ });
76
88
  const api = makeClient(auth, opts.fetchImpl, {
89
+ cliVersion: pkg.version, onVersions,
77
90
  readRetries: opts.networkReadRetries, retryDelayMs: opts.networkRetryDelayMs, sleep: opts.sleep,
78
91
  });
79
92
  const handler = commands[cmd];
80
93
  if (!handler) {
81
- out(t(locale, "usage", { version: pkg.version }));
94
+ out(t(locale, "usage", { version: pkg.version, docs }));
82
95
  return exit(1);
83
96
  }
84
97
 
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"),
@@ -61,3 +94,69 @@ export function pullRequestRecovery(code) {
61
94
  default: return "prRetry";
62
95
  }
63
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
+ // stampPullRequestPage is the pull request's page on this Stamp instance:
129
+ // the link to hand a person (artin 09-27: Stamp links first, GitHub's as
130
+ // well if wanted). null when the repository, number or instance does not
131
+ // check out, so no half-built link is ever printed.
132
+ export function stampPullRequestPage(apiBase, repository, number) {
133
+ if (typeof repository !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(repository)) return null;
134
+ if (!Number.isInteger(number) || number <= 0) return null;
135
+ try {
136
+ const u = new URL(apiBase);
137
+ if (u.protocol === "https:" || u.hostname === "127.0.0.1" || u.hostname === "localhost") {
138
+ return `${u.origin}/github/${repository}/pull/${number}`;
139
+ }
140
+ } catch { /* no page */ }
141
+ return null;
142
+ }
143
+
144
+ // pullRequestNextLines is what `pr create` prints under "Created PR": the
145
+ // pull request's page on this Stamp instance, and the one command that
146
+ // registers it for auto-merge, with the exact head and base the gateway just
147
+ // answered (Imprint, 09-27: agents read CLI output, and auto-merge went
148
+ // unnoticed in --help). A line whose values do not check out is left out,
149
+ // never printed half-filled.
150
+ export function pullRequestNextLines(d, apiBase, tr) {
151
+ const lines = [];
152
+ const repo = typeof d?.repository === "string" && /^[^/\s]+\/[^/\s]+$/.test(d.repository) ? d.repository : null;
153
+ const number = Number.isInteger(d?.pullNumber) && d.pullNumber > 0 ? d.pullNumber : null;
154
+ if (!repo || !number) return lines;
155
+ const page = stampPullRequestPage(apiBase, repo, number);
156
+ if (page) lines.push(tr("prStampPage", { page }));
157
+ const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
158
+ if (sha(d.headSha) && sha(d.baseSha)) {
159
+ lines.push(tr("prNextAutoMerge", { number, repository: repo, head: d.headSha, base: d.baseSha }));
160
+ }
161
+ return lines;
162
+ }
package/lib/pr/read.mjs CHANGED
@@ -386,6 +386,16 @@ function sectionLabel(section, labels) {
386
386
  return labels[key] ?? section;
387
387
  }
388
388
 
389
+ // formatApprovals names who approved the exact head, from the verdict; with
390
+ // no verdict (an older gateway) it falls back to GitHub's review status.
391
+ export function formatApprovals(verdict, reviewStatus) {
392
+ const approvals = Array.isArray(verdict?.approvals) ? verdict.approvals : null;
393
+ if (!approvals) return safeInline(reviewStatus);
394
+ if (approvals.length === 0) return "no approval at this head";
395
+ const who = approvals.map((a) => `${safeInline(a.principal)} (${a.source === "stamp_receipt" ? "Stamp" : "GitHub"})`).join(", ");
396
+ return `approved at head ${safeInline(approvals[0].headSha).slice(0, 12)} by ${who}`;
397
+ }
398
+
389
399
  export function formatPRDetail(detail, labels) {
390
400
  const lines = [
391
401
  `${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
@@ -398,7 +408,12 @@ export function formatPRDetail(detail, labels) {
398
408
  // the checks could not be read — one endpoint, two commands, two answers,
399
409
  // which is the false trail #598 started on.
400
410
  `${labels.checks}: ${detail.ciUnreadable ? labels.ciUnreadable : safeInline(detail.ciStatus)}`,
401
- `${labels.review}: ${safeInline(detail.reviewStatus)}`,
411
+ // Stamp's own approvals first (they are what the verdict counts); GitHub's
412
+ // review decision alone reads "unreviewed" on a PR Stamp approved.
413
+ `${labels.review}: ${formatApprovals(detail.verdict, detail.reviewStatus)}`,
414
+ // The Stamp page first, then GitHub's: the Stamp one is the link to hand
415
+ // a person (artin 09-27).
416
+ ...(labels.stampPage ? [labels.stampPage] : []),
402
417
  safeInline(detail.url),
403
418
  ];
404
419
  if (typeof detail.body === "string" && detail.body !== "") lines.push("", safeMultiline(detail.body));
@@ -11,7 +11,9 @@ import { dirname, join } from "node:path";
11
11
 
12
12
  export function identitiesPath(env) {
13
13
  const fromEnv = String(env?.STAMP_IDENTITIES ?? "").trim();
14
- return fromEnv || join(homedir(), ".stamp", "identities.json");
14
+ if (fromEnv) return fromEnv;
15
+ const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
16
+ return agentDir ? join(agentDir, "identities.json") : join(homedir(), ".stamp", "identities.json");
15
17
  }
16
18
 
17
19
  function readAll(path) {
package/lib/repo/ssh.mjs CHANGED
@@ -12,8 +12,12 @@ import { spawnSync } from "node:child_process";
12
12
 
13
13
  // defaultIdentityPath is where `stamp key enroll` looks for the public key; the
14
14
  // private half is the same path without `.pub`.
15
+ // An agent's default key is its own (artin 09-27), in its state directory,
16
+ // never the ~/.ssh/id_ed25519 every agent on a machine user shares; a human
17
+ // keeps the conventional path.
15
18
  export function defaultIdentityPath(env) {
16
- return join(homedir(), ".ssh", "id_ed25519");
19
+ const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
20
+ return agentDir ? join(agentDir, "ssh", "id_ed25519") : join(homedir(), ".ssh", "id_ed25519");
17
21
  }
18
22
 
19
23
  // resolveIdentity picks the private key in this order and says which source
@@ -40,7 +44,9 @@ export function resolveKnownHostsPath(env, flagValue) {
40
44
  const fromFlag = String(flagValue ?? "").trim();
41
45
  if (fromFlag) return fromFlag;
42
46
  const fromEnv = String(env?.STAMP_KNOWN_HOSTS ?? "").trim();
43
- return fromEnv || join(homedir(), ".stamp", "known_hosts");
47
+ if (fromEnv) return fromEnv;
48
+ const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
49
+ return agentDir ? join(agentDir, "known_hosts") : join(homedir(), ".stamp", "known_hosts");
44
50
  }
45
51
 
46
52
  function shellQuote(value) {
@@ -0,0 +1,50 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ // The gateway names the current CLI on every answer (Stamp-Cli-Latest; artin
6
+ // 09-27: agents ran long-outdated CLIs and nothing told them). The CLI says
7
+ // so on stderr at most once a day, recorded in the agent's own directory
8
+ // (or ~/.stamp for a person). A CLI below Stamp-Cli-Minimum is refused by the
9
+ // gateway itself (CLI_TOO_OLD).
10
+
11
+ export function versionLess(a, b) {
12
+ const parse = (v) => {
13
+ const core = String(v ?? "").trim().replace(/^v/, "").split("-")[0];
14
+ const parts = core.split(".").map((p) => (/^\d+$/.test(p) ? Number(p) : NaN));
15
+ return parts.length && parts.every(Number.isFinite) ? parts : null;
16
+ };
17
+ const pa = parse(a), pb = parse(b);
18
+ if (!pa || !pb) return false;
19
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
20
+ const x = pa[i] ?? 0, y = pb[i] ?? 0;
21
+ if (x !== y) return x < y;
22
+ }
23
+ return false;
24
+ }
25
+
26
+ export function updateCheckPath(env) {
27
+ const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
28
+ return agentDir ? join(agentDir, "update-check.json") : join(homedir(), ".stamp", "update-check.json");
29
+ }
30
+
31
+ const DAY_MS = 24 * 60 * 60 * 1000;
32
+
33
+ // makeUpdateNotice returns the onVersions callback: it warns once per day
34
+ // (per latest version) when a newer CLI exists.
35
+ export function makeUpdateNotice({ current, env, warn, now = () => Date.now() }) {
36
+ let done = false;
37
+ return (latest) => {
38
+ if (done || !latest || !versionLess(current, latest)) return;
39
+ done = true;
40
+ const path = updateCheckPath(env);
41
+ let last = {};
42
+ try { last = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}; } catch { last = {}; }
43
+ if (last.latest === latest && now() - Number(last.at ?? 0) < DAY_MS) return;
44
+ warn(latest);
45
+ try {
46
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
47
+ writeFileSync(path, `${JSON.stringify({ latest, at: now() })}\n`, { mode: 0o600 });
48
+ } catch { /* a notice that cannot be recorded is shown again tomorrow */ }
49
+ };
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
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",