1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
|
import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { repositories, users } from "../db/schema";
import { Layout } from "../views/layout";
import { RepoHeader } from "../views/components";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { listBranches } from "../git/repository";
import {
Alert,
Button,
Container,
EmptyState,
Form,
FormGroup,
Select,
TextArea,
Text,
} from "../views/ui";
const specs = new Hono<AuthEnv>();
const DISABLE_ON_SUBMIT_JS = `
(function() {
var form = document.getElementById('spec-form');
if (!form) return;
form.addEventListener('submit', function() {
var btn = form.querySelector('button[type="submit"]');
var ta = form.querySelector('textarea[name="spec"]');
if (btn) {
btn.disabled = true;
btn.textContent = 'Working... this can take 10-30s';
}
if (ta) ta.readOnly = true;
});
})();
`;
interface ResolvedRepo {
ownerId: string;
ownerUsername: string;
repoId: string;
repoName: string;
defaultBranch: string;
}
async function resolveRepo(
ownerName: string,
repoName: string
): Promise<ResolvedRepo | null> {
try {
const [ownerRow] = await db
.select()
.from(users)
.where(eq(users.username, ownerName))
.limit(1);
if (!ownerRow) return null;
const [repoRow] = await db
.select()
.from(repositories)
.where(
and(
eq(repositories.ownerId, ownerRow.id),
eq(repositories.name, repoName)
)
)
.limit(1);
if (!repoRow) return null;
return {
ownerId: ownerRow.id,
ownerUsername: ownerRow.username,
repoId: repoRow.id,
repoName: repoRow.name,
defaultBranch: repoRow.defaultBranch || "main",
};
} catch {
return null;
}
}
function hasWriteAccess(
resolved: ResolvedRepo,
userId: string | undefined
): boolean {
return !!userId && resolved.ownerId === userId;
}
function SpecForm({
ownerName,
repoName,
branches,
defaultBranch,
spec,
baseRef,
error,
}: {
ownerName: string;
repoName: string;
branches: string[];
defaultBranch: string;
spec?: string;
baseRef?: string;
error?: string;
}) {
const branchList = branches.length > 0 ? branches : [defaultBranch];
const selectedBase = baseRef && branchList.includes(baseRef)
? baseRef
: defaultBranch;
return (
<Container maxWidth={820}>
<div
class="panel"
style="padding:14px 16px;margin-bottom:20px;border-left:3px solid var(--accent)"
>
<strong>Experimental</strong>
{" — "}
AI-generated PRs are draft by default. Review every line before
merging.
</div>
<h2 style="margin-bottom:4px">Spec to PR</h2>
<Text muted style="display:block;margin-bottom:16px">
Describe a feature in plain English. Claude will draft the code
changes and open a pull request against the branch you choose.
</Text>
{error && <Alert variant="error">{error}</Alert>}
<Form
method="post"
action={`/${ownerName}/${repoName}/spec`}
id="spec-form"
>
<FormGroup label="Feature spec" htmlFor="spec">
<TextArea
name="spec"
id="spec"
rows={10}
required
value={spec || ""}
placeholder="add a dark mode toggle to the settings page"
/>
</FormGroup>
<FormGroup label="Base branch" htmlFor="baseRef">
<Select name="baseRef" id="baseRef" value={selectedBase}>
{branchList.map((b) => (
<option value={b} selected={b === selectedBase}>
{b}
</option>
))}
</Select>
</FormGroup>
<Button type="submit" variant="primary">
Generate PR with AI
</Button>
</Form>
<div class="panel" style="margin-top:28px">
<div
class="panel-item"
style="flex-direction:column;align-items:flex-start;gap:4px;padding:14px 16px"
>
<strong>How this works</strong>
</div>
<div class="panel-item" style="padding:12px 16px">
<div>
<strong>1. You write a spec.</strong>
{" "}
<Text muted>
A sentence or a paragraph describing the change you want.
</Text>
</div>
</div>
<div class="panel-item" style="padding:12px 16px">
<div>
<strong>2. Claude drafts the diff.</strong>
{" "}
<Text muted>
We fetch the base branch, run Claude against the repo, and
commit the proposed changes to a new branch.
</Text>
</div>
</div>
<div class="panel-item" style="padding:12px 16px">
<div>
<strong>3. A draft PR opens.</strong>
{" "}
<Text muted>
You review, edit, and merge on your terms. Nothing lands on
{" "}
<code>{selectedBase}</code> automatically.
</Text>
</div>
</div>
</div>
<script dangerouslySetInnerHTML={{ __html: DISABLE_ON_SUBMIT_JS }} />
</Container>
);
}
specs.get("/:owner/:repo/spec", softAuth, requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const resolved = await resolveRepo(owner, repo);
if (!resolved) {
return c.html(
<Layout title="Not Found" user={user}>
<EmptyState title="Repository not found">
<p>No such repository.</p>
</EmptyState>
</Layout>,
404
);
}
if (!hasWriteAccess(resolved, user.id)) {
return c.html(
<Layout title="Forbidden" user={user}>
<RepoHeader owner={owner} repo={repo} />
<EmptyState title="Write access required">
<p>You need write access to generate a spec-to-PR on this repository.</p>
</EmptyState>
</Layout>,
403
);
}
let branches: string[] = [];
try {
branches = await listBranches(owner, repo);
} catch {
branches = [];
}
return c.html(
<Layout title={`Spec to PR — ${owner}/${repo}`} user={user}>
<RepoHeader owner={owner} repo={repo} />
<SpecForm
ownerName={owner}
repoName={repo}
branches={branches}
defaultBranch={resolved.defaultBranch}
/>
</Layout>
);
});
specs.post("/:owner/:repo/spec", softAuth, requireAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.notFound();
if (!hasWriteAccess(resolved, user.id)) {
return c.html(
<Layout title="Forbidden" user={user}>
<RepoHeader owner={owner} repo={repo} />
<EmptyState title="Write access required">
<p>You need write access to generate a spec-to-PR on this repository.</p>
</EmptyState>
</Layout>,
403
);
}
const body = await c.req.parseBody();
const spec = String(body.spec || "").trim();
const baseRef = String(body.baseRef || resolved.defaultBranch).trim()
|| resolved.defaultBranch;
let branches: string[] = [];
try {
branches = await listBranches(owner, repo);
} catch {
branches = [];
}
function renderWithError(error: string, status: 400 | 500 | 503 = 400) {
return c.html(
<Layout title={`Spec to PR — ${owner}/${repo}`} user={user}>
<RepoHeader owner={owner} repo={repo} />
<SpecForm
ownerName={owner}
repoName={repo}
branches={branches}
defaultBranch={resolved!.defaultBranch}
spec={spec}
baseRef={baseRef}
error={error}
/>
</Layout>,
status
);
}
if (!spec) {
return renderWithError("Spec is required.");
}
let createSpecPR:
| ((args: {
repoId: string;
spec: string;
baseRef: string;
userId: string;
}) => Promise<
| { ok: true; prNumber: number }
| { ok: false; error: string }
>)
| null = null;
try {
const mod: any = await import("../lib/spec-to-pr");
createSpecPR =
(mod && (mod.createSpecPR || (mod.default && mod.default.createSpecPR))) ||
null;
} catch {
createSpecPR = null;
}
if (!createSpecPR) {
return renderWithError(
"Backend not available — spec-to-PR is not deployed yet. Please try again later.",
503
);
}
let result:
| { ok: true; prNumber: number }
| { ok: false; error: string };
try {
result = await createSpecPR({
repoId: resolved.repoId,
spec,
baseRef,
userId: user.id,
});
} catch (err) {
const msg =
err instanceof Error ? err.message : "Unexpected error generating PR.";
return renderWithError(`Failed to generate PR: ${msg}`, 500);
}
if (!result || !result.ok) {
const msg = (result && "error" in result && result.error) || "Unknown error.";
return renderWithError(`Failed to generate PR: ${msg}`);
}
return c.redirect(`/${owner}/${repo}/pulls/${result.prNumber}`);
});
export default specs;
|