@botiverse/stamp-cli 0.3.12 → 0.3.13

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
@@ -111,8 +111,10 @@ command exits nonzero and requires a PR re-read before any retry.
111
111
  With an Agent session, `stamp pr approve` records the approval **in Stamp** (a
112
112
  durable receipt), not as a GitHub review: PRs opened through Stamp are authored
113
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
114
+ `--head` and `--base` must be the exact current SHAs, `--base` being the PR's
115
+ recorded base rather than the base branch's tip (a move is refused with
116
+ `PR_HEAD_MOVED` / `PR_BASE_MOVED`, which print the current head and base to
117
+ retry with), the approval counts only for that head, the
116
118
  PR's own author is refused (`SELF_APPROVAL_NOT_ALLOWED`), and there is no
117
119
  `--body`. `stamp pr unapprove` withdraws it. With a human session, `stamp pr
118
120
  approve` submits a GitHub review as the bound user, as before.
@@ -127,7 +129,10 @@ access) and no outstanding request for changes; otherwise it is refused with
127
129
  approved. `--head` and `--base` must be the exact current SHAs (`PR_HEAD_MOVED` /
128
130
  `PR_BASE_MOVED`). The merge happens as the **Stamp App**, pinned to that head, so
129
131
  GitHub refuses it if the head moved; GitHub's branch protection still applies.
130
- The result names `mergedBy: "stamp-app"` and the merging Agent.
132
+ The result names `mergedBy: "stamp-app"` and the merging Agent. Without `--method`
133
+ the merge uses a method the repository allows (squash first, then a merge
134
+ commit, then rebase); a `--method` it does not allow is refused with
135
+ `PR_MERGE_METHOD_NOT_ALLOWED`, naming the allowed ones.
131
136
 
132
137
  The PR's author normally registers auto-merge immediately after creation:
133
138
 
@@ -149,6 +154,25 @@ an already-closed or merged PR is reported as not open rather than as a silent
149
154
  success. If the provider outcome cannot be confirmed, the command exits nonzero
150
155
  and requires a PR re-read before any retry.
151
156
 
157
+ An Agent whose Raft role on the server is owner or admin may also close a
158
+ stale PR that another Agent opened through Stamp **from the same Raft Server**,
159
+ but only with a reason:
160
+
161
+ ```sh
162
+ stamp pr close 123 -R org/repo --reason "Stale for three weeks; superseded by #130."
163
+ stamp pr close 123 -R org/repo --reason-file - # reason from stdin
164
+ ```
165
+
166
+ The reason (nonempty, at most 1000 characters) is posted on the PR first, as
167
+ the Stamp App with the usual attribution block naming who closed it; only then
168
+ is the PR closed, so a PR is never left closed without its explanation. Without
169
+ a reason the admin close is refused with `PR_CLOSE_REASON_REQUIRED`; an admin of
170
+ another server, or a non-admin who is not the author, is refused with
171
+ `PULL_REQUEST_CLOSE_NOT_FOUND` / `PULL_REQUEST_CLOSE_NOT_OWNED` before any
172
+ provider call. The author may pass `--reason` too, and it is posted the same
173
+ way. Admin closes are recorded in Stamp's audit log. Human sessions cannot use
174
+ this command yet.
175
+
152
176
  ### Ordinary PR comments
153
177
 
154
178
  `stamp pr comment 123 -R org/repo --body-file ./comment.md` uses a **human Stamp
@@ -36,10 +36,27 @@ function sectionLabels(locale) {
36
36
  return labels;
37
37
  }
38
38
 
39
+ // instanceLine names the Stamp instance a command talked to: approvals and
40
+ // merges are per instance, and prod and staging otherwise read the same.
41
+ function instanceLine(ctx) {
42
+ let host = "";
43
+ try { host = new URL(ctx.auth?.apiBase).host; } catch { /* no instance to name */ }
44
+ return host ? t(ctx.locale, "prInstance", { host }) : "";
45
+ }
46
+
47
+ function outInstance(ctx) {
48
+ const line = instanceLine(ctx);
49
+ if (line) ctx.out(line);
50
+ }
51
+
39
52
  async function writeCommand(ctx, run) {
40
53
  try {
41
54
  await run();
42
55
  } catch (e) {
56
+ // A refusal is where "which instance?" matters most (an approval made on
57
+ // the other one), so it is named there too.
58
+ const instance = ctx.nameInstance ? instanceLine(ctx) : "";
59
+ if (instance && !(e instanceof AgentError)) ctx.err(`${prefix()}${instance}`);
43
60
  if (e instanceof NetworkError) {
44
61
  // The request left the machine, so whether the write landed is unknown:
45
62
  // keep the uncertainty contract and add what we know about the transport.
@@ -83,12 +100,16 @@ export async function run(ctx) {
83
100
  if (sub === "approve") {
84
101
  ctx.rejectKey = "prApproveRejected";
85
102
  ctx.unknownKey = "prApproveOutcomeUnknown";
103
+ ctx.nameInstance = true;
86
104
  return writeCommand(ctx, async () => {
87
105
  const input = parsePRApproveArgs(args);
88
106
  const result = validatePRApproveResult(await api(input.method, input.path, input.body), input.target);
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 })));
107
+ emit(result, () => {
108
+ out(result.recordedBy === "stamp"
109
+ ? t(locale, "prApprovedByStamp", { actor: result.reviewer, repository: result.repository, number: result.number, head: result.approvedHead })
110
+ : t(locale, "prApproved", { actor: result.reviewerLogin, repository: result.repository, number: result.number }));
111
+ outInstance(ctx);
112
+ });
92
113
  });
93
114
  }
94
115
  if (sub === "unapprove") {
@@ -103,21 +124,29 @@ export async function run(ctx) {
103
124
  if (sub === "merge" && isAutoMergeArgs(args)) {
104
125
  ctx.rejectKey = "prMergeRejected";
105
126
  ctx.unknownKey = "prMergeOutcomeUnknown";
127
+ ctx.nameInstance = true;
106
128
  return writeCommand(ctx, async () => {
107
129
  const input = parsePRAutoMergeArgs(args);
108
130
  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))));
131
+ emit(result, () => {
132
+ out(formatAutoMerge(result, (key, vars) => t(locale, key, vars)));
133
+ outInstance(ctx);
134
+ });
110
135
  });
111
136
  }
112
137
  if (sub === "merge") {
113
138
  ctx.rejectKey = "prMergeRejected";
114
139
  ctx.unknownKey = "prMergeOutcomeUnknown";
140
+ ctx.nameInstance = true;
115
141
  return writeCommand(ctx, async () => {
116
142
  const input = parsePRMergeArgs(args);
117
143
  const result = validatePRMergeResult(await api(input.method, input.path, input.body), input.target);
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 })));
144
+ emit(result, () => {
145
+ out(result.mergedBy === "stamp-app"
146
+ ? t(locale, "prMergedByApp", { actor: result.agent, sha: result.mergeSha, repository: result.repository, number: result.number, head: result.mergedHead })
147
+ : t(locale, "prMerged", { actor: result.actorLogin, sha: result.mergeSha, repository: result.repository, number: result.number }));
148
+ outInstance(ctx);
149
+ });
121
150
  });
122
151
  }
123
152
  if (sub === "close") {
@@ -125,7 +154,7 @@ export async function run(ctx) {
125
154
  ctx.unknownKey = "prCloseOutcomeUnknown";
126
155
  return writeCommand(ctx, async () => {
127
156
  const input = parsePRCloseArgs(args);
128
- const result = validatePRCloseResult(await api(input.method, input.path), input.target);
157
+ const result = validatePRCloseResult(await api(input.method, input.path, input.body), input.target);
129
158
  emit(result, () => out(t(locale, "prClosed", { repository: result.repository, number: result.number, url: result.url })));
130
159
  });
131
160
  }
@@ -212,6 +241,7 @@ export async function run(ctx) {
212
241
  ciUnreadable: t(locale, "prCIUnreadable"),
213
242
  review: t(locale, "prReviewLabel"),
214
243
  })) out(line);
244
+ outInstance(ctx);
215
245
  });
216
246
  return exit(0);
217
247
  }
@@ -0,0 +1,67 @@
1
+ import { t, prefix } from "../locale.mjs";
2
+ import { NetworkError } from "../client.mjs";
3
+ import { formatQueueSetup, formatQueueStatus, parseQueueArgs, queueRequest, setupPath, validateQueueView } from "../queue/setup.mjs";
4
+
5
+ export async function run(ctx) {
6
+ const { args, api, emit, out, err, locale, exit } = ctx;
7
+ const input = parseQueueArgs(args);
8
+
9
+ if (input.action === "setup" || input.action === "status") {
10
+ const req = queueRequest(input);
11
+ const d = validateQueueView(await api(req.method, req.path), input);
12
+ emit(d, () => { for (const line of (input.action === "setup" ? formatQueueSetup(d) : formatQueueStatus(d))) out(line); });
13
+ return exit(0);
14
+ }
15
+
16
+ let confirmed;
17
+ if (input.action === "save") {
18
+ // The digest, revision and source come from a fresh discovery, never from
19
+ // the agent's hands; what is confirmed is shown before it is sent.
20
+ const view = validateQueueView(await api("GET", setupPath(input.repository, input.branch, input.workflow)), input);
21
+ if (!view.canSave || !view.confirmation) {
22
+ emit({ confirmed: null, discovery: view }, () => { for (const line of formatQueueSetup(view)) out(line); });
23
+ err(`${prefix()}${t(locale, "queueCannotSave")}`);
24
+ return exit(1);
25
+ }
26
+ confirmed = {
27
+ branch: view.branch, workflowId: view.workflowId, workflowSha: view.workflowSha, sourceSha: view.sourceSha,
28
+ jobs: view.jobs, required: view.required, additionalWorkflows: view.additionalWorkflows,
29
+ confirmation: view.confirmation, revision: view.revision,
30
+ ciPolicy: input.ciPolicy, maxBatch: input.maxBatch, waitSeconds: input.waitSeconds, timeoutSeconds: input.timeoutSeconds,
31
+ };
32
+ const show = () => {
33
+ out(t(locale, "queueConfirming", { repository: view.repository, branch: view.branch }));
34
+ for (const line of formatQueueSetup(view)) out(` ${line}`);
35
+ out(` ci-policy ${input.ciPolicy}, max-batch ${input.maxBatch}, wait ${input.waitSeconds}s, timeout ${input.timeoutSeconds}s`);
36
+ };
37
+ if (!input.confirm) {
38
+ emit({ confirmed, sent: false }, show);
39
+ err(`${prefix()}${t(locale, "queueConfirmRequired")}`);
40
+ return exit(1);
41
+ }
42
+ if (!ctx.json) show();
43
+ const req = queueRequest(input, view);
44
+ return write(ctx, req, input, confirmed);
45
+ }
46
+ return write(ctx, queueRequest(input), input);
47
+
48
+ async function write(ctx, req, input, confirmed) {
49
+ let d;
50
+ try {
51
+ d = validateQueueView(await api(req.method, req.path, req.body), input);
52
+ } catch (e) {
53
+ if (e instanceof NetworkError) {
54
+ err(`${prefix()}${t(locale, "queueOutcomeUnknown", { repository: input.repository })}`);
55
+ err(`${prefix()}${t(locale, e.code, e.details)}`);
56
+ return exit(1);
57
+ }
58
+ throw e;
59
+ }
60
+ const key = { save: "queueSaved", verify: "queueVerifyStarted", enable: "queueEnabled" }[input.action];
61
+ emit(confirmed ? { confirmed, result: d } : d, () => {
62
+ out(t(locale, key, { repository: d.repository, revision: d.revision ?? d.config?.revision ?? "—", number: input.number ?? "" }));
63
+ for (const line of formatQueueStatus(d)) out(line);
64
+ });
65
+ return exit(0);
66
+ }
67
+ }
package/lib/errors.mjs CHANGED
@@ -37,5 +37,11 @@ export function printGatewayError(error, write) {
37
37
  if (cause) write(`${prefix()}${cause}`);
38
38
  const action = typeof body?.suggestedNextAction === "string" ? body.suggestedNextAction : "";
39
39
  if (action) write(`${prefix()}${action}`);
40
+ // A moved-PR refusal (PR_HEAD_MOVED / PR_BASE_MOVED) hands back the PR's
41
+ // current coordinates; print them as the flags to retry with.
42
+ const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
43
+ if (sha(body?.currentHead) && sha(body?.currentBase)) {
44
+ write(`${prefix()}${t("en", "prCurrentCoordinates", { head: body.currentHead, base: body.currentBase })}`);
45
+ }
40
46
  return Boolean(action);
41
47
  }
package/lib/locale.mjs CHANGED
@@ -4,6 +4,18 @@ 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
+ usageQueue: "usage: {cli} queue setup OWNER/REPO --branch BRANCH [--workflow ID]\n {cli} queue save OWNER/REPO --branch BRANCH --workflow ID --ci-policy head|all --max-batch N --wait SECONDS --timeout SECONDS --confirm\n {cli} queue verify OWNER/REPO --pr NUMBER\n {cli} queue enable OWNER/REPO\n {cli} queue status OWNER/REPO\n(agent; only on a registered queue target of a repository your server's GitHub App covers)",
8
+ queueWorkflowInvalid: "--workflow must be a GitHub Actions workflow id; run {cli} queue setup OWNER/REPO --branch BRANCH to list them.",
9
+ queueCIPolicyInvalid: "--ci-policy must be head (test the batch head) or all (test every prefix).",
10
+ queueLimitsInvalid: "--max-batch must be 1 to 10, --wait 0 to 600 seconds and --timeout 60 to 14400 seconds.",
11
+ queueInvalidResponse: "Stamp returned an unexpected merge queue response; nothing more was sent. Check the service version, then read {cli} queue status.",
12
+ queueCannotSave: "This discovery cannot be saved yet: select a workflow that covers every branch-required check (--workflow ID), then retry.",
13
+ queueConfirming: "Confirming the merge queue setup of {repository} {branch}:",
14
+ queueConfirmRequired: "Nothing was saved. Check the lines above, then run the same command with --confirm.",
15
+ queueSaved: "Saved the merge queue setup of {repository} (revision {revision}). Next: {cli} queue verify {repository} --pr NUMBER with an approved pull request.",
16
+ queueVerifyStarted: "Verification of {repository} started with PR #{number}; it does not merge. Watch {cli} queue status {repository}, then run {cli} queue enable {repository} once it passed.",
17
+ queueEnabled: "The merge queue of {repository} is enabled.",
18
+ queueOutcomeUnknown: "The outcome is unknown. Read {cli} queue status {repository} before sending it again.",
7
19
  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
20
  usagePrRead: "usage: {cli} pr <list|view|review|diff|checks|comment|edit|approve|unapprove|merge|queue> [arguments]",
9
21
  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",
@@ -15,7 +27,7 @@ export const messages = {
15
27
  prReviewVerdict: "Verdict to post",
16
28
  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
29
  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)",
30
+ usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (without --method: the method the repository allows, squash first; 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)",
19
31
  prApproved: "Approved {repository}#{number} as {actor}",
20
32
  prApprovedByStamp: "Approved {repository}#{number} at {head} as {actor} (recorded by Stamp)",
21
33
  prUnapproved: "Withdrew approval of {repository}#{number} at {head} as {actor} (recorded by Stamp)",
@@ -30,12 +42,14 @@ export const messages = {
30
42
  prAutoMergeUnchanged: "(nothing changed)",
31
43
  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
44
  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).",
33
- prApproveOutcomeUnknown: "Approve outcome is unknown. Re-read the PR reviews before sending again; do not automatically resend.",
45
+ prApproveOutcomeUnknown: "Approve outcome is unknown. Re-run the identical command; it returns the recorded result and never approves twice.",
34
46
  prUnapproveRejected: "Unapprove was rejected. Check your agent session, repository access, and --head/--base.",
35
47
  prUnapproveOutcomeUnknown: "Unapprove outcome is unknown. Retry the same command; it is idempotent.",
36
48
  prMergeOutcomeUnknown: "Merge outcome is unknown. Re-read the PR before sending again; do not automatically resend.",
37
49
  apiHumanPrincipal: "This action needs a human STAMP_TOKEN session.",
38
50
  apiWriteCoords: "Re-read the PR and retry with both --head and --base.",
51
+ prWriteFullSHA: "{flag} is not a full commit SHA; pass the full 40-character SHA ({cli} pr view prints the PR's head and base).",
52
+ prCurrentCoordinates: "Current PR coordinates: --head {head} --base {base}",
39
53
  apiGitHubBinding: "Bind your GitHub account in Stamp settings, then retry.",
40
54
  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)",
41
55
  prCommentExpectedHeadInvalid: "--expected-head must be the full 40-character commit SHA you reviewed.",
@@ -44,7 +58,10 @@ export const messages = {
44
58
  prCommentRejected: "Comment request was rejected. Check your session, GitHub binding (humans), repository access and input.",
45
59
  prCommentOutcomeUnknown: "Comment outcome is unknown. Check the PR comments before sending again; do not automatically resend.",
46
60
  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)",
61
+ usagePrClose: "usage: {cli} pr close <NUMBER -R OWNER/REPO|PR_URL> [--reason TEXT|--reason-file FILE|-] (the creating agent, or a server admin with --reason; the reason is posted on the PR before it is closed)",
62
+ prCloseReasonConflict: "Use either --reason or --reason-file, not both.",
63
+ prCloseReasonRead: "Cannot read --reason-file; check the file path or pass - for stdin.",
64
+ prCloseReasonInvalid: "The close reason must be nonempty and at most 1000 characters.",
48
65
  prClosed: "Closed {repository}#{number}: {url}",
49
66
  prCloseRejected: "PR close was rejected. Confirm this agent created the PR through Stamp and still has repository access.",
50
67
  prCloseOutcomeUnknown: "PR close outcome is unknown. Re-read the PR before deciding whether to send the close again; do not automatically resend.",
@@ -88,7 +105,20 @@ export const messages = {
88
105
  verdict_STALE_REVIEW: "approvals are for another head or base",
89
106
  verdict_NEEDS_REVIEW: "needs a non-author approval at this head",
90
107
  verdict_BEHIND: "behind the base",
91
- verdict_BLOCKED: "GitHub blocks the merge for a reason Stamp cannot see",
108
+ verdict_BLOCKED: "GitHub isn't allowing the merge yet",
109
+ // What a BLOCKED is waiting on (gateway pr_blocked.go); {detail} is the
110
+ // gateway's short detail, "" when it has none.
111
+ blocked_REVIEWS_REQUIRED: "more approvals required",
112
+ blocked_CODEOWNERS_REVIEW_REQUIRED: "a code owner review is required",
113
+ blocked_LAST_PUSH_APPROVAL_REQUIRED: "the last push needs an approval from someone else",
114
+ blocked_CHANGES_REQUESTED: "changes requested on GitHub",
115
+ blocked_SIGNED_COMMITS_REQUIRED: "signed commits required (under the current merge method)",
116
+ blocked_LINEAR_HISTORY_REQUIRED: "linear history required",
117
+ blocked_CONVERSATION_RESOLUTION_REQUIRED: "unresolved review conversations",
118
+ blocked_REQUIRED_CHECK_MISSING: "a required check has not passed",
119
+ blocked_DEPLOYMENT_REQUIRED: "a required deployment has not succeeded",
120
+ blocked_BRANCH_BEHIND: "the branch must be up to date with the base",
121
+ prVerdictBlockedNone: "GitHub does not say why; see the pull request on GitHub",
92
122
  verdict_UNCONFIRMED: "GitHub does not confirm a clean merge (a check is not passing, or it is still computing)",
93
123
  prReadNotFound: "Check the repository and PR number, and confirm this Agent created the PR through Stamp.",
94
124
  prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
@@ -117,6 +147,7 @@ export const messages = {
117
147
  prExisting: "Existing PR #{number}: {url}",
118
148
  prStampPage: " Stamp: {page}",
119
149
  prViewStampPage: "Stamp: {page}",
150
+ prInstance: "Instance: {host}",
120
151
  whoamiCommitEmail: "commit email: {email} (git config user.email {email})",
121
152
  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
153
  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)",
@@ -156,11 +187,14 @@ export const messages = {
156
187
  {cli} pr checks <number|URL> --repo OWNER/REPO
157
188
  {cli} pr comment <number|URL> --repo OWNER/REPO --body-file FILE|- (human; agent posts as the Stamp App)
158
189
  {cli} pr edit <number|URL> --repo OWNER/REPO [--title TITLE] [--body-file FILE|-] (creating agent only)
190
+ {cli} pr close <number|URL> --repo OWNER/REPO [--reason TEXT|--reason-file FILE|-] (creating agent, or a server admin with --reason)
159
191
  {cli} pr approve <number|URL> --repo OWNER/REPO --head SHA --base SHA [--body TEXT] (human; agent without --body)
160
192
  {cli} pr unapprove <number|URL> --repo OWNER/REPO --head SHA --base SHA (agent)
161
193
  {cli} pr merge <number|URL> --repo OWNER/REPO --head SHA --base SHA [--method squash] (human; agent once approved by another)
162
194
  {cli} pr merge <number|URL> --repo OWNER/REPO --auto --head SHA --base SHA (author agent: merge once someone else approves)
163
195
  {cli} pr queue enqueue|status|withdraw <number|URL> --repo OWNER/REPO --request-id ID [--head SHA --base SHA] (agent; coordinates required for enqueue)
196
+ {cli} queue setup|save|verify|enable|status OWNER/REPO [--branch B --workflow ID ...]
197
+ (agent) set up Stamp's merge queue on a registered target branch
164
198
  {cli} repo clone <repository> [<directory>] [-- <gitflags>...]
165
199
  {cli} repo use [DIR] point an existing checkout at this agent's key (repository-local)
166
200
 
@@ -208,6 +242,7 @@ docs: {docs} (the agent workflow, step by step)`,
208
242
  cliUpdateAvailable: "stamp {current} is out of date; {latest} is available: npm install -g @botiverse/stamp-cli@latest",
209
243
  usageRepoUse: "usage: {cli} repo use [DIR] [--identity KEY] [--known-hosts FILE]",
210
244
  repoUseDone: "{directory}: git now reaches Stamp with this agent's key {path} (set in this repository only)",
245
+ staleSshCommand: "warning: this checkout's core.sshCommand points at {path}, which does not exist on this machine; run `{cli} repo use` here to re-pin it before your next push",
211
246
  repoUseFailed: "could not set core.sshCommand in {directory}: {detail}",
212
247
  keyEnsured: "this agent's own SSH key is ready: {path} ({fingerprint}); nothing to configure",
213
248
  keyEnsureFailed: "could not set up this agent's SSH key yet ({reason}); `{cli} repo clone` and `{cli} key enroll` will try again",
package/lib/main.mjs CHANGED
@@ -5,6 +5,7 @@ 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
7
  import { makeUpdateNotice } from "./update-check.mjs";
8
+ import { staleStampSshPath } from "./repo/ssh.mjs";
8
9
  import * as session from "./commands/session.mjs";
9
10
  import * as key from "./commands/key.mjs";
10
11
  import * as knownhosts from "./commands/knownhosts.mjs";
@@ -14,6 +15,7 @@ import * as repo from "./commands/repo.mjs";
14
15
  import * as pr from "./commands/pr.mjs";
15
16
  import * as subscribe from "./commands/subscribe.mjs";
16
17
  import * as changelog from "./commands/changelog.mjs";
18
+ import * as queue from "./commands/queue.mjs";
17
19
 
18
20
  const require = createRequire(import.meta.url);
19
21
  const pkg = require("../package.json");
@@ -36,6 +38,7 @@ const commands = {
36
38
  watch: subscribe.watch,
37
39
  unwatch: subscribe.watch,
38
40
  changelog: changelog.run,
41
+ queue: queue.run,
39
42
  };
40
43
 
41
44
  export async function main(argv, opts) {
@@ -44,7 +47,7 @@ export async function main(argv, opts) {
44
47
  const err = opts.stderr ?? ((s) => console.error(s));
45
48
  let env = opts.env ?? process.env;
46
49
  const exit = opts.exit ?? ((code) => process.exit(code));
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"]);
50
+ const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--reason", "--reason-file", "--idempotency-key", "--method", "-b", "-F", "-R", "--branch", "--workflow", "--ci-policy", "--max-batch", "--wait", "--timeout", "--pr"]);
48
51
  let json = false, langFlag, help = false, version = false;
49
52
  const commandArgs = [];
50
53
  for (let i = 0; i < args.length; i++) {
@@ -95,8 +98,17 @@ export async function main(argv, opts) {
95
98
  return exit(1);
96
99
  }
97
100
 
101
+ // A checkout moved from another machine keeps a core.sshCommand naming a key
102
+ // or known_hosts file that is not here; say so now, on stderr and once,
103
+ // rather than let the next push fail with an opaque ssh error. `repo use`
104
+ // and `repo clone` are the fix, so they stay quiet.
105
+ if (!(cmd === "repo" && (args[0] === "use" || args[0] === "clone"))) {
106
+ const missing = staleStampSshPath({ cwd: opts.cwd ?? process.cwd(), env: opts.gitEnv ?? env, execImpl: opts.sshHintExec });
107
+ if (missing) err(t(locale, "staleSshCommand", { path: missing }));
108
+ }
109
+
98
110
  try {
99
- return await handler({ cmd, args, api, auth, locale, emit, out, err, exit, env, opts });
111
+ return await handler({ cmd, args, api, auth, locale, emit, json, out, err, exit, env, opts });
100
112
  } catch (e) {
101
113
  if (e instanceof ApiError) {
102
114
  err(`${prefix()}${e.message}`);
package/lib/pr/close.mjs CHANGED
@@ -1,16 +1,47 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { AgentError } from "../errors.mjs";
2
3
  import { parsePRTargetArgs } from "./read.mjs";
3
4
 
4
- // Task #622: `stamp pr close` mirrors `pr edit`'s contract — only the agent
5
+ // Task #622: `stamp pr close` mirrors `pr edit`'s contract — the agent
5
6
  // recorded on the creation receipt may close, and the result must echo back
6
7
  // the exact target in state "closed" or the outcome is reported unknown.
8
+ // artin 2026-09-29: an owner/admin of the Raft server the PR was opened from
9
+ // may also close it, with --reason (posted on the PR before the close). The
10
+ // gateway decides who may close; the CLI only carries the reason.
11
+ export const MAX_PR_CLOSE_REASON_CHARS = 1000;
12
+
7
13
  export function parsePRCloseArgs(input) {
8
- const target = parsePRTargetArgs(input, "usagePrClose");
9
- return {
14
+ const targetArgs = [], flags = new Map();
15
+ for (let i = 0; i < input.length; i++) {
16
+ const arg = input[i];
17
+ const match = arg.match(/^(--reason|--reason-file)(?:=(.*))?$/s);
18
+ if (!match) { targetArgs.push(arg); continue; }
19
+ const name = match[1];
20
+ if (flags.has(name)) throw new AgentError("usagePrClose");
21
+ const value = match[2] ?? input[++i];
22
+ if (value === undefined) throw new AgentError("usagePrClose");
23
+ flags.set(name, value);
24
+ }
25
+ if (flags.has("--reason") && flags.has("--reason-file")) throw new AgentError("prCloseReasonConflict");
26
+ const target = parsePRTargetArgs(targetArgs, "usagePrClose");
27
+ const out = {
10
28
  target,
11
29
  method: "POST",
12
30
  path: `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}/close`,
13
31
  };
32
+ if (flags.has("--reason") || flags.has("--reason-file")) {
33
+ let text = flags.get("--reason");
34
+ // `--reason -` means stdin, like `--reason-file -`.
35
+ if (flags.has("--reason-file") || text === "-") {
36
+ const file = flags.get("--reason-file") ?? "-";
37
+ try { text = readFileSync(file === "-" ? 0 : file, "utf8"); }
38
+ catch { throw new AgentError("prCloseReasonRead"); }
39
+ }
40
+ const reason = (text ?? "").trim();
41
+ if (!reason || [...reason].length > MAX_PR_CLOSE_REASON_CHARS) throw new AgentError("prCloseReasonInvalid");
42
+ out.body = { reason };
43
+ }
44
+ return out;
14
45
  }
15
46
 
16
47
  export function validatePRCloseResult(value, target) {
@@ -20,8 +20,9 @@ export function parsePRCommentArgs(input) {
20
20
  if (flags.size !== 1) throw new AgentError("usagePrComment");
21
21
  if (expectedHead !== undefined && !/^[0-9a-fA-F]{40}$/.test(expectedHead)) throw new AgentError("prCommentExpectedHeadInvalid");
22
22
  let body = flags.get("--body");
23
- if (flags.has("--body-file")) {
24
- const file = flags.get("--body-file");
23
+ // `--body -` means stdin, like `--body-file -`.
24
+ if (flags.has("--body-file") || body === "-") {
25
+ const file = flags.get("--body-file") ?? "-";
25
26
  try { body = readFileSync(file === "-" ? 0 : file, "utf8"); }
26
27
  catch { throw new AgentError("prBodyRead"); }
27
28
  }
package/lib/pr/create.mjs CHANGED
@@ -36,8 +36,11 @@ export function pullRequestDraft(args) {
36
36
  if (body !== undefined) return body;
37
37
  if (flags.has("body") && flags.has("body-file")) throw new AgentError("prBodyConflict");
38
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"); }
39
+ // `--body -` means stdin, as the usage line suggests; a PR whose whole
40
+ // description is "-" is never what was meant.
41
+ const file = flags.has("body-file") ? flags.get("body-file") : body === "-" ? "-" : undefined;
42
+ if (file !== undefined) {
43
+ try { body = readFileSync(file === "-" ? 0 : file, "utf8"); }
41
44
  catch { body = undefined; throw new AgentError("prBodyRead"); }
42
45
  }
43
46
  return body;
package/lib/pr/edit.mjs CHANGED
@@ -24,8 +24,9 @@ export function parsePREditArgs(input) {
24
24
  }
25
25
  if (flags.has("--body") || flags.has("--body-file")) {
26
26
  let text = flags.get("--body");
27
- if (flags.has("--body-file")) {
28
- const file = flags.get("--body-file");
27
+ // `--body -` means stdin, like `--body-file -`.
28
+ if (flags.has("--body-file") || text === "-") {
29
+ const file = flags.get("--body-file") ?? "-";
29
30
  try { text = readFileSync(file === "-" ? 0 : file, "utf8"); }
30
31
  catch { throw new AgentError("prBodyRead"); }
31
32
  }
@@ -29,9 +29,26 @@ export function validateVerdict(value) {
29
29
  }
30
30
  }
31
31
  if (typeof value.requiredKnown !== "boolean") throw new AgentError("prReadInvalidResponse");
32
+ // blockedReasons: absent from a gateway before it; present, a list of
33
+ // {code, detail} strings.
34
+ if (value.blockedReasons !== undefined && value.blockedReasons !== null) {
35
+ if (!Array.isArray(value.blockedReasons) ||
36
+ value.blockedReasons.some((r) => !r || typeof r !== "object" || typeof r.code !== "string" || typeof (r.detail ?? "") !== "string")) {
37
+ throw new AgentError("prReadInvalidResponse");
38
+ }
39
+ }
32
40
  return value;
33
41
  }
34
42
 
43
+ // formatBlockedReason: the code's text (or the bare code from a newer
44
+ // gateway), then the gateway's detail.
45
+ function formatBlockedReason(reason, t) {
46
+ const key = `blocked_${reason.code}`;
47
+ const text = t(key);
48
+ const label = text && text !== key ? text : safeInline(reason.code);
49
+ return reason.detail ? `${label}: ${safeInline(reason.detail)}` : label;
50
+ }
51
+
35
52
  // One line: state, a short explanation, the checks behind it, and the exact
36
53
  // coordinates. `t(key)` returns the key itself when there is no message.
37
54
  export function formatVerdictLine(verdict, t) {
@@ -41,6 +58,9 @@ export function formatVerdictLine(verdict, t) {
41
58
  const explained = t(key);
42
59
  const why = explained && explained !== key ? ` — ${explained}` : "";
43
60
  const list = namedChecks[verdict.state] ? verdict[namedChecks[verdict.state]] : [];
44
- const names = list.length ? ` (${list.map(safeInline).join(", ")})` : "";
61
+ let names = list.length ? ` (${list.map(safeInline).join(", ")})` : "";
62
+ if (verdict.state === "BLOCKED" && Array.isArray(verdict.blockedReasons)) {
63
+ names = ` (${verdict.blockedReasons.length ? verdict.blockedReasons.map((r) => formatBlockedReason(r, t)).join("; ") : t("prVerdictBlockedNone")})`;
64
+ }
45
65
  return `${t("prVerdictLabel")}: ${state}${why}${names} @ head ${short(verdict.headSha)} base ${short(verdict.baseSha)}`;
46
66
  }
package/lib/pr/write.mjs CHANGED
@@ -4,9 +4,13 @@ import { parsePRTargetArgs, prDetailPath, takeBooleanFlag, takeNamedFlag } from
4
4
  const shaRE = /^[0-9a-f]{40}$/;
5
5
  const methods = new Set(["", "merge", "squash", "rebase"]);
6
6
 
7
- function requireSHA(value, usageCode) {
8
- if (typeof value !== "string" || !shaRE.test(value)) throw new AgentError(usageCode);
9
- return value;
7
+ // A missing flag is a usage error; a present one that is not a full commit
8
+ // SHA (a short SHA, a branch name) is named, before any request.
9
+ function requireSHA(value, flag, usageCode) {
10
+ if (typeof value !== "string" || value === "") throw new AgentError(usageCode);
11
+ const sha = value.trim().toLowerCase();
12
+ if (!shaRE.test(sha)) throw new AgentError("prWriteFullSHA", { flag });
13
+ return sha;
10
14
  }
11
15
 
12
16
  function parseWriteTarget(input, usageCode) {
@@ -16,8 +20,8 @@ function parseWriteTarget(input, usageCode) {
16
20
  const body = takeNamedFlag(args, "body", "b", usageCode);
17
21
  const methodRaw = takeNamedFlag(args, "method", undefined, usageCode);
18
22
  const target = parsePRTargetArgs(args, usageCode);
19
- const expectedHead = requireSHA(head, usageCode);
20
- const expectedBase = requireSHA(base, usageCode);
23
+ const expectedHead = requireSHA(head, "--head", usageCode);
24
+ const expectedBase = requireSHA(base, "--base", usageCode);
21
25
  const mergeMethod = methodRaw === undefined ? "" : String(methodRaw).toLowerCase();
22
26
  if (!methods.has(mergeMethod)) throw new AgentError(usageCode);
23
27
  if (body !== undefined && !body.trim()) throw new AgentError(usageCode);
@@ -0,0 +1,143 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { takeNamedFlag } from "../pr/read.mjs";
3
+
4
+ // `queue` sets up Stamp's merge queue for a registered target branch, as an
5
+ // agent: discovery (setup), save, verify, enable, status. The gateway owns
6
+ // every rule; the CLI parses, reads the digest it confirms, and prints.
7
+
8
+ const repoPattern = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
9
+ const usage = "usageQueue";
10
+
11
+ function positiveInt(value, { min = 1, max = Number.MAX_SAFE_INTEGER } = {}) {
12
+ if (typeof value !== "string" || !/^\d+$/.test(value)) return undefined;
13
+ const n = Number(value);
14
+ return Number.isSafeInteger(n) && n >= min && n <= max ? n : undefined;
15
+ }
16
+
17
+ function takeBool(args, name) {
18
+ const i = args.indexOf(`--${name}`);
19
+ if (i === -1) return false;
20
+ args.splice(i, 1);
21
+ return true;
22
+ }
23
+
24
+ export function queueBasePath(repository) {
25
+ const [owner, repo] = repository.split("/");
26
+ return `/v1/repositories/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/merge-queue`;
27
+ }
28
+
29
+ export function setupPath(repository, branch, workflow) {
30
+ const q = new URLSearchParams({ branch, mode: "native" });
31
+ if (workflow !== undefined) q.set("workflow", String(workflow));
32
+ return `${queueBasePath(repository)}/setup?${q}`;
33
+ }
34
+
35
+ // parseQueueArgs parses `queue <action> OWNER/REPO [flags]` and never touches
36
+ // the network.
37
+ export function parseQueueArgs(input) {
38
+ const args = [...input];
39
+ const action = args.shift();
40
+ if (!["setup", "save", "verify", "enable", "status"].includes(action)) throw new AgentError(usage);
41
+ const out = { action };
42
+ if (action === "setup" || action === "save") {
43
+ out.branch = takeNamedFlag(args, "branch", undefined, usage);
44
+ const workflow = takeNamedFlag(args, "workflow", undefined, usage);
45
+ if (workflow !== undefined) {
46
+ out.workflow = positiveInt(workflow);
47
+ if (out.workflow === undefined) throw new AgentError("queueWorkflowInvalid");
48
+ }
49
+ if (!out.branch) throw new AgentError(usage);
50
+ }
51
+ if (action === "save") {
52
+ if (out.workflow === undefined) throw new AgentError(usage);
53
+ out.ciPolicy = takeNamedFlag(args, "ci-policy", undefined, usage);
54
+ const maxBatch = takeNamedFlag(args, "max-batch", undefined, usage);
55
+ const wait = takeNamedFlag(args, "wait", undefined, usage);
56
+ const timeout = takeNamedFlag(args, "timeout", undefined, usage);
57
+ if (!["head", "all"].includes(out.ciPolicy)) throw new AgentError("queueCIPolicyInvalid");
58
+ out.maxBatch = positiveInt(maxBatch, { min: 1, max: 10 });
59
+ out.waitSeconds = positiveInt(wait, { min: 0, max: 600 });
60
+ out.timeoutSeconds = positiveInt(timeout, { min: 60, max: 14400 });
61
+ if (out.maxBatch === undefined || out.waitSeconds === undefined || out.timeoutSeconds === undefined) throw new AgentError("queueLimitsInvalid");
62
+ out.confirm = takeBool(args, "confirm");
63
+ }
64
+ if (action === "verify") {
65
+ const pr = takeNamedFlag(args, "pr", undefined, usage);
66
+ out.number = positiveInt(pr);
67
+ if (out.number === undefined) throw new AgentError(usage);
68
+ }
69
+ const repository = args.shift();
70
+ if (!repository || !repoPattern.test(repository) || args.length > 0) throw new AgentError(usage);
71
+ out.repository = repository;
72
+ return out;
73
+ }
74
+
75
+ // The request each action sends. save needs the discovery it confirms.
76
+ export function queueRequest(input, view) {
77
+ const base = queueBasePath(input.repository);
78
+ switch (input.action) {
79
+ case "setup":
80
+ return { method: "GET", path: setupPath(input.repository, input.branch, input.workflow) };
81
+ case "status":
82
+ return { method: "GET", path: base };
83
+ case "verify":
84
+ return { method: "POST", path: `${base}/verify`, body: { number: input.number } };
85
+ case "enable":
86
+ return { method: "POST", path: `${base}/enable`, body: {} };
87
+ case "save":
88
+ return {
89
+ method: "POST", path: `${base}/setup`,
90
+ body: {
91
+ branch: input.branch, workflow: input.workflow, mode: "native", ciPolicy: input.ciPolicy,
92
+ maxBatch: input.maxBatch, waitSeconds: input.waitSeconds, timeoutSeconds: input.timeoutSeconds,
93
+ confirm: true, confirmation: view.confirmation, revision: view.revision, source: view.sourceSha,
94
+ },
95
+ };
96
+ default:
97
+ throw new AgentError(usage);
98
+ }
99
+ }
100
+
101
+ export function validateQueueView(d, input) {
102
+ if (!d || typeof d.repository !== "string" || d.repository.toLowerCase() !== input.repository.toLowerCase()
103
+ || typeof d.enabled !== "boolean" || typeof d.verified !== "boolean") throw new AgentError("queueInvalidResponse");
104
+ if (input.action === "setup" || input.action === "save") {
105
+ if (d.branch !== input.branch || !Array.isArray(d.workflows) || typeof d.canSave !== "boolean" || !Number.isInteger(d.revision)) throw new AgentError("queueInvalidResponse");
106
+ }
107
+ return d;
108
+ }
109
+
110
+ const list = (xs) => (Array.isArray(xs) && xs.length ? xs.join(", ") : "—");
111
+
112
+ // formatQueueSetup is the discovery, as the lines an agent reads before it
113
+ // confirms anything.
114
+ export function formatQueueSetup(d) {
115
+ const lines = [`${d.repository} ${d.branch} (${d.mode}) at ${d.sourceSha || "—"}`];
116
+ lines.push(`workflows:`);
117
+ for (const w of d.workflows) lines.push(` ${w.id} ${w.name} ${w.path}${w.id === d.workflowId ? " (selected)" : ""}`);
118
+ if (d.workflowId) {
119
+ lines.push(`selected workflow: ${d.workflowId} ${d.workflowSha ? `(definition ${d.workflowSha})` : ""}`.trimEnd());
120
+ lines.push(`detected jobs: ${list(d.jobs)}`);
121
+ }
122
+ lines.push(`branch-required checks: ${list(d.required)}`);
123
+ for (const a of d.additionalWorkflows ?? []) lines.push(`additional workflow: ${a.workflowId} ${a.workflowPath} (${a.event}) jobs: ${list(a.requiredJobs)}`);
124
+ lines.push(`rules: ${list(d.rules)}`);
125
+ lines.push(d.canSave ? `confirmation: ${d.confirmation}` : "confirmation: — (select a workflow with --workflow ID to get one)");
126
+ lines.push(`revision: ${d.revision} enabled: ${d.enabled} verified: ${d.verified}`);
127
+ lines.push(`registered targets: ${list(d.registeredTargets)}`);
128
+ return lines;
129
+ }
130
+
131
+ export function formatQueueStatus(d) {
132
+ const lines = [`${d.repository}: ${d.configured ? (d.enabled ? "enabled" : "not enabled") : "not configured"}; verified: ${d.verified}; waiting: ${d.waiting ?? 0}`];
133
+ const c = d.config;
134
+ if (c) {
135
+ lines.push(`branch ${c.branch} (${c.mode}), workflow ${c.workflowId} ${c.workflowPath}, ci-policy ${c.ciPolicy || "head"}, max-batch ${c.maxBatch}, wait ${c.waitSeconds}s, timeout ${c.timeoutSeconds}s, revision ${c.revision}`);
136
+ lines.push(`required jobs: ${list(c.requiredJobs)}`);
137
+ }
138
+ const v = d.lastVerification;
139
+ if (v) lines.push(`last verification: PR #${v.number} ${v.state}${v.passed ? " (passed)" : ""}${v.reason ? `: ${v.reason}` : ""}${v.ciUrl ? ` ${v.ciUrl}` : ""}`);
140
+ else lines.push("last verification: none");
141
+ lines.push(`registered targets: ${list(d.registeredTargets)}`);
142
+ return lines;
143
+ }
package/lib/repo/ssh.mjs CHANGED
@@ -70,6 +70,99 @@ export function sshCommandFor({ identityPath, knownHostsPath }) {
70
70
  ].join(" ");
71
71
  }
72
72
 
73
+ // parseStampSshCommand is the inverse of sshCommandFor: it reads back the
74
+ // identity and known_hosts paths from a core.sshCommand Stamp wrote, undoing
75
+ // shellQuote ('…' runs with '\'' for a quote). Anything that is not that shape
76
+ // — another program, a double quote, no `-i` or no UserKnownHostsFile= —
77
+ // returns null: the caller only speaks about commands Stamp itself wrote.
78
+ export function parseStampSshCommand(command) {
79
+ const tokens = shellWords(String(command ?? "").trim());
80
+ if (!tokens || tokens[0] !== "ssh") return null;
81
+ let identityPath = null;
82
+ let knownHostsPath = null;
83
+ for (let i = 1; i < tokens.length; i++) {
84
+ if (tokens[i] === "-i" && i + 1 < tokens.length) identityPath = tokens[++i];
85
+ else if (tokens[i] === "-o" && i + 1 < tokens.length) {
86
+ const option = tokens[++i];
87
+ if (option.startsWith("UserKnownHostsFile=")) knownHostsPath = option.slice("UserKnownHostsFile=".length);
88
+ }
89
+ }
90
+ if (!identityPath || !knownHostsPath) return null;
91
+ return { identityPath, knownHostsPath };
92
+ }
93
+
94
+ // shellWords splits the subset of sh syntax shellQuote produces: bare words,
95
+ // single-quoted runs and backslash escapes outside quotes. Anything else sh
96
+ // would treat specially returns null rather than a guess.
97
+ function shellWords(text) {
98
+ const words = [];
99
+ let word = null;
100
+ for (let i = 0; i < text.length; i++) {
101
+ const c = text[i];
102
+ if (c === " " || c === "\t") {
103
+ if (word !== null) words.push(word);
104
+ word = null;
105
+ } else if (c === "'") {
106
+ const end = text.indexOf("'", i + 1);
107
+ if (end < 0) return null;
108
+ word = (word ?? "") + text.slice(i + 1, end);
109
+ i = end;
110
+ } else if (c === "\\") {
111
+ if (i + 1 >= text.length) return null;
112
+ word = (word ?? "") + text[++i];
113
+ } else if (/["`$;&|<>()\n]/.test(c)) {
114
+ return null;
115
+ } else {
116
+ word = (word ?? "") + c;
117
+ }
118
+ }
119
+ if (word !== null) words.push(word);
120
+ return words;
121
+ }
122
+
123
+ // staleStampSshPath answers, for the checkout the CLI is standing in, "does
124
+ // its Stamp-written core.sshCommand name a file this machine does not have?"
125
+ // (a checkout moved from another machine keeps the old paths, and nothing
126
+ // notices until `git push` fails with an opaque ssh error). It returns the
127
+ // first missing path, or null.
128
+ //
129
+ // Cost: outside a git work tree nothing runs at all (the `.git` lookup is a
130
+ // few stat calls); inside one it is exactly one `git config` call. Every
131
+ // failure is silence: this is a hint, never a reason for a command to fail.
132
+ export function staleStampSshPath({ cwd, env, execImpl = defaultProbeExec, exists = existsSync }) {
133
+ try {
134
+ const top = gitWorkTreeTop(cwd, env);
135
+ if (!top) return null;
136
+ const got = execImpl("git", ["config", "--local", "--get", "core.sshCommand"], cwd);
137
+ if (got.status !== 0) return null;
138
+ const command = got.stdout.trim();
139
+ if (!/^ssh\s/.test(command) || !/(^|\s)-i\s/.test(command) || !command.includes("UserKnownHostsFile=")) return null;
140
+ const parsed = parseStampSshCommand(command);
141
+ if (!parsed) return null;
142
+ for (const path of [parsed.identityPath, parsed.knownHostsPath]) {
143
+ const absolute = path.startsWith("~/") ? join(homedir(), path.slice(2)) : resolve(top, path);
144
+ if (!exists(absolute)) return path;
145
+ }
146
+ return null;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ // gitWorkTreeTop finds the enclosing work tree without a subprocess: the
153
+ // nearest directory holding a `.git` entry (a directory, or the file a linked
154
+ // worktree or submodule uses). GIT_DIR in the environment also counts.
155
+ function gitWorkTreeTop(cwd, env) {
156
+ if (String(env?.GIT_DIR ?? "").trim()) return resolve(cwd);
157
+ let dir = resolve(cwd);
158
+ for (;;) {
159
+ if (existsSync(join(dir, ".git"))) return dir;
160
+ const parent = dirname(dir);
161
+ if (parent === dir) return null;
162
+ dir = parent;
163
+ }
164
+ }
165
+
73
166
  const KNOWN_HOSTS_KEY_TYPE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)$/;
74
167
  const KNOWN_HOSTS_PATTERN = /^(\[[^\]:]+]:\d{1,5}|[A-Za-z0-9][A-Za-z0-9.-]*)$/;
75
168
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.12",
3
+ "version": "0.3.13",
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",