@botiverse/stamp-cli 0.3.4 → 0.3.8
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 +69 -2
- package/lib/commands/changelog.mjs +58 -0
- package/lib/commands/key.mjs +38 -1
- package/lib/commands/knownhosts.mjs +150 -0
- package/lib/commands/pr.mjs +89 -4
- package/lib/commands/receipt.mjs +24 -1
- package/lib/commands/repo.mjs +16 -4
- package/lib/locale.mjs +212 -22
- package/lib/main.mjs +5 -1
- package/lib/pr/close.mjs +25 -0
- package/lib/pr/comment.mjs +8 -3
- package/lib/pr/create.mjs +2 -0
- package/lib/pr/edit.mjs +53 -0
- package/lib/pr/queue.mjs +32 -0
- package/lib/pr/read.mjs +27 -2
- package/lib/pr/review.mjs +88 -0
- package/lib/pr/verdict.mjs +46 -0
- package/lib/pr/write.mjs +97 -3
- package/lib/receipt/list.mjs +54 -0
- package/lib/repo/identities.mjs +43 -0
- package/lib/repo/ssh.mjs +136 -5
- package/package.json +1 -1
package/lib/pr/read.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AgentError } from "../errors.mjs";
|
|
2
|
+
import { validateVerdict } from "./verdict.mjs";
|
|
2
3
|
|
|
3
4
|
const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
|
|
4
5
|
const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
|
|
@@ -35,7 +36,7 @@ export function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
|
|
|
35
36
|
return value;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
function takeBooleanFlag(args, long) {
|
|
39
|
+
export function takeBooleanFlag(args, long) {
|
|
39
40
|
const i = args.indexOf(`--${long}`);
|
|
40
41
|
if (i === -1) return false;
|
|
41
42
|
args.splice(i, 1);
|
|
@@ -239,8 +240,15 @@ export function validatePRDetail(value, expected) {
|
|
|
239
240
|
requireString(detail.headRef);
|
|
240
241
|
requireString(detail.baseRef);
|
|
241
242
|
if (!ciStatuses.has(requireString(detail.ciStatus))) throw new AgentError("prReadInvalidResponse");
|
|
243
|
+
// Optional: absent means the CI sources were actually read. Validated rather
|
|
244
|
+
// than ignored so a malformed value is caught here instead of silently
|
|
245
|
+
// deciding an exit code further down.
|
|
246
|
+
if (detail.ciUnreadable !== undefined && typeof detail.ciUnreadable !== "boolean") {
|
|
247
|
+
throw new AgentError("prReadInvalidResponse");
|
|
248
|
+
}
|
|
242
249
|
requireString(detail.reviewStatus);
|
|
243
250
|
requireString(detail.reviewFreshness);
|
|
251
|
+
detail.verdict = validateVerdict(detail.verdict);
|
|
244
252
|
if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
|
|
245
253
|
requireString(detail.updatedAt);
|
|
246
254
|
requireString(detail.body);
|
|
@@ -381,8 +389,15 @@ function sectionLabel(section, labels) {
|
|
|
381
389
|
export function formatPRDetail(detail, labels) {
|
|
382
390
|
const lines = [
|
|
383
391
|
`${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
|
|
392
|
+
// The verdict comes second, straight under the title: it is the answer
|
|
393
|
+
// the rest of the output explains (task #607).
|
|
394
|
+
...(labels.verdictLine ? [labels.verdictLine] : []),
|
|
384
395
|
`${labels.head}: ${safeInline(detail.headSha)}`,
|
|
385
|
-
|
|
396
|
+
// Forks on ciUnreadable rather than printing ciStatus straight through. Left
|
|
397
|
+
// alone, `pr view` would keep saying "none" while `pr checks` already says
|
|
398
|
+
// the checks could not be read — one endpoint, two commands, two answers,
|
|
399
|
+
// which is the false trail #598 started on.
|
|
400
|
+
`${labels.checks}: ${detail.ciUnreadable ? labels.ciUnreadable : safeInline(detail.ciStatus)}`,
|
|
386
401
|
`${labels.review}: ${safeInline(detail.reviewStatus)}`,
|
|
387
402
|
safeInline(detail.url),
|
|
388
403
|
];
|
|
@@ -404,6 +419,16 @@ export function formatPRChecks(detail) {
|
|
|
404
419
|
}
|
|
405
420
|
|
|
406
421
|
export function prChecksExitCode(detail) {
|
|
422
|
+
// "Unconfigured" and "unavailable" used to share the line below, because
|
|
423
|
+
// nothing on the wire could tell them apart — the comment there named both.
|
|
424
|
+
// `ciUnreadable` is the first thing that can, so the unreadable case gets its
|
|
425
|
+
// own branch instead of continuing to ride on "the set came back empty".
|
|
426
|
+
//
|
|
427
|
+
// This matters beyond tidiness: someone will eventually decide that a repo
|
|
428
|
+
// with genuinely no CI should not exit non-zero, and if the two cases are
|
|
429
|
+
// still merged, that change silently takes fail-closed with it while reading
|
|
430
|
+
// as a pure ergonomics fix in review.
|
|
431
|
+
if (detail.ciUnreadable) return 1;
|
|
407
432
|
// Match `gh pr checks`: an empty check set is not evidence that CI passed.
|
|
408
433
|
// Keep it non-zero so automation cannot treat an unconfigured or unavailable
|
|
409
434
|
// check suite as a green pull request.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// `stamp pr review <n>`: the reviewer's preparation, in one read (task #551,
|
|
2
|
+
// 飞牛 2026-09-18). Everything a non-author exact-head review starts from —
|
|
3
|
+
// the exact head to pin, the base, the merge-base, whether the base has moved
|
|
4
|
+
// since the branch forked (the trap: diffing against the current base then
|
|
5
|
+
// shows unrelated changes), checks, review state — and the local commands
|
|
6
|
+
// that diff and patch-id against the merge-base rather than the base.
|
|
7
|
+
import { safeInline } from "./read.mjs";
|
|
8
|
+
import { formatVerdictLine } from "./verdict.mjs";
|
|
9
|
+
|
|
10
|
+
// The brief does NOT say whether the base has advanced: GitHub's `base.sha`
|
|
11
|
+
// on a pull request is the fork point and stays put while the base branch
|
|
12
|
+
// moves, so `baseSha !== mergeBaseSha` only detects a retarget or rebase and
|
|
13
|
+
// would call an advanced base "current" — the one sentence this tool exists
|
|
14
|
+
// to prevent (飞牛, review of #258). Until the detail carries the base
|
|
15
|
+
// branch's current tip, the rule is stated unconditionally.
|
|
16
|
+
export function reviewBrief(detail) {
|
|
17
|
+
const short = (sha) => sha.slice(0, 12);
|
|
18
|
+
return {
|
|
19
|
+
repository: detail.repository,
|
|
20
|
+
number: detail.number,
|
|
21
|
+
title: detail.title,
|
|
22
|
+
author: detail.author,
|
|
23
|
+
url: detail.url,
|
|
24
|
+
headSha: detail.headSha,
|
|
25
|
+
headRef: detail.headRef,
|
|
26
|
+
baseRef: detail.baseRef,
|
|
27
|
+
baseSha: detail.baseSha,
|
|
28
|
+
mergeBaseSha: detail.mergeBaseSha,
|
|
29
|
+
ciStatus: detail.ciStatus,
|
|
30
|
+
// Carried through because this brief is what a reviewer reads before
|
|
31
|
+
// pinning a verdict to an exact head. Dropping it here let `pr review`
|
|
32
|
+
// keep saying "none" after `pr view` and `pr checks` had both learned to
|
|
33
|
+
// say the checks were refused -- the same quiet falsehood, on the path
|
|
34
|
+
// where it costs the most (cross, reviewing #602).
|
|
35
|
+
ciUnreadable: detail.ciUnreadable === true,
|
|
36
|
+
reviewStatus: detail.reviewStatus,
|
|
37
|
+
// Stamp's verdict for these exact coordinates (task #607), or null from a
|
|
38
|
+
// gateway that does not compute one.
|
|
39
|
+
stampVerdict: detail.verdict ?? null,
|
|
40
|
+
reviewFreshness: detail.reviewFreshness,
|
|
41
|
+
checks: detail.checks.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),
|
|
42
|
+
commands: {
|
|
43
|
+
fetch: `git fetch origin ${detail.headRef} ${detail.baseRef}`,
|
|
44
|
+
diff: `git diff ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
45
|
+
stat: `git diff --stat ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
46
|
+
log: `git log --oneline ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
47
|
+
patchId: `git diff ${short(detail.mergeBaseSha)} ${short(detail.headSha)} | git patch-id --stable`,
|
|
48
|
+
},
|
|
49
|
+
verdict: `GO|CHANGES @ exact ${detail.headSha}`,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function formatPRReview(brief, t) {
|
|
54
|
+
const lines = [
|
|
55
|
+
`${safeInline(brief.repository)} #${brief.number} — ${safeInline(brief.title)} (${safeInline(brief.author)})`,
|
|
56
|
+
...(brief.stampVerdict ? [formatVerdictLine(brief.stampVerdict, t)] : []),
|
|
57
|
+
`${t("prReviewExactHead")}: ${safeInline(brief.headSha)} (${safeInline(brief.headRef)})`,
|
|
58
|
+
`${t("prReviewBase")}: ${safeInline(brief.baseRef)} @ ${safeInline(brief.baseSha)}`,
|
|
59
|
+
`${t("prReviewMergeBase")}: ${safeInline(brief.mergeBaseSha)}`,
|
|
60
|
+
` ${t("prReviewMergeBaseRule")}`,
|
|
61
|
+
brief.ciUnreadable
|
|
62
|
+
? `${t("prChecksLabel")}: ${t("prCIUnreadable")}`
|
|
63
|
+
: `${t("prChecksLabel")}: ${safeInline(brief.ciStatus)}${brief.checks.length ? " — " + brief.checks.map((c) => `${safeInline(c.name)}=${safeInline(c.conclusion || c.status)}`).join(" ") : ""}`,
|
|
64
|
+
`${t("prReviewLabel")}: ${safeInline(brief.reviewStatus)} (${safeInline(brief.reviewFreshness)})`,
|
|
65
|
+
safeInline(brief.url),
|
|
66
|
+
"",
|
|
67
|
+
`${t("prReviewCommands")}:`,
|
|
68
|
+
` ${brief.commands.fetch}`,
|
|
69
|
+
` ${brief.commands.log}`,
|
|
70
|
+
` ${brief.commands.stat}`,
|
|
71
|
+
` ${brief.commands.diff}`,
|
|
72
|
+
` ${brief.commands.patchId}`,
|
|
73
|
+
"",
|
|
74
|
+
// The qualifier goes ON this line, not eight lines above it. `Checks:
|
|
75
|
+
// unreadable` already appears near the top, but this is the line a reviewer
|
|
76
|
+
// copies to record a verdict, and by the time they reach it there is a whole
|
|
77
|
+
// block of commands in between. This card's entire subject is a true
|
|
78
|
+
// statement sitting somewhere other than where the decision is made; putting
|
|
79
|
+
// it only at the top would have been a milder version of the same thing
|
|
80
|
+
// (飞牛, reviewing #282).
|
|
81
|
+
// Stamp's state rides on the same line for the same reason: a reviewer
|
|
82
|
+
// posting GO on a PR whose required CI never ran should see that here.
|
|
83
|
+
`${t("prReviewVerdict")}: ${brief.verdict}` +
|
|
84
|
+
(brief.ciUnreadable ? ` (${t("prVerdictCIUnreadable")})` : "") +
|
|
85
|
+
(brief.stampVerdict ? ` (Stamp: ${safeInline(brief.stampVerdict.state)})` : ""),
|
|
86
|
+
];
|
|
87
|
+
return lines;
|
|
88
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// The pull request verdict (task #607): the gateway's one-line answer to
|
|
2
|
+
// "can this land now, and if not, why not", shared by `pr view`, `pr review`
|
|
3
|
+
// and the web header. The CLI never computes it; it only validates and prints
|
|
4
|
+
// what the gateway decided, pinned to the head and base it was decided for.
|
|
5
|
+
import { AgentError } from "../errors.mjs";
|
|
6
|
+
import { safeInline } from "./read.mjs";
|
|
7
|
+
|
|
8
|
+
// Lists that name the checks behind a state.
|
|
9
|
+
const namedChecks = {
|
|
10
|
+
CI_FAILING: "requiredFailing",
|
|
11
|
+
CI_NOT_EXECUTED: "requiredSkipped",
|
|
12
|
+
CI_PENDING: "requiredPending",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const listFields = ["requiredPassed", "requiredFailing", "requiredPending", "requiredSkipped", "optional"];
|
|
16
|
+
|
|
17
|
+
// Absent is allowed (a gateway before task #607 does not send it). Present
|
|
18
|
+
// must be well formed. An unknown state is NOT an error: a newer gateway may
|
|
19
|
+
// add states, and an older CLI must still print what it was told.
|
|
20
|
+
export function validateVerdict(value) {
|
|
21
|
+
if (value === undefined || value === null) return undefined;
|
|
22
|
+
if (typeof value !== "object" || Array.isArray(value)) throw new AgentError("prReadInvalidResponse");
|
|
23
|
+
for (const field of ["state", "headSha", "baseSha"]) {
|
|
24
|
+
if (typeof value[field] !== "string" || value[field] === "") throw new AgentError("prReadInvalidResponse");
|
|
25
|
+
}
|
|
26
|
+
for (const field of listFields) {
|
|
27
|
+
if (!Array.isArray(value[field]) || value[field].some((name) => typeof name !== "string")) {
|
|
28
|
+
throw new AgentError("prReadInvalidResponse");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (typeof value.requiredKnown !== "boolean") throw new AgentError("prReadInvalidResponse");
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// One line: state, a short explanation, the checks behind it, and the exact
|
|
36
|
+
// coordinates. `t(key)` returns the key itself when there is no message.
|
|
37
|
+
export function formatVerdictLine(verdict, t) {
|
|
38
|
+
const short = (sha) => safeInline(sha).slice(0, 12);
|
|
39
|
+
const state = safeInline(verdict.state);
|
|
40
|
+
const key = `verdict_${verdict.state}`;
|
|
41
|
+
const explained = t(key);
|
|
42
|
+
const why = explained && explained !== key ? ` — ${explained}` : "";
|
|
43
|
+
const list = namedChecks[verdict.state] ? verdict[namedChecks[verdict.state]] : [];
|
|
44
|
+
const names = list.length ? ` (${list.map(safeInline).join(", ")})` : "";
|
|
45
|
+
return `${t("prVerdictLabel")}: ${state}${why}${names} @ head ${short(verdict.headSha)} base ${short(verdict.baseSha)}`;
|
|
46
|
+
}
|
package/lib/pr/write.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentError } from "../errors.mjs";
|
|
2
|
-
import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
|
|
2
|
+
import { parsePRTargetArgs, prDetailPath, takeBooleanFlag, takeNamedFlag } from "./read.mjs";
|
|
3
3
|
|
|
4
4
|
const shaRE = /^[0-9a-f]{40}$/;
|
|
5
5
|
const methods = new Set(["", "merge", "squash", "rebase"]);
|
|
@@ -39,6 +39,19 @@ export function parsePRApproveArgs(input) {
|
|
|
39
39
|
};
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
// An agent withdraws its own Stamp-recorded approval of this exact head. There
|
|
43
|
+
// is no body: a Stamp approval is a vote, not a review.
|
|
44
|
+
export function parsePRUnapproveArgs(input) {
|
|
45
|
+
const parsed = parseWriteTarget(input, "usagePrUnapprove");
|
|
46
|
+
if (parsed.mergeMethod || parsed.body !== undefined) throw new AgentError("usagePrUnapprove");
|
|
47
|
+
return {
|
|
48
|
+
target: parsed.target,
|
|
49
|
+
path: `${prDetailPath(parsed.target)}/unapprove`,
|
|
50
|
+
method: "POST",
|
|
51
|
+
body: { expectedHead: parsed.expectedHead, expectedBase: parsed.expectedBase },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
42
55
|
export function parsePRMergeArgs(input) {
|
|
43
56
|
const parsed = parseWriteTarget(input, "usagePrMerge");
|
|
44
57
|
if (parsed.body !== undefined) throw new AgentError("usagePrMerge");
|
|
@@ -59,24 +72,105 @@ function requireObject(value, code) {
|
|
|
59
72
|
return value;
|
|
60
73
|
}
|
|
61
74
|
|
|
75
|
+
// A human approval is a GitHub review (reviewerLogin); an agent approval is
|
|
76
|
+
// recorded by Stamp (recordedBy "stamp", reviewer = the agent's Raft id).
|
|
77
|
+
function validStampApproval(d, action) {
|
|
78
|
+
return d.recordedBy === "stamp" && d.action === action
|
|
79
|
+
&& typeof d.reviewer === "string" && d.reviewer.length > 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
62
82
|
export function validatePRApproveResult(result, target) {
|
|
63
83
|
const expectedRepo = `${target.owner}/${target.repo}`;
|
|
64
84
|
const d = requireObject(result, "prApproveOutcomeUnknown");
|
|
65
85
|
const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
66
86
|
&& d.number === target.number
|
|
67
87
|
&& shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
|
|
68
|
-
&& typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin)
|
|
88
|
+
&& ((typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin))
|
|
89
|
+
|| validStampApproval(d, "approve"));
|
|
69
90
|
if (!valid) throw new AgentError("prApproveOutcomeUnknown");
|
|
70
91
|
return d;
|
|
71
92
|
}
|
|
72
93
|
|
|
94
|
+
export function validatePRUnapproveResult(result, target) {
|
|
95
|
+
const expectedRepo = `${target.owner}/${target.repo}`;
|
|
96
|
+
const d = requireObject(result, "prUnapproveOutcomeUnknown");
|
|
97
|
+
const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
98
|
+
&& d.number === target.number
|
|
99
|
+
&& shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
|
|
100
|
+
&& validStampApproval(d, "unapprove");
|
|
101
|
+
if (!valid) throw new AgentError("prUnapproveOutcomeUnknown");
|
|
102
|
+
return d;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A human merge is GitHub's, as the bound user (actorLogin); an agent merge is
|
|
106
|
+
// performed by the Stamp App (mergedBy "stamp-app", agent = the Raft id).
|
|
107
|
+
function validAppMerge(d) {
|
|
108
|
+
return d.mergedBy === "stamp-app" && typeof d.agent === "string" && d.agent.length > 0;
|
|
109
|
+
}
|
|
110
|
+
|
|
73
111
|
export function validatePRMergeResult(result, target) {
|
|
74
112
|
const expectedRepo = `${target.owner}/${target.repo}`;
|
|
75
113
|
const d = requireObject(result, "prMergeOutcomeUnknown");
|
|
76
114
|
const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
77
115
|
&& d.number === target.number && d.merged === true
|
|
78
116
|
&& shaRE.test(d.mergeSha) && shaRE.test(d.mergedHead) && shaRE.test(d.mergedBase)
|
|
79
|
-
&& typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin)
|
|
117
|
+
&& ((typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin))
|
|
118
|
+
|| validAppMerge(d));
|
|
80
119
|
if (!valid) throw new AgentError("prMergeOutcomeUnknown");
|
|
81
120
|
return d;
|
|
82
121
|
}
|
|
122
|
+
|
|
123
|
+
// `pr merge --auto` (task #664): the author registers the PR to be merged by
|
|
124
|
+
// Stamp once someone else approves that exact head and the verdict is READY.
|
|
125
|
+
// `--auto --cancel` withdraws; `--auto --status` reads the registration.
|
|
126
|
+
// Register and withdraw pin --head and --base like every write.
|
|
127
|
+
export function isAutoMergeArgs(input) {
|
|
128
|
+
return input.includes("--auto");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function parsePRAutoMergeArgs(input) {
|
|
132
|
+
const args = [...input];
|
|
133
|
+
takeBooleanFlag(args, "auto");
|
|
134
|
+
const cancel = takeBooleanFlag(args, "cancel");
|
|
135
|
+
const status = takeBooleanFlag(args, "status");
|
|
136
|
+
if (cancel && status) throw new AgentError("usagePrMerge");
|
|
137
|
+
if (status) {
|
|
138
|
+
const target = parsePRTargetArgs(args, "usagePrMerge");
|
|
139
|
+
return { kind: "status", target, path: `${prDetailPath(target)}/auto-merge`, method: "GET" };
|
|
140
|
+
}
|
|
141
|
+
const parsed = parseWriteTarget(args, "usagePrMerge");
|
|
142
|
+
if (parsed.body !== undefined || (cancel && parsed.mergeMethod)) throw new AgentError("usagePrMerge");
|
|
143
|
+
return {
|
|
144
|
+
kind: cancel ? "cancel" : "arm",
|
|
145
|
+
target: parsed.target,
|
|
146
|
+
path: `${prDetailPath(parsed.target)}/auto-merge`,
|
|
147
|
+
method: cancel ? "DELETE" : "PUT",
|
|
148
|
+
body: {
|
|
149
|
+
expectedHead: parsed.expectedHead,
|
|
150
|
+
expectedBase: parsed.expectedBase,
|
|
151
|
+
...(parsed.mergeMethod ? { mergeMethod: parsed.mergeMethod } : {}),
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The gateway's answer must be about the PR that was asked for. An unknown
|
|
157
|
+
// state from a newer gateway is passed through, not rejected.
|
|
158
|
+
export function validatePRAutoMergeResult(result, target) {
|
|
159
|
+
const expectedRepo = `${target.owner}/${target.repo}`;
|
|
160
|
+
const d = requireObject(result, "prMergeOutcomeUnknown");
|
|
161
|
+
const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
162
|
+
&& d.number === target.number && typeof d.state === "string" && d.state !== ""
|
|
163
|
+
&& shaRE.test(d.currentHead)
|
|
164
|
+
&& (d.armedHead === undefined || shaRE.test(d.armedHead));
|
|
165
|
+
if (!valid) throw new AgentError("prMergeOutcomeUnknown");
|
|
166
|
+
return d;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// One line: the state, what it means, and the pinned head.
|
|
170
|
+
export function formatAutoMerge(d, t) {
|
|
171
|
+
const key = `prAutoMerge_${d.state}`;
|
|
172
|
+
const vars = { repository: d.repository, number: d.number, head: (d.armedHead || d.currentHead).slice(0, 12), method: d.mergeMethod || "" };
|
|
173
|
+
const text = t(key, vars);
|
|
174
|
+
const line = text !== key ? text : `${d.repository}#${d.number}: ${d.state}`;
|
|
175
|
+
return d.alreadyInEffect ? `${line} ${t("prAutoMergeUnchanged")}` : line;
|
|
176
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { AgentError } from "../errors.mjs";
|
|
2
|
+
import { takeNamedFlag } from "../pr/read.mjs";
|
|
3
|
+
|
|
4
|
+
// `stamp receipt list` (task #580): the session agent lists only its own push
|
|
5
|
+
// receipts — never another agent's, never the same agent's on another server.
|
|
6
|
+
// The endpoint is always paged ({items, nextCursor}); --limit/--cursor opt
|
|
7
|
+
// into walking further, --repo narrows server-side and is bound into the
|
|
8
|
+
// cursor so a cursor minted under one filter cannot replay under another.
|
|
9
|
+
|
|
10
|
+
export const RECEIPT_LIST_MAX_LIMIT = 100;
|
|
11
|
+
|
|
12
|
+
export function parseReceiptListArgs(input) {
|
|
13
|
+
const args = [...input];
|
|
14
|
+
const repo = takeNamedFlag(args, "repo", "R", "usageReceiptList");
|
|
15
|
+
const limitRaw = takeNamedFlag(args, "limit", undefined, "usageReceiptList");
|
|
16
|
+
const cursor = takeNamedFlag(args, "cursor", undefined, "usageReceiptList");
|
|
17
|
+
if (args.length !== 0) throw new AgentError("usageReceiptList");
|
|
18
|
+
|
|
19
|
+
const params = new URLSearchParams();
|
|
20
|
+
if (repo !== undefined) {
|
|
21
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new AgentError("usageReceiptList");
|
|
22
|
+
params.set("repo", repo);
|
|
23
|
+
}
|
|
24
|
+
if (limitRaw !== undefined) {
|
|
25
|
+
if (!/^[1-9][0-9]*$/.test(limitRaw) || Number(limitRaw) > RECEIPT_LIST_MAX_LIMIT) {
|
|
26
|
+
throw new AgentError("usageReceiptList");
|
|
27
|
+
}
|
|
28
|
+
params.set("limit", limitRaw);
|
|
29
|
+
}
|
|
30
|
+
if (cursor !== undefined) params.set("cursor", cursor);
|
|
31
|
+
const query = params.toString();
|
|
32
|
+
return { path: query === "" ? "/v1/receipts" : `/v1/receipts?${query}` };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function validateReceiptList(d) {
|
|
36
|
+
if (!d || !Array.isArray(d.items)) throw new AgentError("receiptListBadResponse");
|
|
37
|
+
for (const item of d.items) {
|
|
38
|
+
if (typeof item?.id !== "string" || typeof item?.status !== "string" ||
|
|
39
|
+
typeof item?.repository !== "string" || typeof item?.targetRef !== "string") {
|
|
40
|
+
throw new AgentError("receiptListBadResponse");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (d.nextCursor !== null && d.nextCursor !== undefined && typeof d.nextCursor !== "string") {
|
|
44
|
+
throw new AgentError("receiptListBadResponse");
|
|
45
|
+
}
|
|
46
|
+
return { items: d.items, nextCursor: d.nextCursor ?? null };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function formatReceiptLine(item) {
|
|
50
|
+
let line = `${item.id} ${item.status} ${item.repository} ${item.targetRef} published=${item.publishedSha ?? "-"}`;
|
|
51
|
+
if (item.publishAttempts) line += ` attempts=${item.publishAttempts}`;
|
|
52
|
+
if (item.nextRetryAt) line += ` nextRetry=${item.nextRetryAt}`;
|
|
53
|
+
return line;
|
|
54
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
// Task #514 (ka-grok): "key enroll 用过哪把钥,clone 就用那把" — the key `stamp
|
|
6
|
+
// key enroll` enrolled is the key `stamp repo clone` uses, recorded at enroll
|
|
7
|
+
// time and read back at clone time, per instance origin. The CLI never scans
|
|
8
|
+
// ~/.ssh or guesses paths: a record is written only from what the operator
|
|
9
|
+
// pointed enroll at, and a missing record falls through to the documented
|
|
10
|
+
// default path, whose absence is reported (not searched around).
|
|
11
|
+
|
|
12
|
+
export function identitiesPath(env) {
|
|
13
|
+
const fromEnv = String(env?.STAMP_IDENTITIES ?? "").trim();
|
|
14
|
+
return fromEnv || join(homedir(), ".stamp", "identities.json");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function readAll(path) {
|
|
18
|
+
if (!existsSync(path)) return {};
|
|
19
|
+
let parsed;
|
|
20
|
+
try { parsed = JSON.parse(readFileSync(path, "utf8")); } catch { return {}; }
|
|
21
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// readRecordedIdentity returns the enrollment record for one origin, or null.
|
|
25
|
+
// A corrupt or foreign-shaped file is "no record", never an exception: the
|
|
26
|
+
// record is a convenience over an explicit flag, not a gate.
|
|
27
|
+
export function readRecordedIdentity(env, origin) {
|
|
28
|
+
const record = readAll(identitiesPath(env))[String(origin ?? "")];
|
|
29
|
+
if (!record || typeof record !== "object" || typeof record.identityPath !== "string" || !record.identityPath) return null;
|
|
30
|
+
return record;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// recordIdentity merges one origin's record into the file (0600: it names a
|
|
34
|
+
// private key path and a key id, not a secret, but it is the operator's).
|
|
35
|
+
export function recordIdentity(env, origin, record) {
|
|
36
|
+
const path = identitiesPath(env);
|
|
37
|
+
const all = readAll(path);
|
|
38
|
+
all[String(origin)] = record;
|
|
39
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
40
|
+
writeFileSync(path, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
|
|
41
|
+
chmodSync(path, 0o600);
|
|
42
|
+
return path;
|
|
43
|
+
}
|
package/lib/repo/ssh.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { dirname, join } from "node:path";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
4
5
|
|
|
5
6
|
// `stamp repo clone` must not ask a human to export GIT_SSH_COMMAND: after
|
|
6
7
|
// `stamp key enroll` the CLI already knows which key it enrolled and the
|
|
@@ -15,11 +16,22 @@ export function defaultIdentityPath(env) {
|
|
|
15
16
|
return join(homedir(), ".ssh", "id_ed25519");
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
// resolveIdentity picks the private key in this order and says which source
|
|
20
|
+
// won: an explicit --identity, the STAMP_SSH_IDENTITY override, the key
|
|
21
|
+
// recorded by `stamp key enroll` for this instance (task #514), the default
|
|
22
|
+
// path. No source scans a directory.
|
|
23
|
+
export function resolveIdentity(env, flagValue, recorded) {
|
|
19
24
|
const fromFlag = String(flagValue ?? "").trim();
|
|
20
|
-
if (fromFlag) return fromFlag;
|
|
25
|
+
if (fromFlag) return { identityPath: fromFlag, source: "flag" };
|
|
21
26
|
const fromEnv = String(env?.STAMP_SSH_IDENTITY ?? "").trim();
|
|
22
|
-
return fromEnv
|
|
27
|
+
if (fromEnv) return { identityPath: fromEnv, source: "env" };
|
|
28
|
+
const fromRecord = String(recorded?.identityPath ?? "").trim();
|
|
29
|
+
if (fromRecord) return { identityPath: fromRecord, source: "enrolled" };
|
|
30
|
+
return { identityPath: defaultIdentityPath(env), source: "default" };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function resolveIdentityPath(env, flagValue, recorded) {
|
|
34
|
+
return resolveIdentity(env, flagValue, recorded).identityPath;
|
|
23
35
|
}
|
|
24
36
|
|
|
25
37
|
// defaultKnownHostsPath is one stable file for every Stamp instance (a
|
|
@@ -94,3 +106,122 @@ export async function fetchPublishedKnownHosts({ apiBase, fetchImpl = fetch }) {
|
|
|
94
106
|
if (!parsed) return { ok: false, invalid: true };
|
|
95
107
|
return { ok: true, pattern: parsed.pattern, line: parsed.line };
|
|
96
108
|
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Does the repo the agent pushes from actually read the file we just wrote?
|
|
112
|
+
//
|
|
113
|
+
// `known-hosts refresh` writes Stamp's canonical path, but git uses whatever
|
|
114
|
+
// core.sshCommand — or ssh's own config — names. The two can differ silently,
|
|
115
|
+
// so the command could report success, print the right fingerprint, and leave
|
|
116
|
+
// the file git consults untouched (#595). That failure surfaces only on
|
|
117
|
+
// rotation day, and it surfaces as "push refused" to someone who was just told
|
|
118
|
+
// the refresh worked — which is the moment people disable host key checking.
|
|
119
|
+
//
|
|
120
|
+
// The effective path is NOT derived by parsing core.sshCommand. Re-implementing
|
|
121
|
+
// ssh's option parsing diverges from ssh itself on `-oFoo=` without a space,
|
|
122
|
+
// `-F`, an unexpanded `~`, and repeated `-o`. The repo's own ssh program is
|
|
123
|
+
// asked with `-G` instead, which reports the value ssh would use.
|
|
124
|
+
|
|
125
|
+
// endpointFor turns the published known_hosts pattern into the host and port to
|
|
126
|
+
// ask ssh about, so the probe targets the same endpoint the pin covers.
|
|
127
|
+
export function endpointFor(pattern) {
|
|
128
|
+
const bracketed = /^\[([^\]:]+)]:(\d{1,5})$/.exec(String(pattern ?? ""));
|
|
129
|
+
if (bracketed) return { host: bracketed[1], port: Number(bracketed[2]) };
|
|
130
|
+
const bare = String(pattern ?? "").trim();
|
|
131
|
+
return bare ? { host: bare, port: 22 } : null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// userKnownHostsFilesIn reads the one `userknownhostsfile` line out of `ssh -G`
|
|
135
|
+
// output. The value may name several files (the default is `known_hosts` plus
|
|
136
|
+
// `known_hosts2`), and a single path may itself contain spaces, so the raw
|
|
137
|
+
// value is kept alongside the whitespace split rather than resolved to one.
|
|
138
|
+
export function userKnownHostsFilesIn(sshGOutput) {
|
|
139
|
+
for (const line of String(sshGOutput ?? "").split("\n")) {
|
|
140
|
+
const m = /^userknownhostsfile\s+(.*)$/i.exec(line.trim());
|
|
141
|
+
if (m) return { raw: m[1].trim(), candidates: m[1].trim().split(/\s+/).filter(Boolean) };
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// canonicalPath names a file the same way regardless of how it was spelled.
|
|
147
|
+
// resolve() alone is not enough: it makes a path absolute but does not follow
|
|
148
|
+
// symlinks, so on macOS the written `/tmp/x` and ssh's `/private/tmp/x` are one
|
|
149
|
+
// file under two names and compared unequal, which told a correctly configured
|
|
150
|
+
// repo it was misconfigured. Symlinked home directories and bind-mounted
|
|
151
|
+
// checkouts do the same thing off macOS.
|
|
152
|
+
//
|
|
153
|
+
// A path that cannot be canonicalised keeps its merely-absolute form. Only the
|
|
154
|
+
// value ssh reports can be in that state — the file this command wrote exists
|
|
155
|
+
// by the time the comparison runs — and a name that resolves to nothing cannot
|
|
156
|
+
// be the file we just wrote, so the fallback decides nothing on its own.
|
|
157
|
+
function canonicalPath(path) {
|
|
158
|
+
const absolute = resolve(path);
|
|
159
|
+
try {
|
|
160
|
+
return realpathSync(absolute);
|
|
161
|
+
} catch {
|
|
162
|
+
return absolute;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// knownHostsIsUsedBy answers "would ssh read the file we wrote?". A path that
|
|
167
|
+
// contains spaces is ambiguous against a value naming several files, so both
|
|
168
|
+
// readings are accepted. The ambiguity is resolved towards agreement on
|
|
169
|
+
// purpose: a false "your repo is misconfigured" is worse than staying quiet,
|
|
170
|
+
// because it sends a correctly configured agent looking for something to
|
|
171
|
+
// change, and the handiest change is StrictHostKeyChecking=no.
|
|
172
|
+
export function knownHostsIsUsedBy(effective, writtenPath) {
|
|
173
|
+
const want = canonicalPath(writtenPath);
|
|
174
|
+
if (canonicalPath(effective.raw) === want) return true;
|
|
175
|
+
return effective.candidates.some((candidate) => canonicalPath(candidate) === want);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function defaultProbeExec(command, args, cwd) {
|
|
179
|
+
const res = spawnSync(command, args, { cwd, encoding: "utf8", timeout: 10_000 });
|
|
180
|
+
return { status: res.status, stdout: res.stdout ?? "" };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// probeRepoKnownHosts reports which known_hosts the repo at `cwd` would use.
|
|
184
|
+
//
|
|
185
|
+
// Every failure — not a repo, no git, ssh missing, a core.sshCommand that will
|
|
186
|
+
// not run — returns `known: false` and the caller stays silent. This check
|
|
187
|
+
// exists to keep people from disabling host key checking; it must never become
|
|
188
|
+
// a reason to start changing a working setup.
|
|
189
|
+
//
|
|
190
|
+
// The probe runs the repo's own core.sshCommand. That is the same string
|
|
191
|
+
// `git push` already executes here, so it adds no exposure for the repo the
|
|
192
|
+
// agent is standing in — but it is why this must never accept a repository
|
|
193
|
+
// path as an argument: running a stranger's configuration is a different act.
|
|
194
|
+
//
|
|
195
|
+
// ACCEPTED LIMIT, not an oversight (飞牛, reviewing #595): this is a
|
|
196
|
+
// configuration-hygiene check, not a tamper-evident one.
|
|
197
|
+
// it answers: which file this repo's configuration SAYS it reads
|
|
198
|
+
// it cannot answer: which file this repo actually reads — the configuration
|
|
199
|
+
// can lie, and `ssh -G` output is produced by that very
|
|
200
|
+
// configuration
|
|
201
|
+
// So "refresh reported nothing" means the configuration is aligned; it does not
|
|
202
|
+
// prove the client is using the pinned file. The stronger check — connecting
|
|
203
|
+
// once with the file just written — is deliberately not done here, because a
|
|
204
|
+
// command that fails on an unreachable network sends people to
|
|
205
|
+
// StrictHostKeyChecking=no. Keep the two claims separate wherever this is
|
|
206
|
+
// described; an accepted limit that is not written down gets read as a
|
|
207
|
+
// guarantee it never made.
|
|
208
|
+
export function probeRepoKnownHosts({ cwd, pattern, execImpl = defaultProbeExec }) {
|
|
209
|
+
const endpoint = endpointFor(pattern);
|
|
210
|
+
if (!endpoint) return { known: false };
|
|
211
|
+
const inside = execImpl("git", ["rev-parse", "--is-inside-work-tree"], cwd);
|
|
212
|
+
if (inside.status !== 0 || inside.stdout.trim() !== "true") return { known: false, inRepo: false };
|
|
213
|
+
|
|
214
|
+
const configured = execImpl("git", ["config", "--get", "core.sshCommand"], cwd);
|
|
215
|
+
// `--get` exits non-zero with empty output when the key is unset. That is the
|
|
216
|
+
// signal itself, not an error: such a repo connects through ssh's own config
|
|
217
|
+
// or a per-invocation GIT_SSH_COMMAND.
|
|
218
|
+
const sshCommand = configured.status === 0 ? configured.stdout.trim() : "";
|
|
219
|
+
const probe = execImpl("/bin/sh", [
|
|
220
|
+
"-c",
|
|
221
|
+
`${sshCommand || "ssh"} -G -p ${endpoint.port} ${endpoint.host}`,
|
|
222
|
+
], cwd);
|
|
223
|
+
if (probe.status !== 0) return { known: false, inRepo: true, configured: sshCommand !== "" };
|
|
224
|
+
const effective = userKnownHostsFilesIn(probe.stdout);
|
|
225
|
+
if (!effective) return { known: false, inRepo: true, configured: sshCommand !== "" };
|
|
226
|
+
return { known: true, inRepo: true, configured: sshCommand !== "", effective };
|
|
227
|
+
}
|