@botiverse/stamp-cli 0.3.13 → 0.4.0

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/lib/pr/close.mjs DELETED
@@ -1,56 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { AgentError } from "../errors.mjs";
3
- import { parsePRTargetArgs } from "./read.mjs";
4
-
5
- // Task #622: `stamp pr close` mirrors `pr edit`'s contract — the agent
6
- // recorded on the creation receipt may close, and the result must echo back
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
-
13
- export function parsePRCloseArgs(input) {
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 = {
28
- target,
29
- method: "POST",
30
- path: `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}/close`,
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;
45
- }
46
-
47
- export function validatePRCloseResult(value, target) {
48
- const repository = `${target.owner}/${target.repo}`;
49
- const valid = value && typeof value === "object" && !Array.isArray(value)
50
- && typeof value.repository === "string" && value.repository.toLowerCase() === repository.toLowerCase()
51
- && value.number === target.number
52
- && typeof value.url === "string" && value.url.toLowerCase() === `https://github.com/${repository}/pull/${target.number}`.toLowerCase()
53
- && value.state === "closed";
54
- if (!valid) throw new AgentError("prCloseOutcomeUnknown");
55
- return value;
56
- }
@@ -1,45 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { AgentError } from "../errors.mjs";
3
- import { parsePRTargetArgs, prDetailPath } from "./read.mjs";
4
-
5
- export function parsePRCommentArgs(input) {
6
- const targetArgs = [], flags = new Map();
7
- for (let i = 0; i < input.length; i++) {
8
- const arg = input[i];
9
- const match = arg.match(/^(--body|--body-file|--expected-head)(?:=(.*))?$/s);
10
- const name = match?.[1] ?? ({ "-b": "--body", "-F": "--body-file" })[arg];
11
- if (!name) { targetArgs.push(arg); continue; }
12
- if (flags.has(name)) throw new AgentError("usagePrComment");
13
- const value = match?.[2] ?? input[++i];
14
- if (value === undefined) throw new AgentError("usagePrComment");
15
- flags.set(name, value);
16
- }
17
- const target = parsePRTargetArgs(targetArgs, "usagePrComment");
18
- const expectedHead = flags.get("--expected-head");
19
- flags.delete("--expected-head");
20
- if (flags.size !== 1) throw new AgentError("usagePrComment");
21
- if (expectedHead !== undefined && !/^[0-9a-fA-F]{40}$/.test(expectedHead)) throw new AgentError("prCommentExpectedHeadInvalid");
22
- let body = flags.get("--body");
23
- // `--body -` means stdin, like `--body-file -`.
24
- if (flags.has("--body-file") || body === "-") {
25
- const file = flags.get("--body-file") ?? "-";
26
- try { body = readFileSync(file === "-" ? 0 : file, "utf8"); }
27
- catch { throw new AgentError("prBodyRead"); }
28
- }
29
- if (!body?.trim() || Buffer.byteLength(body, "utf8") > 65536) throw new AgentError("prCommentBodyInvalid");
30
- const request = { body };
31
- if (expectedHead !== undefined) request.expectedHead = expectedHead.toLowerCase();
32
- return { target, path: `${prDetailPath(target)}/comments`, body: request };
33
- }
34
-
35
- export function validatePRCommentResult(result, target) {
36
- const expectedRepo = `${target.owner}/${target.repo}`;
37
- const valid = result && typeof result === "object" && !Array.isArray(result)
38
- && typeof result.repository === "string" && result.repository.toLowerCase() === expectedRepo.toLowerCase()
39
- && result.number === target.number && Number.isSafeInteger(result.commentId) && result.commentId > 0
40
- && typeof result.actorLogin === "string" && /^[A-Za-z0-9-]+(\[bot\])?$/.test(result.actorLogin)
41
- && typeof result.url === "string"
42
- && result.url.toLowerCase() === `https://github.com/${expectedRepo}/pull/${target.number}#issuecomment-${result.commentId}`.toLowerCase();
43
- if (!valid) throw new AgentError("prCommentOutcomeUnknown");
44
- return result;
45
- }
package/lib/pr/create.mjs DELETED
@@ -1,165 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { readFileSync } from "node:fs";
3
- import { AgentError } from "../errors.mjs";
4
-
5
- const names = new Set(["receipt", "repo", "head", "sha", "base", "title", "body", "body-file", "idempotency-key"]);
6
-
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) {
23
- const flags = new Map();
24
- for (let i = 0; i < args.length; i++) {
25
- const [flag, ...inline] = args[i].split("=");
26
- const name = flag.slice(2);
27
- if (!flag.startsWith("--") || !names.has(name) || flags.has(name)) throw new AgentError("usagePrCreate");
28
- const value = inline.length ? inline.join("=") : args[++i];
29
- if (value === undefined || (!inline.length && value.startsWith("--"))) throw new AgentError("usagePrCreate");
30
- flags.set(name, value);
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
- // `--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"); }
44
- catch { body = undefined; throw new AgentError("prBodyRead"); }
45
- }
46
- return body;
47
- },
48
- };
49
- }
50
-
51
- export function pullRequestInput(args, fromReceipt = null, draft = pullRequestDraft(args)) {
52
- const flags = new Map(draft.flags);
53
- if (fromReceipt) {
54
- flags.set("repo", fromReceipt.repository);
55
- flags.set("head", fromReceipt.targetRef);
56
- flags.set("sha", fromReceipt.publishedSha);
57
- }
58
- for (const name of ["receipt", "repo", "head", "sha", "base", "title"]) {
59
- if (!flags.get(name)?.trim()) throw new AgentError("prRequired", { flag: `--${name}` });
60
- }
61
- if (!/^[^/\s]+\/[^/\s]+$/.test(flags.get("repo"))) throw new AgentError("prRepository");
62
- if (!/^[0-9a-f]{40}$/.test(flags.get("sha"))) throw new AgentError("prSHA");
63
- const ref = (name) => {
64
- const value = flags.get(name);
65
- return value.startsWith("refs/") ? value : `refs/heads/${value}`;
66
- };
67
- const body = draft.body();
68
- if (!body.trim()) throw new AgentError("prBodyRequired");
69
- const input = {
70
- receiptId: flags.get("receipt"), repository: flags.get("repo"),
71
- targetRef: ref("head"), newSha: flags.get("sha"), baseRef: ref("base"),
72
- title: flags.get("title"), body,
73
- };
74
- // Identical retries, including after a lost response or a new CLI process,
75
- // retain the same key. No local credentials or state enter this digest.
76
- // The server MUST scope idempotency by tenant, server and agent identity.
77
- input.idempotencyKey = flags.get("idempotency-key") ?? `stamp-pr-${createHash("sha256").update(JSON.stringify(input)).digest("hex")}`;
78
- if (!/^[A-Za-z0-9._:-]{16,128}$/.test(input.idempotencyKey)) throw new AgentError("prIdempotency");
79
- return input;
80
- }
81
-
82
- export function pullRequestRecovery(code) {
83
- switch (code) {
84
- case "INVALID_PULL_REQUEST_REQUEST": return "prCheckArguments";
85
- case "GITHUB_APP_NOT_CONFIGURED":
86
- case "GITHUB_CLIENT_INVALID": return "prCheckConfiguration";
87
- case "PUBLISHED_RECEIPT_NOT_FOUND": return "prWaitPublished";
88
- case "PUBLISHED_RECEIPT_BINDING_MISMATCH":
89
- case "GITHUB_HEAD_DRIFT": return "prCheckReceipt";
90
- case "REPOSITORY_NOT_AUTHORIZED":
91
- // Gateways before v0.1.38 still answer this for any non-default base.
92
- case "BASE_REF_NOT_AUTHORIZED": return "prCheckAccess";
93
- case "BASE_REF_NOT_FOUND": return "prCheckBase";
94
- case "IDEMPOTENCY_CONFLICT":
95
- case "PUSH_RECEIPT_ALREADY_BOUND":
96
- case "GITHUB_PULL_REQUEST_CONFLICT": return "prCheckExisting";
97
- default: return "prRetry";
98
- }
99
- }
100
-
101
- // waitForPublishedReceipt polls the receipt until GitHub publication is done:
102
- // a push is accepted by the gateway first and published asynchronously, so a
103
- // pr create right after the push used to fail with
104
- // PUBLISHED_RECEIPT_NOT_FOUND and the agent had to poll by hand.
105
- export const publishWaitDefaultMs = 120000;
106
-
107
- // publishWaitMs reads the STAMP_PUBLISH_WAIT_MS test hook. Only a positive
108
- // whole number of milliseconds counts; anything else keeps the default, so
109
- // the hook can shorten the wait but never make it unbounded.
110
- export function publishWaitMs(value) {
111
- return /^[1-9][0-9]{0,8}$/.test(value ?? "") ? Number(value) : publishWaitDefaultMs;
112
- }
113
-
114
- export async function waitForPublishedReceipt(api, id, { timeoutMs = publishWaitDefaultMs, intervalMs = 2000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now } = {}) {
115
- // A NaN, infinite or non-positive bound would make the deadline check
116
- // below never true: the wait must stay bounded whatever the caller passed.
117
- if (!(Number.isFinite(timeoutMs) && timeoutMs > 0)) timeoutMs = publishWaitDefaultMs;
118
- const deadline = now() + timeoutMs;
119
- for (;;) {
120
- const d = await api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
121
- if (d.status === "PUBLISHED") {
122
- if (!d.repository || !d.targetRef || !/^[0-9a-f]{40}$/.test(d.publishedSha ?? "")) throw new AgentError("prReceiptIncomplete", { id });
123
- return d;
124
- }
125
- if (d.status === "FAILED" || d.status === "REJECTED") throw new AgentError("prReceiptNotPublished", { id, status: d.status });
126
- if (now() >= deadline) throw new AgentError("prPublishTimeout", { id, status: d.status });
127
- await sleep(intervalMs);
128
- }
129
- }
130
-
131
- // stampPullRequestPage is the pull request's page on this Stamp instance:
132
- // the link to hand a person (artin 09-27: Stamp links first, GitHub's as
133
- // well if wanted). null when the repository, number or instance does not
134
- // check out, so no half-built link is ever printed.
135
- export function stampPullRequestPage(apiBase, repository, number) {
136
- if (typeof repository !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(repository)) return null;
137
- if (!Number.isInteger(number) || number <= 0) return null;
138
- try {
139
- const u = new URL(apiBase);
140
- if (u.protocol === "https:" || u.hostname === "127.0.0.1" || u.hostname === "localhost") {
141
- return `${u.origin}/github/${repository}/pull/${number}`;
142
- }
143
- } catch { /* no page */ }
144
- return null;
145
- }
146
-
147
- // pullRequestNextLines is what `pr create` prints under "Created PR": the
148
- // pull request's page on this Stamp instance, and the one command that
149
- // registers it for auto-merge, with the exact head and base the gateway just
150
- // answered (Imprint, 09-27: agents read CLI output, and auto-merge went
151
- // unnoticed in --help). A line whose values do not check out is left out,
152
- // never printed half-filled.
153
- export function pullRequestNextLines(d, apiBase, tr) {
154
- const lines = [];
155
- const repo = typeof d?.repository === "string" && /^[^/\s]+\/[^/\s]+$/.test(d.repository) ? d.repository : null;
156
- const number = Number.isInteger(d?.pullNumber) && d.pullNumber > 0 ? d.pullNumber : null;
157
- if (!repo || !number) return lines;
158
- const page = stampPullRequestPage(apiBase, repo, number);
159
- if (page) lines.push(tr("prStampPage", { page }));
160
- const sha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
161
- if (sha(d.headSha) && sha(d.baseSha)) {
162
- lines.push(tr("prNextAutoMerge", { number, repository: repo, head: d.headSha, base: d.baseSha }));
163
- }
164
- return lines;
165
- }
package/lib/pr/edit.mjs DELETED
@@ -1,54 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { AgentError } from "../errors.mjs";
3
- import { parsePRTargetArgs } from "./read.mjs";
4
-
5
- export function parsePREditArgs(input) {
6
- const targetArgs = [], flags = new Map();
7
- for (let i = 0; i < input.length; i++) {
8
- const arg = input[i];
9
- const match = arg.match(/^(--title|--body|--body-file)(?:=(.*))?$/s);
10
- const name = match?.[1] ?? ({ "-b": "--body", "-F": "--body-file" })[arg];
11
- if (!name) { targetArgs.push(arg); continue; }
12
- if (flags.has(name)) throw new AgentError("usagePrEdit");
13
- const value = match?.[2] ?? input[++i];
14
- if (value === undefined) throw new AgentError("usagePrEdit");
15
- flags.set(name, value);
16
- }
17
- if (flags.has("--body") && flags.has("--body-file")) throw new AgentError("prBodyConflict");
18
- const target = parsePRTargetArgs(targetArgs, "usagePrEdit");
19
- const body = {};
20
- if (flags.has("--title")) {
21
- const title = flags.get("--title").trim();
22
- if (!title || Buffer.byteLength(title, "utf8") > 256) throw new AgentError("prEditTitleInvalid");
23
- body.title = title;
24
- }
25
- if (flags.has("--body") || flags.has("--body-file")) {
26
- let text = flags.get("--body");
27
- // `--body -` means stdin, like `--body-file -`.
28
- if (flags.has("--body-file") || text === "-") {
29
- const file = flags.get("--body-file") ?? "-";
30
- try { text = readFileSync(file === "-" ? 0 : file, "utf8"); }
31
- catch { throw new AgentError("prBodyRead"); }
32
- }
33
- if (!text?.trim() || Buffer.byteLength(text, "utf8") > 65536) throw new AgentError("prEditBodyInvalid");
34
- body.body = text;
35
- }
36
- if (!("title" in body) && !("body" in body)) throw new AgentError("usagePrEdit");
37
- return {
38
- target,
39
- path: `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}`,
40
- body,
41
- };
42
- }
43
-
44
- export function validatePREditResult(value, target) {
45
- const repository = `${target.owner}/${target.repo}`;
46
- const valid = value && typeof value === "object" && !Array.isArray(value)
47
- && typeof value.repository === "string" && value.repository.toLowerCase() === repository.toLowerCase()
48
- && value.number === target.number
49
- && typeof value.url === "string" && value.url.toLowerCase() === `https://github.com/${repository}/pull/${target.number}`.toLowerCase()
50
- && typeof value.title === "string" && value.title.trim().length > 0
51
- && typeof value.body === "string";
52
- if (!valid) throw new AgentError("prEditOutcomeUnknown");
53
- return value;
54
- }
package/lib/pr/queue.mjs DELETED
@@ -1,32 +0,0 @@
1
- import { AgentError } from "../errors.mjs";
2
- import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
3
- const sha = /^[0-9a-f]{40}$/;
4
- const id = /^[a-zA-Z0-9][a-zA-Z0-9_-]{15,127}$/;
5
- const states = new Set(["queued", "preparing", "testing", "publishing", "merged", "verified", "failed", "stale", "canceled"]);
6
-
7
- export function parsePRQueueArgs(input) {
8
- const args = [...input];
9
- const action = args.shift();
10
- const usage = "usagePrQueue";
11
- if (!["enqueue", "status", "withdraw"].includes(action)) throw new AgentError(usage);
12
- const requestID = takeNamedFlag(args, "request-id", undefined, usage);
13
- const head = takeNamedFlag(args, "head", undefined, usage);
14
- const base = takeNamedFlag(args, "base", undefined, usage);
15
- if (typeof requestID !== "string" || !id.test(requestID)) throw new AgentError(usage);
16
- if (action === "enqueue" ? !sha.test(head ?? "") || !sha.test(base ?? "") : head !== undefined || base !== undefined) throw new AgentError(usage);
17
- const target = parsePRTargetArgs(args, usage);
18
- return { action, requestID, target, path: `${prDetailPath(target)}/queue/${requestID}`, method: { enqueue: "PUT", status: "GET", withdraw: "DELETE" }[action], ...(action === "enqueue" ? { body: { expectedHead: head, expectedBase: base } } : {}) };
19
- }
20
-
21
- export function validatePRQueueResult(d, input) {
22
- const r = d?.receipt;
23
- const m = r?.member;
24
- if (!d || typeof d.repository !== "string" || d.repository.toLowerCase() !== `${input.target.owner}/${input.target.repo}`.toLowerCase()
25
- || d.number !== input.target.number || d.requestId !== input.requestID
26
- || m?.number !== input.target.number || m?.requestId !== input.requestID || !sha.test(m?.head ?? "")
27
- || !states.has(r?.state) || typeof r?.notificationQueued !== "boolean"
28
- || !sha.test(r?.expectedBase ?? "")
29
- || (input.body && (m.head !== input.body.expectedHead || r.expectedBase !== input.body.expectedBase))
30
- || (r.state === "merged" && !sha.test(r.landingSha ?? ""))) throw new AgentError("prQueueOutcomeUnknown");
31
- return d;
32
- }