Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
specs.tsx12.9 KB · 466 lines
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/**
 * Spec-to-PR — paste a plain-English feature spec, get back a draft PR
 * generated by the Claude API.
 *
 *   GET  /:owner/:repo/spec   — form (requires write access)
 *   POST /:owner/:repo/spec   — hands off to lib/spec-to-pr.ts, redirects to
 *                                the new PR on success, re-renders the form
 *                                with an error banner on failure
 *
 * The backend (`createSpecPR` in `src/lib/spec-to-pr.ts`) is being built in
 * parallel. We import it dynamically so this file compiles and its tests
 * pass even if the module is not yet on disk — if the import fails we
 * fall back to a "Backend not available" banner.
 */
import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { repositories, users, issues } 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>();

// Tiny inline script that disables the submit button + textarea while the
// request is in-flight so users don't accidentally double-click and trigger
// two 10-30s Claude calls. Rendered as a plain <script> tag.
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;
  }
}

/**
 * Write access check. Gluecron has no collaborator table yet, so "write
 * access" == repo owner. Matches the convention used by repo-settings and
 * ai-explain's regenerate endpoint.
 */
function hasWriteAccess(
  resolved: ResolvedRepo,
  userId: string | undefined
): boolean {
  return !!userId && resolved.ownerId === userId;
}

/**
 * Build the default spec text for an issue-driven generation. Format:
 *
 *   Implement: <title>
 *
 *   <body>
 *
 *   Closes #<n>
 *
 * The trailing `Closes #N` is picked up by `src/lib/close-keywords.ts` (J7)
 * so the issue auto-closes when the AI-generated PR is merged. Body is
 * trimmed and falls back to an empty string if missing. Pure helper —
 * exported for tests.
 */
export function buildSpecFromIssue(input: {
  number: number;
  title: string;
  body: string | null | undefined;
}): string {
  const title = (input.title || "").trim();
  const body = (input.body || "").trim();
  const lines: string[] = [];
  if (title) lines.push(`Implement: ${title}`);
  if (body) {
    lines.push("");
    lines.push(body);
  }
  lines.push("");
  lines.push(`Closes #${input.number}`);
  return lines.join("\n");
}

function SpecForm({
  ownerName,
  repoName,
  branches,
  defaultBranch,
  spec,
  baseRef,
  error,
  fromIssueNumber,
  fromIssueTitle,
}: {
  ownerName: string;
  repoName: string;
  branches: string[];
  defaultBranch: string;
  spec?: string;
  baseRef?: string;
  error?: string;
  fromIssueNumber?: number;
  fromIssueTitle?: 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>

      {fromIssueNumber && (
        <Alert variant="info">
          Building from issue{" "}
          <a href={`/${ownerName}/${repoName}/issues/${fromIssueNumber}`}>
            #{fromIssueNumber}
            {fromIssueTitle ? ` — ${fromIssueTitle}` : ""}
          </a>
          . The spec below has been pre-filled from the issue and will
          auto-close it on merge.
        </Alert>
      )}

      <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 = [];
  }

  // Optional: pre-fill from an issue. Triggered from the "Build with AI"
  // button on the issue detail page. Silently no-ops on missing/unknown
  // issue so the form still renders.
  let prefilledSpec: string | undefined;
  let fromIssueNumber: number | undefined;
  let fromIssueTitle: string | undefined;
  const fromIssueRaw = c.req.query("fromIssue");
  if (fromIssueRaw) {
    const n = Number.parseInt(fromIssueRaw, 10);
    if (Number.isInteger(n) && n > 0) {
      try {
        const [issueRow] = await db
          .select()
          .from(issues)
          .where(
            and(eq(issues.repositoryId, resolved.repoId), eq(issues.number, n))
          )
          .limit(1);
        if (issueRow) {
          fromIssueNumber = issueRow.number;
          fromIssueTitle = issueRow.title;
          prefilledSpec = buildSpecFromIssue({
            number: issueRow.number,
            title: issueRow.title,
            body: issueRow.body,
          });
        }
      } catch {
        // Pre-fill is a convenience, never block form render.
      }
    }
  }

  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={prefilledSpec}
        fromIssueNumber={fromIssueNumber}
        fromIssueTitle={fromIssueTitle}
      />
    </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.");
  }

  // Dynamically import the backend so this file works even before the
  // sibling branch landing `src/lib/spec-to-pr.ts` is merged. If the module
  // is missing or throws we surface a soft error instead of 500-ing.
  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;