Skip to content

Commit 3247470

Browse files
committed
Add approval-based PR merging and configurable message signatures
1 parent 021507a commit 3247470

14 files changed

Lines changed: 243 additions & 15 deletions

‎AGENTS.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Repository instructions
2+
3+
Write and maintain all README files in English. This also applies when the conversation is in Polish.

‎README.md‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,9 @@ Use a model available in your own OpenCode 2 installation. Optional fields:
9898
| `trigger` | Mention that starts work; defaults to `@d3ckerbot`. |
9999
| `everySeconds` | Polling interval; defaults to 60 seconds. |
100100
| `check` | Test command as an argument array, such as `["npm", "test"]`; `false` skips tests. |
101-
| `authors` | GitHub usernames allowed to request work. |
101+
| `authors` | GitHub usernames allowed to request work and authorize merging (merge also requires repository write access). |
102+
| `signature` | Signature appended to every posted comment and PR description; defaults to `your-github-login[OpenCode2]`. |
103+
| `autoMerge` | Automatic merge settings: `enabled` (default `true`), `method` (default `squash`), and exact approval `comments`. |
102104

103105
When tests are skipped, the PR explicitly reports that automated tests were not
104106
run. Git consistency checks and the requirement for an actual change remain.
@@ -111,6 +113,49 @@ cd /absolute/path/to/your-project
111113
node "$HOME/opencode2-github-automation/dist/setup.js" init --model provider/model --skip-tests
112114
```
113115

116+
## Automatic merge and message signatures
117+
118+
Example project configuration:
119+
120+
```json
121+
{
122+
"model": "provider/model",
123+
"check": false,
124+
"signature": "d3cker[OpenCode2]",
125+
"autoMerge": {
126+
"enabled": true,
127+
"method": "squash",
128+
"comments": ["/merge", "lgtm, merge", "jest git, możesz mergować", "jest git, można mergować"]
129+
}
130+
}
131+
```
132+
133+
For a PR created by this bot, either approve the current published commit using
134+
GitHub's **Approve** review, or post one of the configured full-message phrases
135+
in the PR conversation. Matching ignores case, repeated whitespace, and final
136+
periods/exclamation marks. Arbitrary positive prose, quoted commands, negations,
137+
and inline code review comments are not interpreted as merge instructions.
138+
139+
The approving account must be in `authors` (by default, the authenticated user)
140+
and have write, maintain, or admin permission on the repository. GitHub does not
141+
allow authors to approve their own PRs; use a configured comment in that case.
142+
Outstanding change requests block merge. The PR must be open, non-draft, and
143+
reported as clean and mergeable by GitHub. The merge request includes the exact
144+
verified head SHA; a changed branch cannot be merged using an older approval.
145+
The bot does not request a protection bypass. Configure required checks and review
146+
rules on GitHub for your repository's policy.
147+
148+
Approvals must be newer than the bot's latest publication. On upgrade, old tasks
149+
start watching for new approvals; historical approvals do not cause a merge.
150+
Pending issue feedback is processed before attempting a merge. Merge failures
151+
are retried at intervals of at least 60 seconds and appear as `mergeError` in
152+
`status` and in `/bot`. Successful merges receive a signed PR comment.
153+
154+
Signatures are appended to issue comments, PR descriptions, and merge
155+
acknowledgements. They identify the message in its text; GitHub still attributes
156+
posts to the account authenticated by your token. Existing posts are not rewritten.
157+
Set `"autoMerge": { "enabled": false }` to disable automatic merging.
158+
114159
## Follow progress and continue work
115160

116161
Starting a session shows a notification and opens a background tab when tabs

‎docs/advanced.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ MVP nie sprząta ich automatycznie.
146146
- GitHub.com i token użytkownika; bez GitHub Enterprise i tokenów instalacji App.
147147
- Worktree izoluje pliki projektu, ale nie jest sandboxem dla narzędzi agenta.
148148
Autorzy issues i uprawnienia wykonawcy muszą być świadomie skonfigurowani.
149-
- Nie wykonujemy auto-merge. PR powstaje tylko przy rzeczywistej zmianie i
149+
- Auto-merge wymaga akceptacji uprawnionego autora dla aktualnej publikacji; szczegóły i konfiguracja są w README. PR powstaje tylko przy rzeczywistej zmianie i
150150
przejściu skonfigurowanych sprawdzeń.
151151
- Testy lokalne używają rzeczywistego Git i SDK V2 oraz atrap GitHub API i sesji.
152152
Nie zastępują testu integracyjnego z Twoim serwerem, modelem i repozytorium.

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "opencode2-automation",
3-
"version": "0.3.1",
3+
"version": "0.4.0-beta.1",
44
"description": "Issue-to-PR automation for OpenCode 2 with a scheduler and GitHub dispatcher",
55
"main": "./dist/index.js",
66
"files": [

‎src/activity.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ export const Activity = z.object({
1010
export type Activity = z.infer<typeof Activity>;
1111
export function activityOf(task: Task): Activity {
1212
return { key: task.key, repo: task.repo, issueNumber: task.issue.number, round: task.round ?? 1,
13-
phase: task.phase, status: task.status,
13+
phase: task.merged ? "merged" : task.phase, status: task.status,
1414
...(task.sessionID ? { sessionID: task.sessionID } : {}),
1515
...(task.worktree ? { worktree: task.worktree } : {}),
1616
sessionReady: task.sessionReady ?? Boolean(task.promptAttempted),
17-
...(task.error ? { error: task.error } : {}),
17+
...(task.error || task.mergeError ? { error: task.error ?? task.mergeError } : {}),
1818
...(task.pr ? { prURL: task.pr.html_url } : {}) };
1919
}

‎src/approval.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { z } from "zod";
2+
3+
export const Review = z.object({ id: z.number(), user: z.object({ login: z.string() }), state: z.string(), commit_id: z.string(), submitted_at: z.string().nullable(), body: z.string().nullable().optional() });
4+
export type Review = z.infer<typeof Review>;
5+
export const DatedComment = z.object({ id: z.number(), body: z.string(), user: z.object({ login: z.string(), type: z.string().optional() }), created_at: z.string(), updated_at: z.string() });
6+
export type DatedComment = z.infer<typeof DatedComment>;
7+
const normalize = (text: string) => text.trim().toLowerCase().replace(/[.!]+$/, "").replace(/\s+/g, " ");
8+
export function approvalAuthors(reviews: Review[], comments: DatedComment[], head: string, since: number, phrases: string[]): string[] {
9+
const latest = new Map<string, Review>();
10+
for (const review of [...reviews].sort((a, b) => a.id - b.id)) {
11+
if (["APPROVED", "CHANGES_REQUESTED", "DISMISSED"].includes(review.state)) latest.set(review.user.login.toLowerCase(), review);
12+
}
13+
// An outstanding request for changes takes precedence over a merge comment.
14+
if ([...latest.values()].some(r => r.state === "CHANGES_REQUESTED")) return [];
15+
const authors = [...latest.values()].filter(r => r.state === "APPROVED" && r.commit_id === head && Date.parse(r.submitted_at ?? "") > since).map(r => r.user.login);
16+
for (const comment of comments) {
17+
if (comment.user.type === "Bot" || comment.body.includes("<!-- opencode2:") || Date.parse(comment.created_at) <= since) continue;
18+
// Exact full-message matching avoids interpreting negations, quotes, or embedded instructions as approval.
19+
if (phrases.some(p => normalize(p) === normalize(comment.body))) authors.push(comment.user.login);
20+
}
21+
return [...new Set(authors)];
22+
}

‎src/config.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,14 @@ export const Repository = z.object({
1616
checks: z.array(z.array(z.string().min(1)).min(1)),
1717
}).strict();
1818
export type Repository = z.infer<typeof Repository>;
19+
export const MergeOptions = z.object({
20+
enabled: z.boolean().default(true),
21+
method: z.enum(["merge", "squash", "rebase"]).default("squash"),
22+
comments: z.array(z.string().trim().min(1)).min(1).default(["/merge", "lgtm, merge", "jest git, możesz mergować", "jest git, można mergować"]),
23+
}).strict();
1924
export const GithubOptions = z.object({
25+
signature: z.string().trim().min(1).max(200).regex(/^[^\r\n]+$/).optional(),
26+
autoMerge: MergeOptions.default({ enabled: true, method: "squash", comments: ["/merge", "lgtm, merge", "jest git, możesz mergować", "jest git, można mergować"] }),
2027
ownerDirectory: absolute,
2128
stateDirectory: absolute,
2229
tokenEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default("GITHUB_TOKEN"),

‎src/dispatcher.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export const Task = z.object({
1818
feedback: z.array(Comment).optional(), pendingFeedback: z.array(Comment).optional(), commentCursor: z.number().optional(),
1919
previousSessionID: z.string().optional(),
2020
checks: z.array(z.string()).optional(), commit: z.string().optional(),
21+
publishedAt: z.number().optional(), merged: z.boolean().optional(), mergeError: z.string().optional(), mergeNextAt: z.number().optional(),
2122
prTitle: z.string().min(1).max(240).optional(),
2223
pr: z.object({ number: z.number(), html_url: z.string(), state: z.string() }).optional(), error: z.string().optional(),
2324
});
@@ -27,6 +28,7 @@ export type Queue = z.infer<typeof Queue>;
2728
export class Blocked extends Error {}
2829

2930
export interface GithubPort {
31+
mergeApproved?(repo: string, number: number, commit: string, since: number, authors: string[], options: GithubOptions["autoMerge"]): Promise<boolean>;
3032
issues(repo: string): Promise<Issue[]>;
3133
issue(repo: string, number: number): Promise<Issue>;
3234
comments(repo: string, number: number): Promise<Comment[]>;
@@ -140,7 +142,7 @@ export class Dispatcher {
140142
const activeSession = resumable.find(t => t.phase === "running" && t.sessionID);
141143
const task = activeSession ?? resumable.find(t => t.nextAt <= this.now());
142144
if (task && task.nextAt > this.now()) return;
143-
if (!task) return;
145+
if (!task) { await this.mergeOnce(); return; }
144146
const repo = this.options.repositories.find(r => r.repo === task.repo);
145147
try {
146148
if (!repo) throw new Blocked("Repository removed from configuration");
@@ -190,7 +192,7 @@ export class Dispatcher {
190192
await this.executor.push(task, repo);
191193
pr = await this.github.ensurePull(task.repo, task.branch, repo.baseBranch, task.prTitle!, `${task.analysis}\n\nCloses #${task.issue.number}\n\nChecks:\n${task.checks?.length ? task.checks.map(c => `- ${c}`).join("\n") : "- Automated tests were not run: no test command configured. Only Git consistency checks were performed."}\n\nOpenCode session: ${task.sessionID}\nCommit: ${task.commit}`);
192194
}
193-
await this.update(task, { pr, phase: "pr_opened", status: "done", attempts: 0 });
195+
await this.update(task, { pr, publishedAt: this.now(), phase: "pr_opened", status: "done", attempts: 0 });
194196
}
195197
} catch (error) {
196198
if (this.signal.aborted) return;
@@ -199,6 +201,28 @@ export class Dispatcher {
199201
await this.update(task, { attempts, error: redact(error, this.secrets), status: blocked ? "blocked" : attempts >= this.options.maxAttempts ? "failed" : "retry_wait", nextAt: Math.max(this.now() + Math.min(3600, 5 * 2 ** attempts) * 1000, error instanceof GithubError ? error.retryAt ?? 0 : 0) });
200202
}
201203
}
204+
private async mergeOnce() {
205+
if (!this.options.autoMerge.enabled || !this.github.mergeApproved) return;
206+
for (const task of this.queue.tasks) {
207+
if (task.status !== "done" || !task.pr || !task.commit || task.merged || task.pendingFeedback?.length || (task.mergeNextAt ?? 0) > this.now()) continue;
208+
const repo = this.options.repositories.find(r => r.repo === task.repo);
209+
if (!repo) continue;
210+
// Older queues start watching now; historical approvals must not trigger an unexpected merge.
211+
if (!task.publishedAt) { await this.update(task, { publishedAt: this.now() }); continue; }
212+
try {
213+
await this.scan(); // Pick up issue feedback before considering a completed task for merge.
214+
if (task.pendingFeedback?.length) continue;
215+
const merged = await this.github.mergeApproved(task.repo, task.pr.number, task.commit, task.publishedAt, repo.allowedAuthors, this.options.autoMerge);
216+
if (merged) {
217+
await this.github.ensureComment(task.repo, task.pr.number, `<!-- opencode2:${task.key}:merged -->`, "Pull request merged.");
218+
await this.update(task, { merged: true, pr: { ...task.pr, state: "closed" }, mergeError: undefined });
219+
} else await this.update(task, { mergeError: undefined, mergeNextAt: this.now() + 60_000 });
220+
} catch (error) {
221+
if (this.signal.aborted) return;
222+
await this.update(task, { mergeError: redact(error, this.secrets), mergeNextAt: Math.max(this.now() + 60_000, error instanceof GithubError ? error.retryAt ?? 0 : 0) });
223+
}
224+
}
225+
}
202226
async retry(key: string, restartSession: boolean) {
203227
if (this.working || this.maintenance) throw new Error("Worker is busy; retry after it finishes");
204228
this.maintenance = this.retryOnce(key, restartSession);

‎src/easy.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import { execFile } from "node:child_process";
22
import { readFile, realpath } from "node:fs/promises";
33
import { join } from "node:path";
44
import { z } from "zod";
5-
import { GithubOptions, SchedulerOptions } from "./config.js";
5+
import { GithubOptions, SchedulerOptions, MergeOptions } from "./config.js";
66

77
export const EasyOptions = z.object({
8+
signature: z.string().trim().min(1).max(200).regex(/^[^\r\n]+$/).optional(),
9+
autoMerge: MergeOptions.optional(),
810
model: z.string().regex(/^[^/\s]+\/\S+$/, "Model must have the form provider/model"),
911
trigger: z.string().regex(/^@[A-Za-z0-9_-]+$/).default("@d3ckerbot"),
1012
everySeconds: z.number().int().min(1).default(60),
@@ -73,7 +75,7 @@ export async function resolveEasy(directory: string, raw: unknown, execute = run
7375
if (check === undefined) throw new Error("Nie wykryto testów. Uruchom init i naciśnij Enter, aby je pominąć, lub użyj --skip-tests.");
7476
const slash = options.model.indexOf("/");
7577
const stateDirectory = join(common, "opencode2-automation");
76-
const github = GithubOptions.parse({ ownerDirectory: root, stateDirectory,
78+
const github = GithubOptions.parse({ signature: options.signature ?? `${login}[OpenCode2]`, autoMerge: options.autoMerge, ownerDirectory: root, stateDirectory,
7779
repositories: [{ repo, directory: root, baseBranch, allowedAuthors: options.authors ?? [login], checks: check === false ? [] : [check] }],
7880
routes: { [options.trigger]: { agent: "build", model: { providerID: options.model.slice(0, slash), id: options.model.slice(slash + 1) } } },
7981
});

0 commit comments

Comments
 (0)