@eduardo191labs/opencode-actions 0.1.1 → 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.
package/dist/git.js CHANGED
@@ -73,6 +73,24 @@ export async function configureIdentity(cwd, config) {
73
73
  await git(cwd, ["config", "user.name", `${name}[bot]`]);
74
74
  await git(cwd, ["config", "user.email", `${name}-bot@users.noreply.github.com`]);
75
75
  }
76
+ /**
77
+ * The marker that keeps a bot commit from triggering the bot.
78
+ *
79
+ * Every commit made from a workflow is pushed with the workflow's token, and
80
+ * GitHub does not start a new workflow run for an `GITHUB_TOKEN` push — but it
81
+ * *does* start one when the run is dispatched by the app, and it always starts
82
+ * one for a pull request branch. Without a marker, each commit the bot makes can
83
+ * start the workflow that made it, and the repository spins.
84
+ *
85
+ * `[skip ci]` is GitHub's own opt-out and is respected by every workflow, which
86
+ * is why it is used instead of a private convention: a repository with its own
87
+ * CI gets the same protection without being told.
88
+ */
89
+ export const SKIP_CI = "[skip ci]";
90
+ /** True when a commit is one the bot made, and so must not re-trigger it. */
91
+ export function isBotCommit(message) {
92
+ return message.includes(SKIP_CI);
93
+ }
76
94
  export async function commitAll(cwd, message, config) {
77
95
  const owner = await state(cwd);
78
96
  if (!owner.dirty)
@@ -80,7 +98,11 @@ export async function commitAll(cwd, message, config) {
80
98
  assertWorkflowWrites(config, owner.changedFiles);
81
99
  await configureIdentity(cwd, config);
82
100
  const trailer = bot(config).commit_trailer;
83
- const full = trailer ? `${message}\n\n${trailer}` : message;
101
+ // The marker goes on the subject line, where GitHub reads it. A trailer is
102
+ // still honoured, but it is not a reliable place to put `[skip ci]`.
103
+ const subject = message.split("\n")[0] ?? message;
104
+ const first = isBotCommit(subject) ? message : `${subject} ${SKIP_CI}${message.slice(subject.length)}`;
105
+ const full = trailer ? `${first}\n\n${trailer}` : first;
84
106
  await git(cwd, ["add", "-A"]);
85
107
  const result = await git(cwd, ["commit", "-m", full]);
86
108
  if (result.code !== 0)
package/dist/github.d.ts CHANGED
@@ -69,7 +69,11 @@ export declare class GitHub {
69
69
  commit_title?: string;
70
70
  commit_message?: string;
71
71
  merge_method?: "merge" | "squash" | "rebase";
72
- }): Promise<unknown>;
72
+ }): Promise<{
73
+ merged: boolean;
74
+ sha: string;
75
+ message?: string;
76
+ }>;
73
77
  /** Create a review, optionally with inline comments and a request-changes verdict. */
74
78
  createReview(ref: RepoRef, number: number, input: {
75
79
  body?: string;
@@ -154,6 +158,10 @@ export interface PullRequest {
154
158
  changed_files: number;
155
159
  additions: number;
156
160
  deletions: number;
161
+ /** Null while GitHub is still computing it. */
162
+ mergeable?: boolean | null;
163
+ mergeable_state?: string;
164
+ merge_commit_sha?: string | null;
157
165
  }
158
166
  export interface PullFile {
159
167
  filename: string;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The Copilot workflow: an issue becomes a working branch and a pull request
3
+ * that keeps being edited until it is merged.
4
+ *
5
+ * The shape matters. Copilot's value is not that it writes a patch once; it is
6
+ * that the patch lives on a branch where the author can ask for another pass,
7
+ * commit to it, and merge it when it is right. This module keeps that state in
8
+ * the pull request itself rather than in the runner, because a run is over in
9
+ * minutes and the conversation is not.
10
+ *
11
+ * Everything here is opt-in through permissions: creating a branch needs
12
+ * `manage_branches`, editing a PR needs `manage_pull_requests`, merging needs
13
+ * `merge_pull_requests` (or `merge_protected` on a protected base).
14
+ */
15
+ import { type BotConfig } from "./config.js";
16
+ import type { GitHub, RepoRef } from "./github.js";
17
+ export interface WorkBranch {
18
+ /** Branch name derived from the issue, stable across runs. */
19
+ branch: string;
20
+ /** The pull request, when one is already open for the branch. */
21
+ pr: number | null;
22
+ }
23
+ /**
24
+ * A branch name that identifies the issue and survives a second run.
25
+ *
26
+ * Stable matters: a follow-up command must commit onto the *same* branch, or
27
+ * the author ends up with four pull requests for one issue. The issue number is
28
+ * the only part that cannot change, so it leads.
29
+ */
30
+ export declare function workBranch(config: BotConfig, issueNumber: number, title: string): string;
31
+ /**
32
+ * The commit trailer that ties a branch back to its issue.
33
+ *
34
+ * Used instead of a runner-side store: the branch and the PR are durable, the
35
+ * runner is not. It is also how a later run finds the issue without being told.
36
+ */
37
+ export declare function issueTrailer(issueNumber: number): string;
38
+ /** Extract the issue a branch or PR belongs to, from a name or a trailer. */
39
+ export declare function issueFromText(text: string): number | null;
40
+ export interface ImplementOptions {
41
+ issueNumber: number;
42
+ title: string;
43
+ body: string;
44
+ /** Run id or comment id, so a reply can be posted where the request was made. */
45
+ requestId?: number;
46
+ }
47
+ /**
48
+ * Create or reuse the working branch, let the agent write the change, and open a
49
+ * PR whose body is generated from the actual diff.
50
+ *
51
+ * Reuse is the point: `implement` on an issue twice must not produce two
52
+ * branches. The existing branch is checked out by name on the base and the agent
53
+ * works on top of it.
54
+ */
55
+ export declare function implementIssue(ctx: {
56
+ github: GitHub;
57
+ repo: RepoRef;
58
+ config: BotConfig;
59
+ workspace: string;
60
+ log: (message: string) => void;
61
+ }, options: ImplementOptions, run: (prompt: string) => Promise<{
62
+ text: string;
63
+ resultJson: any;
64
+ model?: string;
65
+ cost?: number;
66
+ }>): Promise<{
67
+ rejected: string;
68
+ unchanged?: undefined;
69
+ branch?: undefined;
70
+ pr?: undefined;
71
+ text?: undefined;
72
+ updated?: undefined;
73
+ model?: undefined;
74
+ cost?: undefined;
75
+ } | {
76
+ unchanged: boolean;
77
+ branch: string;
78
+ pr: any;
79
+ text: string;
80
+ rejected?: undefined;
81
+ updated?: undefined;
82
+ model?: undefined;
83
+ cost?: undefined;
84
+ } | {
85
+ unchanged: boolean;
86
+ branch: string;
87
+ rejected?: undefined;
88
+ pr?: undefined;
89
+ text?: undefined;
90
+ updated?: undefined;
91
+ model?: undefined;
92
+ cost?: undefined;
93
+ } | {
94
+ branch: string;
95
+ pr: any;
96
+ updated: boolean;
97
+ model: string | undefined;
98
+ cost: number | undefined;
99
+ rejected?: undefined;
100
+ unchanged?: undefined;
101
+ text?: undefined;
102
+ } | {
103
+ branch: string;
104
+ pr: number;
105
+ model: string | undefined;
106
+ cost: number | undefined;
107
+ rejected?: undefined;
108
+ unchanged?: undefined;
109
+ text?: undefined;
110
+ updated?: undefined;
111
+ }>;
112
+ /** The PR a branch already has open, if any. */
113
+ export declare function findPullForBranch(github: GitHub, repo: RepoRef, branch: string): Promise<{
114
+ number: any;
115
+ url: any;
116
+ } | null>;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The Copilot workflow: an issue becomes a working branch and a pull request
3
+ * that keeps being edited until it is merged.
4
+ *
5
+ * The shape matters. Copilot's value is not that it writes a patch once; it is
6
+ * that the patch lives on a branch where the author can ask for another pass,
7
+ * commit to it, and merge it when it is right. This module keeps that state in
8
+ * the pull request itself rather than in the runner, because a run is over in
9
+ * minutes and the conversation is not.
10
+ *
11
+ * Everything here is opt-in through permissions: creating a branch needs
12
+ * `manage_branches`, editing a PR needs `manage_pull_requests`, merging needs
13
+ * `merge_pull_requests` (or `merge_protected` on a protected base).
14
+ */
15
+ import { bot as botLayer, permission } from "./config.js";
16
+ import { assertBranchWrites, assertWorkflowWrites, commitAll, git, push, state } from "./git.js";
17
+ /**
18
+ * A branch name that identifies the issue and survives a second run.
19
+ *
20
+ * Stable matters: a follow-up command must commit onto the *same* branch, or
21
+ * the author ends up with four pull requests for one issue. The issue number is
22
+ * the only part that cannot change, so it leads.
23
+ */
24
+ export function workBranch(config, issueNumber, title) {
25
+ const prefix = botLayer(config).work_branch_prefix ?? "opencode/";
26
+ const slug = title
27
+ .toLowerCase()
28
+ .replace(/[^a-z0-9]+/g, "-")
29
+ .replace(/^-+|-+$/g, "")
30
+ .slice(0, 40)
31
+ .replace(/-+$/g, "");
32
+ return `${prefix}issue-${issueNumber}${slug ? `-${slug}` : ""}`;
33
+ }
34
+ /**
35
+ * The commit trailer that ties a branch back to its issue.
36
+ *
37
+ * Used instead of a runner-side store: the branch and the PR are durable, the
38
+ * runner is not. It is also how a later run finds the issue without being told.
39
+ */
40
+ export function issueTrailer(issueNumber) {
41
+ return `Refs #${issueNumber}`;
42
+ }
43
+ /** Extract the issue a branch or PR belongs to, from a name or a trailer. */
44
+ export function issueFromText(text) {
45
+ const byName = /issue-(\d+)/.exec(text);
46
+ if (byName)
47
+ return Number(byName[1]);
48
+ const byRef = /\b(?:refs|closes|fixes|resolves)\s+#(\d+)/i.exec(text);
49
+ return byRef ? Number(byRef[1]) : null;
50
+ }
51
+ /**
52
+ * Create or reuse the working branch, let the agent write the change, and open a
53
+ * PR whose body is generated from the actual diff.
54
+ *
55
+ * Reuse is the point: `implement` on an issue twice must not produce two
56
+ * branches. The existing branch is checked out by name on the base and the agent
57
+ * works on top of it.
58
+ */
59
+ export async function implementIssue(ctx, options, run) {
60
+ const { github, repo, config } = ctx;
61
+ const base = botLayer(config).base_branch ?? "main";
62
+ const branch = workBranch(config, options.issueNumber, options.title);
63
+ if (permission(config, "manage_branches") !== "allow") {
64
+ return { rejected: "manage_branches is not allowed" };
65
+ }
66
+ assertBranchWrites(config, branch);
67
+ const existing = await findPullForBranch(github, repo, branch);
68
+ const prompt = implementPrompt(options, branch, base, existing ? existing.number : null);
69
+ const result = await run(prompt);
70
+ const current = await state(ctx.workspace);
71
+ if (!current.dirty) {
72
+ return { unchanged: true, branch, pr: existing ? existing.number : null, text: result.text };
73
+ }
74
+ assertWorkflowWrites(config, current.changedFiles);
75
+ // The commit message carries the issue, so a later run can find it again
76
+ // without being told which issue the branch belongs to.
77
+ const commit = await commitAll(ctx.workspace, `${result.resultJson?.commit_message ?? `feat: address #${options.issueNumber}`}\n\n${issueTrailer(options.issueNumber)}`, config);
78
+ if (!commit)
79
+ return { unchanged: true, branch };
80
+ await ensureBranch(github, repo, branch, base, ctx.workspace, config);
81
+ const body = pullBody(options, result.resultJson, result.text);
82
+ if (existing) {
83
+ // A follow-up pass edits the same PR: the description describes the diff as
84
+ // it is now, and the title follows the change rather than the first draft.
85
+ if (permission(config, "manage_pull_requests") === "allow") {
86
+ await github.updatePull(repo, existing.number, {
87
+ body,
88
+ title: (result.resultJson?.pr_title ?? options.title).slice(0, 200),
89
+ });
90
+ }
91
+ return { branch, pr: existing.number, updated: true, model: result.model, cost: result.cost };
92
+ }
93
+ const pull = await github.createPull(repo, {
94
+ title: (result.resultJson?.pr_title ?? options.title).slice(0, 200),
95
+ head: branch,
96
+ base,
97
+ body,
98
+ draft: false,
99
+ });
100
+ ctx.log(`opened PR #${pull.number} for #${options.issueNumber}`);
101
+ if (permission(config, "comment") === "allow" && options.requestId) {
102
+ await github
103
+ .comment(repo, options.issueNumber, `Working on this in #${pull.number}, on branch \`${branch}\`.`)
104
+ .catch(() => { });
105
+ }
106
+ return { branch, pr: pull.number, model: result.model, cost: result.cost };
107
+ }
108
+ /** The PR a branch already has open, if any. */
109
+ export async function findPullForBranch(github, repo, branch) {
110
+ const pulls = await github.paginate(`/repos/${repo.owner}/${repo.repo}/pulls?state=open&head=${repo.owner}:${branch}&per_page=10`, 1);
111
+ const first = pulls[0];
112
+ return first ? { number: first.number, url: first.html_url } : null;
113
+ }
114
+ /**
115
+ * Check the branch out locally and push the commit that is already staged.
116
+ *
117
+ * The branch may exist from a previous run, in which case it is fetched rather
118
+ * than recreated: recreating at the base would discard the earlier work.
119
+ */
120
+ async function ensureBranch(github, repo, branch, base, workspace, config) {
121
+ const exists = await github.getRef(repo, branch).catch(() => null);
122
+ if (exists) {
123
+ // A previous pass left work here. Rebasing onto it keeps that work; resetting
124
+ // to the base would throw it away and make the second run a regression.
125
+ await git(workspace, ["fetch", "origin", branch, "--depth", "1"]).catch(() => null);
126
+ await git(workspace, ["rebase", "FETCH_HEAD"]).catch(async () => {
127
+ await git(workspace, ["rebase", "--abort"]).catch(() => null);
128
+ await git(workspace, ["reset", "--soft", "FETCH_HEAD"]).catch(() => null);
129
+ await commitAll(workspace, `chore: reapply on ${branch}`, config);
130
+ });
131
+ await git(workspace, ["checkout", "-B", branch]).catch(() => null);
132
+ }
133
+ else {
134
+ const head = await github.getRef(repo, base);
135
+ await github.createRef(repo, branch, head.object.sha).catch(() => null);
136
+ await git(workspace, ["checkout", "-B", branch]).catch(() => null);
137
+ }
138
+ await push(workspace, branch, config);
139
+ }
140
+ function pullBody(options, json, text) {
141
+ const summary = json?.summary ?? text.trim();
142
+ const changes = Array.isArray(json?.changes) && json.changes.length ? json.changes.map((c) => `- ${c}`).join("\n") : "";
143
+ const tests = json?.tests ? `\n## Tests\n\n${json.tests}\n` : "";
144
+ return [
145
+ `Closes #${options.issueNumber}`,
146
+ "",
147
+ summary || `Implements #${options.issueNumber}.`,
148
+ changes ? `\n## What changed\n\n${changes}` : "",
149
+ tests,
150
+ "\n---\nGenerated by the bot from the issue. Push to this branch, or ask for another pass, and the description is rewritten from the diff.",
151
+ ]
152
+ .filter(Boolean)
153
+ .join("\n");
154
+ }
155
+ function implementPrompt(options, branch, base, prNumber) {
156
+ return `# Task: implement issue #${options.issueNumber}
157
+
158
+ Branch: \`${branch}\` (already checked out; the base is \`${base}\`)
159
+ ${prNumber ? `Pull request: #${prNumber} (open — this is another pass on the same work)` : ""}
160
+
161
+ ## Issue
162
+
163
+ **${options.title}**
164
+
165
+ ${options.body.slice(0, 8000)}
166
+
167
+ ## What to do
168
+
169
+ 1. Read the code this issue is about before changing anything. If the issue is
170
+ wrong or already fixed, say so and change nothing.
171
+ 2. Make the smallest change that resolves it. Follow the existing style; do not
172
+ reformat unrelated code.
173
+ 3. Run the project's tests or build if one exists and the issue affects it.
174
+
175
+ ## Output
176
+
177
+ Reply with JSON only:
178
+
179
+ \`\`\`json
180
+ {
181
+ "fixable": true,
182
+ "summary": "two or three sentences on what the issue was and what you changed",
183
+ "pr_title": "a pull request title in conventional-commits form",
184
+ "commit_message": "the commit subject line",
185
+ "changes": ["src/file.ts: what changed and why"],
186
+ "tests": "what you ran and what it said, or an explanation of why nothing could be run"
187
+ }
188
+ \`\`\`
189
+
190
+ If the issue cannot be resolved without a decision only a person can make, set
191
+ "fixable": false and put the question in "summary".`;
192
+ }