@saltpub/agent-autoloop 0.0.0-stage → 0.1.2

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.
Files changed (171) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/INSTALL.md +118 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +264 -0
  5. package/README.md +260 -2
  6. package/SECURITY.md +48 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/backup.js +144 -0
  9. package/dist/cli/explain.js +84 -0
  10. package/dist/cli/main.js +1016 -0
  11. package/dist/cli/mcp.js +151 -0
  12. package/dist/cli/runs.js +40 -0
  13. package/dist/cli/spend.js +21 -0
  14. package/dist/cli/status.js +304 -0
  15. package/dist/cli/try.js +6 -0
  16. package/dist/cli/uninstall.js +84 -0
  17. package/dist/cli/update.js +65 -0
  18. package/dist/cli/why.js +115 -0
  19. package/dist/host/background-launcher.js +12 -0
  20. package/dist/host/background.js +24 -0
  21. package/dist/host/channels.js +4 -0
  22. package/dist/host/command.js +98 -0
  23. package/dist/host/config.js +37 -0
  24. package/dist/host/files.js +22 -0
  25. package/dist/host/home.js +5 -0
  26. package/dist/host/http.js +43 -0
  27. package/dist/host/launcher.js +188 -0
  28. package/dist/host/lines.js +15 -0
  29. package/dist/host/node-path.js +33 -0
  30. package/dist/host/npm.js +28 -0
  31. package/dist/host/plugins.js +26 -0
  32. package/dist/host/program.js +14 -0
  33. package/dist/host/runtime.js +179 -0
  34. package/dist/host/server.js +159 -0
  35. package/dist/host/service.js +325 -0
  36. package/dist/host/state.js +203 -0
  37. package/dist/host/up.js +162 -0
  38. package/dist/host/update.js +286 -0
  39. package/dist/host/version.js +81 -0
  40. package/dist/kernel/card-page.js +54 -0
  41. package/dist/kernel/credentials.js +16 -0
  42. package/dist/kernel/cron.js +135 -0
  43. package/dist/kernel/decide.js +826 -0
  44. package/dist/kernel/due.js +73 -0
  45. package/dist/kernel/errors.js +9 -0
  46. package/dist/kernel/evolve.js +264 -0
  47. package/dist/kernel/http.js +357 -0
  48. package/dist/kernel/query.js +202 -0
  49. package/dist/kernel/rules.js +20 -0
  50. package/dist/kernel/store.js +52 -0
  51. package/dist/plugins/acp/agent.js +32 -0
  52. package/dist/plugins/acp/bridge.js +204 -0
  53. package/dist/plugins/claude/agent.js +113 -0
  54. package/dist/plugins/codex/agent.js +105 -0
  55. package/dist/plugins/command/agent.js +25 -0
  56. package/dist/plugins/delivery/action.js +25 -0
  57. package/dist/plugins/delivery/agent.js +13 -0
  58. package/dist/plugins/delivery/delivery.js +388 -0
  59. package/dist/plugins/delivery/github.js +201 -0
  60. package/dist/plugins/delivery/handoff.js +50 -0
  61. package/dist/plugins/delivery/input.js +47 -0
  62. package/dist/plugins/delivery/poll.js +72 -0
  63. package/dist/plugins/delivery/project.js +144 -0
  64. package/dist/plugins/delivery/review-ledger.js +82 -0
  65. package/dist/plugins/delivery/review-policy.js +99 -0
  66. package/dist/plugins/delivery/review.js +280 -0
  67. package/dist/plugins/delivery/run.js +204 -0
  68. package/dist/plugins/desktop/channel.js +94 -0
  69. package/dist/plugins/dsh/agent.js +116 -0
  70. package/dist/plugins/feishu/channel.js +245 -0
  71. package/dist/plugins/github/source.js +30 -0
  72. package/dist/plugins/gitlab/source.js +30 -0
  73. package/dist/plugins/omp/agent.js +3 -0
  74. package/dist/plugins/opencode/agent.js +88 -0
  75. package/dist/plugins/pi/agent.js +92 -0
  76. package/dist/plugins/webhook/channel.js +70 -0
  77. package/dist/plugins/webhook/templates.js +34 -0
  78. package/dist/plugins/xiaojiu/channel.js +410 -0
  79. package/dist/plugins/zcode/agent.js +102 -0
  80. package/dist/protocol/client.js +56 -0
  81. package/dist/protocol/conformance.js +184 -0
  82. package/dist/protocol/job.js +1 -0
  83. package/dist/protocol/rules.js +230 -0
  84. package/dist/protocol/schema.js +70 -0
  85. package/dist/protocol/schema.json +985 -0
  86. package/dist/protocol/validate.js +150 -0
  87. package/dist/worker/agents.js +47 -0
  88. package/dist/worker/contract.js +178 -0
  89. package/dist/worker/run.js +52 -0
  90. package/dist/worker/usage.js +45 -0
  91. package/dist/worker/windows.ps1 +48 -0
  92. package/dist/worker/worker.js +595 -0
  93. package/docs/architecture.en.svg +178 -0
  94. package/docs/architecture.svg +178 -0
  95. package/docs/auto-update.md +53 -0
  96. package/docs/plugins.md +139 -0
  97. package/docs/protocol.md +582 -0
  98. package/docs/state-machines.md +77 -0
  99. package/examples/channel.sh +15 -0
  100. package/examples/plugins/hello-agent/agent.ts +40 -0
  101. package/examples/plugins/hello-channel/channel.ts +54 -0
  102. package/examples/plugins/hello-source/source.ts +19 -0
  103. package/examples/recipes/browser-handoff/README.md +44 -0
  104. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  105. package/examples/recipes/browser-handoff/browser.json +10 -0
  106. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  107. package/examples/recipes/browser-handoff/rules.json +19 -0
  108. package/examples/recipes/feedback/README.md +34 -0
  109. package/examples/recipes/feedback/SKILL.md +22 -0
  110. package/examples/recipes/feedback/event.json +8 -0
  111. package/examples/recipes/feedback/rules.json +37 -0
  112. package/examples/recipes/feishu-brief/README.md +28 -0
  113. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  114. package/examples/recipes/feishu-brief/collect.ts +164 -0
  115. package/examples/recipes/feishu-brief/rules.json +57 -0
  116. package/examples/recipes/feishu-brief/sources.json +13 -0
  117. package/examples/recipes/github-issues/README.md +17 -0
  118. package/examples/recipes/github-issues/SKILL.md +18 -0
  119. package/examples/recipes/github-issues/rules.json +30 -0
  120. package/examples/recipes/inbox-triage/README.md +36 -0
  121. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  122. package/examples/recipes/inbox-triage/collect.ts +191 -0
  123. package/examples/recipes/inbox-triage/rules.json +57 -0
  124. package/examples/recipes/inbox-triage/sources.json +8 -0
  125. package/examples/recipes/morning-brief/README.md +17 -0
  126. package/examples/recipes/morning-brief/SKILL.md +17 -0
  127. package/examples/recipes/morning-brief/rules.json +16 -0
  128. package/examples/recipes/ops-alerts/README.md +18 -0
  129. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  130. package/examples/recipes/ops-alerts/restart.sh +5 -0
  131. package/examples/recipes/ops-alerts/rules.json +29 -0
  132. package/examples/recipes/website-watch/README.md +26 -0
  133. package/examples/recipes/website-watch/SKILL.md +19 -0
  134. package/examples/recipes/website-watch/check.ts +86 -0
  135. package/examples/recipes/website-watch/rules.json +56 -0
  136. package/examples/recipes/website-watch/site.json +6 -0
  137. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  138. package/examples/watch-github-issues.sh +23 -0
  139. package/examples/worker.sh +18 -0
  140. package/package.json +55 -4
  141. package/plugins/acp/agent.ts +31 -0
  142. package/plugins/acp/bridge.ts +190 -0
  143. package/plugins/claude/agent.ts +121 -0
  144. package/plugins/codex/agent.ts +103 -0
  145. package/plugins/command/agent.ts +25 -0
  146. package/plugins/delivery/action.ts +29 -0
  147. package/plugins/delivery/action.yml +28 -0
  148. package/plugins/delivery/agent.ts +15 -0
  149. package/plugins/delivery/delivery.ts +408 -0
  150. package/plugins/delivery/github.ts +207 -0
  151. package/plugins/delivery/handoff.ts +72 -0
  152. package/plugins/delivery/input.ts +55 -0
  153. package/plugins/delivery/poll.ts +65 -0
  154. package/plugins/delivery/project.ts +161 -0
  155. package/plugins/delivery/review-ledger.ts +90 -0
  156. package/plugins/delivery/review-policy.ts +126 -0
  157. package/plugins/delivery/review.ts +324 -0
  158. package/plugins/delivery/run.ts +219 -0
  159. package/plugins/desktop/channel.ts +100 -0
  160. package/plugins/dsh/agent.ts +100 -0
  161. package/plugins/feishu/channel.ts +243 -0
  162. package/plugins/github/source.ts +33 -0
  163. package/plugins/gitlab/source.ts +32 -0
  164. package/plugins/omp/agent.ts +4 -0
  165. package/plugins/opencode/agent.ts +78 -0
  166. package/plugins/pi/agent.ts +80 -0
  167. package/plugins/webhook/channel.ts +74 -0
  168. package/plugins/webhook/templates.ts +32 -0
  169. package/plugins/xiaojiu/channel.ts +426 -0
  170. package/plugins/zcode/agent.ts +96 -0
  171. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,388 @@
1
+ // One pull request from label to live: review, full check, merge, Ship, health. Every step reads GitHub's state back
2
+ // rather than trusting its own last response, and a failure is left for the hub's retry to pick up where it stands.
3
+ import { settings } from "./project.js";
4
+ export class DeliveryRefusal extends Error {
5
+ head;
6
+ constructor(message, head) {
7
+ super(message);
8
+ this.head = head;
9
+ }
10
+ }
11
+ export class DeliverySuperseded extends Error {
12
+ }
13
+ const FINDINGS = "审查发现问题,修复后推新提交才会重审";
14
+ const STALL = 10 * 60_000;
15
+ const labels = (pr) => new Set((pr.labels ?? []).map((label) => label.name));
16
+ const newestFirst = (a, b) => b.id - a.id;
17
+ export const status = (io, head, context, state, description) => io.api(`statuses/${head}`, { state, context, description: [...description].slice(0, 140).join("") }, "POST");
18
+ export async function disableAuto(number, io) {
19
+ let cause;
20
+ for (let attempt = 0; attempt < 3; attempt++) {
21
+ try {
22
+ await io.disableAuto(number);
23
+ }
24
+ catch (error) {
25
+ /* A lost mutation response must be read back, not assumed. */
26
+ cause = error;
27
+ }
28
+ try {
29
+ if (!(await io.api(`pulls/${number}`)).auto_merge)
30
+ return;
31
+ }
32
+ catch (error) {
33
+ /* Known failure: a failed read-back must still confirm cancellation within three attempts. */
34
+ cause = error;
35
+ }
36
+ if (attempt < 2)
37
+ await io.wait();
38
+ }
39
+ throw new Error("无法确认自动合并已关闭", { cause });
40
+ }
41
+ async function newestCheck(head, config, io) {
42
+ const query = `head_sha=${head}&event=pull_request&per_page=100`;
43
+ const { workflow_runs: runs } = await io.api(`actions/workflows/${config.check.workflow}/runs?${query}`);
44
+ return runs.filter((run) => run.head_sha === head && run.event === "pull_request").sort(newestFirst)[0];
45
+ }
46
+ export async function fullCheck(head, config, io, after = 0, startedAt = io.now?.() ?? Date.now()) {
47
+ const { job } = config.check;
48
+ const run = await newestCheck(head, config, io);
49
+ const now = io.now?.() ?? Date.now();
50
+ if (!run || run.id <= after)
51
+ return now - startedAt > STALL ? "stalled" : "waiting";
52
+ const { jobs } = await io.api(`actions/runs/${run.id}/jobs?filter=latest&per_page=100`);
53
+ const required = jobs.filter((candidate) => candidate.name === job || candidate.name.startsWith(`${job} (`));
54
+ if (!required.length)
55
+ return run.status !== "completed" && now - Date.parse(run.created_at) > STALL ? "stalled" : "waiting";
56
+ if (run.status === "completed" && run.conclusion !== "success")
57
+ return "failed";
58
+ const finished = (item) => item.status === "completed" && item.conclusion === "success";
59
+ return finished(run) && required.every(finished) ? "passed" : "waiting";
60
+ }
61
+ export async function waitLive(merged, config, io, head) {
62
+ if (!config.health)
63
+ return;
64
+ if (head)
65
+ await io.report?.("shipping", head, { merge: merged });
66
+ await io.prepareShip?.();
67
+ const query = "branch=main&event=push&per_page=100";
68
+ let ship;
69
+ for (;;) {
70
+ const { workflow_runs } = await io.api(`actions/workflows/${config.ship.workflow}/runs?${query}`);
71
+ const runs = workflow_runs.sort(newestFirst);
72
+ const covering = [];
73
+ for (const run of runs)
74
+ if (run.event === "push" && (await io.contains(merged, run.head_sha)))
75
+ covering.push(run);
76
+ const newest = covering[0];
77
+ if (head && newest && newest.id !== ship) {
78
+ ship = newest.id;
79
+ await io.report?.("shipping", head, { merge: merged, ship });
80
+ }
81
+ const live = await io.live(config);
82
+ if (live) {
83
+ for (const run of covering) {
84
+ if (run.status !== "completed" || run.conclusion !== "success")
85
+ continue;
86
+ const liveHasIt = await io.contains(run.head_sha, live.sha);
87
+ if (liveHasIt)
88
+ return { phase: "live", ship: run.id, release: live.release };
89
+ if (!(await io.releaseRequired(live.sha, run.head_sha, config.internal)))
90
+ return { phase: "docs_only", ship: run.id, release: live.release };
91
+ }
92
+ }
93
+ if (newest?.status === "completed" && newest.conclusion !== "success") {
94
+ throw new DeliveryRefusal(`已经合并,发布没有通过:${newest.html_url}。修复发布后重交原改动。`, head);
95
+ }
96
+ await io.wait();
97
+ }
98
+ }
99
+ async function clearLabels(number, pr, io) {
100
+ // A retry goes by what's left on. A merged PR only goes on to its release while it has `deliver`; an open one with `deliver`
101
+ // alone is a full delivery, so a review-only one must lose `deliver-review` last or the retry merges it.
102
+ const order = pr.merged_at ? ["deliver-review", "deliver"] : ["deliver", "deliver-review"];
103
+ for (const label of ["deliver-attended", ...order]) {
104
+ if (!labels(pr).has(label))
105
+ continue;
106
+ try {
107
+ await io.api(`issues/${number}/labels/${label}`, undefined, "DELETE");
108
+ }
109
+ catch (error) {
110
+ // GitHub returned 404 after an observed labelled PR had already completed Ship; verify the desired state.
111
+ if (labels(await io.api(`pulls/${number}`)).has(label))
112
+ throw error;
113
+ }
114
+ }
115
+ }
116
+ async function synced(number, head, base, io) {
117
+ const until = Date.now() + 15 * 60_000;
118
+ for (;;) {
119
+ const pr = await io.api(`pulls/${number}`);
120
+ if (pr.merged_at)
121
+ return pr;
122
+ if (pr.head.sha !== head && (await io.contains(base, pr.head.sha)))
123
+ return pr;
124
+ if (Date.now() > until)
125
+ throw new Error("已请求同步 main,15 分钟内没有看到同步后的提交,稍后重试");
126
+ await io.wait();
127
+ }
128
+ }
129
+ export async function deliver(repo, number, io, testLocalHealth = false) {
130
+ const reviewOnly = async (pr) => {
131
+ const summary = "审查通过,未合并或发布";
132
+ await status(io, pr.head.sha, "delivery", "success", summary);
133
+ await clearLabels(number, pr, io);
134
+ await io.report?.("reviewed", pr.head.sha);
135
+ return { summary, reviewOnly: true };
136
+ };
137
+ const withdrawn = async (head) => {
138
+ await status(io, head, "delivery", "success", "交付标记已撤回,未合并或发布");
139
+ await io.report?.("withdrawn", head);
140
+ return { summary: "交付标记已撤回" };
141
+ };
142
+ let pr = await io.api(`pulls/${number}`);
143
+ if (!labels(pr).has("deliver") || (!pr.merged_at && pr.state !== "open"))
144
+ return { summary: "没有待交付的标记" };
145
+ if (pr.head.repo?.full_name !== repo || pr.base.ref !== "main")
146
+ throw new DeliveryRefusal("只处理本仓库分支到 main 的合并请求", pr.head.sha);
147
+ if (pr.auto_merge)
148
+ await disableAuto(number, io);
149
+ let head = pr.head.sha;
150
+ const accept = async () => {
151
+ await status(io, head, "delivery", "pending", "正在审查、检查和核实发布");
152
+ await io.report?.("accepted", head);
153
+ };
154
+ if (io.verifyReview)
155
+ await accept();
156
+ const settingsAt = async (commit) => {
157
+ const file = await io.api(`contents/ops/delivery.json?ref=${commit}`);
158
+ const read = settings(JSON.parse(Buffer.from(file.content, "base64").toString("utf8")), testLocalHealth);
159
+ if (read.repo !== repo)
160
+ throw new Error("main 的 repo 设置与交付仓库不一致");
161
+ if (io.reviewStatus)
162
+ read.review.status = io.reviewStatus;
163
+ return read;
164
+ };
165
+ let config = await settingsAt((await io.api("git/ref/heads/main")).object.sha);
166
+ if (!pr.merged_at && !io.verifyReview) {
167
+ // The label stays on after findings, so another event lands here: a second review that misses them would merge the commit.
168
+ // The review status keeps the record, since a failed round writes its error over `delivery`.
169
+ const { statuses } = await io.api(`commits/${head}/status?per_page=100`);
170
+ if (statuses.some((item) => item.context === config.review.status && item.state === "failure"))
171
+ return { summary: "这个提交审查发现过问题,修复后推新提交才会重审" };
172
+ }
173
+ if (!io.verifyReview)
174
+ await accept();
175
+ // Sync inside the run: a thrown sync waits out the hub's growing retry backoff while main keeps moving.
176
+ rounds: for (let round = 1; !pr.merged_at; round++) {
177
+ if (pr.mergeable === false || pr.mergeable_state === "dirty")
178
+ throw new DeliveryRefusal("改动与 main 有合并冲突,请先解决后重新交付。", head);
179
+ let base = (await io.api("git/ref/heads/main")).object.sha;
180
+ if (!(await io.contains(base, head))) {
181
+ try {
182
+ await io.api(`pulls/${number}/update-branch`, { expected_head_sha: head }, "PUT");
183
+ }
184
+ catch (error) {
185
+ const live = await io.api(`pulls/${number}`);
186
+ if (!live.merged_at && live.head.sha === head)
187
+ throw error;
188
+ }
189
+ pr = await synced(number, head, base, io);
190
+ if (pr.merged_at)
191
+ break;
192
+ if (!(await io.contains(head, pr.head.sha)))
193
+ throw new DeliverySuperseded("同步后的分支不包含原来的提交,等待重新交付");
194
+ head = pr.head.sha;
195
+ await status(io, head, "delivery", "pending", "已同步 main,正在审查、检查和核实发布");
196
+ // GitHub syncs with main as it is by then, which may be newer than what was read above: against the older one, those
197
+ // commits would be reviewed as the branch's own.
198
+ base = (await io.api("git/ref/heads/main")).object.sha;
199
+ if (!(await io.contains(base, head))) {
200
+ if (round < 3)
201
+ continue;
202
+ throw new Error("main 已前进,稍后重新同步和检查");
203
+ }
204
+ }
205
+ // The settings of the main this round is against: a newer one may add the health check its release has to pass.
206
+ config = await settingsAt(base);
207
+ const reviewed = await io.review(pr, config, base);
208
+ const exempt = !Array.isArray(reviewed) && "exempt" in reviewed ? reviewed.exempt : null;
209
+ const findings = Array.isArray(reviewed) ? reviewed : [];
210
+ const current = await io.api(`pulls/${number}`);
211
+ if (current.merged_at) {
212
+ pr = current;
213
+ break;
214
+ }
215
+ if (current.head.sha !== head)
216
+ throw new DeliverySuperseded("审查期间提交变了,等待重新交付");
217
+ if (!Array.isArray(reviewed) && "blocked" in reviewed) {
218
+ await status(io, head, config.review.status, "failure", reviewed.blocked);
219
+ throw new DeliveryRefusal(reviewed.blocked, head);
220
+ }
221
+ if (!Array.isArray(reviewed) && "changed" in reviewed) {
222
+ pr = current;
223
+ continue;
224
+ }
225
+ if (findings.length) {
226
+ await status(io, head, "delivery", "failure", FINDINGS);
227
+ // Last: once this stands nothing reviews the commit again, so a failed write must not keep the findings from going out.
228
+ await status(io, head, config.review.status, "failure", FINDINGS);
229
+ return { summary: "审查发现问题,尚未合并", findings, head };
230
+ }
231
+ if (labels(current).has("deliver-review")) {
232
+ if (!exempt)
233
+ return reviewOnly(current);
234
+ // Asked for after this round let the change through without a review: the next round reviews it.
235
+ pr = current;
236
+ continue;
237
+ }
238
+ await io.report?.("checking", head);
239
+ let after = io.checkRecovery?.head === head ? io.checkRecovery.after : 0;
240
+ if (current.draft) {
241
+ // Right after going ready the newest run is still a draft one: only a run started by the change can pass.
242
+ after = (await newestCheck(head, config, io))?.id ?? 0;
243
+ if (io.checkRecovery?.head === head)
244
+ io.checkRecovery.after = after;
245
+ await io.api(`pulls/${number}/ready`, {}, "POST");
246
+ }
247
+ let checkStartedAt = io.now?.() ?? Date.now();
248
+ let merging = false;
249
+ let autoRequested = false;
250
+ const stopAuto = async () => {
251
+ if (pr.auto_merge || autoRequested) {
252
+ await disableAuto(number, io);
253
+ pr.auto_merge = null;
254
+ autoRequested = false;
255
+ }
256
+ };
257
+ try {
258
+ for (;;) {
259
+ const state = await fullCheck(head, config, io, after, checkStartedAt);
260
+ pr = await io.api(`pulls/${number}`);
261
+ if (pr.merged_at)
262
+ break rounds;
263
+ if (pr.head.sha !== head) {
264
+ throw new DeliverySuperseded("检查期间提交变了,等待重新交付");
265
+ }
266
+ if (pr.base.ref !== "main" || pr.state !== "open") {
267
+ throw new DeliveryRefusal("改动已关闭或目标分支已变更,只合并到 main。", head);
268
+ }
269
+ if (pr.mergeable === false || pr.mergeable_state === "dirty") {
270
+ throw new DeliveryRefusal("改动与 main 有合并冲突,请先解决后重新交付。", head);
271
+ }
272
+ if (!labels(pr).has("deliver")) {
273
+ await stopAuto();
274
+ return withdrawn(head);
275
+ }
276
+ if (labels(pr).has("deliver-review")) {
277
+ await stopAuto();
278
+ if (!exempt && !io.verifyReview)
279
+ return reviewOnly(pr);
280
+ continue rounds;
281
+ }
282
+ if (state === "stalled") {
283
+ if (io.checkRecovery?.head === head)
284
+ throw new DeliveryRefusal("GitHub 收下了检查却一直没开始跑(多半是 GitHub 出了事故),已重新触发一次仍不动。等 GitHub 恢复后重新交付。", head);
285
+ await stopAuto();
286
+ await io.api(`pulls/${number}/draft`, {}, "POST");
287
+ io.checkRecovery = { head, after };
288
+ // Converting to draft can start another run. Only a run created after going ready can authorize merging.
289
+ after = (await newestCheck(head, config, io))?.id ?? 0;
290
+ io.checkRecovery.after = after;
291
+ await io.api(`pulls/${number}/ready`, {}, "POST");
292
+ checkStartedAt = io.now?.() ?? Date.now();
293
+ continue;
294
+ }
295
+ if (state === "failed") {
296
+ throw new DeliveryRefusal(`完整检查没有通过。查看 https://github.com/${repo}/pull/${number}/checks`, head);
297
+ }
298
+ if (state === "passed" || pr.auto_merge) {
299
+ if ((await io.api("git/ref/heads/main")).object.sha !== base) {
300
+ await stopAuto();
301
+ if (round < 3)
302
+ continue rounds;
303
+ throw new Error("main 已前进,稍后重新同步和检查");
304
+ }
305
+ const behind = await io.verifyTools?.(head);
306
+ if (behind)
307
+ throw new DeliveryRefusal(behind, head);
308
+ const verified = await io.verifyReview?.(pr, config, base);
309
+ if (verified) {
310
+ if (!Array.isArray(verified) && "blocked" in verified) {
311
+ await stopAuto();
312
+ await status(io, head, config.review.status, "failure", verified.blocked);
313
+ throw new DeliveryRefusal(verified.blocked, head);
314
+ }
315
+ const recheckedExempt = !Array.isArray(verified) && "exempt" in verified ? verified.exempt : null;
316
+ if ((!Array.isArray(verified) && "changed" in verified) || recheckedExempt !== exempt) {
317
+ await stopAuto();
318
+ continue rounds;
319
+ }
320
+ }
321
+ if (state === "passed" && !pr.auto_merge) {
322
+ const checked = pr;
323
+ pr = await io.api(`pulls/${number}`);
324
+ if (pr.merged_at)
325
+ break rounds;
326
+ if (pr.head.sha !== head)
327
+ throw new DeliverySuperseded("要合并的提交变了,等待重新交付");
328
+ if (pr.base.ref !== "main" || pr.state !== "open")
329
+ throw new DeliveryRefusal("改动已关闭或目标分支已变更,只合并到 main。", head);
330
+ if (!labels(pr).has("deliver")) {
331
+ await stopAuto();
332
+ return withdrawn(head);
333
+ }
334
+ if (pr.body !== checked.body || labels(pr).has("deliver-review") || pr.auto_merge) {
335
+ await stopAuto();
336
+ continue rounds;
337
+ }
338
+ const passed = exempt
339
+ ? `${exempt} 写的改动按策略免审`
340
+ : !Array.isArray(reviewed) && "docsOnly" in reviewed
341
+ ? "只改内部文档,按策略免审"
342
+ : "此提交审查通过";
343
+ await status(io, head, config.review.status, "success", `${passed},完整检查通过`);
344
+ if (!merging)
345
+ await io.report?.("merging", head);
346
+ merging = true;
347
+ const auto = io.enableAuto && !config.admin_merge.includes(pr.user.login) ? io.enableAuto : undefined;
348
+ try {
349
+ if (auto) {
350
+ autoRequested = true;
351
+ await auto(pr);
352
+ }
353
+ else
354
+ await io.merge(pr, config);
355
+ }
356
+ catch (error) {
357
+ // The request can be accepted before its response is lost. Read back before any retry.
358
+ pr = await io.api(`pulls/${number}`);
359
+ if (!pr.merged_at && !(auto && pr.auto_merge))
360
+ throw error;
361
+ }
362
+ pr = await io.api(`pulls/${number}`);
363
+ if (pr.merged_at)
364
+ break rounds;
365
+ if (!auto || !pr.auto_merge)
366
+ throw new Error("尚未确认合并,稍后继续核实");
367
+ }
368
+ }
369
+ await io.wait();
370
+ }
371
+ }
372
+ catch (error) {
373
+ await stopAuto();
374
+ throw error;
375
+ }
376
+ }
377
+ const merge = pr.merge_commit_sha;
378
+ const shipped = await waitLive(merge, config, io, pr.head.sha);
379
+ const summary = !shipped
380
+ ? "已合并;项目没有线上服务"
381
+ : shipped.phase === "docs_only"
382
+ ? `仅内部文档变化,已合并,无需发布。已核实线上版本 ${shipped.release}`
383
+ : `已发布并核实线上版本 ${shipped.release}`;
384
+ await status(io, pr.head.sha, "delivery", "success", summary);
385
+ await clearLabels(number, pr, io);
386
+ await io.report?.(shipped?.phase ?? "merged", pr.head.sha, { merge, ship: shipped?.ship });
387
+ return { summary, merged: merge };
388
+ }
@@ -0,0 +1,201 @@
1
+ // The delivery's way to GitHub: the signed-in `gh`, and bare Git objects fetched into a scratch folder.
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { setTimeout } from "node:timers/promises";
6
+ import { git, liveRelease, releaseRequired, REPO } from "./project.js";
7
+ import { readSharedPolicy, reviewDelivery } from "./review.js";
8
+ const LONGEST_WAIT = 1800000;
9
+ class GitHubHiccup extends Error {
10
+ }
11
+ export function isGitHubHiccup(error) {
12
+ return error instanceof GitHubHiccup || (error instanceof Error && !!error.cause && isGitHubHiccup(error.cause));
13
+ }
14
+ export function gh(args, input) {
15
+ const stdin = input === undefined ? undefined : JSON.stringify(input);
16
+ try {
17
+ return execFileSync("gh", args, {
18
+ input: stdin,
19
+ encoding: "utf8",
20
+ timeout: 60000,
21
+ maxBuffer: 32 * 1024 * 1024,
22
+ stdio: ["pipe", "pipe", "pipe"],
23
+ }).trim();
24
+ }
25
+ catch (error) {
26
+ const stderr = error.stderr?.trim();
27
+ if (stderr && /\bHTTP 5\d\d\b|Something went wrong while executing your query/.test(stderr))
28
+ throw new GitHubHiccup(stderr);
29
+ throw error;
30
+ }
31
+ }
32
+ export function github(repo) {
33
+ if (!REPO.test(repo))
34
+ throw new Error("仓库要写成 owner/name");
35
+ return async (path, body, method = body === undefined ? "GET" : "POST") => {
36
+ const ready = /^pulls\/(\d+)\/(ready|draft)$/.exec(path);
37
+ if (ready) {
38
+ gh(["pr", "ready", ready[1], "--repo", repo, ...(ready[2] === "draft" ? ["--undo"] : [])]);
39
+ return {};
40
+ }
41
+ const text = gh(["api", `repos/${repo}/${path}`, "--method", method, ...(body === undefined ? [] : ["--input", "-"])], body);
42
+ return text ? JSON.parse(text) : {};
43
+ };
44
+ }
45
+ export function pages(repo, path) {
46
+ if (!REPO.test(repo))
47
+ throw new Error("仓库要写成 owner/name");
48
+ return JSON.parse(gh(["api", `repos/${repo}/${path}`, "--paginate", "--slurp"])).flat();
49
+ }
50
+ const commitSha = /^[a-f0-9]{40}$/;
51
+ const commitPrefix = /^[a-f0-9]{7,40}$/;
52
+ function decoded(file) {
53
+ return JSON.parse(Buffer.from(file.content, "base64").toString("utf8"));
54
+ }
55
+ export function createIO(repo, folder, options = {}) {
56
+ const api = github(repo);
57
+ const bare = join(folder, "objects.git");
58
+ const started = Date.now();
59
+ let initialized = false;
60
+ const fetched = new Set();
61
+ const localCommit = (sha) => {
62
+ if (!initialized || !commitPrefix.test(sha))
63
+ return;
64
+ try {
65
+ return git(bare, "rev-parse", "--verify", `${sha}^{commit}`);
66
+ }
67
+ catch (error) {
68
+ if (error.status !== 128)
69
+ throw error;
70
+ }
71
+ };
72
+ const fetchObjects = (...refs) => {
73
+ if (!initialized) {
74
+ mkdirSync(bare, { recursive: true });
75
+ git(bare, "init", "--bare", "--template=");
76
+ git(bare, "config", "remote.origin.url", `https://github.com/${repo}.git`);
77
+ initialized = true;
78
+ }
79
+ const missing = refs.filter((ref) => !commitSha.test(ref) || (!fetched.has(ref) && !localCommit(ref)));
80
+ if (missing.length) {
81
+ git(bare, "fetch", "--no-tags", "origin", ...missing);
82
+ missing.filter((ref) => commitSha.test(ref)).forEach((ref) => fetched.add(ref));
83
+ }
84
+ };
85
+ const ancestors = new Map();
86
+ let reviewer;
87
+ const review = (pr, config, main) => checkReview(pr, config, main, false);
88
+ const verifyReview = (pr, config, main) => checkReview(pr, config, main, true);
89
+ async function checkReview(pr, config, main, verifyOnly) {
90
+ fetchObjects(main, pr.head.sha);
91
+ const policy = options.reviewPolicy ? await readSharedPolicy(options.reviewPolicy, github) : undefined;
92
+ return reviewDelivery(bare, join(folder, `review-${pr.head.sha}`), main, pr, config, {
93
+ api,
94
+ statuses: (sha) => pages(repo, `commits/${sha}/statuses?per_page=100`),
95
+ policy,
96
+ reviewerId: () => (reviewer ??= Number(gh(["api", "user", "--jq", ".id"]))),
97
+ verifyOnly,
98
+ onReview: () => options.report?.("reviewing", pr.head.sha),
99
+ });
100
+ }
101
+ const kit = options.toolkit && options.toolkit.toLowerCase() !== repo.toLowerCase() ? github(options.toolkit) : null;
102
+ return {
103
+ api,
104
+ review,
105
+ verifyReview,
106
+ reviewStatus: options.reviewStatus,
107
+ report: options.report,
108
+ now: Date.now,
109
+ ...(options.autoMerge && {
110
+ async enableAuto(pr) {
111
+ gh([
112
+ "pr",
113
+ "merge",
114
+ String(pr.number),
115
+ "--repo",
116
+ repo,
117
+ "--auto",
118
+ "--squash",
119
+ "--match-head-commit",
120
+ pr.head.sha,
121
+ ]);
122
+ },
123
+ }),
124
+ ...(kit && {
125
+ async verifyTools(head) {
126
+ const installed = decoded(await api(`contents/ops/delivery/kit.json?ref=${head}`)).kit;
127
+ const main = (await kit("git/ref/heads/main")).object.sha;
128
+ const latest = (await kit(`commits?sha=${main}&path=delivery&per_page=1`))[0]?.sha;
129
+ if (!commitSha.test(installed ?? "") || !commitSha.test(latest ?? ""))
130
+ throw new Error("无法识别项目安装的交付工具或工具仓库 main 上的版本");
131
+ const includes = async (base, head) => base === head || ["ahead", "identical"].includes((await kit(`compare/${base}...${head}`)).status);
132
+ if ((await includes(installed, main)) && (await includes(latest, installed)))
133
+ return null;
134
+ return `ops/delivery/ 装的是 ${options.toolkit} ${installed.slice(0, 12)},不是 main 上的最新版(交付工具最近一次改在 ${latest.slice(0, 12)})。请重新安装并提交后再交付。`;
135
+ },
136
+ }),
137
+ async merge(pr, config) {
138
+ if (config.admin_merge.includes(pr.user.login)) {
139
+ const number = String(pr.number);
140
+ gh(["pr", "merge", number, "--repo", repo, "--squash", "--admin", "--match-head-commit", pr.head.sha]);
141
+ return;
142
+ }
143
+ const result = await api(`pulls/${pr.number}/merge`, { sha: pr.head.sha, merge_method: "squash" }, "PUT");
144
+ if (!result.merged)
145
+ throw new Error("GitHub 没有接受合并");
146
+ },
147
+ async disableAuto(number) {
148
+ gh(["pr", "merge", String(number), "--repo", repo, "--disable-auto"]);
149
+ },
150
+ prepareShip() {
151
+ // Every older Ship run would otherwise consume a compare request, even when the exact merge is already live.
152
+ fetchObjects("refs/heads/main");
153
+ },
154
+ async contains(base, head) {
155
+ if (base === head)
156
+ return true;
157
+ const key = `${base}:${head}`;
158
+ if (!ancestors.has(key)) {
159
+ if (initialized && commitPrefix.test(base) && commitPrefix.test(head)) {
160
+ try {
161
+ git(bare, "merge-base", "--is-ancestor", base, head);
162
+ ancestors.set(key, true);
163
+ return true;
164
+ }
165
+ catch (error) {
166
+ const status = error.status;
167
+ // All objects in this scratch repository are fetched with their full history.
168
+ if (status === 1) {
169
+ ancestors.set(key, false);
170
+ return false;
171
+ }
172
+ if (status !== 128)
173
+ throw error;
174
+ }
175
+ }
176
+ const { status } = await api(`compare/${base}...${head}`);
177
+ ancestors.set(key, ["ahead", "identical"].includes(status));
178
+ }
179
+ return ancestors.get(key);
180
+ },
181
+ async releaseRequired(base, head, patterns) {
182
+ let full;
183
+ try {
184
+ full = localCommit(base) ?? (base.length < 40 ? (await api(`commits/${base}`)).sha : base);
185
+ fetchObjects(full, head);
186
+ }
187
+ catch (error) {
188
+ if (isGitHubHiccup(error))
189
+ throw error;
190
+ return true;
191
+ }
192
+ return releaseRequired(bare, full, head, patterns);
193
+ },
194
+ live: liveRelease,
195
+ async wait() {
196
+ if (Date.now() - started > LONGEST_WAIT)
197
+ throw new Error("等待超过半小时,保留远端状态,稍后继续核实");
198
+ await setTimeout(5000);
199
+ },
200
+ };
201
+ }
@@ -0,0 +1,50 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { question } from "./input.js";
5
+ const retryKey = "delivery-retry";
6
+ const retryInterval = 60_000;
7
+ const acknowledgeWithin = 180_000;
8
+ export const hasLabel = (issue, name) => issue.labels.some((label) => label.name === name);
9
+ export function unattendedFailure(labels, last, now = Date.now()) {
10
+ return (hasLabel({ labels }, "deliver-attended") &&
11
+ !hasLabel({ labels }, "deliver") &&
12
+ last?.state === "failure" &&
13
+ now - Date.parse(last.created_at) >= acknowledgeWithin);
14
+ }
15
+ export function retryState(timers) {
16
+ const saved = timers.find((timer) => timer.key === retryKey)?.about;
17
+ return saved ? JSON.parse(saved) : undefined;
18
+ }
19
+ export function retryHandoff(timers, head, hiccup, now = Date.now(), canReturn = true, checkRecovery) {
20
+ const previous = retryState(timers);
21
+ const count = previous?.head === head ? previous : { head, github: 0, execution: 0 };
22
+ if (checkRecovery?.head === head)
23
+ count.checkAfter = checkRecovery.after;
24
+ const kind = hiccup ? "github" : "execution";
25
+ const limit = hiccup ? 60 : 5;
26
+ count[kind] = Math.min(count[kind] + 1, limit);
27
+ if (count[kind] === limit && canReturn)
28
+ return null;
29
+ return { key: retryKey, at: new Date(now + retryInterval).toISOString(), about: JSON.stringify(count) };
30
+ }
31
+ export function runHook(program, data, timeout) {
32
+ const executable = program.startsWith("~/") ? join(homedir(), program.slice(2)) : program;
33
+ execFileSync(executable, [], { input: JSON.stringify(data), stdio: ["pipe", "ignore", "pipe"], timeout });
34
+ }
35
+ const matter = (text) => text
36
+ .toLowerCase()
37
+ .replace(/[^a-z0-9._-]/g, "-")
38
+ .slice(0, 64);
39
+ export function tellReturn(program, repo, number, head, reason) {
40
+ const key = matter(`${repo.split("/")[1]}.${number}.${head.slice(0, 12)}`);
41
+ const url = `https://github.com/${repo}/pull/${number}`;
42
+ const text = [...question({ number, title: "", body: reason, html_url: url }).text].slice(0, 300).join("");
43
+ runHook(program, { key, text: `上线流程停在 ${repo} 的第 ${number} 项改动。\n${text}\n${url}` }, 60_000);
44
+ }
45
+ export function tellQuestion(program, repo, issue) {
46
+ const { text, title } = question(issue);
47
+ const key = matter(`ask.${repo.split("/")[1]}.${issue.number}`);
48
+ const body = text === issue.html_url ? "" : `${[...text].slice(0, 600).join("")}\n`;
49
+ runHook(program, { key, text: `云端有件事需要你决定。\n${title}\n${body}${issue.html_url}` }, 60_000);
50
+ }