Skip to content

Commit ea2bcfe

Browse files
committed
Interpret base branch requests in natural language
1 parent af12bb0 commit ea2bcfe

11 files changed

Lines changed: 232 additions & 52 deletions

File tree

‎README.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ git switch codex/issue-dialogue-capabilities
167167
git pull --ff-only
168168
```
169169

170-
Then complete update steps 2 and 3 (`0.5.0-beta.1`). Reopen each project you want
170+
Then complete update steps 2 and 3 (`0.5.0-beta.2`). Reopen each project you want
171171
the restarted service to handle.
172172

173173
## 4. Remove automation from one project
@@ -302,9 +302,12 @@ if you want media support with a text-only main model.
302302
mention is needed. The bot enters `waiting` and resumes after the next scan.
303303
Permission questions require the exact `/allow QUESTION_ID` or
304304
`/deny QUESTION_ID` shown in the comment. Explicit OpenCode deny rules remain.
305-
- **Base branch:** set `baseBranch` in the JSON, or put `/base release/next`
306-
on its own line in the initial issue request. The branch must exist on `origin`.
307-
The worktree and PR use that base. Existing tasks keep their pinned base.
305+
- **Base branch:** write naturally, such as "use branch develop" or "work from
306+
release/next", in the issue or an authorized comment. The configured model
307+
interprets the request, including languages such as Polish. Unclear or missing
308+
branches trigger a question in the issue before work starts. `baseBranch` is
309+
only the default; `/base` remains an optional shortcut. Existing tasks keep
310+
their pinned base.
308311
- **Media:** declare actual model capabilities and a helper if needed:
309312

310313
```json

‎docs/advanced.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ OpenCode service must be running for polling to work.
2828
| --- | --- |
2929
| `ownerDirectory` | Absolute path of the checkout that owns automation. Worker worktrees do not activate another scheduler. |
3030
| `stateDirectory` | Shared location for queues, locks, and worktrees. Keep it consistent across components and restarts. |
31-
| `repositories` | Repositories with existing local checkouts, base branches, allowed authors, and checks. |
31+
| `repositories` | Repositories with existing local checkouts, default base branches, allowed authors, and checks. A natural-language request can override the base before work starts. |
3232
| `allowedAuthors` | GitHub users authorized to request work and approve merging. Merging also requires repository write access. |
3333
| `checks` | Arrays of executable arguments, e.g. `[["npm", "test"]]`. `[]` skips automated tests and reports that in the PR. No implicit shell. |
3434
| `routes` | Maps full mentions to agents and models available in OpenCode. |

‎docs/runtime.md‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,29 @@ No terminal UI is needed to answer in GitHub.
2626

2727
## Base branches
2828

29-
Set `"baseBranch": "develop"` in the project JSON, or put a directive in the
30-
issue body or an authorized comment included when work is accepted:
29+
Write your preference in the issue or an authorized comment in ordinary language:
3130

3231
```text
33-
@opencodebot Add an export button.
34-
/base release/next
32+
@opencodebot Add an export button. Please use branch release/next.
3533
```
3634

37-
`Base branch: release/next` on its own line also works. The last explicit
38-
directive wins over the project setting; without either, the GitHub default
39-
branch is used. Arbitrary prose and quoted directives are not branch commands.
40-
The branch must exist on `origin`; a missing branch fails without falling back.
35+
The configured main model interprets the intended base, including requests in
36+
Polish and other languages it understands. No special command syntax is required.
37+
For example, "work from develop" selects `develop`; "do not use develop; use
38+
release/next instead" selects `release/next`. Clear later corrections take
39+
precedence. Quoted messages and fenced code examples are excluded from selection.
40+
41+
`/base release/next` and `Base branch: release/next` remain optional shortcuts.
42+
`baseBranch` in the JSON is the default when no preference is given; if omitted,
43+
the GitHub default branch is used. A selected name must occur in authorized user
44+
text and must exist on `origin`; the model cannot invent a replacement branch.
45+
46+
If the request is ambiguous, or the branch does not exist, the bot asks in the
47+
issue after its initial acknowledgement. No worktree or coding session is created
48+
until the base is resolved. Reply naturally (or with just the branch name) from
49+
an account in `authors`. Questions and replies survive service restarts. An
50+
unavailable Git connection or invalid model response causes a retry, never a
51+
silent fallback to the default branch.
4152

4253
The dispatcher fetches that branch, creates a task branch/worktree from its
4354
commit, and targets the same base in the PR. This choice stays pinned through

‎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.5.0-beta.1",
3+
"version": "0.5.0-beta.2",
44
"description": "Issue-to-PR automation for OpenCode 2 with a scheduler and GitHub dispatcher",
55
"main": "./dist/index.js",
66
"files": [

‎src/branch.ts‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,40 @@
1+
import { z } from "zod";
12
import { BranchName } from "./config.js";
23

3-
// A standalone directive is unambiguous and works for both English and non-English issues.
4-
export function requestedBase(texts: string[], fallback: string): string {
5-
let selected = fallback;
6-
for (const text of texts) {
7-
let fence: string | undefined;
8-
for (const line of text.split(/\r?\n/)) {
9-
const delimiter = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1];
10-
if (delimiter) {
11-
if (!fence) fence = delimiter;
12-
else if (delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = undefined;
13-
continue;
14-
}
15-
if (fence) continue;
16-
const match = /^\s*(?:\/base\s+|base\s+branch\s*:\s*)(\S+)\s*$/i.exec(line);
17-
if (match) selected = BranchName.parse(match[1]!.replace(/^`([^`]+)`$/, "$1"));
4+
export type BranchInput = { text: string; question?: string };
5+
export type BaseChoice = { kind: "branch"; branch: string } | { kind: "question"; question: string };
6+
const Decision = z.discriminatedUnion("kind", [
7+
z.object({ kind: z.literal("default") }).strict(),
8+
z.object({ kind: z.literal("branch"), branch: z.string().min(1).max(250), source: z.number().int().nonnegative(), quote: z.string().min(1) }).strict(),
9+
z.object({ kind: z.literal("question"), question: z.string().min(1).max(4000) }).strict(),
10+
]);
11+
12+
// Quoted messages and code examples are context, not branch-selection requests.
13+
export function branchText(text: string): string {
14+
let fence: string | undefined;
15+
return text.split(/\r?\n/).filter(line => {
16+
const delimiter = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1];
17+
if (delimiter) {
18+
if (!fence) fence = delimiter;
19+
else if (delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = undefined;
20+
return false;
1821
}
22+
return !fence && !/^\s*>/.test(line);
23+
}).join("\n").trim();
24+
}
25+
26+
export function baseChoice(raw: string, inputs: BranchInput[], fallback: string): BaseChoice {
27+
const json = raw.trim().replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/i, "$1");
28+
const decision = Decision.parse(JSON.parse(json));
29+
if (decision.kind === "question") return decision;
30+
if (decision.kind === "default") return { kind: "branch", branch: BranchName.parse(fallback) };
31+
const source = inputs[decision.source]?.text;
32+
// Require a literal branch name in the authorized user's text. The model may
33+
// interpret intent, negation, and corrections, but cannot invent another ref.
34+
const tokens = decision.quote.match(/[A-Za-z0-9_/.-]+/g) ?? [];
35+
if (!source?.includes(decision.quote) || !tokens.some(t => [decision.branch, `origin/${decision.branch}`].includes(t.replace(/[.,]+$/, "")))) {
36+
throw new Error("Base branch selection was not supported by the user's text; selection will retry");
1937
}
20-
return selected;
38+
if (!BranchName.safeParse(decision.branch).success) return { kind: "question", question: `The requested branch name ${JSON.stringify(decision.branch)} is not valid. Which existing branch on origin should I use as the base?` };
39+
return { kind: "branch", branch: decision.branch };
2140
}

‎src/dispatcher.ts‎

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import { z } from "zod";
33
import { type GithubOptions, type Repository, Route, matchRoute } from "./config.js";
44
import { GithubError, Issue, Comment, type Pull } from "./github.js";
55
import { Serial, redact, type Store } from "./state.js";
6-
import { requestedBase } from "./branch.js";
6+
import { branchText, type BranchInput, type BaseChoice } from "./branch.js";
77
import { activityOf, type Activity } from "./activity.js";
88

9-
export const PendingQuestion = z.object({ id: z.string(), text: z.string(), sessionID: z.string(), commentID: z.number().optional(),
9+
export const PendingQuestion = z.object({ id: z.string(), text: z.string(), sessionID: z.string().optional(), purpose: z.literal("base").optional(), commentID: z.number().optional(),
1010
permission: z.object({ action: z.string(), resources: z.array(z.string()) }).optional(),
1111
answer: Comment.optional(), delivered: z.boolean().optional(), answerSent: z.boolean().optional() });
1212
const Phase = z.enum(["queued", "analyzing", "commented", "running", "verifying", "publishing", "pr_opened"]);
@@ -16,6 +16,7 @@ export const Task = z.object({
1616
attempts: z.number(), nextAt: z.number(), createdAt: z.number(),
1717
analysis: z.string().optional(), commentID: z.number().optional(),
1818
baseBranch: z.string().optional(), question: PendingQuestion.optional(),
19+
baseDialogue: z.array(z.object({ question: z.string(), answer: Comment })).optional(),
1920
permissions: z.array(z.object({ sessionID: z.string(), action: z.string(), resources: z.array(z.string()), allow: z.boolean() })).optional(),
2021
helpers: z.array(z.object({ id: z.string(), parentID: z.string(), capability: z.enum(["vision", "audio"]) })).optional(),
2122
branch: z.string(), worktree: z.string().optional(), baseSha: z.string().optional(),
@@ -45,6 +46,8 @@ export interface GithubPort {
4546
ensurePull(repo: string, branch: string, base: string, title: string, body: string): Promise<Pull>;
4647
}
4748
export interface Executor {
49+
selectBase(task: Task, repo: Repository, inputs: BranchInput[]): Promise<BaseChoice>;
50+
hasBranch(repo: Repository, branch: string): Promise<boolean>;
4851
analyze(task: Task): Promise<string>;
4952
title(task: Task): Promise<string>;
5053
prepare(task: Task, repo: Repository): Promise<{ worktree: string; baseSha: string }>;
@@ -108,7 +111,7 @@ export class Dispatcher {
108111
const reply = authorized.find(c => c.id > q.commentID! && (!q.permission || [`/allow ${q.id}`, `/deny ${q.id}`].includes(c.body.trim())));
109112
if (reply) {
110113
q.answer = reply;
111-
if (q.permission) existing.permissions = [...existing.permissions ?? [], { sessionID: q.sessionID, ...q.permission, allow: reply.body.trim().startsWith("/allow ") }];
114+
if (q.permission && q.sessionID) existing.permissions = [...existing.permissions ?? [], { sessionID: q.sessionID, ...q.permission, allow: reply.body.trim().startsWith("/allow ") }];
112115
if (existing.status === "waiting") existing.status = "ready";
113116
remaining = remaining.filter(c => c.id !== reply.id);
114117
existing.pendingFeedback = (existing.pendingFeedback ?? []).filter(c => c.id !== reply.id);
@@ -154,7 +157,7 @@ export class Dispatcher {
154157
// A lost comment response must not strand a waiting question after a restart.
155158
for (const pending of this.queue.tasks.filter(t => t.status === "waiting" && t.question && !t.question.commentID && t.nextAt <= this.now())) {
156159
const q = pending.question!;
157-
try { await this.question(q.sessionID, q.id, q.text, q.permission); }
160+
try { await this.publishQuestion(pending, q); }
158161
catch (error) { if (this.signal.aborted) return; await this.update(pending, { error: redact(error, this.secrets), nextAt: this.now() + 60_000 }); }
159162
}
160163
await this.serial.run(async () => {
@@ -192,10 +195,6 @@ export class Dispatcher {
192195
if (task.analysis && (latest.body !== task.issue.body || latest.title !== task.issue.title || JSON.stringify(route) !== JSON.stringify(task.route))) throw new Blocked("Issue or route changed after analysis; review before restarting");
193196
await this.update(task, { issue: latest, route });
194197
}
195-
if (!task.baseBranch && repo) {
196-
const baseBranch = requestedBase([task.source !== "comment" ? task.issue.body ?? "" : "", ...(task.feedback ?? []).map(c => c.body)], repo.baseBranch);
197-
await this.update(task, { baseBranch }); repo = { ...repo, baseBranch };
198-
}
199198
if (task.phase === "queued" || task.phase === "analyzing") {
200199
await this.update(task, { phase: "analyzing" });
201200
if (!task.analysis) await this.update(task, { analysis: await this.executor.analyze(task) });
@@ -204,6 +203,8 @@ export class Dispatcher {
204203
}
205204
if (task.phase === "commented") {
206205
if (!task.commentID) throw new Blocked("Missing confirmed analysis comment");
206+
if (!task.baseBranch) await this.resolveBase(task, repo);
207+
repo = { ...repo, baseBranch: task.baseBranch! };
207208
const workspace = await this.executor.prepare(task, repo);
208209
await this.update(task, { ...workspace, phase: "running", attempts: 0 });
209210
}
@@ -236,6 +237,29 @@ export class Dispatcher {
236237
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) });
237238
}
238239
}
240+
private async resolveBase(task: Task, repo: Repository) {
241+
const q = task.question;
242+
if (q?.purpose === "base" && !q.delivered) {
243+
if (!q.answer) { await this.publishQuestion(task, q); throw new WaitingForAnswer("Waiting for a base branch reply"); }
244+
if (!this.authorized(q.answer.user.login, repo.allowedAuthors)) throw new Blocked("The branch reply author is no longer authorized");
245+
await this.update(task, { baseDialogue: [...task.baseDialogue ?? [], { question: q.text, answer: q.answer }], question: { ...q, delivered: true, answerSent: true } });
246+
}
247+
const inputs: BranchInput[] = [
248+
...(this.authorized(task.issue.user.login, repo.allowedAuthors) ? [task.issue.title, task.issue.body ?? ""].map(text => ({ text })) : []),
249+
...(task.feedback ?? []).filter(c => this.authorized(c.user.login, repo.allowedAuthors)).map(c => ({ text: c.body })),
250+
...(task.baseDialogue ?? []).filter(d => this.authorized(d.answer.user.login, repo.allowedAuthors)).map(d => ({ text: d.answer.body, question: d.question })),
251+
].map(input => ({ ...input, text: branchText(input.text) })).filter(input => input.text);
252+
let choice = await this.executor.selectBase(task, repo, inputs);
253+
if (choice.kind === "branch" && !await this.executor.hasBranch(repo, choice.branch)) {
254+
choice = { kind: "question", question: `Branch ${JSON.stringify(choice.branch)} does not exist on origin. Which existing branch should I use as the base? You can reply in your own words.` };
255+
}
256+
if (choice.kind === "question") {
257+
const id = `base_${createHash("sha256").update(JSON.stringify({ key: task.key, inputs, question: choice.question })).digest("hex").slice(0, 24)}`;
258+
await this.askTask(task, { id, text: choice.question, purpose: "base" });
259+
throw new WaitingForAnswer("Waiting for a base branch reply");
260+
}
261+
await this.update(task, { baseBranch: choice.branch, ...(task.question?.purpose === "base" ? { question: undefined } : {}) });
262+
}
239263
private async mergeOnce() {
240264
if (!this.options.autoMerge.enabled || !this.github.mergeApproved) return;
241265
for (const task of this.queue.tasks) {
@@ -270,11 +294,18 @@ export class Dispatcher {
270294
async question(sessionID: string, id: string, text: string, permission?: { action: string; resources: string[] }) {
271295
const task = this.queue.tasks.find(t => t.sessionID === sessionID);
272296
if (!task || task.phase !== "running" || !["ready", "retry_wait", "waiting"].includes(task.status)) throw new Error("No active bot task for this session");
297+
return this.askTask(task, { id, text, sessionID, ...(permission ? { permission } : {}) });
298+
}
299+
private async askTask(task: Task, input: z.infer<typeof PendingQuestion>) {
273300
let question!: z.infer<typeof PendingQuestion>;
274301
await this.serial.run(async () => {
275-
if (!task.question || task.question.delivered) task.question = { id, text, sessionID, ...(permission ? { permission } : {}) };
302+
if (!task.question || task.question.delivered) task.question = input;
276303
question = task.question; await this.store.save(this.queue);
277304
});
305+
await this.publishQuestion(task, question);
306+
return { id: question.id };
307+
}
308+
private async publishQuestion(task: Task, question: z.infer<typeof PendingQuestion>) {
278309
if (!question.commentID) {
279310
const body = `Question (${question.id})\n\n${question.text}\n\n${question.permission ? `Reply with /allow ${question.id} or /deny ${question.id}.` : "Reply in this issue to continue. Only configured authors can answer."}`;
280311
const marker = `<!-- opencode2:${task.key}:question:${question.id} -->`;
@@ -288,7 +319,6 @@ export class Dispatcher {
288319
});
289320
} finally { if (this.questionPosts.get(marker) === post) this.questionPosts.delete(marker); }
290321
}
291-
return { id: question.id };
292322
}
293323
async helper(sessionID: string, callID: string, capability: "vision" | "audio") {
294324
const task = this.queue.tasks.find(t => t.sessionID === sessionID);

0 commit comments

Comments
 (0)