@saltpub/agent-autoloop 0.0.0-stage → 0.1.3

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 (177) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/INSTALL.md +120 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +268 -0
  5. package/README.md +264 -2
  6. package/SECURITY.md +49 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/agents.js +14 -0
  9. package/dist/cli/backup.js +144 -0
  10. package/dist/cli/dashboard/app.js +424 -0
  11. package/dist/cli/dashboard/index.html +15 -0
  12. package/dist/cli/dashboard/style.css +629 -0
  13. package/dist/cli/dashboard.js +94 -0
  14. package/dist/cli/explain.js +84 -0
  15. package/dist/cli/main.js +1142 -0
  16. package/dist/cli/mcp.js +151 -0
  17. package/dist/cli/runs.js +40 -0
  18. package/dist/cli/spend.js +21 -0
  19. package/dist/cli/status.js +272 -0
  20. package/dist/cli/try.js +6 -0
  21. package/dist/cli/ui.js +75 -0
  22. package/dist/cli/uninstall.js +86 -0
  23. package/dist/cli/update.js +65 -0
  24. package/dist/cli/why.js +115 -0
  25. package/dist/host/background-launcher.js +12 -0
  26. package/dist/host/background.js +24 -0
  27. package/dist/host/channels.js +4 -0
  28. package/dist/host/command.js +98 -0
  29. package/dist/host/config.js +37 -0
  30. package/dist/host/files.js +22 -0
  31. package/dist/host/home.js +5 -0
  32. package/dist/host/http.js +45 -0
  33. package/dist/host/launcher.js +188 -0
  34. package/dist/host/lines.js +15 -0
  35. package/dist/host/node-path.js +33 -0
  36. package/dist/host/npm.js +28 -0
  37. package/dist/host/plugins.js +26 -0
  38. package/dist/host/program.js +14 -0
  39. package/dist/host/runtime.js +179 -0
  40. package/dist/host/server.js +159 -0
  41. package/dist/host/service.js +325 -0
  42. package/dist/host/state.js +203 -0
  43. package/dist/host/up.js +162 -0
  44. package/dist/host/update.js +286 -0
  45. package/dist/host/version.js +81 -0
  46. package/dist/kernel/card-page.js +54 -0
  47. package/dist/kernel/credentials.js +16 -0
  48. package/dist/kernel/cron.js +135 -0
  49. package/dist/kernel/decide.js +826 -0
  50. package/dist/kernel/due.js +73 -0
  51. package/dist/kernel/errors.js +9 -0
  52. package/dist/kernel/evolve.js +264 -0
  53. package/dist/kernel/http.js +357 -0
  54. package/dist/kernel/query.js +202 -0
  55. package/dist/kernel/rules.js +20 -0
  56. package/dist/kernel/store.js +52 -0
  57. package/dist/plugins/acp/agent.js +32 -0
  58. package/dist/plugins/acp/bridge.js +204 -0
  59. package/dist/plugins/claude/agent.js +113 -0
  60. package/dist/plugins/codex/agent.js +105 -0
  61. package/dist/plugins/command/agent.js +25 -0
  62. package/dist/plugins/delivery/action.js +25 -0
  63. package/dist/plugins/delivery/agent.js +13 -0
  64. package/dist/plugins/delivery/delivery.js +388 -0
  65. package/dist/plugins/delivery/github.js +201 -0
  66. package/dist/plugins/delivery/handoff.js +50 -0
  67. package/dist/plugins/delivery/input.js +47 -0
  68. package/dist/plugins/delivery/poll.js +72 -0
  69. package/dist/plugins/delivery/project.js +144 -0
  70. package/dist/plugins/delivery/review-ledger.js +82 -0
  71. package/dist/plugins/delivery/review-policy.js +99 -0
  72. package/dist/plugins/delivery/review.js +280 -0
  73. package/dist/plugins/delivery/run.js +204 -0
  74. package/dist/plugins/desktop/channel.js +94 -0
  75. package/dist/plugins/dsh/agent.js +116 -0
  76. package/dist/plugins/feishu/channel.js +245 -0
  77. package/dist/plugins/github/source.js +30 -0
  78. package/dist/plugins/gitlab/source.js +30 -0
  79. package/dist/plugins/omp/agent.js +3 -0
  80. package/dist/plugins/opencode/agent.js +88 -0
  81. package/dist/plugins/pi/agent.js +92 -0
  82. package/dist/plugins/webhook/channel.js +70 -0
  83. package/dist/plugins/webhook/templates.js +34 -0
  84. package/dist/plugins/xiaojiu/channel.js +410 -0
  85. package/dist/plugins/zcode/agent.js +102 -0
  86. package/dist/protocol/client.js +56 -0
  87. package/dist/protocol/conformance.js +184 -0
  88. package/dist/protocol/job.js +1 -0
  89. package/dist/protocol/rules.js +230 -0
  90. package/dist/protocol/schema.js +70 -0
  91. package/dist/protocol/schema.json +985 -0
  92. package/dist/protocol/validate.js +150 -0
  93. package/dist/worker/agents.js +47 -0
  94. package/dist/worker/contract.js +178 -0
  95. package/dist/worker/run.js +52 -0
  96. package/dist/worker/usage.js +45 -0
  97. package/dist/worker/windows.ps1 +48 -0
  98. package/dist/worker/worker.js +595 -0
  99. package/docs/architecture.en.svg +178 -0
  100. package/docs/architecture.svg +178 -0
  101. package/docs/auto-update.md +53 -0
  102. package/docs/plugins.md +139 -0
  103. package/docs/protocol.md +582 -0
  104. package/docs/state-machines.md +77 -0
  105. package/examples/channel.sh +15 -0
  106. package/examples/plugins/hello-agent/agent.ts +40 -0
  107. package/examples/plugins/hello-channel/channel.ts +54 -0
  108. package/examples/plugins/hello-source/source.ts +19 -0
  109. package/examples/recipes/browser-handoff/README.md +44 -0
  110. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  111. package/examples/recipes/browser-handoff/browser.json +10 -0
  112. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  113. package/examples/recipes/browser-handoff/rules.json +19 -0
  114. package/examples/recipes/feedback/README.md +34 -0
  115. package/examples/recipes/feedback/SKILL.md +22 -0
  116. package/examples/recipes/feedback/event.json +8 -0
  117. package/examples/recipes/feedback/rules.json +37 -0
  118. package/examples/recipes/feishu-brief/README.md +28 -0
  119. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  120. package/examples/recipes/feishu-brief/collect.ts +164 -0
  121. package/examples/recipes/feishu-brief/rules.json +57 -0
  122. package/examples/recipes/feishu-brief/sources.json +13 -0
  123. package/examples/recipes/github-issues/README.md +17 -0
  124. package/examples/recipes/github-issues/SKILL.md +18 -0
  125. package/examples/recipes/github-issues/rules.json +30 -0
  126. package/examples/recipes/inbox-triage/README.md +36 -0
  127. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  128. package/examples/recipes/inbox-triage/collect.ts +191 -0
  129. package/examples/recipes/inbox-triage/rules.json +57 -0
  130. package/examples/recipes/inbox-triage/sources.json +8 -0
  131. package/examples/recipes/morning-brief/README.md +17 -0
  132. package/examples/recipes/morning-brief/SKILL.md +17 -0
  133. package/examples/recipes/morning-brief/rules.json +16 -0
  134. package/examples/recipes/ops-alerts/README.md +18 -0
  135. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  136. package/examples/recipes/ops-alerts/restart.sh +5 -0
  137. package/examples/recipes/ops-alerts/rules.json +29 -0
  138. package/examples/recipes/website-watch/README.md +26 -0
  139. package/examples/recipes/website-watch/SKILL.md +19 -0
  140. package/examples/recipes/website-watch/check.ts +86 -0
  141. package/examples/recipes/website-watch/rules.json +56 -0
  142. package/examples/recipes/website-watch/site.json +6 -0
  143. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  144. package/examples/watch-github-issues.sh +23 -0
  145. package/examples/worker.sh +18 -0
  146. package/package.json +57 -4
  147. package/plugins/acp/agent.ts +31 -0
  148. package/plugins/acp/bridge.ts +190 -0
  149. package/plugins/claude/agent.ts +121 -0
  150. package/plugins/codex/agent.ts +103 -0
  151. package/plugins/command/agent.ts +25 -0
  152. package/plugins/delivery/action.ts +29 -0
  153. package/plugins/delivery/action.yml +28 -0
  154. package/plugins/delivery/agent.ts +15 -0
  155. package/plugins/delivery/delivery.ts +408 -0
  156. package/plugins/delivery/github.ts +207 -0
  157. package/plugins/delivery/handoff.ts +72 -0
  158. package/plugins/delivery/input.ts +55 -0
  159. package/plugins/delivery/poll.ts +65 -0
  160. package/plugins/delivery/project.ts +161 -0
  161. package/plugins/delivery/review-ledger.ts +90 -0
  162. package/plugins/delivery/review-policy.ts +126 -0
  163. package/plugins/delivery/review.ts +324 -0
  164. package/plugins/delivery/run.ts +219 -0
  165. package/plugins/desktop/channel.ts +100 -0
  166. package/plugins/dsh/agent.ts +100 -0
  167. package/plugins/feishu/channel.ts +243 -0
  168. package/plugins/github/source.ts +33 -0
  169. package/plugins/gitlab/source.ts +32 -0
  170. package/plugins/omp/agent.ts +4 -0
  171. package/plugins/opencode/agent.ts +78 -0
  172. package/plugins/pi/agent.ts +80 -0
  173. package/plugins/webhook/channel.ts +74 -0
  174. package/plugins/webhook/templates.ts +32 -0
  175. package/plugins/xiaojiu/channel.ts +426 -0
  176. package/plugins/zcode/agent.ts +96 -0
  177. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,47 @@
1
+ export function subjectNumber(repo, context) {
2
+ const subjects = [...new Set(context.events.map((event) => event.subject))];
3
+ const suffix = subjects[0]?.slice(repo.length + 1);
4
+ if (subjects.length !== 1 || !subjects[0].startsWith(`${repo}#`) || !/^[1-9]\d*$/.test(suffix)) {
5
+ throw new Error("事件没有指向规则指定仓库的同一个事项");
6
+ }
7
+ const number = Number(suffix);
8
+ if (!Number.isSafeInteger(number))
9
+ throw new Error("事项编号不正确");
10
+ return number;
11
+ }
12
+ export function question(issue) {
13
+ const lines = (issue.body ?? "").replace(/```[\s\S]*?```/g, "").split("\n");
14
+ const text = lines
15
+ .filter((line) => !/\/Users\/|\/home\/|Traceback|^\s+at /.test(line))
16
+ .join("\n")
17
+ .trim();
18
+ return {
19
+ key: `owner-${issue.number}`,
20
+ title: [...issue.title].slice(0, 100).join(""),
21
+ text: [...(text || issue.html_url)].slice(0, 1500).join(""),
22
+ options: ["已处理", "暂不处理"],
23
+ about: issue.html_url,
24
+ };
25
+ }
26
+ /** The hub reads a receipt up to the first three backticks, even inside a string, so what people wrote can't spell them. */
27
+ export const receiptBlock = (receipt) => `\`\`\`agent-autoloop\n${JSON.stringify(receipt).replaceAll("`", "\\u0060")}\n\`\`\``;
28
+ export function deliveryReceipt(number, result, attended) {
29
+ if (!result.findings?.length)
30
+ return result.summary;
31
+ const text = result.findings.map((finding) => `${finding.title}:${finding.text}`).join("\n");
32
+ // Left as written, a finding could hold a receipt block of its own, and the hub would act on it.
33
+ if (attended)
34
+ return `${result.summary}\n${text.replaceAll("```", "'''")}`;
35
+ // An open card with the same key takes the new one in, so findings on a new commit need a key of their own.
36
+ const key = `review-${number}-${result.head?.slice(0, 12)}`;
37
+ const notice = { key, title: "交付前需要修复问题", text: [...text].slice(0, 1500).join("") };
38
+ return `${result.summary}\n${receiptBlock({ notice: [notice] })}`;
39
+ }
40
+ export function pendingEvents(repo, rows) {
41
+ return rows.map(({ number, head, labelEvent, kind }) => ({
42
+ id: `${repo}#${number}:${labelEvent}:${head}`,
43
+ type: `${kind}.labeled`,
44
+ subject: `${repo}#${number}`,
45
+ link: `https://github.com/${repo}/${kind === "pull_request" ? "pull" : "issues"}/${number}`,
46
+ }));
47
+ }
@@ -0,0 +1,72 @@
1
+ // What's waiting for delivery, as events: each labelled item, with an id that stays the same until something changes.
2
+ import { github, pages } from "./github.js";
3
+ import { hasLabel, unattendedFailure } from "./handoff.js";
4
+ import { pendingEvents } from "./input.js";
5
+ export async function poll(repo, dispatch = false) {
6
+ const api = github(repo);
7
+ const rows = [];
8
+ const order = dispatch ? "&sort=created&direction=asc" : "";
9
+ for (const label of ["deliver", "ask-owner"]) {
10
+ for (const issue of pages(repo, `issues?state=all&labels=${label}&per_page=100${order}`)) {
11
+ if (!issue.pull_request && issue.state !== "open")
12
+ continue;
13
+ const events = pages(repo, `issues/${issue.number}/events?per_page=100`);
14
+ const marked = events.filter((event) => event.event === "labeled" && event.label?.name === label).at(-1);
15
+ const pr = issue.pull_request ? await api(`pulls/${issue.number}`) : null;
16
+ if (!dispatch && pr?.state === "closed" && !pr.merged_at)
17
+ continue;
18
+ rows.push({
19
+ number: issue.number,
20
+ head: pr?.head.sha ?? "",
21
+ // One item without a readable record must not hold up the others.
22
+ labelEvent: marked?.id ?? 0,
23
+ kind: pr ? "pull_request" : "issues",
24
+ });
25
+ }
26
+ }
27
+ const events = pendingEvents(repo, rows);
28
+ if (!dispatch)
29
+ return events;
30
+ const prefix = `delivery.${repo.toLowerCase().replace("/", ".")}`;
31
+ const pending = events.map((event) => ({
32
+ ...event,
33
+ type: `${prefix}.${event.type === "pull_request.labeled" ? "pr" : "issue"}`,
34
+ }));
35
+ for (const issue of pages(repo, "issues?state=all&labels=deliver-attended&per_page=100")) {
36
+ if (!issue.pull_request || hasLabel(issue, "deliver"))
37
+ continue;
38
+ const pr = await api(`pulls/${issue.number}`);
39
+ if (!hasLabel(pr, "deliver-attended") || hasLabel(pr, "deliver"))
40
+ continue;
41
+ const { statuses } = await api(`commits/${pr.head.sha}/status?per_page=100`);
42
+ const failure = statuses.find((item) => item.context === "delivery");
43
+ if (!unattendedFailure(pr.labels, failure))
44
+ continue;
45
+ pending.push({
46
+ id: `${repo}#${issue.number}:unacknowledged:${failure.id}:${pr.head.sha}`,
47
+ type: `${prefix}.unacknowledged`,
48
+ subject: `${repo}#${issue.number}`,
49
+ link: pr.html_url,
50
+ });
51
+ }
52
+ return pending;
53
+ }
54
+ if (import.meta.main) {
55
+ const [, , first, ...rest] = process.argv;
56
+ const dispatch = first === "--dispatch";
57
+ const repos = dispatch ? rest : [first];
58
+ if (!repos.length)
59
+ throw new Error("请指定至少一个 owner/name 仓库");
60
+ const results = await Promise.allSettled(repos.map((repo) => poll(repo, dispatch)));
61
+ const events = results
62
+ .flatMap((result, index) => {
63
+ if (result.status === "fulfilled")
64
+ return result.value;
65
+ if (!dispatch)
66
+ throw result.reason;
67
+ console.error(`${repos[index]} 的交付标签暂时读不到,下轮再查`);
68
+ return [];
69
+ })
70
+ .slice(0, 100);
71
+ console.log(`看过了,${events.length} 件待处理\n\`\`\`agent-autoloop\n${JSON.stringify({ events })}\n\`\`\``);
72
+ }
@@ -0,0 +1,144 @@
1
+ // A project's delivery settings and what they say about a release. The Ship action runs from a copy of this file in the
2
+ // project, so it imports nothing beyond Node.
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ export const REPO = /^[\w.-]+\/[\w.-]+$/;
5
+ export const AGENT = /^[a-z][a-z0-9-]{0,31}$/;
6
+ /** A file that isn't executable or a link, or isn't there: only such a change can be left out of a review or a release. */
7
+ export const PLAIN_FILE_MODES = ["000000", "100644"];
8
+ const SETTINGS_KEYS = ["repo", "internal", "admin_merge", "check", "ship", "review", "health"];
9
+ const isWords = (value) => Array.isArray(value) && value.every((word) => typeof word === "string" && word.length > 0);
10
+ const isPaths = (value) => isWords(value) && value.every((path) => !path.startsWith("/") && !path.split("/").includes(".."));
11
+ /** A model and a depth go onto Codex's command line: neither may read as an option. */
12
+ function isReviewer(value) {
13
+ if (value === null)
14
+ return true;
15
+ if (typeof value !== "object" || Array.isArray(value))
16
+ return false;
17
+ const { model, effort, command, ...unknown } = value;
18
+ if (Object.keys(unknown).length)
19
+ return false;
20
+ if (command !== undefined)
21
+ return model === undefined && effort === undefined && isWords(command) && command.length > 0;
22
+ const named = model === undefined || (typeof model === "string" && /^[A-Za-z0-9][\w.-]*$/.test(model));
23
+ return named && (effort === undefined || (typeof effort === "string" && /^[a-z]+$/.test(effort)));
24
+ }
25
+ /** Settings may write a named group the way Python does; JavaScript only reads the other way. */
26
+ const jsPattern = (pattern) => pattern.replace("(?P<sha>", "(?<sha>");
27
+ export function settings(value, testLocalHealth = false) {
28
+ const bad = () => {
29
+ throw new Error("ops/delivery.json 的设置不正确");
30
+ };
31
+ if (!value || !REPO.test(value.repo ?? "") || !isPaths(value.internal))
32
+ bad();
33
+ if (Object.keys(value).some((key) => !SETTINGS_KEYS.includes(key)))
34
+ bad();
35
+ const { review, health } = value;
36
+ if (!review || !isPaths([review.points]) || (review.xhigh !== undefined && !isPaths(review.xhigh)))
37
+ bad();
38
+ if (review.command !== undefined && (!isWords(review.command) || !review.command.length))
39
+ bad();
40
+ if (review.status !== undefined && (typeof review.status !== "string" || !review.status.trim()))
41
+ bad();
42
+ const { agents = {}, trusted = [] } = review;
43
+ if (!agents || typeof agents !== "object" || Array.isArray(agents))
44
+ bad();
45
+ if (!Object.entries(agents).every(([name, reviewer]) => AGENT.test(name) && isReviewer(reviewer)))
46
+ bad();
47
+ if (!Array.isArray(trusted) || !trusted.every((id) => Number.isSafeInteger(id) && id > 0))
48
+ bad();
49
+ // Anyone who can write a commit status, a workflow of the PR's own included, could otherwise name its agent.
50
+ if (Object.keys(agents).length && !trusted.length)
51
+ bad();
52
+ if (value.admin_merge !== undefined && !isWords(value.admin_merge))
53
+ bad();
54
+ for (const workflow of [value.check?.workflow, value.ship?.workflow]) {
55
+ if (workflow !== undefined && !/^[\w.-]+\.ya?ml$/.test(workflow))
56
+ bad();
57
+ }
58
+ if (value.check?.job !== undefined && (typeof value.check.job !== "string" || !value.check.job))
59
+ bad();
60
+ if (health) {
61
+ const url = new URL(health.url);
62
+ const secure = url.protocol === "https:" || (testLocalHealth && url.protocol === "http:" && url.hostname === "127.0.0.1");
63
+ if (!secure || url.username || url.password)
64
+ bad();
65
+ if (typeof health.field !== "string" || typeof health.pattern !== "string")
66
+ bad();
67
+ if (!/\(\?(?:P)?<sha>/.test(health.pattern))
68
+ bad();
69
+ new RegExp(jsPattern(health.pattern));
70
+ const { require } = health;
71
+ if (require !== undefined && (!require || typeof require !== "object" || Array.isArray(require)))
72
+ bad();
73
+ }
74
+ return {
75
+ ...value,
76
+ admin_merge: value.admin_merge ?? [],
77
+ check: { workflow: "check.yml", job: "check", ...value.check },
78
+ ship: { workflow: "ship.yml", ...value.ship },
79
+ review: { xhigh: [], status: "agent-review", ...review, agents, trusted },
80
+ ...(health && { health: { require: {}, ...health } }),
81
+ };
82
+ }
83
+ export function git(root, ...args) {
84
+ const options = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "core.quotePath=false"];
85
+ return execFileSync("git", [...options, ...args], {
86
+ cwd: root,
87
+ encoding: "utf8",
88
+ timeout: 60000,
89
+ maxBuffer: 32 * 1024 * 1024,
90
+ stdio: ["ignore", "pipe", "pipe"],
91
+ }).trim();
92
+ }
93
+ export function readMainSettings(root, testLocalHealth = false, ref = "origin/main") {
94
+ return settings(JSON.parse(git(root, "show", `${ref}:ops/delivery.json`)), testLocalHealth);
95
+ }
96
+ function globToRegExp(pattern) {
97
+ const parts = pattern.split(/(\*\*\/|\*)/).map((part) => {
98
+ if (part === "**/")
99
+ return "(?:.*/)?";
100
+ if (part === "*")
101
+ return "[^/]*";
102
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
103
+ });
104
+ return new RegExp(`^${parts.join("")}$`);
105
+ }
106
+ export const matches = (name, patterns) => patterns.some((pattern) => globToRegExp(pattern).test(name));
107
+ export function releaseRequired(root, base, head, patterns) {
108
+ const isAncestor = spawnSync("git", ["merge-base", "--is-ancestor", base, head], { cwd: root, stdio: "ignore" });
109
+ if (isAncestor.status !== 0)
110
+ return true;
111
+ const records = git(root, "diff", "--raw", "-z", "--no-renames", "--no-ext-diff", "--no-textconv", base, head, "--").split("\0");
112
+ for (let index = 0; index + 1 < records.length; index += 2) {
113
+ const modes = records[index].replace(/^:/, "").split(" ").slice(0, 2);
114
+ const plainFile = modes.every((mode) => PLAIN_FILE_MODES.includes(mode));
115
+ if (!plainFile || !matches(records[index + 1], patterns))
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+ export async function liveRelease(config, request = fetch) {
121
+ if (!config.health)
122
+ return null;
123
+ const { url, require, field, pattern } = config.health;
124
+ try {
125
+ const response = await request(url, {
126
+ signal: AbortSignal.timeout(15000),
127
+ redirect: "error",
128
+ headers: { "cache-control": "no-cache" },
129
+ });
130
+ if (!response.ok)
131
+ return null;
132
+ const body = await response.json();
133
+ if (!body || Object.entries(require).some(([key, value]) => body[key] !== value))
134
+ return null;
135
+ if (typeof body[field] !== "string")
136
+ return null;
137
+ const release = body[field];
138
+ const sha = new RegExp(`^(?:${jsPattern(pattern)})$`).exec(release)?.groups?.sha;
139
+ return sha && /^[a-f0-9]{7,40}$/.test(sha) ? { sha, release } : null;
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
@@ -0,0 +1,82 @@
1
+ import { createHash } from "node:crypto";
2
+ const SECTION = "## Codex 审查";
3
+ const ROUND = /^第 (\d+) 轮(([^)\n]+),([a-z]+(?: \+ [a-z]+)*),审到 ([0-9a-f]{7,40})):/gm;
4
+ const ITEM = /^(\d+)\. /;
5
+ export const REVIEW_ROUNDS = 3;
6
+ function section(body) {
7
+ return /^## Codex 审查\n([\s\S]*?)(?=^## |$(?![\s\S]))/m.exec(body);
8
+ }
9
+ export function ledger(description) {
10
+ const body = (description ?? "").replaceAll("\r\n", "\n");
11
+ const match = section(body);
12
+ const record = match?.[1] ?? "";
13
+ const matches = [...record.matchAll(ROUND)];
14
+ const rounds = matches.map(([, number, signature, effort, head], index) => ({
15
+ number: Number(number),
16
+ signature,
17
+ effort,
18
+ head,
19
+ // Bind all earlier rounds too. Removing an old finding must invalidate the latest proof.
20
+ digest: createHash("sha256")
21
+ .update(record
22
+ .slice(0, matches[index + 1]?.index)
23
+ .replace(/^ 处理:[^\n]*$/gm, " 处理:")
24
+ .trim())
25
+ .digest("hex"),
26
+ }));
27
+ const waiting = new Map();
28
+ let current;
29
+ for (const line of record.split("\n")) {
30
+ const item = ITEM.exec(line);
31
+ if (item) {
32
+ current = Number(item[1]);
33
+ waiting.set(current, true);
34
+ }
35
+ else if (line.startsWith("第 ") && line.includes(" 轮(")) {
36
+ current = undefined;
37
+ }
38
+ else if (current !== undefined) {
39
+ const handled = /^ +处理:(.*)$/.exec(line);
40
+ if (handled)
41
+ waiting.set(current, !handled[1].trim());
42
+ }
43
+ }
44
+ return {
45
+ body,
46
+ record: record.trim(),
47
+ rounds,
48
+ author: match ? (body.slice(0, match.index) + body.slice(match.index + match[0].length)).trim() : body.trim(),
49
+ unhandled: [...waiting].filter(([, pending]) => pending).map(([item]) => item),
50
+ numbered: Math.max(0, ...waiting.keys()),
51
+ append(text) {
52
+ if (!match)
53
+ return `${body.trimEnd()}${body.trim() ? "\n\n" : ""}${SECTION}\n\n${text}\n`;
54
+ const end = match.index + match[0].length;
55
+ const rest = body.slice(end);
56
+ return `${body.slice(0, end).trimEnd()}\n\n${text}\n${rest ? `\n${rest}` : ""}`;
57
+ },
58
+ };
59
+ }
60
+ export function renderRound(current, signature, effort, head, findings) {
61
+ const header = `第 ${current.rounds.length + 1} 轮(${signature},${effort.join(" + ")},审到 ${head}):`;
62
+ if (!findings.length)
63
+ return `${header}没有发现问题。`;
64
+ const round = current.rounds.length + 1;
65
+ return [
66
+ `${header}发现 ${findings.length} 条。`,
67
+ // Patching the same spot round after round rarely converges. Later rounds still review only the new commits.
68
+ ...(round >= REVIEW_ROUNDS
69
+ ? [
70
+ `\n已经审了 ${round} 轮还有问题,先退一步想想是不是要换个做法。换做法就推新提交,下一轮只审新改的部分;不换就在每条的“处理:”后写清不改的理由。`,
71
+ ]
72
+ : []),
73
+ ...findings.map(({ title, text }, index) => {
74
+ const body = text
75
+ .replaceAll("\r\n", "\n")
76
+ .split("\n")
77
+ .map((line) => (line ? ` ${line}` : ""))
78
+ .join("\n");
79
+ return `\n${current.numbered + index + 1}. **${title.replace(/\s+/g, " ").trim()}**\n\n${body}\n\n 处理:`;
80
+ }),
81
+ ].join("\n");
82
+ }
@@ -0,0 +1,99 @@
1
+ import { createHash } from "node:crypto";
2
+ import { AGENT, REPO } from "./project.js";
3
+ export const EFFORTS = ["low", "medium", "high", "xhigh", "max", "ultra"];
4
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
5
+ const isObject = (value) => value && typeof value === "object" && !Array.isArray(value);
6
+ export function sharedPolicy(value) {
7
+ const bad = () => {
8
+ throw new Error("共用审查策略不正确:请检查审查器、深度、可信账号和非空默认审查列表");
9
+ };
10
+ if (!isObject(value) || Object.keys(value).sort().join() !== "agents,default,reviewers,trusted_submitters")
11
+ bad();
12
+ const { trusted_submitters, reviewers, agents, default: fallback } = value;
13
+ if (!Array.isArray(trusted_submitters) || !trusted_submitters.every((id) => Number.isSafeInteger(id) && id > 0))
14
+ bad();
15
+ if (!isObject(reviewers) || !isObject(agents))
16
+ bad();
17
+ const validPlan = (plan) => Array.isArray(plan) && plan.every((name) => typeof name === "string" && Object.hasOwn(reviewers, name));
18
+ if (!validPlan(fallback) || !fallback.length)
19
+ bad();
20
+ for (const [agent, plan] of Object.entries(agents))
21
+ if (!AGENT.test(agent) || !validPlan(plan))
22
+ bad();
23
+ const normalized = Object.fromEntries(Object.entries(reviewers).map(([name, raw]) => {
24
+ const reviewer = typeof raw === "string" ? { model: raw, effort: "high" } : raw;
25
+ if (!AGENT.test(name) ||
26
+ !isObject(reviewer) ||
27
+ Object.keys(reviewer).sort().join() !== "effort,model" ||
28
+ typeof reviewer.model !== "string" ||
29
+ !MODEL.test(reviewer.model) ||
30
+ !EFFORTS.includes(reviewer.effort))
31
+ bad();
32
+ return [name, reviewer];
33
+ }));
34
+ return { trusted_submitters, reviewers: normalized, agents, default: fallback };
35
+ }
36
+ export async function readSharedPolicy(spec, apiFor) {
37
+ const [repo, path, ...rest] = spec.split(":");
38
+ if (!REPO.test(repo) ||
39
+ !path ||
40
+ rest.length ||
41
+ path.split("/").some((part) => !part || part === "." || part === ".."))
42
+ throw new Error("共用审查策略要写成 owner/repo:仓库内路径");
43
+ const { content } = await apiFor(repo)(`contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=main`);
44
+ return sharedPolicy(JSON.parse(Buffer.from(content, "base64").toString("utf8")));
45
+ }
46
+ export function selectReview(config, agent, required, policy) {
47
+ if (policy) {
48
+ const selected = agent && Object.hasOwn(policy.agents, agent) ? policy.agents[agent] : policy.default;
49
+ return (required && !selected.length ? policy.default : selected).map((name) => ({
50
+ name,
51
+ ...policy.reviewers[name],
52
+ }));
53
+ }
54
+ const listed = agent !== null && Object.hasOwn(config.review.agents, agent) ? config.review.agents[agent] : undefined;
55
+ const reviewer = listed === undefined || (listed === null && required) ? { command: config.review.command } : listed;
56
+ return reviewer ? [{ name: "codex", ...reviewer }] : [];
57
+ }
58
+ const DEFAULT_MODEL = "gpt-6.2-sol";
59
+ const commandPlan = (command) => `command/${createHash("sha256").update(JSON.stringify(command)).digest("hex")}`;
60
+ /**
61
+ * Whether a recorded round already did the review these reviewers would do now. A round's credit is what ran (each
62
+ * reviewer's command, or its model at the depth it ran), not what the policy called it: an agent's deep reviewer and
63
+ * the default reviewer raised to the same depth by a deep-review path are the same review.
64
+ */
65
+ export function reviewCovers(round, reviewers, efforts) {
66
+ const ran = round.effort.split(" + ");
67
+ const done = round.signature.split(" + ").map((entry, index) => {
68
+ // Entries are "command/hash", "name/model[@configured depth]", or a bare model from older rounds; the depth that ran is
69
+ // recorded apart.
70
+ const plan = entry.startsWith("command/") || !entry.includes("/") ? entry : entry.slice(entry.indexOf("/") + 1);
71
+ return `${plan.replace(/@[a-z]+$/, "")}@${ran[index]}`;
72
+ });
73
+ return reviewers.every(({ command, model = DEFAULT_MODEL }, index) => {
74
+ const at = done.indexOf(`${command ? commandPlan(command) : model}@${efforts[index]}`);
75
+ if (at < 0)
76
+ return false;
77
+ done.splice(at, 1);
78
+ return true;
79
+ });
80
+ }
81
+ export function reviewSignature(reviewers) {
82
+ const model = DEFAULT_MODEL;
83
+ if (reviewers.length === 1) {
84
+ const [reviewer] = reviewers;
85
+ // Match the name that older rounds used for the default plan.
86
+ if (reviewer.name === "codex" &&
87
+ (reviewer.model ?? model) === model &&
88
+ (reviewer.effort ?? "high") === "high" &&
89
+ !reviewer.command)
90
+ return model;
91
+ }
92
+ return reviewers
93
+ .map(({ name, model: selected = model, effort = "high", command }) => {
94
+ if (command)
95
+ return commandPlan(command);
96
+ return `${name}/${selected}${effort === "high" ? "" : `@${effort}`}`;
97
+ })
98
+ .join(" + ");
99
+ }